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 if (Subtarget->hasNEON()) {
430 addDRTypeForNEON(MVT::v2f32);
431 addDRTypeForNEON(MVT::v8i8);
432 addDRTypeForNEON(MVT::v4i16);
433 addDRTypeForNEON(MVT::v2i32);
434 addDRTypeForNEON(MVT::v1i64);
436 addQRTypeForNEON(MVT::v4f32);
437 addQRTypeForNEON(MVT::v2f64);
438 addQRTypeForNEON(MVT::v16i8);
439 addQRTypeForNEON(MVT::v8i16);
440 addQRTypeForNEON(MVT::v4i32);
441 addQRTypeForNEON(MVT::v2i64);
443 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
444 // neither Neon nor VFP support any arithmetic operations on it.
445 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
446 // supported for v4f32.
447 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
448 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
449 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
450 // FIXME: Code duplication: FDIV and FREM are expanded always, see
451 // ARMTargetLowering::addTypeForNEON method for details.
452 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
453 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
454 // FIXME: Create unittest.
455 // In another words, find a way when "copysign" appears in DAG with vector
457 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
458 // FIXME: Code duplication: SETCC has custom operation action, see
459 // ARMTargetLowering::addTypeForNEON method for details.
460 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
461 // FIXME: Create unittest for FNEG and for FABS.
462 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
463 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
464 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
465 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
466 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
467 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
468 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
469 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
470 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
471 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
472 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
473 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
474 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
475 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
476 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
477 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
478 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
479 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
480 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
482 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
483 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
484 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
485 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
486 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
487 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
488 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
489 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
490 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
491 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
492 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
493 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
494 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
495 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
496 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
498 // Mark v2f32 intrinsics.
499 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
500 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
501 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
502 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
503 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
504 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
505 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
506 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
507 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
508 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
509 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
510 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
511 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
512 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
513 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
515 // Neon does not support some operations on v1i64 and v2i64 types.
516 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
517 // Custom handling for some quad-vector types to detect VMULL.
518 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
519 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
520 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
521 // Custom handling for some vector types to avoid expensive expansions
522 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
523 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
524 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
525 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
526 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
527 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
528 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
529 // a destination type that is wider than the source, and nor does
530 // it have a FP_TO_[SU]INT instruction with a narrower destination than
532 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
533 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
534 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
535 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
537 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
538 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
540 // NEON does not have single instruction CTPOP for vectors with element
541 // types wider than 8-bits. However, custom lowering can leverage the
542 // v8i8/v16i8 vcnt instruction.
543 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
544 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
545 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
546 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
548 // NEON only has FMA instructions as of VFP4.
549 if (!Subtarget->hasVFP4()) {
550 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
551 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
554 setTargetDAGCombine(ISD::INTRINSIC_VOID);
555 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
556 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
557 setTargetDAGCombine(ISD::SHL);
558 setTargetDAGCombine(ISD::SRL);
559 setTargetDAGCombine(ISD::SRA);
560 setTargetDAGCombine(ISD::SIGN_EXTEND);
561 setTargetDAGCombine(ISD::ZERO_EXTEND);
562 setTargetDAGCombine(ISD::ANY_EXTEND);
563 setTargetDAGCombine(ISD::SELECT_CC);
564 setTargetDAGCombine(ISD::BUILD_VECTOR);
565 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
566 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
567 setTargetDAGCombine(ISD::STORE);
568 setTargetDAGCombine(ISD::FP_TO_SINT);
569 setTargetDAGCombine(ISD::FP_TO_UINT);
570 setTargetDAGCombine(ISD::FDIV);
571 setTargetDAGCombine(ISD::LOAD);
573 // It is legal to extload from v4i8 to v4i16 or v4i32.
574 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
576 for (MVT VT : MVT::integer_vector_valuetypes()) {
577 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
578 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
579 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
584 // ARM and Thumb2 support UMLAL/SMLAL.
585 if (!Subtarget->isThumb1Only())
586 setTargetDAGCombine(ISD::ADDC);
588 if (Subtarget->isFPOnlySP()) {
589 // When targetting a floating-point unit with only single-precision
590 // operations, f64 is legal for the few double-precision instructions which
591 // are present However, no double-precision operations other than moves,
592 // loads and stores are provided by the hardware.
593 setOperationAction(ISD::FADD, MVT::f64, Expand);
594 setOperationAction(ISD::FSUB, MVT::f64, Expand);
595 setOperationAction(ISD::FMUL, MVT::f64, Expand);
596 setOperationAction(ISD::FMA, MVT::f64, Expand);
597 setOperationAction(ISD::FDIV, MVT::f64, Expand);
598 setOperationAction(ISD::FREM, MVT::f64, Expand);
599 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
600 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
601 setOperationAction(ISD::FNEG, MVT::f64, Expand);
602 setOperationAction(ISD::FABS, MVT::f64, Expand);
603 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
604 setOperationAction(ISD::FSIN, MVT::f64, Expand);
605 setOperationAction(ISD::FCOS, MVT::f64, Expand);
606 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
607 setOperationAction(ISD::FPOW, MVT::f64, Expand);
608 setOperationAction(ISD::FLOG, MVT::f64, Expand);
609 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
610 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
611 setOperationAction(ISD::FEXP, MVT::f64, Expand);
612 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
613 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
614 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
615 setOperationAction(ISD::FRINT, MVT::f64, Expand);
616 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
617 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
618 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
619 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
620 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
621 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
622 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
623 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
624 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
625 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
628 computeRegisterProperties(Subtarget->getRegisterInfo());
630 // ARM does not have floating-point extending loads.
631 for (MVT VT : MVT::fp_valuetypes()) {
632 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
633 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
636 // ... or truncating stores
637 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
638 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
639 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
641 // ARM does not have i1 sign extending load.
642 for (MVT VT : MVT::integer_valuetypes())
643 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
645 // ARM supports all 4 flavors of integer indexed load / store.
646 if (!Subtarget->isThumb1Only()) {
647 for (unsigned im = (unsigned)ISD::PRE_INC;
648 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
649 setIndexedLoadAction(im, MVT::i1, Legal);
650 setIndexedLoadAction(im, MVT::i8, Legal);
651 setIndexedLoadAction(im, MVT::i16, Legal);
652 setIndexedLoadAction(im, MVT::i32, Legal);
653 setIndexedStoreAction(im, MVT::i1, Legal);
654 setIndexedStoreAction(im, MVT::i8, Legal);
655 setIndexedStoreAction(im, MVT::i16, Legal);
656 setIndexedStoreAction(im, MVT::i32, Legal);
660 setOperationAction(ISD::SADDO, MVT::i32, Custom);
661 setOperationAction(ISD::UADDO, MVT::i32, Custom);
662 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
663 setOperationAction(ISD::USUBO, MVT::i32, Custom);
665 // i64 operation support.
666 setOperationAction(ISD::MUL, MVT::i64, Expand);
667 setOperationAction(ISD::MULHU, MVT::i32, Expand);
668 if (Subtarget->isThumb1Only()) {
669 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
670 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
672 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
673 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
674 setOperationAction(ISD::MULHS, MVT::i32, Expand);
676 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
677 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
678 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
679 setOperationAction(ISD::SRL, MVT::i64, Custom);
680 setOperationAction(ISD::SRA, MVT::i64, Custom);
682 if (!Subtarget->isThumb1Only()) {
683 // FIXME: We should do this for Thumb1 as well.
684 setOperationAction(ISD::ADDC, MVT::i32, Custom);
685 setOperationAction(ISD::ADDE, MVT::i32, Custom);
686 setOperationAction(ISD::SUBC, MVT::i32, Custom);
687 setOperationAction(ISD::SUBE, MVT::i32, Custom);
690 // ARM does not have ROTL.
691 setOperationAction(ISD::ROTL, MVT::i32, Expand);
692 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
693 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
694 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
695 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
697 // These just redirect to CTTZ and CTLZ on ARM.
698 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
699 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
701 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
703 // Only ARMv6 has BSWAP.
704 if (!Subtarget->hasV6Ops())
705 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
707 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
708 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
709 // These are expanded into libcalls if the cpu doesn't have HW divider.
710 setOperationAction(ISD::SDIV, MVT::i32, Expand);
711 setOperationAction(ISD::UDIV, MVT::i32, Expand);
714 // FIXME: Also set divmod for SREM on EABI
715 setOperationAction(ISD::SREM, MVT::i32, Expand);
716 setOperationAction(ISD::UREM, MVT::i32, Expand);
717 // Register based DivRem for AEABI (RTABI 4.2)
718 if (Subtarget->isTargetAEABI()) {
719 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
720 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
721 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
722 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
723 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
724 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
725 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
726 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
728 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
729 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
730 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
731 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
732 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
733 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
734 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
735 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
737 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
738 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
740 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
741 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
744 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
745 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
746 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
747 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
748 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
750 setOperationAction(ISD::TRAP, MVT::Other, Legal);
752 // Use the default implementation.
753 setOperationAction(ISD::VASTART, MVT::Other, Custom);
754 setOperationAction(ISD::VAARG, MVT::Other, Expand);
755 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
756 setOperationAction(ISD::VAEND, MVT::Other, Expand);
757 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
758 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
760 if (!Subtarget->isTargetMachO()) {
761 // Non-MachO platforms may return values in these registers via the
762 // personality function.
763 setExceptionPointerRegister(ARM::R0);
764 setExceptionSelectorRegister(ARM::R1);
767 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
768 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
770 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
772 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
773 // the default expansion. If we are targeting a single threaded system,
774 // then set them all for expand so we can lower them later into their
776 if (TM.Options.ThreadModel == ThreadModel::Single)
777 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
778 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
779 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
780 // to ldrex/strex loops already.
781 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
783 // On v8, we have particularly efficient implementations of atomic fences
784 // if they can be combined with nearby atomic loads and stores.
785 if (!Subtarget->hasV8Ops()) {
786 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
787 setInsertFencesForAtomic(true);
790 // If there's anything we can use as a barrier, go through custom lowering
792 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
793 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
795 // Set them all for expansion, which will force libcalls.
796 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
797 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
798 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
799 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
800 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
801 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
802 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
803 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
804 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
805 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
806 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
807 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
808 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
809 // Unordered/Monotonic case.
810 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
811 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
814 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
816 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
817 if (!Subtarget->hasV6Ops()) {
818 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
819 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
821 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
823 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
824 !Subtarget->isThumb1Only()) {
825 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
826 // iff target supports vfp2.
827 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
828 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
831 // We want to custom lower some of our intrinsics.
832 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
833 if (Subtarget->isTargetDarwin()) {
834 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
835 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
836 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
839 setOperationAction(ISD::SETCC, MVT::i32, Expand);
840 setOperationAction(ISD::SETCC, MVT::f32, Expand);
841 setOperationAction(ISD::SETCC, MVT::f64, Expand);
842 setOperationAction(ISD::SELECT, MVT::i32, Custom);
843 setOperationAction(ISD::SELECT, MVT::f32, Custom);
844 setOperationAction(ISD::SELECT, MVT::f64, Custom);
845 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
846 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
847 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
849 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
850 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
851 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
852 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
853 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
855 // We don't support sin/cos/fmod/copysign/pow
856 setOperationAction(ISD::FSIN, MVT::f64, Expand);
857 setOperationAction(ISD::FSIN, MVT::f32, Expand);
858 setOperationAction(ISD::FCOS, MVT::f32, Expand);
859 setOperationAction(ISD::FCOS, MVT::f64, Expand);
860 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
861 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
862 setOperationAction(ISD::FREM, MVT::f64, Expand);
863 setOperationAction(ISD::FREM, MVT::f32, Expand);
864 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
865 !Subtarget->isThumb1Only()) {
866 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
867 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
869 setOperationAction(ISD::FPOW, MVT::f64, Expand);
870 setOperationAction(ISD::FPOW, MVT::f32, Expand);
872 if (!Subtarget->hasVFP4()) {
873 setOperationAction(ISD::FMA, MVT::f64, Expand);
874 setOperationAction(ISD::FMA, MVT::f32, Expand);
877 // Various VFP goodness
878 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
879 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
880 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
881 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
882 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
885 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
886 if (!Subtarget->hasFP16()) {
887 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
888 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
892 // Combine sin / cos into one node or libcall if possible.
893 if (Subtarget->hasSinCos()) {
894 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
895 setLibcallName(RTLIB::SINCOS_F64, "sincos");
896 if (Subtarget->getTargetTriple().isiOS()) {
897 // For iOS, we don't want to the normal expansion of a libcall to
898 // sincos. We want to issue a libcall to __sincos_stret.
899 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
900 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
904 // FP-ARMv8 implements a lot of rounding-like FP operations.
905 if (Subtarget->hasFPARMv8()) {
906 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
907 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
908 setOperationAction(ISD::FROUND, MVT::f32, Legal);
909 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
910 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
911 setOperationAction(ISD::FRINT, MVT::f32, Legal);
912 if (!Subtarget->isFPOnlySP()) {
913 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
914 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
915 setOperationAction(ISD::FROUND, MVT::f64, Legal);
916 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
917 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
918 setOperationAction(ISD::FRINT, MVT::f64, Legal);
921 // We have target-specific dag combine patterns for the following nodes:
922 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
923 setTargetDAGCombine(ISD::ADD);
924 setTargetDAGCombine(ISD::SUB);
925 setTargetDAGCombine(ISD::MUL);
926 setTargetDAGCombine(ISD::AND);
927 setTargetDAGCombine(ISD::OR);
928 setTargetDAGCombine(ISD::XOR);
930 if (Subtarget->hasV6Ops())
931 setTargetDAGCombine(ISD::SRL);
933 setStackPointerRegisterToSaveRestore(ARM::SP);
935 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
936 !Subtarget->hasVFP2())
937 setSchedulingPreference(Sched::RegPressure);
939 setSchedulingPreference(Sched::Hybrid);
941 //// temporary - rewrite interface to use type
942 MaxStoresPerMemset = 8;
943 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
944 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
945 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
946 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
947 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
949 // On ARM arguments smaller than 4 bytes are extended, so all arguments
950 // are at least 4 bytes aligned.
951 setMinStackArgumentAlignment(4);
953 // Prefer likely predicted branches to selects on out-of-order cores.
954 PredictableSelectIsExpensive = Subtarget->isLikeA9();
956 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
959 bool ARMTargetLowering::useSoftFloat() const {
960 return Subtarget->useSoftFloat();
963 // FIXME: It might make sense to define the representative register class as the
964 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
965 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
966 // SPR's representative would be DPR_VFP2. This should work well if register
967 // pressure tracking were modified such that a register use would increment the
968 // pressure of the register class's representative and all of it's super
969 // classes' representatives transitively. We have not implemented this because
970 // of the difficulty prior to coalescing of modeling operand register classes
971 // due to the common occurrence of cross class copies and subregister insertions
973 std::pair<const TargetRegisterClass *, uint8_t>
974 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
976 const TargetRegisterClass *RRC = nullptr;
978 switch (VT.SimpleTy) {
980 return TargetLowering::findRepresentativeClass(TRI, VT);
981 // Use DPR as representative register class for all floating point
982 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
983 // the cost is 1 for both f32 and f64.
984 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
985 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
986 RRC = &ARM::DPRRegClass;
987 // When NEON is used for SP, only half of the register file is available
988 // because operations that define both SP and DP results will be constrained
989 // to the VFP2 class (D0-D15). We currently model this constraint prior to
990 // coalescing by double-counting the SP regs. See the FIXME above.
991 if (Subtarget->useNEONForSinglePrecisionFP())
994 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
995 case MVT::v4f32: case MVT::v2f64:
996 RRC = &ARM::DPRRegClass;
1000 RRC = &ARM::DPRRegClass;
1004 RRC = &ARM::DPRRegClass;
1008 return std::make_pair(RRC, Cost);
1011 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1012 switch ((ARMISD::NodeType)Opcode) {
1013 case ARMISD::FIRST_NUMBER: break;
1014 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1015 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1016 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1017 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1018 case ARMISD::CALL: return "ARMISD::CALL";
1019 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1020 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1021 case ARMISD::tCALL: return "ARMISD::tCALL";
1022 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1023 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1024 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1025 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1026 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1027 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1028 case ARMISD::CMP: return "ARMISD::CMP";
1029 case ARMISD::CMN: return "ARMISD::CMN";
1030 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1031 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1032 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1033 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1034 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1036 case ARMISD::CMOV: return "ARMISD::CMOV";
1038 case ARMISD::RBIT: return "ARMISD::RBIT";
1040 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1041 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1042 case ARMISD::RRX: return "ARMISD::RRX";
1044 case ARMISD::ADDC: return "ARMISD::ADDC";
1045 case ARMISD::ADDE: return "ARMISD::ADDE";
1046 case ARMISD::SUBC: return "ARMISD::SUBC";
1047 case ARMISD::SUBE: return "ARMISD::SUBE";
1049 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1050 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1052 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1053 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1055 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1057 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1059 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1061 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1063 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1065 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1067 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1068 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1069 case ARMISD::VCGE: return "ARMISD::VCGE";
1070 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1071 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1072 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1073 case ARMISD::VCGT: return "ARMISD::VCGT";
1074 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1075 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1076 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1077 case ARMISD::VTST: return "ARMISD::VTST";
1079 case ARMISD::VSHL: return "ARMISD::VSHL";
1080 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1081 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1082 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1083 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1084 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1085 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1086 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1087 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1088 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1089 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1090 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1091 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1092 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1093 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1094 case ARMISD::VSLI: return "ARMISD::VSLI";
1095 case ARMISD::VSRI: return "ARMISD::VSRI";
1096 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1097 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1098 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1099 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1100 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1101 case ARMISD::VDUP: return "ARMISD::VDUP";
1102 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1103 case ARMISD::VEXT: return "ARMISD::VEXT";
1104 case ARMISD::VREV64: return "ARMISD::VREV64";
1105 case ARMISD::VREV32: return "ARMISD::VREV32";
1106 case ARMISD::VREV16: return "ARMISD::VREV16";
1107 case ARMISD::VZIP: return "ARMISD::VZIP";
1108 case ARMISD::VUZP: return "ARMISD::VUZP";
1109 case ARMISD::VTRN: return "ARMISD::VTRN";
1110 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1111 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1112 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1113 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1114 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1115 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1116 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1117 case ARMISD::FMAX: return "ARMISD::FMAX";
1118 case ARMISD::FMIN: return "ARMISD::FMIN";
1119 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1120 case ARMISD::VMINNM: return "ARMISD::VMIN";
1121 case ARMISD::BFI: return "ARMISD::BFI";
1122 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1123 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1124 case ARMISD::VBSL: return "ARMISD::VBSL";
1125 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1126 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1127 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1128 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1129 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1130 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1131 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1132 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1133 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1134 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1135 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1136 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1137 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1138 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1139 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1140 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1141 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1142 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1143 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1144 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1149 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1150 if (!VT.isVector()) return getPointerTy();
1151 return VT.changeVectorElementTypeToInteger();
1154 /// getRegClassFor - Return the register class that should be used for the
1155 /// specified value type.
1156 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1157 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1158 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1159 // load / store 4 to 8 consecutive D registers.
1160 if (Subtarget->hasNEON()) {
1161 if (VT == MVT::v4i64)
1162 return &ARM::QQPRRegClass;
1163 if (VT == MVT::v8i64)
1164 return &ARM::QQQQPRRegClass;
1166 return TargetLowering::getRegClassFor(VT);
1169 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1170 // source/dest is aligned and the copy size is large enough. We therefore want
1171 // to align such objects passed to memory intrinsics.
1172 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1173 unsigned &PrefAlign) const {
1174 if (!isa<MemIntrinsic>(CI))
1177 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1178 // cycle faster than 4-byte aligned LDM.
1179 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1183 // Create a fast isel object.
1185 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1186 const TargetLibraryInfo *libInfo) const {
1187 return ARM::createFastISel(funcInfo, libInfo);
1190 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1191 unsigned NumVals = N->getNumValues();
1193 return Sched::RegPressure;
1195 for (unsigned i = 0; i != NumVals; ++i) {
1196 EVT VT = N->getValueType(i);
1197 if (VT == MVT::Glue || VT == MVT::Other)
1199 if (VT.isFloatingPoint() || VT.isVector())
1203 if (!N->isMachineOpcode())
1204 return Sched::RegPressure;
1206 // Load are scheduled for latency even if there instruction itinerary
1207 // is not available.
1208 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1209 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1211 if (MCID.getNumDefs() == 0)
1212 return Sched::RegPressure;
1213 if (!Itins->isEmpty() &&
1214 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1217 return Sched::RegPressure;
1220 //===----------------------------------------------------------------------===//
1222 //===----------------------------------------------------------------------===//
1224 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1225 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1227 default: llvm_unreachable("Unknown condition code!");
1228 case ISD::SETNE: return ARMCC::NE;
1229 case ISD::SETEQ: return ARMCC::EQ;
1230 case ISD::SETGT: return ARMCC::GT;
1231 case ISD::SETGE: return ARMCC::GE;
1232 case ISD::SETLT: return ARMCC::LT;
1233 case ISD::SETLE: return ARMCC::LE;
1234 case ISD::SETUGT: return ARMCC::HI;
1235 case ISD::SETUGE: return ARMCC::HS;
1236 case ISD::SETULT: return ARMCC::LO;
1237 case ISD::SETULE: return ARMCC::LS;
1241 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1242 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1243 ARMCC::CondCodes &CondCode2) {
1244 CondCode2 = ARMCC::AL;
1246 default: llvm_unreachable("Unknown FP condition!");
1248 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1250 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1252 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1253 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1254 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1255 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1256 case ISD::SETO: CondCode = ARMCC::VC; break;
1257 case ISD::SETUO: CondCode = ARMCC::VS; break;
1258 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1259 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1260 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1262 case ISD::SETULT: CondCode = ARMCC::LT; break;
1264 case ISD::SETULE: CondCode = ARMCC::LE; break;
1266 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1270 //===----------------------------------------------------------------------===//
1271 // Calling Convention Implementation
1272 //===----------------------------------------------------------------------===//
1274 #include "ARMGenCallingConv.inc"
1276 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1277 /// account presence of floating point hardware and calling convention
1278 /// limitations, such as support for variadic functions.
1280 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1281 bool isVarArg) const {
1284 llvm_unreachable("Unsupported calling convention");
1285 case CallingConv::ARM_AAPCS:
1286 case CallingConv::ARM_APCS:
1287 case CallingConv::GHC:
1289 case CallingConv::ARM_AAPCS_VFP:
1290 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1291 case CallingConv::C:
1292 if (!Subtarget->isAAPCS_ABI())
1293 return CallingConv::ARM_APCS;
1294 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1295 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1297 return CallingConv::ARM_AAPCS_VFP;
1299 return CallingConv::ARM_AAPCS;
1300 case CallingConv::Fast:
1301 if (!Subtarget->isAAPCS_ABI()) {
1302 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1303 return CallingConv::Fast;
1304 return CallingConv::ARM_APCS;
1305 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1306 return CallingConv::ARM_AAPCS_VFP;
1308 return CallingConv::ARM_AAPCS;
1312 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1313 /// CallingConvention.
1314 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1316 bool isVarArg) const {
1317 switch (getEffectiveCallingConv(CC, isVarArg)) {
1319 llvm_unreachable("Unsupported calling convention");
1320 case CallingConv::ARM_APCS:
1321 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1322 case CallingConv::ARM_AAPCS:
1323 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1324 case CallingConv::ARM_AAPCS_VFP:
1325 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1326 case CallingConv::Fast:
1327 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1328 case CallingConv::GHC:
1329 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1333 /// LowerCallResult - Lower the result values of a call into the
1334 /// appropriate copies out of appropriate physical registers.
1336 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1337 CallingConv::ID CallConv, bool isVarArg,
1338 const SmallVectorImpl<ISD::InputArg> &Ins,
1339 SDLoc dl, SelectionDAG &DAG,
1340 SmallVectorImpl<SDValue> &InVals,
1341 bool isThisReturn, SDValue ThisVal) const {
1343 // Assign locations to each value returned by this call.
1344 SmallVector<CCValAssign, 16> RVLocs;
1345 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1346 *DAG.getContext(), Call);
1347 CCInfo.AnalyzeCallResult(Ins,
1348 CCAssignFnForNode(CallConv, /* Return*/ true,
1351 // Copy all of the result registers out of their specified physreg.
1352 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1353 CCValAssign VA = RVLocs[i];
1355 // Pass 'this' value directly from the argument to return value, to avoid
1356 // reg unit interference
1357 if (i == 0 && isThisReturn) {
1358 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1359 "unexpected return calling convention register assignment");
1360 InVals.push_back(ThisVal);
1365 if (VA.needsCustom()) {
1366 // Handle f64 or half of a v2f64.
1367 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1369 Chain = Lo.getValue(1);
1370 InFlag = Lo.getValue(2);
1371 VA = RVLocs[++i]; // skip ahead to next loc
1372 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1374 Chain = Hi.getValue(1);
1375 InFlag = Hi.getValue(2);
1376 if (!Subtarget->isLittle())
1378 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1380 if (VA.getLocVT() == MVT::v2f64) {
1381 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1382 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1383 DAG.getConstant(0, dl, MVT::i32));
1385 VA = RVLocs[++i]; // skip ahead to next loc
1386 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1387 Chain = Lo.getValue(1);
1388 InFlag = Lo.getValue(2);
1389 VA = RVLocs[++i]; // skip ahead to next loc
1390 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1391 Chain = Hi.getValue(1);
1392 InFlag = Hi.getValue(2);
1393 if (!Subtarget->isLittle())
1395 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1396 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1397 DAG.getConstant(1, dl, MVT::i32));
1400 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1402 Chain = Val.getValue(1);
1403 InFlag = Val.getValue(2);
1406 switch (VA.getLocInfo()) {
1407 default: llvm_unreachable("Unknown loc info!");
1408 case CCValAssign::Full: break;
1409 case CCValAssign::BCvt:
1410 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1414 InVals.push_back(Val);
1420 /// LowerMemOpCallTo - Store the argument to the stack.
1422 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1423 SDValue StackPtr, SDValue Arg,
1424 SDLoc dl, SelectionDAG &DAG,
1425 const CCValAssign &VA,
1426 ISD::ArgFlagsTy Flags) const {
1427 unsigned LocMemOffset = VA.getLocMemOffset();
1428 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1429 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1430 return DAG.getStore(Chain, dl, Arg, PtrOff,
1431 MachinePointerInfo::getStack(LocMemOffset),
1435 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1436 SDValue Chain, SDValue &Arg,
1437 RegsToPassVector &RegsToPass,
1438 CCValAssign &VA, CCValAssign &NextVA,
1440 SmallVectorImpl<SDValue> &MemOpChains,
1441 ISD::ArgFlagsTy Flags) const {
1443 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1444 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1445 unsigned id = Subtarget->isLittle() ? 0 : 1;
1446 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1448 if (NextVA.isRegLoc())
1449 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1451 assert(NextVA.isMemLoc());
1452 if (!StackPtr.getNode())
1453 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1455 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1461 /// LowerCall - Lowering a call into a callseq_start <-
1462 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1465 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1466 SmallVectorImpl<SDValue> &InVals) const {
1467 SelectionDAG &DAG = CLI.DAG;
1469 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1470 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1471 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1472 SDValue Chain = CLI.Chain;
1473 SDValue Callee = CLI.Callee;
1474 bool &isTailCall = CLI.IsTailCall;
1475 CallingConv::ID CallConv = CLI.CallConv;
1476 bool doesNotRet = CLI.DoesNotReturn;
1477 bool isVarArg = CLI.IsVarArg;
1479 MachineFunction &MF = DAG.getMachineFunction();
1480 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1481 bool isThisReturn = false;
1482 bool isSibCall = false;
1484 // Disable tail calls if they're not supported.
1485 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1489 // Check if it's really possible to do a tail call.
1490 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1491 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1492 Outs, OutVals, Ins, DAG);
1493 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1494 report_fatal_error("failed to perform tail call elimination on a call "
1495 "site marked musttail");
1496 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1497 // detected sibcalls.
1504 // Analyze operands of the call, assigning locations to each operand.
1505 SmallVector<CCValAssign, 16> ArgLocs;
1506 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1507 *DAG.getContext(), Call);
1508 CCInfo.AnalyzeCallOperands(Outs,
1509 CCAssignFnForNode(CallConv, /* Return*/ false,
1512 // Get a count of how many bytes are to be pushed on the stack.
1513 unsigned NumBytes = CCInfo.getNextStackOffset();
1515 // For tail calls, memory operands are available in our caller's stack.
1519 // Adjust the stack pointer for the new arguments...
1520 // These operations are automatically eliminated by the prolog/epilog pass
1522 Chain = DAG.getCALLSEQ_START(Chain,
1523 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1525 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1527 RegsToPassVector RegsToPass;
1528 SmallVector<SDValue, 8> MemOpChains;
1530 // Walk the register/memloc assignments, inserting copies/loads. In the case
1531 // of tail call optimization, arguments are handled later.
1532 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1534 ++i, ++realArgIdx) {
1535 CCValAssign &VA = ArgLocs[i];
1536 SDValue Arg = OutVals[realArgIdx];
1537 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1538 bool isByVal = Flags.isByVal();
1540 // Promote the value if needed.
1541 switch (VA.getLocInfo()) {
1542 default: llvm_unreachable("Unknown loc info!");
1543 case CCValAssign::Full: break;
1544 case CCValAssign::SExt:
1545 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1547 case CCValAssign::ZExt:
1548 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1550 case CCValAssign::AExt:
1551 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1553 case CCValAssign::BCvt:
1554 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1558 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1559 if (VA.needsCustom()) {
1560 if (VA.getLocVT() == MVT::v2f64) {
1561 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1562 DAG.getConstant(0, dl, MVT::i32));
1563 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1564 DAG.getConstant(1, dl, MVT::i32));
1566 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1567 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1569 VA = ArgLocs[++i]; // skip ahead to next loc
1570 if (VA.isRegLoc()) {
1571 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1572 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1574 assert(VA.isMemLoc());
1576 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1577 dl, DAG, VA, Flags));
1580 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1581 StackPtr, MemOpChains, Flags);
1583 } else if (VA.isRegLoc()) {
1584 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1585 assert(VA.getLocVT() == MVT::i32 &&
1586 "unexpected calling convention register assignment");
1587 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1588 "unexpected use of 'returned'");
1589 isThisReturn = true;
1591 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1592 } else if (isByVal) {
1593 assert(VA.isMemLoc());
1594 unsigned offset = 0;
1596 // True if this byval aggregate will be split between registers
1598 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1599 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1601 if (CurByValIdx < ByValArgsCount) {
1603 unsigned RegBegin, RegEnd;
1604 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1606 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1608 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1609 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1610 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1611 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1612 MachinePointerInfo(),
1613 false, false, false,
1614 DAG.InferPtrAlignment(AddArg));
1615 MemOpChains.push_back(Load.getValue(1));
1616 RegsToPass.push_back(std::make_pair(j, Load));
1619 // If parameter size outsides register area, "offset" value
1620 // helps us to calculate stack slot for remained part properly.
1621 offset = RegEnd - RegBegin;
1623 CCInfo.nextInRegsParam();
1626 if (Flags.getByValSize() > 4*offset) {
1627 unsigned LocMemOffset = VA.getLocMemOffset();
1628 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1629 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1631 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1632 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1633 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1635 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1638 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1639 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1640 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1643 } else if (!isSibCall) {
1644 assert(VA.isMemLoc());
1646 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1647 dl, DAG, VA, Flags));
1651 if (!MemOpChains.empty())
1652 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1654 // Build a sequence of copy-to-reg nodes chained together with token chain
1655 // and flag operands which copy the outgoing args into the appropriate regs.
1657 // Tail call byval lowering might overwrite argument registers so in case of
1658 // tail call optimization the copies to registers are lowered later.
1660 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1661 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1662 RegsToPass[i].second, InFlag);
1663 InFlag = Chain.getValue(1);
1666 // For tail calls lower the arguments to the 'real' stack slot.
1668 // Force all the incoming stack arguments to be loaded from the stack
1669 // before any new outgoing arguments are stored to the stack, because the
1670 // outgoing stack slots may alias the incoming argument stack slots, and
1671 // the alias isn't otherwise explicit. This is slightly more conservative
1672 // than necessary, because it means that each store effectively depends
1673 // on every argument instead of just those arguments it would clobber.
1675 // Do not flag preceding copytoreg stuff together with the following stuff.
1677 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1678 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1679 RegsToPass[i].second, InFlag);
1680 InFlag = Chain.getValue(1);
1685 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1686 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1687 // node so that legalize doesn't hack it.
1688 bool isDirect = false;
1689 bool isARMFunc = false;
1690 bool isLocalARMFunc = false;
1691 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1693 if (EnableARMLongCalls) {
1694 assert((Subtarget->isTargetWindows() ||
1695 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1696 "long-calls with non-static relocation model!");
1697 // Handle a global address or an external symbol. If it's not one of
1698 // those, the target's already in a register, so we don't need to do
1700 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1701 const GlobalValue *GV = G->getGlobal();
1702 // Create a constant pool entry for the callee address
1703 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1704 ARMConstantPoolValue *CPV =
1705 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1707 // Get the address of the callee into a register
1708 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1709 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1710 Callee = DAG.getLoad(getPointerTy(), dl,
1711 DAG.getEntryNode(), CPAddr,
1712 MachinePointerInfo::getConstantPool(),
1713 false, false, false, 0);
1714 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1715 const char *Sym = S->getSymbol();
1717 // Create a constant pool entry for the callee address
1718 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1719 ARMConstantPoolValue *CPV =
1720 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1721 ARMPCLabelIndex, 0);
1722 // Get the address of the callee into a register
1723 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1724 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1725 Callee = DAG.getLoad(getPointerTy(), dl,
1726 DAG.getEntryNode(), CPAddr,
1727 MachinePointerInfo::getConstantPool(),
1728 false, false, false, 0);
1730 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1731 const GlobalValue *GV = G->getGlobal();
1733 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1734 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1735 getTargetMachine().getRelocationModel() != Reloc::Static;
1736 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1737 // ARM call to a local ARM function is predicable.
1738 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1739 // tBX takes a register source operand.
1740 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1741 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1742 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1743 DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1744 0, ARMII::MO_NONLAZY));
1745 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1746 MachinePointerInfo::getGOT(), false, false, true, 0);
1747 } else if (Subtarget->isTargetCOFF()) {
1748 assert(Subtarget->isTargetWindows() &&
1749 "Windows is the only supported COFF target");
1750 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1751 ? ARMII::MO_DLLIMPORT
1752 : ARMII::MO_NO_FLAG;
1753 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1755 if (GV->hasDLLImportStorageClass())
1756 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1757 DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1758 Callee), MachinePointerInfo::getGOT(),
1759 false, false, false, 0);
1761 // On ELF targets for PIC code, direct calls should go through the PLT
1762 unsigned OpFlags = 0;
1763 if (Subtarget->isTargetELF() &&
1764 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1765 OpFlags = ARMII::MO_PLT;
1766 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1768 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1770 bool isStub = Subtarget->isTargetMachO() &&
1771 getTargetMachine().getRelocationModel() != Reloc::Static;
1772 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1773 // tBX takes a register source operand.
1774 const char *Sym = S->getSymbol();
1775 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1776 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1777 ARMConstantPoolValue *CPV =
1778 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1779 ARMPCLabelIndex, 4);
1780 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1781 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1782 Callee = DAG.getLoad(getPointerTy(), dl,
1783 DAG.getEntryNode(), CPAddr,
1784 MachinePointerInfo::getConstantPool(),
1785 false, false, false, 0);
1786 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1787 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1788 getPointerTy(), Callee, PICLabel);
1790 unsigned OpFlags = 0;
1791 // On ELF targets for PIC code, direct calls should go through the PLT
1792 if (Subtarget->isTargetELF() &&
1793 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1794 OpFlags = ARMII::MO_PLT;
1795 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1799 // FIXME: handle tail calls differently.
1801 bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1802 if (Subtarget->isThumb()) {
1803 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1804 CallOpc = ARMISD::CALL_NOLINK;
1806 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1808 if (!isDirect && !Subtarget->hasV5TOps())
1809 CallOpc = ARMISD::CALL_NOLINK;
1810 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1811 // Emit regular call when code size is the priority
1813 // "mov lr, pc; b _foo" to avoid confusing the RSP
1814 CallOpc = ARMISD::CALL_NOLINK;
1816 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1819 std::vector<SDValue> Ops;
1820 Ops.push_back(Chain);
1821 Ops.push_back(Callee);
1823 // Add argument registers to the end of the list so that they are known live
1825 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1826 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1827 RegsToPass[i].second.getValueType()));
1829 // Add a register mask operand representing the call-preserved registers.
1831 const uint32_t *Mask;
1832 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1834 // For 'this' returns, use the R0-preserving mask if applicable
1835 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1837 // Set isThisReturn to false if the calling convention is not one that
1838 // allows 'returned' to be modeled in this way, so LowerCallResult does
1839 // not try to pass 'this' straight through
1840 isThisReturn = false;
1841 Mask = ARI->getCallPreservedMask(MF, CallConv);
1844 Mask = ARI->getCallPreservedMask(MF, CallConv);
1846 assert(Mask && "Missing call preserved mask for calling convention");
1847 Ops.push_back(DAG.getRegisterMask(Mask));
1850 if (InFlag.getNode())
1851 Ops.push_back(InFlag);
1853 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1855 MF.getFrameInfo()->setHasTailCall();
1856 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1859 // Returns a chain and a flag for retval copy to use.
1860 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1861 InFlag = Chain.getValue(1);
1863 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1864 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1866 InFlag = Chain.getValue(1);
1868 // Handle result values, copying them out of physregs into vregs that we
1870 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1871 InVals, isThisReturn,
1872 isThisReturn ? OutVals[0] : SDValue());
1875 /// HandleByVal - Every parameter *after* a byval parameter is passed
1876 /// on the stack. Remember the next parameter register to allocate,
1877 /// and then confiscate the rest of the parameter registers to insure
1879 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1880 unsigned Align) const {
1881 assert((State->getCallOrPrologue() == Prologue ||
1882 State->getCallOrPrologue() == Call) &&
1883 "unhandled ParmContext");
1885 // Byval (as with any stack) slots are always at least 4 byte aligned.
1886 Align = std::max(Align, 4U);
1888 unsigned Reg = State->AllocateReg(GPRArgRegs);
1892 unsigned AlignInRegs = Align / 4;
1893 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1894 for (unsigned i = 0; i < Waste; ++i)
1895 Reg = State->AllocateReg(GPRArgRegs);
1900 unsigned Excess = 4 * (ARM::R4 - Reg);
1902 // Special case when NSAA != SP and parameter size greater than size of
1903 // all remained GPR regs. In that case we can't split parameter, we must
1904 // send it to stack. We also must set NCRN to R4, so waste all
1905 // remained registers.
1906 const unsigned NSAAOffset = State->getNextStackOffset();
1907 if (NSAAOffset != 0 && Size > Excess) {
1908 while (State->AllocateReg(GPRArgRegs))
1913 // First register for byval parameter is the first register that wasn't
1914 // allocated before this method call, so it would be "reg".
1915 // If parameter is small enough to be saved in range [reg, r4), then
1916 // the end (first after last) register would be reg + param-size-in-regs,
1917 // else parameter would be splitted between registers and stack,
1918 // end register would be r4 in this case.
1919 unsigned ByValRegBegin = Reg;
1920 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1921 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1922 // Note, first register is allocated in the beginning of function already,
1923 // allocate remained amount of registers we need.
1924 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1925 State->AllocateReg(GPRArgRegs);
1926 // A byval parameter that is split between registers and memory needs its
1927 // size truncated here.
1928 // In the case where the entire structure fits in registers, we set the
1929 // size in memory to zero.
1930 Size = std::max<int>(Size - Excess, 0);
1934 /// MatchingStackOffset - Return true if the given stack call argument is
1935 /// already available in the same position (relatively) of the caller's
1936 /// incoming argument stack.
1938 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1939 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1940 const TargetInstrInfo *TII) {
1941 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1943 if (Arg.getOpcode() == ISD::CopyFromReg) {
1944 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1945 if (!TargetRegisterInfo::isVirtualRegister(VR))
1947 MachineInstr *Def = MRI->getVRegDef(VR);
1950 if (!Flags.isByVal()) {
1951 if (!TII->isLoadFromStackSlot(Def, FI))
1956 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1957 if (Flags.isByVal())
1958 // ByVal argument is passed in as a pointer but it's now being
1959 // dereferenced. e.g.
1960 // define @foo(%struct.X* %A) {
1961 // tail call @bar(%struct.X* byval %A)
1964 SDValue Ptr = Ld->getBasePtr();
1965 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1968 FI = FINode->getIndex();
1972 assert(FI != INT_MAX);
1973 if (!MFI->isFixedObjectIndex(FI))
1975 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1978 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1979 /// for tail call optimization. Targets which want to do tail call
1980 /// optimization should implement this function.
1982 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1983 CallingConv::ID CalleeCC,
1985 bool isCalleeStructRet,
1986 bool isCallerStructRet,
1987 const SmallVectorImpl<ISD::OutputArg> &Outs,
1988 const SmallVectorImpl<SDValue> &OutVals,
1989 const SmallVectorImpl<ISD::InputArg> &Ins,
1990 SelectionDAG& DAG) const {
1991 const Function *CallerF = DAG.getMachineFunction().getFunction();
1992 CallingConv::ID CallerCC = CallerF->getCallingConv();
1993 bool CCMatch = CallerCC == CalleeCC;
1995 // Look for obvious safe cases to perform tail call optimization that do not
1996 // require ABI changes. This is what gcc calls sibcall.
1998 // Do not sibcall optimize vararg calls unless the call site is not passing
2000 if (isVarArg && !Outs.empty())
2003 // Exception-handling functions need a special set of instructions to indicate
2004 // a return to the hardware. Tail-calling another function would probably
2006 if (CallerF->hasFnAttribute("interrupt"))
2009 // Also avoid sibcall optimization if either caller or callee uses struct
2010 // return semantics.
2011 if (isCalleeStructRet || isCallerStructRet)
2014 // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2015 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2016 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2017 // support in the assembler and linker to be used. This would need to be
2018 // fixed to fully support tail calls in Thumb1.
2020 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2021 // LR. This means if we need to reload LR, it takes an extra instructions,
2022 // which outweighs the value of the tail call; but here we don't know yet
2023 // whether LR is going to be used. Probably the right approach is to
2024 // generate the tail call here and turn it back into CALL/RET in
2025 // emitEpilogue if LR is used.
2027 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2028 // but we need to make sure there are enough registers; the only valid
2029 // registers are the 4 used for parameters. We don't currently do this
2031 if (Subtarget->isThumb1Only())
2034 // Externally-defined functions with weak linkage should not be
2035 // tail-called on ARM when the OS does not support dynamic
2036 // pre-emption of symbols, as the AAELF spec requires normal calls
2037 // to undefined weak functions to be replaced with a NOP or jump to the
2038 // next instruction. The behaviour of branch instructions in this
2039 // situation (as used for tail calls) is implementation-defined, so we
2040 // cannot rely on the linker replacing the tail call with a return.
2041 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2042 const GlobalValue *GV = G->getGlobal();
2043 const Triple TT(getTargetMachine().getTargetTriple());
2044 if (GV->hasExternalWeakLinkage() &&
2045 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2049 // If the calling conventions do not match, then we'd better make sure the
2050 // results are returned in the same way as what the caller expects.
2052 SmallVector<CCValAssign, 16> RVLocs1;
2053 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2054 *DAG.getContext(), Call);
2055 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2057 SmallVector<CCValAssign, 16> RVLocs2;
2058 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2059 *DAG.getContext(), Call);
2060 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2062 if (RVLocs1.size() != RVLocs2.size())
2064 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2065 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2067 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2069 if (RVLocs1[i].isRegLoc()) {
2070 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2073 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2079 // If Caller's vararg or byval argument has been split between registers and
2080 // stack, do not perform tail call, since part of the argument is in caller's
2082 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2083 getInfo<ARMFunctionInfo>();
2084 if (AFI_Caller->getArgRegsSaveSize())
2087 // If the callee takes no arguments then go on to check the results of the
2089 if (!Outs.empty()) {
2090 // Check if stack adjustment is needed. For now, do not do this if any
2091 // argument is passed on the stack.
2092 SmallVector<CCValAssign, 16> ArgLocs;
2093 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2094 *DAG.getContext(), Call);
2095 CCInfo.AnalyzeCallOperands(Outs,
2096 CCAssignFnForNode(CalleeCC, false, isVarArg));
2097 if (CCInfo.getNextStackOffset()) {
2098 MachineFunction &MF = DAG.getMachineFunction();
2100 // Check if the arguments are already laid out in the right way as
2101 // the caller's fixed stack objects.
2102 MachineFrameInfo *MFI = MF.getFrameInfo();
2103 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2104 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2105 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2107 ++i, ++realArgIdx) {
2108 CCValAssign &VA = ArgLocs[i];
2109 EVT RegVT = VA.getLocVT();
2110 SDValue Arg = OutVals[realArgIdx];
2111 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2112 if (VA.getLocInfo() == CCValAssign::Indirect)
2114 if (VA.needsCustom()) {
2115 // f64 and vector types are split into multiple registers or
2116 // register/stack-slot combinations. The types will not match
2117 // the registers; give up on memory f64 refs until we figure
2118 // out what to do about this.
2121 if (!ArgLocs[++i].isRegLoc())
2123 if (RegVT == MVT::v2f64) {
2124 if (!ArgLocs[++i].isRegLoc())
2126 if (!ArgLocs[++i].isRegLoc())
2129 } else if (!VA.isRegLoc()) {
2130 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2142 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2143 MachineFunction &MF, bool isVarArg,
2144 const SmallVectorImpl<ISD::OutputArg> &Outs,
2145 LLVMContext &Context) const {
2146 SmallVector<CCValAssign, 16> RVLocs;
2147 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2148 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2152 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2153 SDLoc DL, SelectionDAG &DAG) {
2154 const MachineFunction &MF = DAG.getMachineFunction();
2155 const Function *F = MF.getFunction();
2157 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2159 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2160 // version of the "preferred return address". These offsets affect the return
2161 // instruction if this is a return from PL1 without hypervisor extensions.
2162 // IRQ/FIQ: +4 "subs pc, lr, #4"
2163 // SWI: 0 "subs pc, lr, #0"
2164 // ABORT: +4 "subs pc, lr, #4"
2165 // UNDEF: +4/+2 "subs pc, lr, #0"
2166 // UNDEF varies depending on where the exception came from ARM or Thumb
2167 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2170 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2173 else if (IntKind == "SWI" || IntKind == "UNDEF")
2176 report_fatal_error("Unsupported interrupt attribute. If present, value "
2177 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2179 RetOps.insert(RetOps.begin() + 1,
2180 DAG.getConstant(LROffset, DL, MVT::i32, false));
2182 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2186 ARMTargetLowering::LowerReturn(SDValue Chain,
2187 CallingConv::ID CallConv, bool isVarArg,
2188 const SmallVectorImpl<ISD::OutputArg> &Outs,
2189 const SmallVectorImpl<SDValue> &OutVals,
2190 SDLoc dl, SelectionDAG &DAG) const {
2192 // CCValAssign - represent the assignment of the return value to a location.
2193 SmallVector<CCValAssign, 16> RVLocs;
2195 // CCState - Info about the registers and stack slots.
2196 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2197 *DAG.getContext(), Call);
2199 // Analyze outgoing return values.
2200 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2204 SmallVector<SDValue, 4> RetOps;
2205 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2206 bool isLittleEndian = Subtarget->isLittle();
2208 MachineFunction &MF = DAG.getMachineFunction();
2209 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2210 AFI->setReturnRegsCount(RVLocs.size());
2212 // Copy the result values into the output registers.
2213 for (unsigned i = 0, realRVLocIdx = 0;
2215 ++i, ++realRVLocIdx) {
2216 CCValAssign &VA = RVLocs[i];
2217 assert(VA.isRegLoc() && "Can only return in registers!");
2219 SDValue Arg = OutVals[realRVLocIdx];
2221 switch (VA.getLocInfo()) {
2222 default: llvm_unreachable("Unknown loc info!");
2223 case CCValAssign::Full: break;
2224 case CCValAssign::BCvt:
2225 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2229 if (VA.needsCustom()) {
2230 if (VA.getLocVT() == MVT::v2f64) {
2231 // Extract the first half and return it in two registers.
2232 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2233 DAG.getConstant(0, dl, MVT::i32));
2234 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2235 DAG.getVTList(MVT::i32, MVT::i32), Half);
2237 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2238 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2240 Flag = Chain.getValue(1);
2241 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2242 VA = RVLocs[++i]; // skip ahead to next loc
2243 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2244 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2246 Flag = Chain.getValue(1);
2247 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2248 VA = RVLocs[++i]; // skip ahead to next loc
2250 // Extract the 2nd half and fall through to handle it as an f64 value.
2251 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2252 DAG.getConstant(1, dl, MVT::i32));
2254 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2256 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2257 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2258 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2259 fmrrd.getValue(isLittleEndian ? 0 : 1),
2261 Flag = Chain.getValue(1);
2262 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2263 VA = RVLocs[++i]; // skip ahead to next loc
2264 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2265 fmrrd.getValue(isLittleEndian ? 1 : 0),
2268 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2270 // Guarantee that all emitted copies are
2271 // stuck together, avoiding something bad.
2272 Flag = Chain.getValue(1);
2273 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2276 // Update chain and glue.
2279 RetOps.push_back(Flag);
2281 // CPUs which aren't M-class use a special sequence to return from
2282 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2283 // though we use "subs pc, lr, #N").
2285 // M-class CPUs actually use a normal return sequence with a special
2286 // (hardware-provided) value in LR, so the normal code path works.
2287 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2288 !Subtarget->isMClass()) {
2289 if (Subtarget->isThumb1Only())
2290 report_fatal_error("interrupt attribute is not supported in Thumb1");
2291 return LowerInterruptReturn(RetOps, dl, DAG);
2294 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2297 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2298 if (N->getNumValues() != 1)
2300 if (!N->hasNUsesOfValue(1, 0))
2303 SDValue TCChain = Chain;
2304 SDNode *Copy = *N->use_begin();
2305 if (Copy->getOpcode() == ISD::CopyToReg) {
2306 // If the copy has a glue operand, we conservatively assume it isn't safe to
2307 // perform a tail call.
2308 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2310 TCChain = Copy->getOperand(0);
2311 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2312 SDNode *VMov = Copy;
2313 // f64 returned in a pair of GPRs.
2314 SmallPtrSet<SDNode*, 2> Copies;
2315 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2317 if (UI->getOpcode() != ISD::CopyToReg)
2321 if (Copies.size() > 2)
2324 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2326 SDValue UseChain = UI->getOperand(0);
2327 if (Copies.count(UseChain.getNode()))
2331 // We are at the top of this chain.
2332 // If the copy has a glue operand, we conservatively assume it
2333 // isn't safe to perform a tail call.
2334 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2340 } else if (Copy->getOpcode() == ISD::BITCAST) {
2341 // f32 returned in a single GPR.
2342 if (!Copy->hasOneUse())
2344 Copy = *Copy->use_begin();
2345 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2347 // If the copy has a glue operand, we conservatively assume it isn't safe to
2348 // perform a tail call.
2349 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2351 TCChain = Copy->getOperand(0);
2356 bool HasRet = false;
2357 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2359 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2360 UI->getOpcode() != ARMISD::INTRET_FLAG)
2372 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2373 if (!Subtarget->supportsTailCall())
2376 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2379 return !Subtarget->isThumb1Only();
2382 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2383 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2384 // one of the above mentioned nodes. It has to be wrapped because otherwise
2385 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2386 // be used to form addressing mode. These wrapped nodes will be selected
2388 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2389 EVT PtrVT = Op.getValueType();
2390 // FIXME there is no actual debug info here
2392 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2394 if (CP->isMachineConstantPoolEntry())
2395 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2396 CP->getAlignment());
2398 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2399 CP->getAlignment());
2400 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2403 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2404 return MachineJumpTableInfo::EK_Inline;
2407 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2408 SelectionDAG &DAG) const {
2409 MachineFunction &MF = DAG.getMachineFunction();
2410 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2411 unsigned ARMPCLabelIndex = 0;
2413 EVT PtrVT = getPointerTy();
2414 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2415 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2417 if (RelocM == Reloc::Static) {
2418 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2420 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2421 ARMPCLabelIndex = AFI->createPICLabelUId();
2422 ARMConstantPoolValue *CPV =
2423 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2424 ARMCP::CPBlockAddress, PCAdj);
2425 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2427 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2428 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2429 MachinePointerInfo::getConstantPool(),
2430 false, false, false, 0);
2431 if (RelocM == Reloc::Static)
2433 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2434 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2437 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2439 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2440 SelectionDAG &DAG) const {
2442 EVT PtrVT = getPointerTy();
2443 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2444 MachineFunction &MF = DAG.getMachineFunction();
2445 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2446 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2447 ARMConstantPoolValue *CPV =
2448 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2449 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2450 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2451 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2452 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2453 MachinePointerInfo::getConstantPool(),
2454 false, false, false, 0);
2455 SDValue Chain = Argument.getValue(1);
2457 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2458 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2460 // call __tls_get_addr.
2463 Entry.Node = Argument;
2464 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2465 Args.push_back(Entry);
2467 // FIXME: is there useful debug info available here?
2468 TargetLowering::CallLoweringInfo CLI(DAG);
2469 CLI.setDebugLoc(dl).setChain(Chain)
2470 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2471 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2474 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2475 return CallResult.first;
2478 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2479 // "local exec" model.
2481 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2483 TLSModel::Model model) const {
2484 const GlobalValue *GV = GA->getGlobal();
2487 SDValue Chain = DAG.getEntryNode();
2488 EVT PtrVT = getPointerTy();
2489 // Get the Thread Pointer
2490 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2492 if (model == TLSModel::InitialExec) {
2493 MachineFunction &MF = DAG.getMachineFunction();
2494 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2495 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2496 // Initial exec model.
2497 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2498 ARMConstantPoolValue *CPV =
2499 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2500 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2502 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2503 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2504 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2505 MachinePointerInfo::getConstantPool(),
2506 false, false, false, 0);
2507 Chain = Offset.getValue(1);
2509 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2510 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2512 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2513 MachinePointerInfo::getConstantPool(),
2514 false, false, false, 0);
2517 assert(model == TLSModel::LocalExec);
2518 ARMConstantPoolValue *CPV =
2519 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2520 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2521 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2522 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2523 MachinePointerInfo::getConstantPool(),
2524 false, false, false, 0);
2527 // The address of the thread local variable is the add of the thread
2528 // pointer with the offset of the variable.
2529 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2533 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2534 // TODO: implement the "local dynamic" model
2535 assert(Subtarget->isTargetELF() &&
2536 "TLS not implemented for non-ELF targets");
2537 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2539 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2542 case TLSModel::GeneralDynamic:
2543 case TLSModel::LocalDynamic:
2544 return LowerToTLSGeneralDynamicModel(GA, DAG);
2545 case TLSModel::InitialExec:
2546 case TLSModel::LocalExec:
2547 return LowerToTLSExecModels(GA, DAG, model);
2549 llvm_unreachable("bogus TLS model");
2552 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2553 SelectionDAG &DAG) const {
2554 EVT PtrVT = getPointerTy();
2556 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2557 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2558 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2559 ARMConstantPoolValue *CPV =
2560 ARMConstantPoolConstant::Create(GV,
2561 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2562 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2563 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2564 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2566 MachinePointerInfo::getConstantPool(),
2567 false, false, false, 0);
2568 SDValue Chain = Result.getValue(1);
2569 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2570 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2572 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2573 MachinePointerInfo::getGOT(),
2574 false, false, false, 0);
2578 // If we have T2 ops, we can materialize the address directly via movt/movw
2579 // pair. This is always cheaper.
2580 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2582 // FIXME: Once remat is capable of dealing with instructions with register
2583 // operands, expand this into two nodes.
2584 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2585 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2587 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2588 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2589 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2590 MachinePointerInfo::getConstantPool(),
2591 false, false, false, 0);
2595 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2596 SelectionDAG &DAG) const {
2597 EVT PtrVT = getPointerTy();
2599 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2600 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2602 if (Subtarget->useMovt(DAG.getMachineFunction()))
2605 // FIXME: Once remat is capable of dealing with instructions with register
2606 // operands, expand this into multiple nodes
2608 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2610 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2611 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2613 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2614 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2615 MachinePointerInfo::getGOT(), false, false, false, 0);
2619 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2620 SelectionDAG &DAG) const {
2621 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2622 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2623 "Windows on ARM expects to use movw/movt");
2625 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2626 const ARMII::TOF TargetFlags =
2627 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2628 EVT PtrVT = getPointerTy();
2634 // FIXME: Once remat is capable of dealing with instructions with register
2635 // operands, expand this into two nodes.
2636 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2637 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2639 if (GV->hasDLLImportStorageClass())
2640 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2641 MachinePointerInfo::getGOT(), false, false, false, 0);
2645 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2646 SelectionDAG &DAG) const {
2647 assert(Subtarget->isTargetELF() &&
2648 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2649 MachineFunction &MF = DAG.getMachineFunction();
2650 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2651 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2652 EVT PtrVT = getPointerTy();
2654 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2655 ARMConstantPoolValue *CPV =
2656 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2657 ARMPCLabelIndex, PCAdj);
2658 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2659 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2660 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2661 MachinePointerInfo::getConstantPool(),
2662 false, false, false, 0);
2663 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2664 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2668 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2670 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2671 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2672 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2673 Op.getOperand(1), Val);
2677 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2679 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2680 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2684 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2685 const ARMSubtarget *Subtarget) const {
2686 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2689 default: return SDValue(); // Don't custom lower most intrinsics.
2690 case Intrinsic::arm_rbit: {
2691 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2692 "RBIT intrinsic must have i32 type!");
2693 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2695 case Intrinsic::arm_thread_pointer: {
2696 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2697 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2699 case Intrinsic::eh_sjlj_lsda: {
2700 MachineFunction &MF = DAG.getMachineFunction();
2701 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2702 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2703 EVT PtrVT = getPointerTy();
2704 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2706 unsigned PCAdj = (RelocM != Reloc::PIC_)
2707 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2708 ARMConstantPoolValue *CPV =
2709 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2710 ARMCP::CPLSDA, PCAdj);
2711 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2712 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2714 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2715 MachinePointerInfo::getConstantPool(),
2716 false, false, false, 0);
2718 if (RelocM == Reloc::PIC_) {
2719 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2720 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2724 case Intrinsic::arm_neon_vmulls:
2725 case Intrinsic::arm_neon_vmullu: {
2726 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2727 ? ARMISD::VMULLs : ARMISD::VMULLu;
2728 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2729 Op.getOperand(1), Op.getOperand(2));
2734 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2735 const ARMSubtarget *Subtarget) {
2736 // FIXME: handle "fence singlethread" more efficiently.
2738 if (!Subtarget->hasDataBarrier()) {
2739 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2740 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2742 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2743 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2744 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2745 DAG.getConstant(0, dl, MVT::i32));
2748 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2749 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2750 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2751 if (Subtarget->isMClass()) {
2752 // Only a full system barrier exists in the M-class architectures.
2753 Domain = ARM_MB::SY;
2754 } else if (Subtarget->isSwift() && Ord == Release) {
2755 // Swift happens to implement ISHST barriers in a way that's compatible with
2756 // Release semantics but weaker than ISH so we'd be fools not to use
2757 // it. Beware: other processors probably don't!
2758 Domain = ARM_MB::ISHST;
2761 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2762 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2763 DAG.getConstant(Domain, dl, MVT::i32));
2766 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2767 const ARMSubtarget *Subtarget) {
2768 // ARM pre v5TE and Thumb1 does not have preload instructions.
2769 if (!(Subtarget->isThumb2() ||
2770 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2771 // Just preserve the chain.
2772 return Op.getOperand(0);
2775 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2777 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2778 // ARMv7 with MP extension has PLDW.
2779 return Op.getOperand(0);
2781 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2782 if (Subtarget->isThumb()) {
2784 isRead = ~isRead & 1;
2785 isData = ~isData & 1;
2788 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2789 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2790 DAG.getConstant(isData, dl, MVT::i32));
2793 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2794 MachineFunction &MF = DAG.getMachineFunction();
2795 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2797 // vastart just stores the address of the VarArgsFrameIndex slot into the
2798 // memory location argument.
2800 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2801 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2802 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2803 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2804 MachinePointerInfo(SV), false, false, 0);
2808 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2809 SDValue &Root, SelectionDAG &DAG,
2811 MachineFunction &MF = DAG.getMachineFunction();
2812 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2814 const TargetRegisterClass *RC;
2815 if (AFI->isThumb1OnlyFunction())
2816 RC = &ARM::tGPRRegClass;
2818 RC = &ARM::GPRRegClass;
2820 // Transform the arguments stored in physical registers into virtual ones.
2821 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2822 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2825 if (NextVA.isMemLoc()) {
2826 MachineFrameInfo *MFI = MF.getFrameInfo();
2827 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2829 // Create load node to retrieve arguments from the stack.
2830 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2831 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2832 MachinePointerInfo::getFixedStack(FI),
2833 false, false, false, 0);
2835 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2836 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2838 if (!Subtarget->isLittle())
2839 std::swap (ArgValue, ArgValue2);
2840 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2843 // The remaining GPRs hold either the beginning of variable-argument
2844 // data, or the beginning of an aggregate passed by value (usually
2845 // byval). Either way, we allocate stack slots adjacent to the data
2846 // provided by our caller, and store the unallocated registers there.
2847 // If this is a variadic function, the va_list pointer will begin with
2848 // these values; otherwise, this reassembles a (byval) structure that
2849 // was split between registers and memory.
2850 // Return: The frame index registers were stored into.
2852 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2853 SDLoc dl, SDValue &Chain,
2854 const Value *OrigArg,
2855 unsigned InRegsParamRecordIdx,
2857 unsigned ArgSize) const {
2858 // Currently, two use-cases possible:
2859 // Case #1. Non-var-args function, and we meet first byval parameter.
2860 // Setup first unallocated register as first byval register;
2861 // eat all remained registers
2862 // (these two actions are performed by HandleByVal method).
2863 // Then, here, we initialize stack frame with
2864 // "store-reg" instructions.
2865 // Case #2. Var-args function, that doesn't contain byval parameters.
2866 // The same: eat all remained unallocated registers,
2867 // initialize stack frame.
2869 MachineFunction &MF = DAG.getMachineFunction();
2870 MachineFrameInfo *MFI = MF.getFrameInfo();
2871 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2872 unsigned RBegin, REnd;
2873 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2874 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2876 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2877 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2882 ArgOffset = -4 * (ARM::R4 - RBegin);
2884 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2885 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2887 SmallVector<SDValue, 4> MemOps;
2888 const TargetRegisterClass *RC =
2889 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2891 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2892 unsigned VReg = MF.addLiveIn(Reg, RC);
2893 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2895 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2896 MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2897 MemOps.push_back(Store);
2898 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2899 DAG.getConstant(4, dl, getPointerTy()));
2902 if (!MemOps.empty())
2903 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2907 // Setup stack frame, the va_list pointer will start from.
2909 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2910 SDLoc dl, SDValue &Chain,
2912 unsigned TotalArgRegsSaveSize,
2913 bool ForceMutable) const {
2914 MachineFunction &MF = DAG.getMachineFunction();
2915 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2917 // Try to store any remaining integer argument regs
2918 // to their spots on the stack so that they may be loaded by deferencing
2919 // the result of va_next.
2920 // If there is no regs to be stored, just point address after last
2921 // argument passed via stack.
2922 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2923 CCInfo.getInRegsParamsCount(),
2924 CCInfo.getNextStackOffset(), 4);
2925 AFI->setVarArgsFrameIndex(FrameIndex);
2929 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2930 CallingConv::ID CallConv, bool isVarArg,
2931 const SmallVectorImpl<ISD::InputArg>
2933 SDLoc dl, SelectionDAG &DAG,
2934 SmallVectorImpl<SDValue> &InVals)
2936 MachineFunction &MF = DAG.getMachineFunction();
2937 MachineFrameInfo *MFI = MF.getFrameInfo();
2939 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2941 // Assign locations to all of the incoming arguments.
2942 SmallVector<CCValAssign, 16> ArgLocs;
2943 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2944 *DAG.getContext(), Prologue);
2945 CCInfo.AnalyzeFormalArguments(Ins,
2946 CCAssignFnForNode(CallConv, /* Return*/ false,
2949 SmallVector<SDValue, 16> ArgValues;
2951 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2952 unsigned CurArgIdx = 0;
2954 // Initially ArgRegsSaveSize is zero.
2955 // Then we increase this value each time we meet byval parameter.
2956 // We also increase this value in case of varargs function.
2957 AFI->setArgRegsSaveSize(0);
2959 // Calculate the amount of stack space that we need to allocate to store
2960 // byval and variadic arguments that are passed in registers.
2961 // We need to know this before we allocate the first byval or variadic
2962 // argument, as they will be allocated a stack slot below the CFA (Canonical
2963 // Frame Address, the stack pointer at entry to the function).
2964 unsigned ArgRegBegin = ARM::R4;
2965 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2966 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
2969 CCValAssign &VA = ArgLocs[i];
2970 unsigned Index = VA.getValNo();
2971 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
2972 if (!Flags.isByVal())
2975 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
2976 unsigned RBegin, REnd;
2977 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
2978 ArgRegBegin = std::min(ArgRegBegin, RBegin);
2980 CCInfo.nextInRegsParam();
2982 CCInfo.rewindByValRegsInfo();
2984 int lastInsIndex = -1;
2985 if (isVarArg && MFI->hasVAStart()) {
2986 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2987 if (RegIdx != array_lengthof(GPRArgRegs))
2988 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
2991 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
2992 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
2994 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2995 CCValAssign &VA = ArgLocs[i];
2996 if (Ins[VA.getValNo()].isOrigArg()) {
2997 std::advance(CurOrigArg,
2998 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
2999 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3001 // Arguments stored in registers.
3002 if (VA.isRegLoc()) {
3003 EVT RegVT = VA.getLocVT();
3005 if (VA.needsCustom()) {
3006 // f64 and vector types are split up into multiple registers or
3007 // combinations of registers and stack slots.
3008 if (VA.getLocVT() == MVT::v2f64) {
3009 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3011 VA = ArgLocs[++i]; // skip ahead to next loc
3013 if (VA.isMemLoc()) {
3014 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3015 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3016 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3017 MachinePointerInfo::getFixedStack(FI),
3018 false, false, false, 0);
3020 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3023 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3024 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3025 ArgValue, ArgValue1,
3026 DAG.getIntPtrConstant(0, dl));
3027 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3028 ArgValue, ArgValue2,
3029 DAG.getIntPtrConstant(1, dl));
3031 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3034 const TargetRegisterClass *RC;
3036 if (RegVT == MVT::f32)
3037 RC = &ARM::SPRRegClass;
3038 else if (RegVT == MVT::f64)
3039 RC = &ARM::DPRRegClass;
3040 else if (RegVT == MVT::v2f64)
3041 RC = &ARM::QPRRegClass;
3042 else if (RegVT == MVT::i32)
3043 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3044 : &ARM::GPRRegClass;
3046 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3048 // Transform the arguments in physical registers into virtual ones.
3049 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3050 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3053 // If this is an 8 or 16-bit value, it is really passed promoted
3054 // to 32 bits. Insert an assert[sz]ext to capture this, then
3055 // truncate to the right size.
3056 switch (VA.getLocInfo()) {
3057 default: llvm_unreachable("Unknown loc info!");
3058 case CCValAssign::Full: break;
3059 case CCValAssign::BCvt:
3060 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3062 case CCValAssign::SExt:
3063 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3064 DAG.getValueType(VA.getValVT()));
3065 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3067 case CCValAssign::ZExt:
3068 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3069 DAG.getValueType(VA.getValVT()));
3070 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3074 InVals.push_back(ArgValue);
3076 } else { // VA.isRegLoc()
3079 assert(VA.isMemLoc());
3080 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3082 int index = VA.getValNo();
3084 // Some Ins[] entries become multiple ArgLoc[] entries.
3085 // Process them only once.
3086 if (index != lastInsIndex)
3088 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3089 // FIXME: For now, all byval parameter objects are marked mutable.
3090 // This can be changed with more analysis.
3091 // In case of tail call optimization mark all arguments mutable.
3092 // Since they could be overwritten by lowering of arguments in case of
3094 if (Flags.isByVal()) {
3095 assert(Ins[index].isOrigArg() &&
3096 "Byval arguments cannot be implicit");
3097 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3099 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3100 CurByValIndex, VA.getLocMemOffset(),
3101 Flags.getByValSize());
3102 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3103 CCInfo.nextInRegsParam();
3105 unsigned FIOffset = VA.getLocMemOffset();
3106 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3109 // Create load nodes to retrieve arguments from the stack.
3110 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3111 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3112 MachinePointerInfo::getFixedStack(FI),
3113 false, false, false, 0));
3115 lastInsIndex = index;
3121 if (isVarArg && MFI->hasVAStart())
3122 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3123 CCInfo.getNextStackOffset(),
3124 TotalArgRegsSaveSize);
3126 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3131 /// isFloatingPointZero - Return true if this is +0.0.
3132 static bool isFloatingPointZero(SDValue Op) {
3133 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3134 return CFP->getValueAPF().isPosZero();
3135 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3136 // Maybe this has already been legalized into the constant pool?
3137 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3138 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3139 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3140 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3141 return CFP->getValueAPF().isPosZero();
3143 } else if (Op->getOpcode() == ISD::BITCAST &&
3144 Op->getValueType(0) == MVT::f64) {
3145 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3146 // created by LowerConstantFP().
3147 SDValue BitcastOp = Op->getOperand(0);
3148 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3149 SDValue MoveOp = BitcastOp->getOperand(0);
3150 if (MoveOp->getOpcode() == ISD::TargetConstant &&
3151 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3159 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3160 /// the given operands.
3162 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3163 SDValue &ARMcc, SelectionDAG &DAG,
3165 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3166 unsigned C = RHSC->getZExtValue();
3167 if (!isLegalICmpImmediate(C)) {
3168 // Constant does not fit, try adjusting it by one?
3173 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3174 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3175 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3180 if (C != 0 && isLegalICmpImmediate(C-1)) {
3181 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3182 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3187 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3188 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3189 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3194 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3195 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3196 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3203 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3204 ARMISD::NodeType CompareType;
3207 CompareType = ARMISD::CMP;
3212 CompareType = ARMISD::CMPZ;
3215 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3216 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3219 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3221 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3223 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3225 if (!isFloatingPointZero(RHS))
3226 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3228 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3229 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3232 /// duplicateCmp - Glue values can have only one use, so this function
3233 /// duplicates a comparison node.
3235 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3236 unsigned Opc = Cmp.getOpcode();
3238 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3239 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3241 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3242 Cmp = Cmp.getOperand(0);
3243 Opc = Cmp.getOpcode();
3244 if (Opc == ARMISD::CMPFP)
3245 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3247 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3248 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3250 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3253 std::pair<SDValue, SDValue>
3254 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3255 SDValue &ARMcc) const {
3256 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3258 SDValue Value, OverflowCmp;
3259 SDValue LHS = Op.getOperand(0);
3260 SDValue RHS = Op.getOperand(1);
3263 // FIXME: We are currently always generating CMPs because we don't support
3264 // generating CMN through the backend. This is not as good as the natural
3265 // CMP case because it causes a register dependency and cannot be folded
3268 switch (Op.getOpcode()) {
3270 llvm_unreachable("Unknown overflow instruction!");
3272 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3273 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3274 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3277 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3278 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3279 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3282 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3283 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3284 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3287 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3288 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3289 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3293 return std::make_pair(Value, OverflowCmp);
3298 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3299 // Let legalize expand this if it isn't a legal type yet.
3300 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3303 SDValue Value, OverflowCmp;
3305 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3306 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3308 // We use 0 and 1 as false and true values.
3309 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3310 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3311 EVT VT = Op.getValueType();
3313 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3314 ARMcc, CCR, OverflowCmp);
3316 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3317 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3321 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3322 SDValue Cond = Op.getOperand(0);
3323 SDValue SelectTrue = Op.getOperand(1);
3324 SDValue SelectFalse = Op.getOperand(2);
3326 unsigned Opc = Cond.getOpcode();
3328 if (Cond.getResNo() == 1 &&
3329 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3330 Opc == ISD::USUBO)) {
3331 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3334 SDValue Value, OverflowCmp;
3336 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3337 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3338 EVT VT = Op.getValueType();
3340 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3346 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3347 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3349 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3350 const ConstantSDNode *CMOVTrue =
3351 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3352 const ConstantSDNode *CMOVFalse =
3353 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3355 if (CMOVTrue && CMOVFalse) {
3356 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3357 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3361 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3363 False = SelectFalse;
3364 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3369 if (True.getNode() && False.getNode()) {
3370 EVT VT = Op.getValueType();
3371 SDValue ARMcc = Cond.getOperand(2);
3372 SDValue CCR = Cond.getOperand(3);
3373 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3374 assert(True.getValueType() == VT);
3375 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3380 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3381 // undefined bits before doing a full-word comparison with zero.
3382 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3383 DAG.getConstant(1, dl, Cond.getValueType()));
3385 return DAG.getSelectCC(dl, Cond,
3386 DAG.getConstant(0, dl, Cond.getValueType()),
3387 SelectTrue, SelectFalse, ISD::SETNE);
3390 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3391 bool &swpCmpOps, bool &swpVselOps) {
3392 // Start by selecting the GE condition code for opcodes that return true for
3394 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3396 CondCode = ARMCC::GE;
3398 // and GT for opcodes that return false for 'equality'.
3399 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3401 CondCode = ARMCC::GT;
3403 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3404 // to swap the compare operands.
3405 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3409 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3410 // If we have an unordered opcode, we need to swap the operands to the VSEL
3411 // instruction (effectively negating the condition).
3413 // This also has the effect of swapping which one of 'less' or 'greater'
3414 // returns true, so we also swap the compare operands. It also switches
3415 // whether we return true for 'equality', so we compensate by picking the
3416 // opposite condition code to our original choice.
3417 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3418 CC == ISD::SETUGT) {
3419 swpCmpOps = !swpCmpOps;
3420 swpVselOps = !swpVselOps;
3421 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3424 // 'ordered' is 'anything but unordered', so use the VS condition code and
3425 // swap the VSEL operands.
3426 if (CC == ISD::SETO) {
3427 CondCode = ARMCC::VS;
3431 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3432 // code and swap the VSEL operands.
3433 if (CC == ISD::SETUNE) {
3434 CondCode = ARMCC::EQ;
3439 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3440 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3441 SDValue Cmp, SelectionDAG &DAG) const {
3442 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3443 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3444 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3445 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3446 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3448 SDValue TrueLow = TrueVal.getValue(0);
3449 SDValue TrueHigh = TrueVal.getValue(1);
3450 SDValue FalseLow = FalseVal.getValue(0);
3451 SDValue FalseHigh = FalseVal.getValue(1);
3453 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3455 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3456 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3458 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3460 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3465 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3466 EVT VT = Op.getValueType();
3467 SDValue LHS = Op.getOperand(0);
3468 SDValue RHS = Op.getOperand(1);
3469 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3470 SDValue TrueVal = Op.getOperand(2);
3471 SDValue FalseVal = Op.getOperand(3);
3474 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3475 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3478 // If softenSetCCOperands only returned one value, we should compare it to
3480 if (!RHS.getNode()) {
3481 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3486 if (LHS.getValueType() == MVT::i32) {
3487 // Try to generate VSEL on ARMv8.
3488 // The VSEL instruction can't use all the usual ARM condition
3489 // codes: it only has two bits to select the condition code, so it's
3490 // constrained to use only GE, GT, VS and EQ.
3492 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3493 // swap the operands of the previous compare instruction (effectively
3494 // inverting the compare condition, swapping 'less' and 'greater') and
3495 // sometimes need to swap the operands to the VSEL (which inverts the
3496 // condition in the sense of firing whenever the previous condition didn't)
3497 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3498 TrueVal.getValueType() == MVT::f64)) {
3499 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3500 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3501 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3502 CC = ISD::getSetCCInverse(CC, true);
3503 std::swap(TrueVal, FalseVal);
3508 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3509 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3510 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3513 ARMCC::CondCodes CondCode, CondCode2;
3514 FPCCToARMCC(CC, CondCode, CondCode2);
3516 // Try to generate VMAXNM/VMINNM on ARMv8.
3517 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3518 TrueVal.getValueType() == MVT::f64)) {
3519 // We can use VMAXNM/VMINNM for a compare followed by a select with the
3520 // same operands, as follows:
3521 // c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3523 // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3524 bool swapSides = false;
3525 if (!getTargetMachine().Options.NoNaNsFPMath) {
3526 // transformability may depend on which way around we compare
3534 // the non-NaN should be RHS
3535 swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3541 // the non-NaN should be LHS
3542 swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3546 swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3548 CC = ISD::getSetCCSwappedOperands(CC);
3549 std::swap(LHS, RHS);
3551 if (LHS == TrueVal && RHS == FalseVal) {
3552 bool canTransform = true;
3553 // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3554 if (!getTargetMachine().Options.UnsafeFPMath &&
3555 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3556 const ConstantFPSDNode *Zero;
3563 // RHS must not be -0
3564 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3565 !Zero->isNegative();
3570 // LHS must not be -0
3571 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3572 !Zero->isNegative();
3577 // RHS must not be +0
3578 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3584 // LHS must not be +0
3585 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3591 // Note: If one of the elements in a pair is a number and the other
3592 // element is NaN, the corresponding result element is the number.
3593 // This is consistent with the IEEE 754-2008 standard.
3594 // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3600 if (!DAG.isKnownNeverNaN(RHS))
3602 return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3605 if (!DAG.isKnownNeverNaN(LHS))
3609 return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3612 if (!DAG.isKnownNeverNaN(RHS))
3614 return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3617 if (!DAG.isKnownNeverNaN(LHS))
3621 return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3626 bool swpCmpOps = false;
3627 bool swpVselOps = false;
3628 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3630 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3631 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3633 std::swap(LHS, RHS);
3635 std::swap(TrueVal, FalseVal);
3639 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3640 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3641 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3642 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3643 if (CondCode2 != ARMCC::AL) {
3644 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3645 // FIXME: Needs another CMP because flag can have but one use.
3646 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3647 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3652 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3653 /// to morph to an integer compare sequence.
3654 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3655 const ARMSubtarget *Subtarget) {
3656 SDNode *N = Op.getNode();
3657 if (!N->hasOneUse())
3658 // Otherwise it requires moving the value from fp to integer registers.
3660 if (!N->getNumValues())
3662 EVT VT = Op.getValueType();
3663 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3664 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3665 // vmrs are very slow, e.g. cortex-a8.
3668 if (isFloatingPointZero(Op)) {
3672 return ISD::isNormalLoad(N);
3675 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3676 if (isFloatingPointZero(Op))
3677 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3679 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3680 return DAG.getLoad(MVT::i32, SDLoc(Op),
3681 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3682 Ld->isVolatile(), Ld->isNonTemporal(),
3683 Ld->isInvariant(), Ld->getAlignment());
3685 llvm_unreachable("Unknown VFP cmp argument!");
3688 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3689 SDValue &RetVal1, SDValue &RetVal2) {
3692 if (isFloatingPointZero(Op)) {
3693 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3694 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3698 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3699 SDValue Ptr = Ld->getBasePtr();
3700 RetVal1 = DAG.getLoad(MVT::i32, dl,
3701 Ld->getChain(), Ptr,
3702 Ld->getPointerInfo(),
3703 Ld->isVolatile(), Ld->isNonTemporal(),
3704 Ld->isInvariant(), Ld->getAlignment());
3706 EVT PtrType = Ptr.getValueType();
3707 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3708 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3709 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3710 RetVal2 = DAG.getLoad(MVT::i32, dl,
3711 Ld->getChain(), NewPtr,
3712 Ld->getPointerInfo().getWithOffset(4),
3713 Ld->isVolatile(), Ld->isNonTemporal(),
3714 Ld->isInvariant(), NewAlign);
3718 llvm_unreachable("Unknown VFP cmp argument!");
3721 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3722 /// f32 and even f64 comparisons to integer ones.
3724 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3725 SDValue Chain = Op.getOperand(0);
3726 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3727 SDValue LHS = Op.getOperand(2);
3728 SDValue RHS = Op.getOperand(3);
3729 SDValue Dest = Op.getOperand(4);
3732 bool LHSSeenZero = false;
3733 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3734 bool RHSSeenZero = false;
3735 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3736 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3737 // If unsafe fp math optimization is enabled and there are no other uses of
3738 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3739 // to an integer comparison.
3740 if (CC == ISD::SETOEQ)
3742 else if (CC == ISD::SETUNE)
3745 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3747 if (LHS.getValueType() == MVT::f32) {
3748 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3749 bitcastf32Toi32(LHS, DAG), Mask);
3750 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3751 bitcastf32Toi32(RHS, DAG), Mask);
3752 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3753 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3754 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3755 Chain, Dest, ARMcc, CCR, Cmp);
3760 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3761 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3762 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3763 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3764 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3765 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3766 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3767 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3768 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3774 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3775 SDValue Chain = Op.getOperand(0);
3776 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3777 SDValue LHS = Op.getOperand(2);
3778 SDValue RHS = Op.getOperand(3);
3779 SDValue Dest = Op.getOperand(4);
3782 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3783 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3786 // If softenSetCCOperands only returned one value, we should compare it to
3788 if (!RHS.getNode()) {
3789 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3794 if (LHS.getValueType() == MVT::i32) {
3796 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3797 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3798 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3799 Chain, Dest, ARMcc, CCR, Cmp);
3802 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3804 if (getTargetMachine().Options.UnsafeFPMath &&
3805 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3806 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3807 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3808 if (Result.getNode())
3812 ARMCC::CondCodes CondCode, CondCode2;
3813 FPCCToARMCC(CC, CondCode, CondCode2);
3815 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3816 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3817 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3818 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3819 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3820 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3821 if (CondCode2 != ARMCC::AL) {
3822 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3823 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3824 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3829 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3830 SDValue Chain = Op.getOperand(0);
3831 SDValue Table = Op.getOperand(1);
3832 SDValue Index = Op.getOperand(2);
3835 EVT PTy = getPointerTy();
3836 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3837 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3838 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), dl, PTy);
3839 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3840 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3841 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3842 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3843 if (Subtarget->isThumb2()) {
3844 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3845 // which does another jump to the destination. This also makes it easier
3846 // to translate it to TBB / TBH later.
3847 // FIXME: This might not work if the function is extremely large.
3848 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3849 Addr, Op.getOperand(2), JTI, UId);
3851 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3852 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3853 MachinePointerInfo::getJumpTable(),
3854 false, false, false, 0);
3855 Chain = Addr.getValue(1);
3856 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3857 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3859 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3860 MachinePointerInfo::getJumpTable(),
3861 false, false, false, 0);
3862 Chain = Addr.getValue(1);
3863 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3867 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3868 EVT VT = Op.getValueType();
3871 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3872 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3874 return DAG.UnrollVectorOp(Op.getNode());
3877 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3878 "Invalid type for custom lowering!");
3879 if (VT != MVT::v4i16)
3880 return DAG.UnrollVectorOp(Op.getNode());
3882 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3883 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3886 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3887 EVT VT = Op.getValueType();
3889 return LowerVectorFP_TO_INT(Op, DAG);
3890 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3892 if (Op.getOpcode() == ISD::FP_TO_SINT)
3893 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3896 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3898 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3899 /*isSigned*/ false, SDLoc(Op)).first;
3905 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3906 EVT VT = Op.getValueType();
3909 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3910 if (VT.getVectorElementType() == MVT::f32)
3912 return DAG.UnrollVectorOp(Op.getNode());
3915 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3916 "Invalid type for custom lowering!");
3917 if (VT != MVT::v4f32)
3918 return DAG.UnrollVectorOp(Op.getNode());
3922 switch (Op.getOpcode()) {
3923 default: llvm_unreachable("Invalid opcode!");
3924 case ISD::SINT_TO_FP:
3925 CastOpc = ISD::SIGN_EXTEND;
3926 Opc = ISD::SINT_TO_FP;
3928 case ISD::UINT_TO_FP:
3929 CastOpc = ISD::ZERO_EXTEND;
3930 Opc = ISD::UINT_TO_FP;
3934 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3935 return DAG.getNode(Opc, dl, VT, Op);
3938 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3939 EVT VT = Op.getValueType();
3941 return LowerVectorINT_TO_FP(Op, DAG);
3942 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3944 if (Op.getOpcode() == ISD::SINT_TO_FP)
3945 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3948 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3950 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3951 /*isSigned*/ false, SDLoc(Op)).first;
3957 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3958 // Implement fcopysign with a fabs and a conditional fneg.
3959 SDValue Tmp0 = Op.getOperand(0);
3960 SDValue Tmp1 = Op.getOperand(1);
3962 EVT VT = Op.getValueType();
3963 EVT SrcVT = Tmp1.getValueType();
3964 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3965 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3966 bool UseNEON = !InGPR && Subtarget->hasNEON();
3969 // Use VBSL to copy the sign bit.
3970 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3971 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3972 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3973 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3975 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3976 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3977 DAG.getConstant(32, dl, MVT::i32));
3978 else /*if (VT == MVT::f32)*/
3979 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3980 if (SrcVT == MVT::f32) {
3981 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3983 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3984 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3985 DAG.getConstant(32, dl, MVT::i32));
3986 } else if (VT == MVT::f32)
3987 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3988 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3989 DAG.getConstant(32, dl, MVT::i32));
3990 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3991 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3993 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3995 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3996 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3997 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3999 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4000 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4001 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4002 if (VT == MVT::f32) {
4003 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4004 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4005 DAG.getConstant(0, dl, MVT::i32));
4007 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4013 // Bitcast operand 1 to i32.
4014 if (SrcVT == MVT::f64)
4015 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4017 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4019 // Or in the signbit with integer operations.
4020 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4021 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4022 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4023 if (VT == MVT::f32) {
4024 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4025 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4026 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4027 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4030 // f64: Or the high part with signbit and then combine two parts.
4031 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4033 SDValue Lo = Tmp0.getValue(0);
4034 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4035 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4036 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4039 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4040 MachineFunction &MF = DAG.getMachineFunction();
4041 MachineFrameInfo *MFI = MF.getFrameInfo();
4042 MFI->setReturnAddressIsTaken(true);
4044 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4047 EVT VT = Op.getValueType();
4049 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4051 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4052 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4053 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4054 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4055 MachinePointerInfo(), false, false, false, 0);
4058 // Return LR, which contains the return address. Mark it an implicit live-in.
4059 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4060 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4063 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4064 const ARMBaseRegisterInfo &ARI =
4065 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4066 MachineFunction &MF = DAG.getMachineFunction();
4067 MachineFrameInfo *MFI = MF.getFrameInfo();
4068 MFI->setFrameAddressIsTaken(true);
4070 EVT VT = Op.getValueType();
4071 SDLoc dl(Op); // FIXME probably not meaningful
4072 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4073 unsigned FrameReg = ARI.getFrameRegister(MF);
4074 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4076 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4077 MachinePointerInfo(),
4078 false, false, false, 0);
4082 // FIXME? Maybe this could be a TableGen attribute on some registers and
4083 // this table could be generated automatically from RegInfo.
4084 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4086 unsigned Reg = StringSwitch<unsigned>(RegName)
4087 .Case("sp", ARM::SP)
4091 report_fatal_error("Invalid register name global variable");
4094 /// ExpandBITCAST - If the target supports VFP, this function is called to
4095 /// expand a bit convert where either the source or destination type is i64 to
4096 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4097 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4098 /// vectors), since the legalizer won't know what to do with that.
4099 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4100 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4102 SDValue Op = N->getOperand(0);
4104 // This function is only supposed to be called for i64 types, either as the
4105 // source or destination of the bit convert.
4106 EVT SrcVT = Op.getValueType();
4107 EVT DstVT = N->getValueType(0);
4108 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4109 "ExpandBITCAST called for non-i64 type");
4111 // Turn i64->f64 into VMOVDRR.
4112 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4113 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4114 DAG.getConstant(0, dl, MVT::i32));
4115 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4116 DAG.getConstant(1, dl, MVT::i32));
4117 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4118 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4121 // Turn f64->i64 into VMOVRRD.
4122 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4124 if (TLI.isBigEndian() && SrcVT.isVector() &&
4125 SrcVT.getVectorNumElements() > 1)
4126 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4127 DAG.getVTList(MVT::i32, MVT::i32),
4128 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4130 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4131 DAG.getVTList(MVT::i32, MVT::i32), Op);
4132 // Merge the pieces into a single i64 value.
4133 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4139 /// getZeroVector - Returns a vector of specified type with all zero elements.
4140 /// Zero vectors are used to represent vector negation and in those cases
4141 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4142 /// not support i64 elements, so sometimes the zero vectors will need to be
4143 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4145 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4146 assert(VT.isVector() && "Expected a vector type");
4147 // The canonical modified immediate encoding of a zero vector is....0!
4148 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4149 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4150 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4151 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4154 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4155 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4156 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4157 SelectionDAG &DAG) const {
4158 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4159 EVT VT = Op.getValueType();
4160 unsigned VTBits = VT.getSizeInBits();
4162 SDValue ShOpLo = Op.getOperand(0);
4163 SDValue ShOpHi = Op.getOperand(1);
4164 SDValue ShAmt = Op.getOperand(2);
4166 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4168 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4170 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4171 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4172 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4173 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4174 DAG.getConstant(VTBits, dl, MVT::i32));
4175 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4176 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4177 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4179 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4180 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4181 ISD::SETGE, ARMcc, DAG, dl);
4182 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4183 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4186 SDValue Ops[2] = { Lo, Hi };
4187 return DAG.getMergeValues(Ops, dl);
4190 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4191 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4192 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4193 SelectionDAG &DAG) const {
4194 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4195 EVT VT = Op.getValueType();
4196 unsigned VTBits = VT.getSizeInBits();
4198 SDValue ShOpLo = Op.getOperand(0);
4199 SDValue ShOpHi = Op.getOperand(1);
4200 SDValue ShAmt = Op.getOperand(2);
4203 assert(Op.getOpcode() == ISD::SHL_PARTS);
4204 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4205 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4206 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4207 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4208 DAG.getConstant(VTBits, dl, MVT::i32));
4209 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4210 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4212 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4213 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4214 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4215 ISD::SETGE, ARMcc, DAG, dl);
4216 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4217 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4220 SDValue Ops[2] = { Lo, Hi };
4221 return DAG.getMergeValues(Ops, dl);
4224 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4225 SelectionDAG &DAG) const {
4226 // The rounding mode is in bits 23:22 of the FPSCR.
4227 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4228 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4229 // so that the shift + and get folded into a bitfield extract.
4231 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4232 DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4234 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4235 DAG.getConstant(1U << 22, dl, MVT::i32));
4236 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4237 DAG.getConstant(22, dl, MVT::i32));
4238 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4239 DAG.getConstant(3, dl, MVT::i32));
4242 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4243 const ARMSubtarget *ST) {
4244 EVT VT = N->getValueType(0);
4247 if (!ST->hasV6T2Ops())
4250 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4251 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4254 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4255 /// for each 16-bit element from operand, repeated. The basic idea is to
4256 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4258 /// Trace for v4i16:
4259 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4260 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4261 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4262 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4263 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4264 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4265 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4266 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4267 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4268 EVT VT = N->getValueType(0);
4271 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4272 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4273 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4274 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4275 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4276 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4279 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4280 /// bit-count for each 16-bit element from the operand. We need slightly
4281 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4282 /// 64/128-bit registers.
4284 /// Trace for v4i16:
4285 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4286 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4287 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4288 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4289 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4290 EVT VT = N->getValueType(0);
4293 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4294 if (VT.is64BitVector()) {
4295 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4296 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4297 DAG.getIntPtrConstant(0, DL));
4299 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4300 BitCounts, DAG.getIntPtrConstant(0, DL));
4301 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4305 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4306 /// bit-count for each 32-bit element from the operand. The idea here is
4307 /// to split the vector into 16-bit elements, leverage the 16-bit count
4308 /// routine, and then combine the results.
4310 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4311 /// input = [v0 v1 ] (vi: 32-bit elements)
4312 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4313 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4314 /// vrev: N0 = [k1 k0 k3 k2 ]
4316 /// N1 =+[k1 k0 k3 k2 ]
4318 /// N2 =+[k1 k3 k0 k2 ]
4320 /// Extended =+[k1 k3 k0 k2 ]
4322 /// Extracted=+[k1 k3 ]
4324 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4325 EVT VT = N->getValueType(0);
4328 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4330 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4331 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4332 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4333 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4334 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4336 if (VT.is64BitVector()) {
4337 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4338 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4339 DAG.getIntPtrConstant(0, DL));
4341 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4342 DAG.getIntPtrConstant(0, DL));
4343 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4347 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4348 const ARMSubtarget *ST) {
4349 EVT VT = N->getValueType(0);
4351 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4352 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4353 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4354 "Unexpected type for custom ctpop lowering");
4356 if (VT.getVectorElementType() == MVT::i32)
4357 return lowerCTPOP32BitElements(N, DAG);
4359 return lowerCTPOP16BitElements(N, DAG);
4362 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4363 const ARMSubtarget *ST) {
4364 EVT VT = N->getValueType(0);
4370 // Lower vector shifts on NEON to use VSHL.
4371 assert(ST->hasNEON() && "unexpected vector shift");
4373 // Left shifts translate directly to the vshiftu intrinsic.
4374 if (N->getOpcode() == ISD::SHL)
4375 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4376 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4378 N->getOperand(0), N->getOperand(1));
4380 assert((N->getOpcode() == ISD::SRA ||
4381 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4383 // NEON uses the same intrinsics for both left and right shifts. For
4384 // right shifts, the shift amounts are negative, so negate the vector of
4386 EVT ShiftVT = N->getOperand(1).getValueType();
4387 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4388 getZeroVector(ShiftVT, DAG, dl),
4390 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4391 Intrinsic::arm_neon_vshifts :
4392 Intrinsic::arm_neon_vshiftu);
4393 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4394 DAG.getConstant(vshiftInt, dl, MVT::i32),
4395 N->getOperand(0), NegatedCount);
4398 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4399 const ARMSubtarget *ST) {
4400 EVT VT = N->getValueType(0);
4403 // We can get here for a node like i32 = ISD::SHL i32, i64
4407 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4408 "Unknown shift to lower!");
4410 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4411 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4412 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4415 // If we are in thumb mode, we don't have RRX.
4416 if (ST->isThumb1Only()) return SDValue();
4418 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4419 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4420 DAG.getConstant(0, dl, MVT::i32));
4421 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4422 DAG.getConstant(1, dl, MVT::i32));
4424 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4425 // captures the result into a carry flag.
4426 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4427 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4429 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4430 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4432 // Merge the pieces into a single i64 value.
4433 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4436 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4437 SDValue TmpOp0, TmpOp1;
4438 bool Invert = false;
4442 SDValue Op0 = Op.getOperand(0);
4443 SDValue Op1 = Op.getOperand(1);
4444 SDValue CC = Op.getOperand(2);
4445 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4446 EVT VT = Op.getValueType();
4447 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4450 if (Op1.getValueType().isFloatingPoint()) {
4451 switch (SetCCOpcode) {
4452 default: llvm_unreachable("Illegal FP comparison");
4454 case ISD::SETNE: Invert = true; // Fallthrough
4456 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4458 case ISD::SETLT: Swap = true; // Fallthrough
4460 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4462 case ISD::SETLE: Swap = true; // Fallthrough
4464 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4465 case ISD::SETUGE: Swap = true; // Fallthrough
4466 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4467 case ISD::SETUGT: Swap = true; // Fallthrough
4468 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4469 case ISD::SETUEQ: Invert = true; // Fallthrough
4471 // Expand this to (OLT | OGT).
4475 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4476 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4478 case ISD::SETUO: Invert = true; // Fallthrough
4480 // Expand this to (OLT | OGE).
4484 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4485 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4489 // Integer comparisons.
4490 switch (SetCCOpcode) {
4491 default: llvm_unreachable("Illegal integer comparison");
4492 case ISD::SETNE: Invert = true;
4493 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4494 case ISD::SETLT: Swap = true;
4495 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4496 case ISD::SETLE: Swap = true;
4497 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4498 case ISD::SETULT: Swap = true;
4499 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4500 case ISD::SETULE: Swap = true;
4501 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4504 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4505 if (Opc == ARMISD::VCEQ) {
4508 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4510 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4513 // Ignore bitconvert.
4514 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4515 AndOp = AndOp.getOperand(0);
4517 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4519 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4520 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4527 std::swap(Op0, Op1);
4529 // If one of the operands is a constant vector zero, attempt to fold the
4530 // comparison to a specialized compare-against-zero form.
4532 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4534 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4535 if (Opc == ARMISD::VCGE)
4536 Opc = ARMISD::VCLEZ;
4537 else if (Opc == ARMISD::VCGT)
4538 Opc = ARMISD::VCLTZ;
4543 if (SingleOp.getNode()) {
4546 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4548 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4550 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4552 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4554 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4556 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4559 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4562 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4565 Result = DAG.getNOT(dl, Result, VT);
4570 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4571 /// valid vector constant for a NEON instruction with a "modified immediate"
4572 /// operand (e.g., VMOV). If so, return the encoded value.
4573 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4574 unsigned SplatBitSize, SelectionDAG &DAG,
4575 SDLoc dl, EVT &VT, bool is128Bits,
4576 NEONModImmType type) {
4577 unsigned OpCmode, Imm;
4579 // SplatBitSize is set to the smallest size that splats the vector, so a
4580 // zero vector will always have SplatBitSize == 8. However, NEON modified
4581 // immediate instructions others than VMOV do not support the 8-bit encoding
4582 // of a zero vector, and the default encoding of zero is supposed to be the
4587 switch (SplatBitSize) {
4589 if (type != VMOVModImm)
4591 // Any 1-byte value is OK. Op=0, Cmode=1110.
4592 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4595 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4599 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4600 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4601 if ((SplatBits & ~0xff) == 0) {
4602 // Value = 0x00nn: Op=x, Cmode=100x.
4607 if ((SplatBits & ~0xff00) == 0) {
4608 // Value = 0xnn00: Op=x, Cmode=101x.
4610 Imm = SplatBits >> 8;
4616 // NEON's 32-bit VMOV supports splat values where:
4617 // * only one byte is nonzero, or
4618 // * the least significant byte is 0xff and the second byte is nonzero, or
4619 // * the least significant 2 bytes are 0xff and the third is nonzero.
4620 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4621 if ((SplatBits & ~0xff) == 0) {
4622 // Value = 0x000000nn: Op=x, Cmode=000x.
4627 if ((SplatBits & ~0xff00) == 0) {
4628 // Value = 0x0000nn00: Op=x, Cmode=001x.
4630 Imm = SplatBits >> 8;
4633 if ((SplatBits & ~0xff0000) == 0) {
4634 // Value = 0x00nn0000: Op=x, Cmode=010x.
4636 Imm = SplatBits >> 16;
4639 if ((SplatBits & ~0xff000000) == 0) {
4640 // Value = 0xnn000000: Op=x, Cmode=011x.
4642 Imm = SplatBits >> 24;
4646 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4647 if (type == OtherModImm) return SDValue();
4649 if ((SplatBits & ~0xffff) == 0 &&
4650 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4651 // Value = 0x0000nnff: Op=x, Cmode=1100.
4653 Imm = SplatBits >> 8;
4657 if ((SplatBits & ~0xffffff) == 0 &&
4658 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4659 // Value = 0x00nnffff: Op=x, Cmode=1101.
4661 Imm = SplatBits >> 16;
4665 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4666 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4667 // VMOV.I32. A (very) minor optimization would be to replicate the value
4668 // and fall through here to test for a valid 64-bit splat. But, then the
4669 // caller would also need to check and handle the change in size.
4673 if (type != VMOVModImm)
4675 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4676 uint64_t BitMask = 0xff;
4678 unsigned ImmMask = 1;
4680 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4681 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4684 } else if ((SplatBits & BitMask) != 0) {
4691 if (DAG.getTargetLoweringInfo().isBigEndian())
4692 // swap higher and lower 32 bit word
4693 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4695 // Op=1, Cmode=1110.
4697 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4702 llvm_unreachable("unexpected size for isNEONModifiedImm");
4705 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4706 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4709 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4710 const ARMSubtarget *ST) const {
4714 bool IsDouble = Op.getValueType() == MVT::f64;
4715 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4717 // Use the default (constant pool) lowering for double constants when we have
4719 if (IsDouble && Subtarget->isFPOnlySP())
4722 // Try splatting with a VMOV.f32...
4723 APFloat FPVal = CFP->getValueAPF();
4724 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4727 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4728 // We have code in place to select a valid ConstantFP already, no need to
4733 // It's a float and we are trying to use NEON operations where
4734 // possible. Lower it to a splat followed by an extract.
4736 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4737 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4739 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4740 DAG.getConstant(0, DL, MVT::i32));
4743 // The rest of our options are NEON only, make sure that's allowed before
4745 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4749 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4751 // It wouldn't really be worth bothering for doubles except for one very
4752 // important value, which does happen to match: 0.0. So make sure we don't do
4754 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4757 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4758 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4759 VMovVT, false, VMOVModImm);
4760 if (NewVal != SDValue()) {
4762 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4765 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4767 // It's a float: cast and extract a vector element.
4768 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4770 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4771 DAG.getConstant(0, DL, MVT::i32));
4774 // Finally, try a VMVN.i32
4775 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4777 if (NewVal != SDValue()) {
4779 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4782 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4784 // It's a float: cast and extract a vector element.
4785 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4787 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4788 DAG.getConstant(0, DL, MVT::i32));
4794 // check if an VEXT instruction can handle the shuffle mask when the
4795 // vector sources of the shuffle are the same.
4796 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4797 unsigned NumElts = VT.getVectorNumElements();
4799 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4805 // If this is a VEXT shuffle, the immediate value is the index of the first
4806 // element. The other shuffle indices must be the successive elements after
4808 unsigned ExpectedElt = Imm;
4809 for (unsigned i = 1; i < NumElts; ++i) {
4810 // Increment the expected index. If it wraps around, just follow it
4811 // back to index zero and keep going.
4813 if (ExpectedElt == NumElts)
4816 if (M[i] < 0) continue; // ignore UNDEF indices
4817 if (ExpectedElt != static_cast<unsigned>(M[i]))
4825 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4826 bool &ReverseVEXT, unsigned &Imm) {
4827 unsigned NumElts = VT.getVectorNumElements();
4828 ReverseVEXT = false;
4830 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4836 // If this is a VEXT shuffle, the immediate value is the index of the first
4837 // element. The other shuffle indices must be the successive elements after
4839 unsigned ExpectedElt = Imm;
4840 for (unsigned i = 1; i < NumElts; ++i) {
4841 // Increment the expected index. If it wraps around, it may still be
4842 // a VEXT but the source vectors must be swapped.
4844 if (ExpectedElt == NumElts * 2) {
4849 if (M[i] < 0) continue; // ignore UNDEF indices
4850 if (ExpectedElt != static_cast<unsigned>(M[i]))
4854 // Adjust the index value if the source operands will be swapped.
4861 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4862 /// instruction with the specified blocksize. (The order of the elements
4863 /// within each block of the vector is reversed.)
4864 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4865 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4866 "Only possible block sizes for VREV are: 16, 32, 64");
4868 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4872 unsigned NumElts = VT.getVectorNumElements();
4873 unsigned BlockElts = M[0] + 1;
4874 // If the first shuffle index is UNDEF, be optimistic.
4876 BlockElts = BlockSize / EltSz;
4878 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4881 for (unsigned i = 0; i < NumElts; ++i) {
4882 if (M[i] < 0) continue; // ignore UNDEF indices
4883 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4890 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4891 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4892 // range, then 0 is placed into the resulting vector. So pretty much any mask
4893 // of 8 elements can work here.
4894 return VT == MVT::v8i8 && M.size() == 8;
4897 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4898 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4902 unsigned NumElts = VT.getVectorNumElements();
4903 WhichResult = (M[0] == 0 ? 0 : 1);
4904 for (unsigned i = 0; i < NumElts; i += 2) {
4905 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4906 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4912 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4913 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4914 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4915 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4916 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4920 unsigned NumElts = VT.getVectorNumElements();
4921 WhichResult = (M[0] == 0 ? 0 : 1);
4922 for (unsigned i = 0; i < NumElts; i += 2) {
4923 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4924 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4930 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4931 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4935 unsigned NumElts = VT.getVectorNumElements();
4936 WhichResult = (M[0] == 0 ? 0 : 1);
4937 for (unsigned i = 0; i != NumElts; ++i) {
4938 if (M[i] < 0) continue; // ignore UNDEF indices
4939 if ((unsigned) M[i] != 2 * i + WhichResult)
4943 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4944 if (VT.is64BitVector() && EltSz == 32)
4950 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4951 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4952 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4953 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4954 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4958 unsigned Half = VT.getVectorNumElements() / 2;
4959 WhichResult = (M[0] == 0 ? 0 : 1);
4960 for (unsigned j = 0; j != 2; ++j) {
4961 unsigned Idx = WhichResult;
4962 for (unsigned i = 0; i != Half; ++i) {
4963 int MIdx = M[i + j * Half];
4964 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4970 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4971 if (VT.is64BitVector() && EltSz == 32)
4977 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4978 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4982 unsigned NumElts = VT.getVectorNumElements();
4983 WhichResult = (M[0] == 0 ? 0 : 1);
4984 unsigned Idx = WhichResult * NumElts / 2;
4985 for (unsigned i = 0; i != NumElts; i += 2) {
4986 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4987 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4992 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4993 if (VT.is64BitVector() && EltSz == 32)
4999 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5000 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5001 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5002 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5003 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5007 unsigned NumElts = VT.getVectorNumElements();
5008 WhichResult = (M[0] == 0 ? 0 : 1);
5009 unsigned Idx = WhichResult * NumElts / 2;
5010 for (unsigned i = 0; i != NumElts; i += 2) {
5011 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5012 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5017 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5018 if (VT.is64BitVector() && EltSz == 32)
5024 /// \return true if this is a reverse operation on an vector.
5025 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5026 unsigned NumElts = VT.getVectorNumElements();
5027 // Make sure the mask has the right size.
5028 if (NumElts != M.size())
5031 // Look for <15, ..., 3, -1, 1, 0>.
5032 for (unsigned i = 0; i != NumElts; ++i)
5033 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5039 // If N is an integer constant that can be moved into a register in one
5040 // instruction, return an SDValue of such a constant (will become a MOV
5041 // instruction). Otherwise return null.
5042 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5043 const ARMSubtarget *ST, SDLoc dl) {
5045 if (!isa<ConstantSDNode>(N))
5047 Val = cast<ConstantSDNode>(N)->getZExtValue();
5049 if (ST->isThumb1Only()) {
5050 if (Val <= 255 || ~Val <= 255)
5051 return DAG.getConstant(Val, dl, MVT::i32);
5053 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5054 return DAG.getConstant(Val, dl, MVT::i32);
5059 // If this is a case we can't handle, return null and let the default
5060 // expansion code take care of it.
5061 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5062 const ARMSubtarget *ST) const {
5063 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5065 EVT VT = Op.getValueType();
5067 APInt SplatBits, SplatUndef;
5068 unsigned SplatBitSize;
5070 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5071 if (SplatBitSize <= 64) {
5072 // Check if an immediate VMOV works.
5074 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5075 SplatUndef.getZExtValue(), SplatBitSize,
5076 DAG, dl, VmovVT, VT.is128BitVector(),
5078 if (Val.getNode()) {
5079 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5080 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5083 // Try an immediate VMVN.
5084 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5085 Val = isNEONModifiedImm(NegatedImm,
5086 SplatUndef.getZExtValue(), SplatBitSize,
5087 DAG, dl, VmovVT, VT.is128BitVector(),
5089 if (Val.getNode()) {
5090 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5091 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5094 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5095 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5096 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5098 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5099 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5105 // Scan through the operands to see if only one value is used.
5107 // As an optimisation, even if more than one value is used it may be more
5108 // profitable to splat with one value then change some lanes.
5110 // Heuristically we decide to do this if the vector has a "dominant" value,
5111 // defined as splatted to more than half of the lanes.
5112 unsigned NumElts = VT.getVectorNumElements();
5113 bool isOnlyLowElement = true;
5114 bool usesOnlyOneValue = true;
5115 bool hasDominantValue = false;
5116 bool isConstant = true;
5118 // Map of the number of times a particular SDValue appears in the
5120 DenseMap<SDValue, unsigned> ValueCounts;
5122 for (unsigned i = 0; i < NumElts; ++i) {
5123 SDValue V = Op.getOperand(i);
5124 if (V.getOpcode() == ISD::UNDEF)
5127 isOnlyLowElement = false;
5128 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5131 ValueCounts.insert(std::make_pair(V, 0));
5132 unsigned &Count = ValueCounts[V];
5134 // Is this value dominant? (takes up more than half of the lanes)
5135 if (++Count > (NumElts / 2)) {
5136 hasDominantValue = true;
5140 if (ValueCounts.size() != 1)
5141 usesOnlyOneValue = false;
5142 if (!Value.getNode() && ValueCounts.size() > 0)
5143 Value = ValueCounts.begin()->first;
5145 if (ValueCounts.size() == 0)
5146 return DAG.getUNDEF(VT);
5148 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5149 // Keep going if we are hitting this case.
5150 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5151 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5153 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5155 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5156 // i32 and try again.
5157 if (hasDominantValue && EltSize <= 32) {
5161 // If we are VDUPing a value that comes directly from a vector, that will
5162 // cause an unnecessary move to and from a GPR, where instead we could
5163 // just use VDUPLANE. We can only do this if the lane being extracted
5164 // is at a constant index, as the VDUP from lane instructions only have
5165 // constant-index forms.
5166 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5167 isa<ConstantSDNode>(Value->getOperand(1))) {
5168 // We need to create a new undef vector to use for the VDUPLANE if the
5169 // size of the vector from which we get the value is different than the
5170 // size of the vector that we need to create. We will insert the element
5171 // such that the register coalescer will remove unnecessary copies.
5172 if (VT != Value->getOperand(0).getValueType()) {
5173 ConstantSDNode *constIndex;
5174 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5175 assert(constIndex && "The index is not a constant!");
5176 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5177 VT.getVectorNumElements();
5178 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5179 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5180 Value, DAG.getConstant(index, dl, MVT::i32)),
5181 DAG.getConstant(index, dl, MVT::i32));
5183 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5184 Value->getOperand(0), Value->getOperand(1));
5186 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5188 if (!usesOnlyOneValue) {
5189 // The dominant value was splatted as 'N', but we now have to insert
5190 // all differing elements.
5191 for (unsigned I = 0; I < NumElts; ++I) {
5192 if (Op.getOperand(I) == Value)
5194 SmallVector<SDValue, 3> Ops;
5196 Ops.push_back(Op.getOperand(I));
5197 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5198 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5203 if (VT.getVectorElementType().isFloatingPoint()) {
5204 SmallVector<SDValue, 8> Ops;
5205 for (unsigned i = 0; i < NumElts; ++i)
5206 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5208 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5209 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5210 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5212 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5214 if (usesOnlyOneValue) {
5215 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5216 if (isConstant && Val.getNode())
5217 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5221 // If all elements are constants and the case above didn't get hit, fall back
5222 // to the default expansion, which will generate a load from the constant
5227 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5229 SDValue shuffle = ReconstructShuffle(Op, DAG);
5230 if (shuffle != SDValue())
5234 // Vectors with 32- or 64-bit elements can be built by directly assigning
5235 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5236 // will be legalized.
5237 if (EltSize >= 32) {
5238 // Do the expansion with floating-point types, since that is what the VFP
5239 // registers are defined to use, and since i64 is not legal.
5240 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5241 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5242 SmallVector<SDValue, 8> Ops;
5243 for (unsigned i = 0; i < NumElts; ++i)
5244 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5245 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5246 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5249 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5250 // know the default expansion would otherwise fall back on something even
5251 // worse. For a vector with one or two non-undef values, that's
5252 // scalar_to_vector for the elements followed by a shuffle (provided the
5253 // shuffle is valid for the target) and materialization element by element
5254 // on the stack followed by a load for everything else.
5255 if (!isConstant && !usesOnlyOneValue) {
5256 SDValue Vec = DAG.getUNDEF(VT);
5257 for (unsigned i = 0 ; i < NumElts; ++i) {
5258 SDValue V = Op.getOperand(i);
5259 if (V.getOpcode() == ISD::UNDEF)
5261 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5262 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5270 // Gather data to see if the operation can be modelled as a
5271 // shuffle in combination with VEXTs.
5272 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5273 SelectionDAG &DAG) const {
5275 EVT VT = Op.getValueType();
5276 unsigned NumElts = VT.getVectorNumElements();
5278 SmallVector<SDValue, 2> SourceVecs;
5279 SmallVector<unsigned, 2> MinElts;
5280 SmallVector<unsigned, 2> MaxElts;
5282 for (unsigned i = 0; i < NumElts; ++i) {
5283 SDValue V = Op.getOperand(i);
5284 if (V.getOpcode() == ISD::UNDEF)
5286 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5287 // A shuffle can only come from building a vector from various
5288 // elements of other vectors.
5290 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5291 VT.getVectorElementType()) {
5292 // This code doesn't know how to handle shuffles where the vector
5293 // element types do not match (this happens because type legalization
5294 // promotes the return type of EXTRACT_VECTOR_ELT).
5295 // FIXME: It might be appropriate to extend this code to handle
5296 // mismatched types.
5300 // Record this extraction against the appropriate vector if possible...
5301 SDValue SourceVec = V.getOperand(0);
5302 // If the element number isn't a constant, we can't effectively
5303 // analyze what's going on.
5304 if (!isa<ConstantSDNode>(V.getOperand(1)))
5306 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5307 bool FoundSource = false;
5308 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5309 if (SourceVecs[j] == SourceVec) {
5310 if (MinElts[j] > EltNo)
5312 if (MaxElts[j] < EltNo)
5319 // Or record a new source if not...
5321 SourceVecs.push_back(SourceVec);
5322 MinElts.push_back(EltNo);
5323 MaxElts.push_back(EltNo);
5327 // Currently only do something sane when at most two source vectors
5329 if (SourceVecs.size() > 2)
5332 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5333 int VEXTOffsets[2] = {0, 0};
5335 // This loop extracts the usage patterns of the source vectors
5336 // and prepares appropriate SDValues for a shuffle if possible.
5337 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5338 if (SourceVecs[i].getValueType() == VT) {
5339 // No VEXT necessary
5340 ShuffleSrcs[i] = SourceVecs[i];
5343 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5344 // It probably isn't worth padding out a smaller vector just to
5345 // break it down again in a shuffle.
5349 // Since only 64-bit and 128-bit vectors are legal on ARM and
5350 // we've eliminated the other cases...
5351 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5352 "unexpected vector sizes in ReconstructShuffle");
5354 if (MaxElts[i] - MinElts[i] >= NumElts) {
5355 // Span too large for a VEXT to cope
5359 if (MinElts[i] >= NumElts) {
5360 // The extraction can just take the second half
5361 VEXTOffsets[i] = NumElts;
5362 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5364 DAG.getIntPtrConstant(NumElts, dl));
5365 } else if (MaxElts[i] < NumElts) {
5366 // The extraction can just take the first half
5368 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5370 DAG.getIntPtrConstant(0, dl));
5372 // An actual VEXT is needed
5373 VEXTOffsets[i] = MinElts[i];
5374 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5376 DAG.getIntPtrConstant(0, dl));
5377 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5379 DAG.getIntPtrConstant(NumElts, dl));
5380 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5381 DAG.getConstant(VEXTOffsets[i], dl,
5386 SmallVector<int, 8> Mask;
5388 for (unsigned i = 0; i < NumElts; ++i) {
5389 SDValue Entry = Op.getOperand(i);
5390 if (Entry.getOpcode() == ISD::UNDEF) {
5395 SDValue ExtractVec = Entry.getOperand(0);
5396 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5397 .getOperand(1))->getSExtValue();
5398 if (ExtractVec == SourceVecs[0]) {
5399 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5401 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5405 // Final check before we try to produce nonsense...
5406 if (isShuffleMaskLegal(Mask, VT))
5407 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5413 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5414 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5415 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5416 /// are assumed to be legal.
5418 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5420 if (VT.getVectorNumElements() == 4 &&
5421 (VT.is128BitVector() || VT.is64BitVector())) {
5422 unsigned PFIndexes[4];
5423 for (unsigned i = 0; i != 4; ++i) {
5427 PFIndexes[i] = M[i];
5430 // Compute the index in the perfect shuffle table.
5431 unsigned PFTableIndex =
5432 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5433 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5434 unsigned Cost = (PFEntry >> 30);
5441 unsigned Imm, WhichResult;
5443 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5444 return (EltSize >= 32 ||
5445 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5446 isVREVMask(M, VT, 64) ||
5447 isVREVMask(M, VT, 32) ||
5448 isVREVMask(M, VT, 16) ||
5449 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5450 isVTBLMask(M, VT) ||
5451 isVTRNMask(M, VT, WhichResult) ||
5452 isVUZPMask(M, VT, WhichResult) ||
5453 isVZIPMask(M, VT, WhichResult) ||
5454 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5455 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5456 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5457 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5460 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5461 /// the specified operations to build the shuffle.
5462 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5463 SDValue RHS, SelectionDAG &DAG,
5465 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5466 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5467 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5470 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5479 OP_VUZPL, // VUZP, left result
5480 OP_VUZPR, // VUZP, right result
5481 OP_VZIPL, // VZIP, left result
5482 OP_VZIPR, // VZIP, right result
5483 OP_VTRNL, // VTRN, left result
5484 OP_VTRNR // VTRN, right result
5487 if (OpNum == OP_COPY) {
5488 if (LHSID == (1*9+2)*9+3) return LHS;
5489 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5493 SDValue OpLHS, OpRHS;
5494 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5495 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5496 EVT VT = OpLHS.getValueType();
5499 default: llvm_unreachable("Unknown shuffle opcode!");
5501 // VREV divides the vector in half and swaps within the half.
5502 if (VT.getVectorElementType() == MVT::i32 ||
5503 VT.getVectorElementType() == MVT::f32)
5504 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5505 // vrev <4 x i16> -> VREV32
5506 if (VT.getVectorElementType() == MVT::i16)
5507 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5508 // vrev <4 x i8> -> VREV16
5509 assert(VT.getVectorElementType() == MVT::i8);
5510 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5515 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5516 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5520 return DAG.getNode(ARMISD::VEXT, dl, VT,
5522 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5525 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5526 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5529 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5530 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5533 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5534 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5538 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5539 ArrayRef<int> ShuffleMask,
5540 SelectionDAG &DAG) {
5541 // Check to see if we can use the VTBL instruction.
5542 SDValue V1 = Op.getOperand(0);
5543 SDValue V2 = Op.getOperand(1);
5546 SmallVector<SDValue, 8> VTBLMask;
5547 for (ArrayRef<int>::iterator
5548 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5549 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5551 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5552 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5553 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5555 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5556 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5559 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5560 SelectionDAG &DAG) {
5562 SDValue OpLHS = Op.getOperand(0);
5563 EVT VT = OpLHS.getValueType();
5565 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5566 "Expect an v8i16/v16i8 type");
5567 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5568 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5569 // extract the first 8 bytes into the top double word and the last 8 bytes
5570 // into the bottom double word. The v8i16 case is similar.
5571 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5572 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5573 DAG.getConstant(ExtractNum, DL, MVT::i32));
5576 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5577 SDValue V1 = Op.getOperand(0);
5578 SDValue V2 = Op.getOperand(1);
5580 EVT VT = Op.getValueType();
5581 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5583 // Convert shuffles that are directly supported on NEON to target-specific
5584 // DAG nodes, instead of keeping them as shuffles and matching them again
5585 // during code selection. This is more efficient and avoids the possibility
5586 // of inconsistencies between legalization and selection.
5587 // FIXME: floating-point vectors should be canonicalized to integer vectors
5588 // of the same time so that they get CSEd properly.
5589 ArrayRef<int> ShuffleMask = SVN->getMask();
5591 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5592 if (EltSize <= 32) {
5593 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5594 int Lane = SVN->getSplatIndex();
5595 // If this is undef splat, generate it via "just" vdup, if possible.
5596 if (Lane == -1) Lane = 0;
5598 // Test if V1 is a SCALAR_TO_VECTOR.
5599 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5600 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5602 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5603 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5605 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5606 !isa<ConstantSDNode>(V1.getOperand(0))) {
5607 bool IsScalarToVector = true;
5608 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5609 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5610 IsScalarToVector = false;
5613 if (IsScalarToVector)
5614 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5616 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5617 DAG.getConstant(Lane, dl, MVT::i32));
5622 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5625 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5626 DAG.getConstant(Imm, dl, MVT::i32));
5629 if (isVREVMask(ShuffleMask, VT, 64))
5630 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5631 if (isVREVMask(ShuffleMask, VT, 32))
5632 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5633 if (isVREVMask(ShuffleMask, VT, 16))
5634 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5636 if (V2->getOpcode() == ISD::UNDEF &&
5637 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5638 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5639 DAG.getConstant(Imm, dl, MVT::i32));
5642 // Check for Neon shuffles that modify both input vectors in place.
5643 // If both results are used, i.e., if there are two shuffles with the same
5644 // source operands and with masks corresponding to both results of one of
5645 // these operations, DAG memoization will ensure that a single node is
5646 // used for both shuffles.
5647 unsigned WhichResult;
5648 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5649 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5650 V1, V2).getValue(WhichResult);
5651 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5652 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5653 V1, V2).getValue(WhichResult);
5654 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5655 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5656 V1, V2).getValue(WhichResult);
5658 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5659 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5660 V1, V1).getValue(WhichResult);
5661 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5662 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5663 V1, V1).getValue(WhichResult);
5664 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5665 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5666 V1, V1).getValue(WhichResult);
5669 // If the shuffle is not directly supported and it has 4 elements, use
5670 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5671 unsigned NumElts = VT.getVectorNumElements();
5673 unsigned PFIndexes[4];
5674 for (unsigned i = 0; i != 4; ++i) {
5675 if (ShuffleMask[i] < 0)
5678 PFIndexes[i] = ShuffleMask[i];
5681 // Compute the index in the perfect shuffle table.
5682 unsigned PFTableIndex =
5683 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5684 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5685 unsigned Cost = (PFEntry >> 30);
5688 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5691 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5692 if (EltSize >= 32) {
5693 // Do the expansion with floating-point types, since that is what the VFP
5694 // registers are defined to use, and since i64 is not legal.
5695 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5696 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5697 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5698 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5699 SmallVector<SDValue, 8> Ops;
5700 for (unsigned i = 0; i < NumElts; ++i) {
5701 if (ShuffleMask[i] < 0)
5702 Ops.push_back(DAG.getUNDEF(EltVT));
5704 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5705 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5706 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5709 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5710 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5713 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5714 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5716 if (VT == MVT::v8i8) {
5717 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5718 if (NewOp.getNode())
5725 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5726 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5727 SDValue Lane = Op.getOperand(2);
5728 if (!isa<ConstantSDNode>(Lane))
5734 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5735 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5736 SDValue Lane = Op.getOperand(1);
5737 if (!isa<ConstantSDNode>(Lane))
5740 SDValue Vec = Op.getOperand(0);
5741 if (Op.getValueType() == MVT::i32 &&
5742 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5744 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5750 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5751 // The only time a CONCAT_VECTORS operation can have legal types is when
5752 // two 64-bit vectors are concatenated to a 128-bit vector.
5753 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5754 "unexpected CONCAT_VECTORS");
5756 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5757 SDValue Op0 = Op.getOperand(0);
5758 SDValue Op1 = Op.getOperand(1);
5759 if (Op0.getOpcode() != ISD::UNDEF)
5760 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5761 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5762 DAG.getIntPtrConstant(0, dl));
5763 if (Op1.getOpcode() != ISD::UNDEF)
5764 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5765 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5766 DAG.getIntPtrConstant(1, dl));
5767 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5770 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5771 /// element has been zero/sign-extended, depending on the isSigned parameter,
5772 /// from an integer type half its size.
5773 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5775 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5776 EVT VT = N->getValueType(0);
5777 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5778 SDNode *BVN = N->getOperand(0).getNode();
5779 if (BVN->getValueType(0) != MVT::v4i32 ||
5780 BVN->getOpcode() != ISD::BUILD_VECTOR)
5782 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5783 unsigned HiElt = 1 - LoElt;
5784 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5785 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5786 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5787 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5788 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5791 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5792 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5795 if (Hi0->isNullValue() && Hi1->isNullValue())
5801 if (N->getOpcode() != ISD::BUILD_VECTOR)
5804 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5805 SDNode *Elt = N->getOperand(i).getNode();
5806 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5807 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5808 unsigned HalfSize = EltSize / 2;
5810 if (!isIntN(HalfSize, C->getSExtValue()))
5813 if (!isUIntN(HalfSize, C->getZExtValue()))
5824 /// isSignExtended - Check if a node is a vector value that is sign-extended
5825 /// or a constant BUILD_VECTOR with sign-extended elements.
5826 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5827 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5829 if (isExtendedBUILD_VECTOR(N, DAG, true))
5834 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5835 /// or a constant BUILD_VECTOR with zero-extended elements.
5836 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5837 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5839 if (isExtendedBUILD_VECTOR(N, DAG, false))
5844 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5845 if (OrigVT.getSizeInBits() >= 64)
5848 assert(OrigVT.isSimple() && "Expecting a simple value type");
5850 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5851 switch (OrigSimpleTy) {
5852 default: llvm_unreachable("Unexpected Vector Type");
5861 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5862 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5863 /// We insert the required extension here to get the vector to fill a D register.
5864 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5867 unsigned ExtOpcode) {
5868 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5869 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5870 // 64-bits we need to insert a new extension so that it will be 64-bits.
5871 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5872 if (OrigTy.getSizeInBits() >= 64)
5875 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5876 EVT NewVT = getExtensionTo64Bits(OrigTy);
5878 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5881 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5882 /// does not do any sign/zero extension. If the original vector is less
5883 /// than 64 bits, an appropriate extension will be added after the load to
5884 /// reach a total size of 64 bits. We have to add the extension separately
5885 /// because ARM does not have a sign/zero extending load for vectors.
5886 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5887 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5889 // The load already has the right type.
5890 if (ExtendedTy == LD->getMemoryVT())
5891 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5892 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5893 LD->isNonTemporal(), LD->isInvariant(),
5894 LD->getAlignment());
5896 // We need to create a zextload/sextload. We cannot just create a load
5897 // followed by a zext/zext node because LowerMUL is also run during normal
5898 // operation legalization where we can't create illegal types.
5899 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5900 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5901 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5902 LD->isNonTemporal(), LD->getAlignment());
5905 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5906 /// extending load, or BUILD_VECTOR with extended elements, return the
5907 /// unextended value. The unextended vector should be 64 bits so that it can
5908 /// be used as an operand to a VMULL instruction. If the original vector size
5909 /// before extension is less than 64 bits we add a an extension to resize
5910 /// the vector to 64 bits.
5911 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5912 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5913 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5914 N->getOperand(0)->getValueType(0),
5918 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5919 return SkipLoadExtensionForVMULL(LD, DAG);
5921 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5922 // have been legalized as a BITCAST from v4i32.
5923 if (N->getOpcode() == ISD::BITCAST) {
5924 SDNode *BVN = N->getOperand(0).getNode();
5925 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5926 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5927 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5928 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5929 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5931 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5932 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5933 EVT VT = N->getValueType(0);
5934 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5935 unsigned NumElts = VT.getVectorNumElements();
5936 MVT TruncVT = MVT::getIntegerVT(EltSize);
5937 SmallVector<SDValue, 8> Ops;
5939 for (unsigned i = 0; i != NumElts; ++i) {
5940 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5941 const APInt &CInt = C->getAPIntValue();
5942 // Element types smaller than 32 bits are not legal, so use i32 elements.
5943 // The values are implicitly truncated so sext vs. zext doesn't matter.
5944 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
5946 return DAG.getNode(ISD::BUILD_VECTOR, dl,
5947 MVT::getVectorVT(TruncVT, NumElts), Ops);
5950 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5951 unsigned Opcode = N->getOpcode();
5952 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5953 SDNode *N0 = N->getOperand(0).getNode();
5954 SDNode *N1 = N->getOperand(1).getNode();
5955 return N0->hasOneUse() && N1->hasOneUse() &&
5956 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5961 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5962 unsigned Opcode = N->getOpcode();
5963 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5964 SDNode *N0 = N->getOperand(0).getNode();
5965 SDNode *N1 = N->getOperand(1).getNode();
5966 return N0->hasOneUse() && N1->hasOneUse() &&
5967 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5972 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5973 // Multiplications are only custom-lowered for 128-bit vectors so that
5974 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5975 EVT VT = Op.getValueType();
5976 assert(VT.is128BitVector() && VT.isInteger() &&
5977 "unexpected type for custom-lowering ISD::MUL");
5978 SDNode *N0 = Op.getOperand(0).getNode();
5979 SDNode *N1 = Op.getOperand(1).getNode();
5980 unsigned NewOpc = 0;
5982 bool isN0SExt = isSignExtended(N0, DAG);
5983 bool isN1SExt = isSignExtended(N1, DAG);
5984 if (isN0SExt && isN1SExt)
5985 NewOpc = ARMISD::VMULLs;
5987 bool isN0ZExt = isZeroExtended(N0, DAG);
5988 bool isN1ZExt = isZeroExtended(N1, DAG);
5989 if (isN0ZExt && isN1ZExt)
5990 NewOpc = ARMISD::VMULLu;
5991 else if (isN1SExt || isN1ZExt) {
5992 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5993 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5994 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5995 NewOpc = ARMISD::VMULLs;
5997 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5998 NewOpc = ARMISD::VMULLu;
6000 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6002 NewOpc = ARMISD::VMULLu;
6008 if (VT == MVT::v2i64)
6009 // Fall through to expand this. It is not legal.
6012 // Other vector multiplications are legal.
6017 // Legalize to a VMULL instruction.
6020 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6022 Op0 = SkipExtensionForVMULL(N0, DAG);
6023 assert(Op0.getValueType().is64BitVector() &&
6024 Op1.getValueType().is64BitVector() &&
6025 "unexpected types for extended operands to VMULL");
6026 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6029 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6030 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6037 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6038 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6039 EVT Op1VT = Op1.getValueType();
6040 return DAG.getNode(N0->getOpcode(), DL, VT,
6041 DAG.getNode(NewOpc, DL, VT,
6042 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6043 DAG.getNode(NewOpc, DL, VT,
6044 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6048 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6050 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6051 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6052 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6053 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6054 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6055 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6056 // Get reciprocal estimate.
6057 // float4 recip = vrecpeq_f32(yf);
6058 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6059 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6061 // Because char has a smaller range than uchar, we can actually get away
6062 // without any newton steps. This requires that we use a weird bias
6063 // of 0xb000, however (again, this has been exhaustively tested).
6064 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6065 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6066 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6067 Y = DAG.getConstant(0xb000, dl, MVT::i32);
6068 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6069 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6070 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6071 // Convert back to short.
6072 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6073 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6078 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6080 // Convert to float.
6081 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6082 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6083 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6084 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6085 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6086 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6088 // Use reciprocal estimate and one refinement step.
6089 // float4 recip = vrecpeq_f32(yf);
6090 // recip *= vrecpsq_f32(yf, recip);
6091 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6092 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6094 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6095 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6097 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6098 // Because short has a smaller range than ushort, we can actually get away
6099 // with only a single newton step. This requires that we use a weird bias
6100 // of 89, however (again, this has been exhaustively tested).
6101 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6102 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6103 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6104 N1 = DAG.getConstant(0x89, dl, MVT::i32);
6105 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6106 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6107 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6108 // Convert back to integer and return.
6109 // return vmovn_s32(vcvt_s32_f32(result));
6110 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6111 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6115 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6116 EVT VT = Op.getValueType();
6117 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6118 "unexpected type for custom-lowering ISD::SDIV");
6121 SDValue N0 = Op.getOperand(0);
6122 SDValue N1 = Op.getOperand(1);
6125 if (VT == MVT::v8i8) {
6126 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6127 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6129 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6130 DAG.getIntPtrConstant(4, dl));
6131 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6132 DAG.getIntPtrConstant(4, dl));
6133 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6134 DAG.getIntPtrConstant(0, dl));
6135 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6136 DAG.getIntPtrConstant(0, dl));
6138 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6139 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6141 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6142 N0 = LowerCONCAT_VECTORS(N0, DAG);
6144 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6147 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6150 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6151 EVT VT = Op.getValueType();
6152 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6153 "unexpected type for custom-lowering ISD::UDIV");
6156 SDValue N0 = Op.getOperand(0);
6157 SDValue N1 = Op.getOperand(1);
6160 if (VT == MVT::v8i8) {
6161 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6162 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6164 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6165 DAG.getIntPtrConstant(4, dl));
6166 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6167 DAG.getIntPtrConstant(4, dl));
6168 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6169 DAG.getIntPtrConstant(0, dl));
6170 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6171 DAG.getIntPtrConstant(0, dl));
6173 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6174 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6176 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6177 N0 = LowerCONCAT_VECTORS(N0, DAG);
6179 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6180 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6186 // v4i16 sdiv ... Convert to float.
6187 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6188 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6189 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6190 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6191 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6192 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6194 // Use reciprocal estimate and two refinement steps.
6195 // float4 recip = vrecpeq_f32(yf);
6196 // recip *= vrecpsq_f32(yf, recip);
6197 // recip *= vrecpsq_f32(yf, recip);
6198 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6199 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6201 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6202 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6204 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6205 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6206 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6208 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6209 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6210 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6211 // and that it will never cause us to return an answer too large).
6212 // float4 result = as_float4(as_int4(xf*recip) + 2);
6213 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6214 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6215 N1 = DAG.getConstant(2, dl, MVT::i32);
6216 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6217 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6218 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6219 // Convert back to integer and return.
6220 // return vmovn_u32(vcvt_s32_f32(result));
6221 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6222 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6226 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6227 EVT VT = Op.getNode()->getValueType(0);
6228 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6231 bool ExtraOp = false;
6232 switch (Op.getOpcode()) {
6233 default: llvm_unreachable("Invalid code");
6234 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6235 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6236 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6237 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6241 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6243 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6244 Op.getOperand(1), Op.getOperand(2));
6247 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6248 assert(Subtarget->isTargetDarwin());
6250 // For iOS, we want to call an alternative entry point: __sincos_stret,
6251 // return values are passed via sret.
6253 SDValue Arg = Op.getOperand(0);
6254 EVT ArgVT = Arg.getValueType();
6255 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6257 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6258 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6260 // Pair of floats / doubles used to pass the result.
6261 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6263 // Create stack object for sret.
6264 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6265 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6266 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6267 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6273 Entry.Ty = RetTy->getPointerTo();
6274 Entry.isSExt = false;
6275 Entry.isZExt = false;
6276 Entry.isSRet = true;
6277 Args.push_back(Entry);
6281 Entry.isSExt = false;
6282 Entry.isZExt = false;
6283 Args.push_back(Entry);
6285 const char *LibcallName = (ArgVT == MVT::f64)
6286 ? "__sincos_stret" : "__sincosf_stret";
6287 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6289 TargetLowering::CallLoweringInfo CLI(DAG);
6290 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6291 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6293 .setDiscardResult();
6295 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6297 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6298 MachinePointerInfo(), false, false, false, 0);
6300 // Address of cos field.
6301 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6302 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6303 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6304 MachinePointerInfo(), false, false, false, 0);
6306 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6307 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6308 LoadSin.getValue(0), LoadCos.getValue(0));
6311 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6312 // Monotonic load/store is legal for all targets
6313 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6316 // Acquire/Release load/store is not legal for targets without a
6317 // dmb or equivalent available.
6321 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6322 SmallVectorImpl<SDValue> &Results,
6324 const ARMSubtarget *Subtarget) {
6326 SDValue Cycles32, OutChain;
6328 if (Subtarget->hasPerfMon()) {
6329 // Under Power Management extensions, the cycle-count is:
6330 // mrc p15, #0, <Rt>, c9, c13, #0
6331 SDValue Ops[] = { N->getOperand(0), // Chain
6332 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6333 DAG.getConstant(15, DL, MVT::i32),
6334 DAG.getConstant(0, DL, MVT::i32),
6335 DAG.getConstant(9, DL, MVT::i32),
6336 DAG.getConstant(13, DL, MVT::i32),
6337 DAG.getConstant(0, DL, MVT::i32)
6340 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6341 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6342 OutChain = Cycles32.getValue(1);
6344 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6345 // there are older ARM CPUs that have implementation-specific ways of
6346 // obtaining this information (FIXME!).
6347 Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6348 OutChain = DAG.getEntryNode();
6352 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6353 Cycles32, DAG.getConstant(0, DL, MVT::i32));
6354 Results.push_back(Cycles64);
6355 Results.push_back(OutChain);
6358 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6359 switch (Op.getOpcode()) {
6360 default: llvm_unreachable("Don't know how to custom lower this!");
6361 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6362 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6363 case ISD::GlobalAddress:
6364 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6365 default: llvm_unreachable("unknown object format");
6367 return LowerGlobalAddressWindows(Op, DAG);
6369 return LowerGlobalAddressELF(Op, DAG);
6371 return LowerGlobalAddressDarwin(Op, DAG);
6373 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6374 case ISD::SELECT: return LowerSELECT(Op, DAG);
6375 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6376 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6377 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6378 case ISD::VASTART: return LowerVASTART(Op, DAG);
6379 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6380 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6381 case ISD::SINT_TO_FP:
6382 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6383 case ISD::FP_TO_SINT:
6384 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6385 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6386 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6387 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6388 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6389 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6390 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6391 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6393 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6396 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6397 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6398 case ISD::SRL_PARTS:
6399 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6400 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6401 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6402 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6403 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6404 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6405 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6406 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6407 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6408 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6409 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6410 case ISD::MUL: return LowerMUL(Op, DAG);
6411 case ISD::SDIV: return LowerSDIV(Op, DAG);
6412 case ISD::UDIV: return LowerUDIV(Op, DAG);
6416 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6421 return LowerXALUO(Op, DAG);
6422 case ISD::ATOMIC_LOAD:
6423 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6424 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6426 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6427 case ISD::DYNAMIC_STACKALLOC:
6428 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6429 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6430 llvm_unreachable("Don't know how to custom lower this!");
6431 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6432 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6436 /// ReplaceNodeResults - Replace the results of node with an illegal result
6437 /// type with new values built out of custom code.
6438 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6439 SmallVectorImpl<SDValue>&Results,
6440 SelectionDAG &DAG) const {
6442 switch (N->getOpcode()) {
6444 llvm_unreachable("Don't know how to custom expand this!");
6446 Res = ExpandBITCAST(N, DAG);
6450 Res = Expand64BitShift(N, DAG, Subtarget);
6452 case ISD::READCYCLECOUNTER:
6453 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6457 Results.push_back(Res);
6460 //===----------------------------------------------------------------------===//
6461 // ARM Scheduler Hooks
6462 //===----------------------------------------------------------------------===//
6464 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6465 /// registers the function context.
6466 void ARMTargetLowering::
6467 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6468 MachineBasicBlock *DispatchBB, int FI) const {
6469 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6470 DebugLoc dl = MI->getDebugLoc();
6471 MachineFunction *MF = MBB->getParent();
6472 MachineRegisterInfo *MRI = &MF->getRegInfo();
6473 MachineConstantPool *MCP = MF->getConstantPool();
6474 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6475 const Function *F = MF->getFunction();
6477 bool isThumb = Subtarget->isThumb();
6478 bool isThumb2 = Subtarget->isThumb2();
6480 unsigned PCLabelId = AFI->createPICLabelUId();
6481 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6482 ARMConstantPoolValue *CPV =
6483 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6484 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6486 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6487 : &ARM::GPRRegClass;
6489 // Grab constant pool and fixed stack memory operands.
6490 MachineMemOperand *CPMMO =
6491 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6492 MachineMemOperand::MOLoad, 4, 4);
6494 MachineMemOperand *FIMMOSt =
6495 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6496 MachineMemOperand::MOStore, 4, 4);
6498 // Load the address of the dispatch MBB into the jump buffer.
6500 // Incoming value: jbuf
6501 // ldr.n r5, LCPI1_1
6504 // str r5, [$jbuf, #+4] ; &jbuf[1]
6505 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6506 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6507 .addConstantPoolIndex(CPI)
6508 .addMemOperand(CPMMO));
6509 // Set the low bit because of thumb mode.
6510 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6512 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6513 .addReg(NewVReg1, RegState::Kill)
6515 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6516 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6517 .addReg(NewVReg2, RegState::Kill)
6519 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6520 .addReg(NewVReg3, RegState::Kill)
6522 .addImm(36) // &jbuf[1] :: pc
6523 .addMemOperand(FIMMOSt));
6524 } else if (isThumb) {
6525 // Incoming value: jbuf
6526 // ldr.n r1, LCPI1_4
6530 // add r2, $jbuf, #+4 ; &jbuf[1]
6532 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6533 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6534 .addConstantPoolIndex(CPI)
6535 .addMemOperand(CPMMO));
6536 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6537 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6538 .addReg(NewVReg1, RegState::Kill)
6540 // Set the low bit because of thumb mode.
6541 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6542 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6543 .addReg(ARM::CPSR, RegState::Define)
6545 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6546 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6547 .addReg(ARM::CPSR, RegState::Define)
6548 .addReg(NewVReg2, RegState::Kill)
6549 .addReg(NewVReg3, RegState::Kill));
6550 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6551 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6553 .addImm(36); // &jbuf[1] :: pc
6554 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6555 .addReg(NewVReg4, RegState::Kill)
6556 .addReg(NewVReg5, RegState::Kill)
6558 .addMemOperand(FIMMOSt));
6560 // Incoming value: jbuf
6563 // str r1, [$jbuf, #+4] ; &jbuf[1]
6564 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6565 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6566 .addConstantPoolIndex(CPI)
6568 .addMemOperand(CPMMO));
6569 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6570 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6571 .addReg(NewVReg1, RegState::Kill)
6572 .addImm(PCLabelId));
6573 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6574 .addReg(NewVReg2, RegState::Kill)
6576 .addImm(36) // &jbuf[1] :: pc
6577 .addMemOperand(FIMMOSt));
6581 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6582 MachineBasicBlock *MBB) const {
6583 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6584 DebugLoc dl = MI->getDebugLoc();
6585 MachineFunction *MF = MBB->getParent();
6586 MachineRegisterInfo *MRI = &MF->getRegInfo();
6587 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6588 MachineFrameInfo *MFI = MF->getFrameInfo();
6589 int FI = MFI->getFunctionContextIndex();
6591 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6592 : &ARM::GPRnopcRegClass;
6594 // Get a mapping of the call site numbers to all of the landing pads they're
6596 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6597 unsigned MaxCSNum = 0;
6598 MachineModuleInfo &MMI = MF->getMMI();
6599 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6601 if (!BB->isLandingPad()) continue;
6603 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6605 for (MachineBasicBlock::iterator
6606 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6607 if (!II->isEHLabel()) continue;
6609 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6610 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6612 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6613 for (SmallVectorImpl<unsigned>::iterator
6614 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6615 CSI != CSE; ++CSI) {
6616 CallSiteNumToLPad[*CSI].push_back(BB);
6617 MaxCSNum = std::max(MaxCSNum, *CSI);
6623 // Get an ordered list of the machine basic blocks for the jump table.
6624 std::vector<MachineBasicBlock*> LPadList;
6625 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6626 LPadList.reserve(CallSiteNumToLPad.size());
6627 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6628 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6629 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6630 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6631 LPadList.push_back(*II);
6632 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6636 assert(!LPadList.empty() &&
6637 "No landing pad destinations for the dispatch jump table!");
6639 // Create the jump table and associated information.
6640 MachineJumpTableInfo *JTI =
6641 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6642 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6643 unsigned UId = AFI->createJumpTableUId();
6644 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6646 // Create the MBBs for the dispatch code.
6648 // Shove the dispatch's address into the return slot in the function context.
6649 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6650 DispatchBB->setIsLandingPad();
6652 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6653 unsigned trap_opcode;
6654 if (Subtarget->isThumb())
6655 trap_opcode = ARM::tTRAP;
6657 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6659 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6660 DispatchBB->addSuccessor(TrapBB);
6662 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6663 DispatchBB->addSuccessor(DispContBB);
6666 MF->insert(MF->end(), DispatchBB);
6667 MF->insert(MF->end(), DispContBB);
6668 MF->insert(MF->end(), TrapBB);
6670 // Insert code into the entry block that creates and registers the function
6672 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6674 MachineMemOperand *FIMMOLd =
6675 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6676 MachineMemOperand::MOLoad |
6677 MachineMemOperand::MOVolatile, 4, 4);
6679 MachineInstrBuilder MIB;
6680 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6682 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6683 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6685 // Add a register mask with no preserved registers. This results in all
6686 // registers being marked as clobbered.
6687 MIB.addRegMask(RI.getNoPreservedMask());
6689 unsigned NumLPads = LPadList.size();
6690 if (Subtarget->isThumb2()) {
6691 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6692 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6695 .addMemOperand(FIMMOLd));
6697 if (NumLPads < 256) {
6698 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6700 .addImm(LPadList.size()));
6702 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6703 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6704 .addImm(NumLPads & 0xFFFF));
6706 unsigned VReg2 = VReg1;
6707 if ((NumLPads & 0xFFFF0000) != 0) {
6708 VReg2 = MRI->createVirtualRegister(TRC);
6709 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6711 .addImm(NumLPads >> 16));
6714 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6719 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6724 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6725 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6726 .addJumpTableIndex(MJTI)
6729 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6732 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6733 .addReg(NewVReg3, RegState::Kill)
6735 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6737 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6738 .addReg(NewVReg4, RegState::Kill)
6740 .addJumpTableIndex(MJTI)
6742 } else if (Subtarget->isThumb()) {
6743 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6744 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6747 .addMemOperand(FIMMOLd));
6749 if (NumLPads < 256) {
6750 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6754 MachineConstantPool *ConstantPool = MF->getConstantPool();
6755 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6756 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6758 // MachineConstantPool wants an explicit alignment.
6759 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6761 Align = getDataLayout()->getTypeAllocSize(C->getType());
6762 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6764 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6765 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6766 .addReg(VReg1, RegState::Define)
6767 .addConstantPoolIndex(Idx));
6768 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6773 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6778 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6779 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6780 .addReg(ARM::CPSR, RegState::Define)
6784 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6785 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6786 .addJumpTableIndex(MJTI)
6789 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6790 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6791 .addReg(ARM::CPSR, RegState::Define)
6792 .addReg(NewVReg2, RegState::Kill)
6795 MachineMemOperand *JTMMOLd =
6796 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6797 MachineMemOperand::MOLoad, 4, 4);
6799 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6800 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6801 .addReg(NewVReg4, RegState::Kill)
6803 .addMemOperand(JTMMOLd));
6805 unsigned NewVReg6 = NewVReg5;
6806 if (RelocM == Reloc::PIC_) {
6807 NewVReg6 = MRI->createVirtualRegister(TRC);
6808 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6809 .addReg(ARM::CPSR, RegState::Define)
6810 .addReg(NewVReg5, RegState::Kill)
6814 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6815 .addReg(NewVReg6, RegState::Kill)
6816 .addJumpTableIndex(MJTI)
6819 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6820 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6823 .addMemOperand(FIMMOLd));
6825 if (NumLPads < 256) {
6826 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6829 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6830 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6831 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6832 .addImm(NumLPads & 0xFFFF));
6834 unsigned VReg2 = VReg1;
6835 if ((NumLPads & 0xFFFF0000) != 0) {
6836 VReg2 = MRI->createVirtualRegister(TRC);
6837 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6839 .addImm(NumLPads >> 16));
6842 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6846 MachineConstantPool *ConstantPool = MF->getConstantPool();
6847 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6848 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6850 // MachineConstantPool wants an explicit alignment.
6851 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6853 Align = getDataLayout()->getTypeAllocSize(C->getType());
6854 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6856 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6857 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6858 .addReg(VReg1, RegState::Define)
6859 .addConstantPoolIndex(Idx)
6861 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6863 .addReg(VReg1, RegState::Kill));
6866 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6871 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6873 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6875 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6876 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6877 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6878 .addJumpTableIndex(MJTI)
6881 MachineMemOperand *JTMMOLd =
6882 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6883 MachineMemOperand::MOLoad, 4, 4);
6884 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6886 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6887 .addReg(NewVReg3, RegState::Kill)
6890 .addMemOperand(JTMMOLd));
6892 if (RelocM == Reloc::PIC_) {
6893 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6894 .addReg(NewVReg5, RegState::Kill)
6896 .addJumpTableIndex(MJTI)
6899 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6900 .addReg(NewVReg5, RegState::Kill)
6901 .addJumpTableIndex(MJTI)
6906 // Add the jump table entries as successors to the MBB.
6907 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6908 for (std::vector<MachineBasicBlock*>::iterator
6909 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6910 MachineBasicBlock *CurMBB = *I;
6911 if (SeenMBBs.insert(CurMBB).second)
6912 DispContBB->addSuccessor(CurMBB);
6915 // N.B. the order the invoke BBs are processed in doesn't matter here.
6916 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6917 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6918 for (MachineBasicBlock *BB : InvokeBBs) {
6920 // Remove the landing pad successor from the invoke block and replace it
6921 // with the new dispatch block.
6922 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6924 while (!Successors.empty()) {
6925 MachineBasicBlock *SMBB = Successors.pop_back_val();
6926 if (SMBB->isLandingPad()) {
6927 BB->removeSuccessor(SMBB);
6928 MBBLPads.push_back(SMBB);
6932 BB->addSuccessor(DispatchBB);
6934 // Find the invoke call and mark all of the callee-saved registers as
6935 // 'implicit defined' so that they're spilled. This prevents code from
6936 // moving instructions to before the EH block, where they will never be
6938 for (MachineBasicBlock::reverse_iterator
6939 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6940 if (!II->isCall()) continue;
6942 DenseMap<unsigned, bool> DefRegs;
6943 for (MachineInstr::mop_iterator
6944 OI = II->operands_begin(), OE = II->operands_end();
6946 if (!OI->isReg()) continue;
6947 DefRegs[OI->getReg()] = true;
6950 MachineInstrBuilder MIB(*MF, &*II);
6952 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6953 unsigned Reg = SavedRegs[i];
6954 if (Subtarget->isThumb2() &&
6955 !ARM::tGPRRegClass.contains(Reg) &&
6956 !ARM::hGPRRegClass.contains(Reg))
6958 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6960 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6963 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6970 // Mark all former landing pads as non-landing pads. The dispatch is the only
6972 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6973 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6974 (*I)->setIsLandingPad(false);
6976 // The instruction is gone now.
6977 MI->eraseFromParent();
6981 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6982 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6983 E = MBB->succ_end(); I != E; ++I)
6986 llvm_unreachable("Expecting a BB with two successors!");
6989 /// Return the load opcode for a given load size. If load size >= 8,
6990 /// neon opcode will be returned.
6991 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6993 return LdSize == 16 ? ARM::VLD1q32wb_fixed
6994 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6996 return LdSize == 4 ? ARM::tLDRi
6997 : LdSize == 2 ? ARM::tLDRHi
6998 : LdSize == 1 ? ARM::tLDRBi : 0;
7000 return LdSize == 4 ? ARM::t2LDR_POST
7001 : LdSize == 2 ? ARM::t2LDRH_POST
7002 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7003 return LdSize == 4 ? ARM::LDR_POST_IMM
7004 : LdSize == 2 ? ARM::LDRH_POST
7005 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7008 /// Return the store opcode for a given store size. If store size >= 8,
7009 /// neon opcode will be returned.
7010 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7012 return StSize == 16 ? ARM::VST1q32wb_fixed
7013 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7015 return StSize == 4 ? ARM::tSTRi
7016 : StSize == 2 ? ARM::tSTRHi
7017 : StSize == 1 ? ARM::tSTRBi : 0;
7019 return StSize == 4 ? ARM::t2STR_POST
7020 : StSize == 2 ? ARM::t2STRH_POST
7021 : StSize == 1 ? ARM::t2STRB_POST : 0;
7022 return StSize == 4 ? ARM::STR_POST_IMM
7023 : StSize == 2 ? ARM::STRH_POST
7024 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7027 /// Emit a post-increment load operation with given size. The instructions
7028 /// will be added to BB at Pos.
7029 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7030 const TargetInstrInfo *TII, DebugLoc dl,
7031 unsigned LdSize, unsigned Data, unsigned AddrIn,
7032 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7033 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7034 assert(LdOpc != 0 && "Should have a load opcode");
7036 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7037 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7039 } else if (IsThumb1) {
7040 // load + update AddrIn
7041 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7042 .addReg(AddrIn).addImm(0));
7043 MachineInstrBuilder MIB =
7044 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7045 MIB = AddDefaultT1CC(MIB);
7046 MIB.addReg(AddrIn).addImm(LdSize);
7047 AddDefaultPred(MIB);
7048 } else if (IsThumb2) {
7049 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7050 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7053 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7054 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7055 .addReg(0).addImm(LdSize));
7059 /// Emit a post-increment store operation with given size. The instructions
7060 /// will be added to BB at Pos.
7061 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7062 const TargetInstrInfo *TII, DebugLoc dl,
7063 unsigned StSize, unsigned Data, unsigned AddrIn,
7064 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7065 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7066 assert(StOpc != 0 && "Should have a store opcode");
7068 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7069 .addReg(AddrIn).addImm(0).addReg(Data));
7070 } else if (IsThumb1) {
7071 // store + update AddrIn
7072 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7073 .addReg(AddrIn).addImm(0));
7074 MachineInstrBuilder MIB =
7075 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7076 MIB = AddDefaultT1CC(MIB);
7077 MIB.addReg(AddrIn).addImm(StSize);
7078 AddDefaultPred(MIB);
7079 } else if (IsThumb2) {
7080 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7081 .addReg(Data).addReg(AddrIn).addImm(StSize));
7083 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7084 .addReg(Data).addReg(AddrIn).addReg(0)
7090 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7091 MachineBasicBlock *BB) const {
7092 // This pseudo instruction has 3 operands: dst, src, size
7093 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7094 // Otherwise, we will generate unrolled scalar copies.
7095 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7096 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7097 MachineFunction::iterator It = BB;
7100 unsigned dest = MI->getOperand(0).getReg();
7101 unsigned src = MI->getOperand(1).getReg();
7102 unsigned SizeVal = MI->getOperand(2).getImm();
7103 unsigned Align = MI->getOperand(3).getImm();
7104 DebugLoc dl = MI->getDebugLoc();
7106 MachineFunction *MF = BB->getParent();
7107 MachineRegisterInfo &MRI = MF->getRegInfo();
7108 unsigned UnitSize = 0;
7109 const TargetRegisterClass *TRC = nullptr;
7110 const TargetRegisterClass *VecTRC = nullptr;
7112 bool IsThumb1 = Subtarget->isThumb1Only();
7113 bool IsThumb2 = Subtarget->isThumb2();
7117 } else if (Align & 2) {
7120 // Check whether we can use NEON instructions.
7121 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7122 Subtarget->hasNEON()) {
7123 if ((Align % 16 == 0) && SizeVal >= 16)
7125 else if ((Align % 8 == 0) && SizeVal >= 8)
7128 // Can't use NEON instructions.
7133 // Select the correct opcode and register class for unit size load/store
7134 bool IsNeon = UnitSize >= 8;
7135 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7137 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7138 : UnitSize == 8 ? &ARM::DPRRegClass
7141 unsigned BytesLeft = SizeVal % UnitSize;
7142 unsigned LoopSize = SizeVal - BytesLeft;
7144 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7145 // Use LDR and STR to copy.
7146 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7147 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7148 unsigned srcIn = src;
7149 unsigned destIn = dest;
7150 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7151 unsigned srcOut = MRI.createVirtualRegister(TRC);
7152 unsigned destOut = MRI.createVirtualRegister(TRC);
7153 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7154 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7155 IsThumb1, IsThumb2);
7156 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7157 IsThumb1, IsThumb2);
7162 // Handle the leftover bytes with LDRB and STRB.
7163 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7164 // [destOut] = STRB_POST(scratch, destIn, 1)
7165 for (unsigned i = 0; i < BytesLeft; i++) {
7166 unsigned srcOut = MRI.createVirtualRegister(TRC);
7167 unsigned destOut = MRI.createVirtualRegister(TRC);
7168 unsigned scratch = MRI.createVirtualRegister(TRC);
7169 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7170 IsThumb1, IsThumb2);
7171 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7172 IsThumb1, IsThumb2);
7176 MI->eraseFromParent(); // The instruction is gone now.
7180 // Expand the pseudo op to a loop.
7183 // movw varEnd, # --> with thumb2
7185 // ldrcp varEnd, idx --> without thumb2
7186 // fallthrough --> loopMBB
7188 // PHI varPhi, varEnd, varLoop
7189 // PHI srcPhi, src, srcLoop
7190 // PHI destPhi, dst, destLoop
7191 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7192 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7193 // subs varLoop, varPhi, #UnitSize
7195 // fallthrough --> exitMBB
7197 // epilogue to handle left-over bytes
7198 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7199 // [destOut] = STRB_POST(scratch, destLoop, 1)
7200 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7201 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7202 MF->insert(It, loopMBB);
7203 MF->insert(It, exitMBB);
7205 // Transfer the remainder of BB and its successor edges to exitMBB.
7206 exitMBB->splice(exitMBB->begin(), BB,
7207 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7208 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7210 // Load an immediate to varEnd.
7211 unsigned varEnd = MRI.createVirtualRegister(TRC);
7212 if (Subtarget->useMovt(*MF)) {
7213 unsigned Vtmp = varEnd;
7214 if ((LoopSize & 0xFFFF0000) != 0)
7215 Vtmp = MRI.createVirtualRegister(TRC);
7216 AddDefaultPred(BuildMI(BB, dl,
7217 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7218 Vtmp).addImm(LoopSize & 0xFFFF));
7220 if ((LoopSize & 0xFFFF0000) != 0)
7221 AddDefaultPred(BuildMI(BB, dl,
7222 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7225 .addImm(LoopSize >> 16));
7227 MachineConstantPool *ConstantPool = MF->getConstantPool();
7228 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7229 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7231 // MachineConstantPool wants an explicit alignment.
7232 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7234 Align = getDataLayout()->getTypeAllocSize(C->getType());
7235 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7238 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7239 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7241 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7242 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7244 BB->addSuccessor(loopMBB);
7246 // Generate the loop body:
7247 // varPhi = PHI(varLoop, varEnd)
7248 // srcPhi = PHI(srcLoop, src)
7249 // destPhi = PHI(destLoop, dst)
7250 MachineBasicBlock *entryBB = BB;
7252 unsigned varLoop = MRI.createVirtualRegister(TRC);
7253 unsigned varPhi = MRI.createVirtualRegister(TRC);
7254 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7255 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7256 unsigned destLoop = MRI.createVirtualRegister(TRC);
7257 unsigned destPhi = MRI.createVirtualRegister(TRC);
7259 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7260 .addReg(varLoop).addMBB(loopMBB)
7261 .addReg(varEnd).addMBB(entryBB);
7262 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7263 .addReg(srcLoop).addMBB(loopMBB)
7264 .addReg(src).addMBB(entryBB);
7265 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7266 .addReg(destLoop).addMBB(loopMBB)
7267 .addReg(dest).addMBB(entryBB);
7269 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7270 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7271 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7272 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7273 IsThumb1, IsThumb2);
7274 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7275 IsThumb1, IsThumb2);
7277 // Decrement loop variable by UnitSize.
7279 MachineInstrBuilder MIB =
7280 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7281 MIB = AddDefaultT1CC(MIB);
7282 MIB.addReg(varPhi).addImm(UnitSize);
7283 AddDefaultPred(MIB);
7285 MachineInstrBuilder MIB =
7286 BuildMI(*BB, BB->end(), dl,
7287 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7288 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7289 MIB->getOperand(5).setReg(ARM::CPSR);
7290 MIB->getOperand(5).setIsDef(true);
7292 BuildMI(*BB, BB->end(), dl,
7293 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7294 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7296 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7297 BB->addSuccessor(loopMBB);
7298 BB->addSuccessor(exitMBB);
7300 // Add epilogue to handle BytesLeft.
7302 MachineInstr *StartOfExit = exitMBB->begin();
7304 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7305 // [destOut] = STRB_POST(scratch, destLoop, 1)
7306 unsigned srcIn = srcLoop;
7307 unsigned destIn = destLoop;
7308 for (unsigned i = 0; i < BytesLeft; i++) {
7309 unsigned srcOut = MRI.createVirtualRegister(TRC);
7310 unsigned destOut = MRI.createVirtualRegister(TRC);
7311 unsigned scratch = MRI.createVirtualRegister(TRC);
7312 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7313 IsThumb1, IsThumb2);
7314 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7315 IsThumb1, IsThumb2);
7320 MI->eraseFromParent(); // The instruction is gone now.
7325 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7326 MachineBasicBlock *MBB) const {
7327 const TargetMachine &TM = getTargetMachine();
7328 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7329 DebugLoc DL = MI->getDebugLoc();
7331 assert(Subtarget->isTargetWindows() &&
7332 "__chkstk is only supported on Windows");
7333 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7335 // __chkstk takes the number of words to allocate on the stack in R4, and
7336 // returns the stack adjustment in number of bytes in R4. This will not
7337 // clober any other registers (other than the obvious lr).
7339 // Although, technically, IP should be considered a register which may be
7340 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7341 // thumb-2 environment, so there is no interworking required. As a result, we
7342 // do not expect a veneer to be emitted by the linker, clobbering IP.
7344 // Each module receives its own copy of __chkstk, so no import thunk is
7345 // required, again, ensuring that IP is not clobbered.
7347 // Finally, although some linkers may theoretically provide a trampoline for
7348 // out of range calls (which is quite common due to a 32M range limitation of
7349 // branches for Thumb), we can generate the long-call version via
7350 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7353 switch (TM.getCodeModel()) {
7354 case CodeModel::Small:
7355 case CodeModel::Medium:
7356 case CodeModel::Default:
7357 case CodeModel::Kernel:
7358 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7359 .addImm((unsigned)ARMCC::AL).addReg(0)
7360 .addExternalSymbol("__chkstk")
7361 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7362 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7363 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7365 case CodeModel::Large:
7366 case CodeModel::JITDefault: {
7367 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7368 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7370 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7371 .addExternalSymbol("__chkstk");
7372 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7373 .addImm((unsigned)ARMCC::AL).addReg(0)
7374 .addReg(Reg, RegState::Kill)
7375 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7376 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7377 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7382 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7384 .addReg(ARM::SP).addReg(ARM::R4)));
7386 MI->eraseFromParent();
7391 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7392 MachineBasicBlock *BB) const {
7393 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7394 DebugLoc dl = MI->getDebugLoc();
7395 bool isThumb2 = Subtarget->isThumb2();
7396 switch (MI->getOpcode()) {
7399 llvm_unreachable("Unexpected instr type to insert");
7401 // The Thumb2 pre-indexed stores have the same MI operands, they just
7402 // define them differently in the .td files from the isel patterns, so
7403 // they need pseudos.
7404 case ARM::t2STR_preidx:
7405 MI->setDesc(TII->get(ARM::t2STR_PRE));
7407 case ARM::t2STRB_preidx:
7408 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7410 case ARM::t2STRH_preidx:
7411 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7414 case ARM::STRi_preidx:
7415 case ARM::STRBi_preidx: {
7416 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7417 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7418 // Decode the offset.
7419 unsigned Offset = MI->getOperand(4).getImm();
7420 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7421 Offset = ARM_AM::getAM2Offset(Offset);
7425 MachineMemOperand *MMO = *MI->memoperands_begin();
7426 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7427 .addOperand(MI->getOperand(0)) // Rn_wb
7428 .addOperand(MI->getOperand(1)) // Rt
7429 .addOperand(MI->getOperand(2)) // Rn
7430 .addImm(Offset) // offset (skip GPR==zero_reg)
7431 .addOperand(MI->getOperand(5)) // pred
7432 .addOperand(MI->getOperand(6))
7433 .addMemOperand(MMO);
7434 MI->eraseFromParent();
7437 case ARM::STRr_preidx:
7438 case ARM::STRBr_preidx:
7439 case ARM::STRH_preidx: {
7441 switch (MI->getOpcode()) {
7442 default: llvm_unreachable("unexpected opcode!");
7443 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7444 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7445 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7447 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7448 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7449 MIB.addOperand(MI->getOperand(i));
7450 MI->eraseFromParent();
7454 case ARM::tMOVCCr_pseudo: {
7455 // To "insert" a SELECT_CC instruction, we actually have to insert the
7456 // diamond control-flow pattern. The incoming instruction knows the
7457 // destination vreg to set, the condition code register to branch on, the
7458 // true/false values to select between, and a branch opcode to use.
7459 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7460 MachineFunction::iterator It = BB;
7466 // cmpTY ccX, r1, r2
7468 // fallthrough --> copy0MBB
7469 MachineBasicBlock *thisMBB = BB;
7470 MachineFunction *F = BB->getParent();
7471 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7472 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7473 F->insert(It, copy0MBB);
7474 F->insert(It, sinkMBB);
7476 // Transfer the remainder of BB and its successor edges to sinkMBB.
7477 sinkMBB->splice(sinkMBB->begin(), BB,
7478 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7479 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7481 BB->addSuccessor(copy0MBB);
7482 BB->addSuccessor(sinkMBB);
7484 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7485 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7488 // %FalseValue = ...
7489 // # fallthrough to sinkMBB
7492 // Update machine-CFG edges
7493 BB->addSuccessor(sinkMBB);
7496 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7499 BuildMI(*BB, BB->begin(), dl,
7500 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7501 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7502 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7504 MI->eraseFromParent(); // The pseudo instruction is gone now.
7509 case ARM::BCCZi64: {
7510 // If there is an unconditional branch to the other successor, remove it.
7511 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7513 // Compare both parts that make up the double comparison separately for
7515 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7517 unsigned LHS1 = MI->getOperand(1).getReg();
7518 unsigned LHS2 = MI->getOperand(2).getReg();
7520 AddDefaultPred(BuildMI(BB, dl,
7521 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7522 .addReg(LHS1).addImm(0));
7523 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7524 .addReg(LHS2).addImm(0)
7525 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7527 unsigned RHS1 = MI->getOperand(3).getReg();
7528 unsigned RHS2 = MI->getOperand(4).getReg();
7529 AddDefaultPred(BuildMI(BB, dl,
7530 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7531 .addReg(LHS1).addReg(RHS1));
7532 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7533 .addReg(LHS2).addReg(RHS2)
7534 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7537 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7538 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7539 if (MI->getOperand(0).getImm() == ARMCC::NE)
7540 std::swap(destMBB, exitMBB);
7542 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7543 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7545 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7547 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7549 MI->eraseFromParent(); // The pseudo instruction is gone now.
7553 case ARM::Int_eh_sjlj_setjmp:
7554 case ARM::Int_eh_sjlj_setjmp_nofp:
7555 case ARM::tInt_eh_sjlj_setjmp:
7556 case ARM::t2Int_eh_sjlj_setjmp:
7557 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7558 EmitSjLjDispatchBlock(MI, BB);
7563 // To insert an ABS instruction, we have to insert the
7564 // diamond control-flow pattern. The incoming instruction knows the
7565 // source vreg to test against 0, the destination vreg to set,
7566 // the condition code register to branch on, the
7567 // true/false values to select between, and a branch opcode to use.
7572 // BCC (branch to SinkBB if V0 >= 0)
7573 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7574 // SinkBB: V1 = PHI(V2, V3)
7575 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7576 MachineFunction::iterator BBI = BB;
7578 MachineFunction *Fn = BB->getParent();
7579 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7580 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7581 Fn->insert(BBI, RSBBB);
7582 Fn->insert(BBI, SinkBB);
7584 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7585 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7586 bool ABSSrcKIll = MI->getOperand(1).isKill();
7587 bool isThumb2 = Subtarget->isThumb2();
7588 MachineRegisterInfo &MRI = Fn->getRegInfo();
7589 // In Thumb mode S must not be specified if source register is the SP or
7590 // PC and if destination register is the SP, so restrict register class
7591 unsigned NewRsbDstReg =
7592 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7594 // Transfer the remainder of BB and its successor edges to sinkMBB.
7595 SinkBB->splice(SinkBB->begin(), BB,
7596 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7597 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7599 BB->addSuccessor(RSBBB);
7600 BB->addSuccessor(SinkBB);
7602 // fall through to SinkMBB
7603 RSBBB->addSuccessor(SinkBB);
7605 // insert a cmp at the end of BB
7606 AddDefaultPred(BuildMI(BB, dl,
7607 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7608 .addReg(ABSSrcReg).addImm(0));
7610 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7612 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7613 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7615 // insert rsbri in RSBBB
7616 // Note: BCC and rsbri will be converted into predicated rsbmi
7617 // by if-conversion pass
7618 BuildMI(*RSBBB, RSBBB->begin(), dl,
7619 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7620 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7621 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7623 // insert PHI in SinkBB,
7624 // reuse ABSDstReg to not change uses of ABS instruction
7625 BuildMI(*SinkBB, SinkBB->begin(), dl,
7626 TII->get(ARM::PHI), ABSDstReg)
7627 .addReg(NewRsbDstReg).addMBB(RSBBB)
7628 .addReg(ABSSrcReg).addMBB(BB);
7630 // remove ABS instruction
7631 MI->eraseFromParent();
7633 // return last added BB
7636 case ARM::COPY_STRUCT_BYVAL_I32:
7638 return EmitStructByval(MI, BB);
7639 case ARM::WIN__CHKSTK:
7640 return EmitLowered__chkstk(MI, BB);
7644 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7645 SDNode *Node) const {
7646 const MCInstrDesc *MCID = &MI->getDesc();
7647 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7648 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7649 // operand is still set to noreg. If needed, set the optional operand's
7650 // register to CPSR, and remove the redundant implicit def.
7652 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7654 // Rename pseudo opcodes.
7655 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7657 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7658 MCID = &TII->get(NewOpc);
7660 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7661 "converted opcode should be the same except for cc_out");
7665 // Add the optional cc_out operand
7666 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7668 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7670 // Any ARM instruction that sets the 's' bit should specify an optional
7671 // "cc_out" operand in the last operand position.
7672 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7673 assert(!NewOpc && "Optional cc_out operand required");
7676 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7677 // since we already have an optional CPSR def.
7678 bool definesCPSR = false;
7679 bool deadCPSR = false;
7680 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7682 const MachineOperand &MO = MI->getOperand(i);
7683 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7687 MI->RemoveOperand(i);
7692 assert(!NewOpc && "Optional cc_out operand required");
7695 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7697 assert(!MI->getOperand(ccOutIdx).getReg() &&
7698 "expect uninitialized optional cc_out operand");
7702 // If this instruction was defined with an optional CPSR def and its dag node
7703 // had a live implicit CPSR def, then activate the optional CPSR def.
7704 MachineOperand &MO = MI->getOperand(ccOutIdx);
7705 MO.setReg(ARM::CPSR);
7709 //===----------------------------------------------------------------------===//
7710 // ARM Optimization Hooks
7711 //===----------------------------------------------------------------------===//
7713 // Helper function that checks if N is a null or all ones constant.
7714 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7715 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7718 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7721 // Return true if N is conditionally 0 or all ones.
7722 // Detects these expressions where cc is an i1 value:
7724 // (select cc 0, y) [AllOnes=0]
7725 // (select cc y, 0) [AllOnes=0]
7726 // (zext cc) [AllOnes=0]
7727 // (sext cc) [AllOnes=0/1]
7728 // (select cc -1, y) [AllOnes=1]
7729 // (select cc y, -1) [AllOnes=1]
7731 // Invert is set when N is the null/all ones constant when CC is false.
7732 // OtherOp is set to the alternative value of N.
7733 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7734 SDValue &CC, bool &Invert,
7736 SelectionDAG &DAG) {
7737 switch (N->getOpcode()) {
7738 default: return false;
7740 CC = N->getOperand(0);
7741 SDValue N1 = N->getOperand(1);
7742 SDValue N2 = N->getOperand(2);
7743 if (isZeroOrAllOnes(N1, AllOnes)) {
7748 if (isZeroOrAllOnes(N2, AllOnes)) {
7755 case ISD::ZERO_EXTEND:
7756 // (zext cc) can never be the all ones value.
7760 case ISD::SIGN_EXTEND: {
7762 EVT VT = N->getValueType(0);
7763 CC = N->getOperand(0);
7764 if (CC.getValueType() != MVT::i1)
7768 // When looking for an AllOnes constant, N is an sext, and the 'other'
7770 OtherOp = DAG.getConstant(0, dl, VT);
7771 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7772 // When looking for a 0 constant, N can be zext or sext.
7773 OtherOp = DAG.getConstant(1, dl, VT);
7775 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
7782 // Combine a constant select operand into its use:
7784 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7785 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7786 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7787 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7788 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7790 // The transform is rejected if the select doesn't have a constant operand that
7791 // is null, or all ones when AllOnes is set.
7793 // Also recognize sext/zext from i1:
7795 // (add (zext cc), x) -> (select cc (add x, 1), x)
7796 // (add (sext cc), x) -> (select cc (add x, -1), x)
7798 // These transformations eventually create predicated instructions.
7800 // @param N The node to transform.
7801 // @param Slct The N operand that is a select.
7802 // @param OtherOp The other N operand (x above).
7803 // @param DCI Context.
7804 // @param AllOnes Require the select constant to be all ones instead of null.
7805 // @returns The new node, or SDValue() on failure.
7807 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7808 TargetLowering::DAGCombinerInfo &DCI,
7809 bool AllOnes = false) {
7810 SelectionDAG &DAG = DCI.DAG;
7811 EVT VT = N->getValueType(0);
7812 SDValue NonConstantVal;
7815 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7816 NonConstantVal, DAG))
7819 // Slct is now know to be the desired identity constant when CC is true.
7820 SDValue TrueVal = OtherOp;
7821 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7822 OtherOp, NonConstantVal);
7823 // Unless SwapSelectOps says CC should be false.
7825 std::swap(TrueVal, FalseVal);
7827 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7828 CCOp, TrueVal, FalseVal);
7831 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7833 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7834 TargetLowering::DAGCombinerInfo &DCI) {
7835 SDValue N0 = N->getOperand(0);
7836 SDValue N1 = N->getOperand(1);
7837 if (N0.getNode()->hasOneUse()) {
7838 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7839 if (Result.getNode())
7842 if (N1.getNode()->hasOneUse()) {
7843 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7844 if (Result.getNode())
7850 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7851 // (only after legalization).
7852 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7853 TargetLowering::DAGCombinerInfo &DCI,
7854 const ARMSubtarget *Subtarget) {
7856 // Only perform optimization if after legalize, and if NEON is available. We
7857 // also expected both operands to be BUILD_VECTORs.
7858 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7859 || N0.getOpcode() != ISD::BUILD_VECTOR
7860 || N1.getOpcode() != ISD::BUILD_VECTOR)
7863 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7864 EVT VT = N->getValueType(0);
7865 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7868 // Check that the vector operands are of the right form.
7869 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7870 // operands, where N is the size of the formed vector.
7871 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7872 // index such that we have a pair wise add pattern.
7874 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7875 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7877 SDValue Vec = N0->getOperand(0)->getOperand(0);
7878 SDNode *V = Vec.getNode();
7879 unsigned nextIndex = 0;
7881 // For each operands to the ADD which are BUILD_VECTORs,
7882 // check to see if each of their operands are an EXTRACT_VECTOR with
7883 // the same vector and appropriate index.
7884 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7885 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7886 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7888 SDValue ExtVec0 = N0->getOperand(i);
7889 SDValue ExtVec1 = N1->getOperand(i);
7891 // First operand is the vector, verify its the same.
7892 if (V != ExtVec0->getOperand(0).getNode() ||
7893 V != ExtVec1->getOperand(0).getNode())
7896 // Second is the constant, verify its correct.
7897 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7898 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7900 // For the constant, we want to see all the even or all the odd.
7901 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7902 || C1->getZExtValue() != nextIndex+1)
7911 // Create VPADDL node.
7912 SelectionDAG &DAG = DCI.DAG;
7913 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7917 // Build operand list.
7918 SmallVector<SDValue, 8> Ops;
7919 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
7920 TLI.getPointerTy()));
7922 // Input is the vector.
7925 // Get widened type and narrowed type.
7927 unsigned numElem = VT.getVectorNumElements();
7929 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7930 switch (inputLaneType.getSimpleVT().SimpleTy) {
7931 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7932 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7933 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7935 llvm_unreachable("Invalid vector element type for padd optimization.");
7938 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
7939 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7940 return DAG.getNode(ExtOp, dl, VT, tmp);
7943 static SDValue findMUL_LOHI(SDValue V) {
7944 if (V->getOpcode() == ISD::UMUL_LOHI ||
7945 V->getOpcode() == ISD::SMUL_LOHI)
7950 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7951 TargetLowering::DAGCombinerInfo &DCI,
7952 const ARMSubtarget *Subtarget) {
7954 if (Subtarget->isThumb1Only()) return SDValue();
7956 // Only perform the checks after legalize when the pattern is available.
7957 if (DCI.isBeforeLegalize()) return SDValue();
7959 // Look for multiply add opportunities.
7960 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7961 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7962 // a glue link from the first add to the second add.
7963 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7964 // a S/UMLAL instruction.
7967 // \ / \ [no multiline comment]
7973 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7974 SDValue AddcOp0 = AddcNode->getOperand(0);
7975 SDValue AddcOp1 = AddcNode->getOperand(1);
7977 // Check if the two operands are from the same mul_lohi node.
7978 if (AddcOp0.getNode() == AddcOp1.getNode())
7981 assert(AddcNode->getNumValues() == 2 &&
7982 AddcNode->getValueType(0) == MVT::i32 &&
7983 "Expect ADDC with two result values. First: i32");
7985 // Check that we have a glued ADDC node.
7986 if (AddcNode->getValueType(1) != MVT::Glue)
7989 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7990 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7991 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7992 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7993 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7996 // Look for the glued ADDE.
7997 SDNode* AddeNode = AddcNode->getGluedUser();
8001 // Make sure it is really an ADDE.
8002 if (AddeNode->getOpcode() != ISD::ADDE)
8005 assert(AddeNode->getNumOperands() == 3 &&
8006 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8007 "ADDE node has the wrong inputs");
8009 // Check for the triangle shape.
8010 SDValue AddeOp0 = AddeNode->getOperand(0);
8011 SDValue AddeOp1 = AddeNode->getOperand(1);
8013 // Make sure that the ADDE operands are not coming from the same node.
8014 if (AddeOp0.getNode() == AddeOp1.getNode())
8017 // Find the MUL_LOHI node walking up ADDE's operands.
8018 bool IsLeftOperandMUL = false;
8019 SDValue MULOp = findMUL_LOHI(AddeOp0);
8020 if (MULOp == SDValue())
8021 MULOp = findMUL_LOHI(AddeOp1);
8023 IsLeftOperandMUL = true;
8024 if (MULOp == SDValue())
8027 // Figure out the right opcode.
8028 unsigned Opc = MULOp->getOpcode();
8029 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8031 // Figure out the high and low input values to the MLAL node.
8032 SDValue* HiAdd = nullptr;
8033 SDValue* LoMul = nullptr;
8034 SDValue* LowAdd = nullptr;
8036 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8037 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8040 if (IsLeftOperandMUL)
8046 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8047 // whose low result is fed to the ADDC we are checking.
8049 if (AddcOp0 == MULOp.getValue(0)) {
8053 if (AddcOp1 == MULOp.getValue(0)) {
8061 // Create the merged node.
8062 SelectionDAG &DAG = DCI.DAG;
8064 // Build operand list.
8065 SmallVector<SDValue, 8> Ops;
8066 Ops.push_back(LoMul->getOperand(0));
8067 Ops.push_back(LoMul->getOperand(1));
8068 Ops.push_back(*LowAdd);
8069 Ops.push_back(*HiAdd);
8071 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8072 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8074 // Replace the ADDs' nodes uses by the MLA node's values.
8075 SDValue HiMLALResult(MLALNode.getNode(), 1);
8076 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8078 SDValue LoMLALResult(MLALNode.getNode(), 0);
8079 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8081 // Return original node to notify the driver to stop replacing.
8082 SDValue resNode(AddcNode, 0);
8086 /// PerformADDCCombine - Target-specific dag combine transform from
8087 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8088 static SDValue PerformADDCCombine(SDNode *N,
8089 TargetLowering::DAGCombinerInfo &DCI,
8090 const ARMSubtarget *Subtarget) {
8092 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8096 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8097 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8098 /// called with the default operands, and if that fails, with commuted
8100 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8101 TargetLowering::DAGCombinerInfo &DCI,
8102 const ARMSubtarget *Subtarget){
8104 // Attempt to create vpaddl for this add.
8105 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8106 if (Result.getNode())
8109 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8110 if (N0.getNode()->hasOneUse()) {
8111 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8112 if (Result.getNode()) return Result;
8117 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8119 static SDValue PerformADDCombine(SDNode *N,
8120 TargetLowering::DAGCombinerInfo &DCI,
8121 const ARMSubtarget *Subtarget) {
8122 SDValue N0 = N->getOperand(0);
8123 SDValue N1 = N->getOperand(1);
8125 // First try with the default operand order.
8126 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8127 if (Result.getNode())
8130 // If that didn't work, try again with the operands commuted.
8131 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8134 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8136 static SDValue PerformSUBCombine(SDNode *N,
8137 TargetLowering::DAGCombinerInfo &DCI) {
8138 SDValue N0 = N->getOperand(0);
8139 SDValue N1 = N->getOperand(1);
8141 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8142 if (N1.getNode()->hasOneUse()) {
8143 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8144 if (Result.getNode()) return Result;
8150 /// PerformVMULCombine
8151 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8152 /// special multiplier accumulator forwarding.
8158 // However, for (A + B) * (A + B),
8165 static SDValue PerformVMULCombine(SDNode *N,
8166 TargetLowering::DAGCombinerInfo &DCI,
8167 const ARMSubtarget *Subtarget) {
8168 if (!Subtarget->hasVMLxForwarding())
8171 SelectionDAG &DAG = DCI.DAG;
8172 SDValue N0 = N->getOperand(0);
8173 SDValue N1 = N->getOperand(1);
8174 unsigned Opcode = N0.getOpcode();
8175 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8176 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8177 Opcode = N1.getOpcode();
8178 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8179 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8187 EVT VT = N->getValueType(0);
8189 SDValue N00 = N0->getOperand(0);
8190 SDValue N01 = N0->getOperand(1);
8191 return DAG.getNode(Opcode, DL, VT,
8192 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8193 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8196 static SDValue PerformMULCombine(SDNode *N,
8197 TargetLowering::DAGCombinerInfo &DCI,
8198 const ARMSubtarget *Subtarget) {
8199 SelectionDAG &DAG = DCI.DAG;
8201 if (Subtarget->isThumb1Only())
8204 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8207 EVT VT = N->getValueType(0);
8208 if (VT.is64BitVector() || VT.is128BitVector())
8209 return PerformVMULCombine(N, DCI, Subtarget);
8213 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8217 int64_t MulAmt = C->getSExtValue();
8218 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8220 ShiftAmt = ShiftAmt & (32 - 1);
8221 SDValue V = N->getOperand(0);
8225 MulAmt >>= ShiftAmt;
8228 if (isPowerOf2_32(MulAmt - 1)) {
8229 // (mul x, 2^N + 1) => (add (shl x, N), x)
8230 Res = DAG.getNode(ISD::ADD, DL, VT,
8232 DAG.getNode(ISD::SHL, DL, VT,
8234 DAG.getConstant(Log2_32(MulAmt - 1), DL,
8236 } else if (isPowerOf2_32(MulAmt + 1)) {
8237 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8238 Res = DAG.getNode(ISD::SUB, DL, VT,
8239 DAG.getNode(ISD::SHL, DL, VT,
8241 DAG.getConstant(Log2_32(MulAmt + 1), DL,
8247 uint64_t MulAmtAbs = -MulAmt;
8248 if (isPowerOf2_32(MulAmtAbs + 1)) {
8249 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8250 Res = DAG.getNode(ISD::SUB, DL, VT,
8252 DAG.getNode(ISD::SHL, DL, VT,
8254 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8256 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8257 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8258 Res = DAG.getNode(ISD::ADD, DL, VT,
8260 DAG.getNode(ISD::SHL, DL, VT,
8262 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8264 Res = DAG.getNode(ISD::SUB, DL, VT,
8265 DAG.getConstant(0, DL, MVT::i32), Res);
8272 Res = DAG.getNode(ISD::SHL, DL, VT,
8273 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8275 // Do not add new nodes to DAG combiner worklist.
8276 DCI.CombineTo(N, Res, false);
8280 static SDValue PerformANDCombine(SDNode *N,
8281 TargetLowering::DAGCombinerInfo &DCI,
8282 const ARMSubtarget *Subtarget) {
8284 // Attempt to use immediate-form VBIC
8285 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8287 EVT VT = N->getValueType(0);
8288 SelectionDAG &DAG = DCI.DAG;
8290 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8293 APInt SplatBits, SplatUndef;
8294 unsigned SplatBitSize;
8297 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8298 if (SplatBitSize <= 64) {
8300 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8301 SplatUndef.getZExtValue(), SplatBitSize,
8302 DAG, dl, VbicVT, VT.is128BitVector(),
8304 if (Val.getNode()) {
8306 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8307 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8308 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8313 if (!Subtarget->isThumb1Only()) {
8314 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8315 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8316 if (Result.getNode())
8323 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8324 static SDValue PerformORCombine(SDNode *N,
8325 TargetLowering::DAGCombinerInfo &DCI,
8326 const ARMSubtarget *Subtarget) {
8327 // Attempt to use immediate-form VORR
8328 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8330 EVT VT = N->getValueType(0);
8331 SelectionDAG &DAG = DCI.DAG;
8333 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8336 APInt SplatBits, SplatUndef;
8337 unsigned SplatBitSize;
8339 if (BVN && Subtarget->hasNEON() &&
8340 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8341 if (SplatBitSize <= 64) {
8343 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8344 SplatUndef.getZExtValue(), SplatBitSize,
8345 DAG, dl, VorrVT, VT.is128BitVector(),
8347 if (Val.getNode()) {
8349 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8350 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8351 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8356 if (!Subtarget->isThumb1Only()) {
8357 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8358 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8359 if (Result.getNode())
8363 // The code below optimizes (or (and X, Y), Z).
8364 // The AND operand needs to have a single user to make these optimizations
8366 SDValue N0 = N->getOperand(0);
8367 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8369 SDValue N1 = N->getOperand(1);
8371 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8372 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8373 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8375 unsigned SplatBitSize;
8378 APInt SplatBits0, SplatBits1;
8379 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8380 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8381 // Ensure that the second operand of both ands are constants
8382 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8383 HasAnyUndefs) && !HasAnyUndefs) {
8384 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8385 HasAnyUndefs) && !HasAnyUndefs) {
8386 // Ensure that the bit width of the constants are the same and that
8387 // the splat arguments are logical inverses as per the pattern we
8388 // are trying to simplify.
8389 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8390 SplatBits0 == ~SplatBits1) {
8391 // Canonicalize the vector type to make instruction selection
8393 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8394 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8398 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8404 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8407 // BFI is only available on V6T2+
8408 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8412 // 1) or (and A, mask), val => ARMbfi A, val, mask
8413 // iff (val & mask) == val
8415 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8416 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8417 // && mask == ~mask2
8418 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8419 // && ~mask == mask2
8420 // (i.e., copy a bitfield value into another bitfield of the same width)
8425 SDValue N00 = N0.getOperand(0);
8427 // The value and the mask need to be constants so we can verify this is
8428 // actually a bitfield set. If the mask is 0xffff, we can do better
8429 // via a movt instruction, so don't use BFI in that case.
8430 SDValue MaskOp = N0.getOperand(1);
8431 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8434 unsigned Mask = MaskC->getZExtValue();
8438 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8439 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8441 unsigned Val = N1C->getZExtValue();
8442 if ((Val & ~Mask) != Val)
8445 if (ARM::isBitFieldInvertedMask(Mask)) {
8446 Val >>= countTrailingZeros(~Mask);
8448 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8449 DAG.getConstant(Val, DL, MVT::i32),
8450 DAG.getConstant(Mask, DL, MVT::i32));
8452 // Do not add new nodes to DAG combiner worklist.
8453 DCI.CombineTo(N, Res, false);
8456 } else if (N1.getOpcode() == ISD::AND) {
8457 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8458 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8461 unsigned Mask2 = N11C->getZExtValue();
8463 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8465 if (ARM::isBitFieldInvertedMask(Mask) &&
8467 // The pack halfword instruction works better for masks that fit it,
8468 // so use that when it's available.
8469 if (Subtarget->hasT2ExtractPack() &&
8470 (Mask == 0xffff || Mask == 0xffff0000))
8473 unsigned amt = countTrailingZeros(Mask2);
8474 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8475 DAG.getConstant(amt, DL, MVT::i32));
8476 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8477 DAG.getConstant(Mask, DL, MVT::i32));
8478 // Do not add new nodes to DAG combiner worklist.
8479 DCI.CombineTo(N, Res, false);
8481 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8483 // The pack halfword instruction works better for masks that fit it,
8484 // so use that when it's available.
8485 if (Subtarget->hasT2ExtractPack() &&
8486 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8489 unsigned lsb = countTrailingZeros(Mask);
8490 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8491 DAG.getConstant(lsb, DL, MVT::i32));
8492 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8493 DAG.getConstant(Mask2, DL, MVT::i32));
8494 // Do not add new nodes to DAG combiner worklist.
8495 DCI.CombineTo(N, Res, false);
8500 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8501 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8502 ARM::isBitFieldInvertedMask(~Mask)) {
8503 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8504 // where lsb(mask) == #shamt and masked bits of B are known zero.
8505 SDValue ShAmt = N00.getOperand(1);
8506 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8507 unsigned LSB = countTrailingZeros(Mask);
8511 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8512 DAG.getConstant(~Mask, DL, MVT::i32));
8514 // Do not add new nodes to DAG combiner worklist.
8515 DCI.CombineTo(N, Res, false);
8521 static SDValue PerformXORCombine(SDNode *N,
8522 TargetLowering::DAGCombinerInfo &DCI,
8523 const ARMSubtarget *Subtarget) {
8524 EVT VT = N->getValueType(0);
8525 SelectionDAG &DAG = DCI.DAG;
8527 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8530 if (!Subtarget->isThumb1Only()) {
8531 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8532 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8533 if (Result.getNode())
8540 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8541 /// the bits being cleared by the AND are not demanded by the BFI.
8542 static SDValue PerformBFICombine(SDNode *N,
8543 TargetLowering::DAGCombinerInfo &DCI) {
8544 SDValue N1 = N->getOperand(1);
8545 if (N1.getOpcode() == ISD::AND) {
8546 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8549 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8550 unsigned LSB = countTrailingZeros(~InvMask);
8551 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8553 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8554 "undefined behavior");
8555 unsigned Mask = (1u << Width) - 1;
8556 unsigned Mask2 = N11C->getZExtValue();
8557 if ((Mask & (~Mask2)) == 0)
8558 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8559 N->getOperand(0), N1.getOperand(0),
8565 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8566 /// ARMISD::VMOVRRD.
8567 static SDValue PerformVMOVRRDCombine(SDNode *N,
8568 TargetLowering::DAGCombinerInfo &DCI,
8569 const ARMSubtarget *Subtarget) {
8570 // vmovrrd(vmovdrr x, y) -> x,y
8571 SDValue InDouble = N->getOperand(0);
8572 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8573 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8575 // vmovrrd(load f64) -> (load i32), (load i32)
8576 SDNode *InNode = InDouble.getNode();
8577 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8578 InNode->getValueType(0) == MVT::f64 &&
8579 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8580 !cast<LoadSDNode>(InNode)->isVolatile()) {
8581 // TODO: Should this be done for non-FrameIndex operands?
8582 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8584 SelectionDAG &DAG = DCI.DAG;
8586 SDValue BasePtr = LD->getBasePtr();
8587 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8588 LD->getPointerInfo(), LD->isVolatile(),
8589 LD->isNonTemporal(), LD->isInvariant(),
8590 LD->getAlignment());
8592 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8593 DAG.getConstant(4, DL, MVT::i32));
8594 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8595 LD->getPointerInfo(), LD->isVolatile(),
8596 LD->isNonTemporal(), LD->isInvariant(),
8597 std::min(4U, LD->getAlignment() / 2));
8599 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8600 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8601 std::swap (NewLD1, NewLD2);
8602 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8609 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8610 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8611 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8612 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8613 SDValue Op0 = N->getOperand(0);
8614 SDValue Op1 = N->getOperand(1);
8615 if (Op0.getOpcode() == ISD::BITCAST)
8616 Op0 = Op0.getOperand(0);
8617 if (Op1.getOpcode() == ISD::BITCAST)
8618 Op1 = Op1.getOperand(0);
8619 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8620 Op0.getNode() == Op1.getNode() &&
8621 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8622 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8623 N->getValueType(0), Op0.getOperand(0));
8627 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8628 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8629 /// i64 vector to have f64 elements, since the value can then be loaded
8630 /// directly into a VFP register.
8631 static bool hasNormalLoadOperand(SDNode *N) {
8632 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8633 for (unsigned i = 0; i < NumElts; ++i) {
8634 SDNode *Elt = N->getOperand(i).getNode();
8635 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8641 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8642 /// ISD::BUILD_VECTOR.
8643 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8644 TargetLowering::DAGCombinerInfo &DCI,
8645 const ARMSubtarget *Subtarget) {
8646 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8647 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8648 // into a pair of GPRs, which is fine when the value is used as a scalar,
8649 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8650 SelectionDAG &DAG = DCI.DAG;
8651 if (N->getNumOperands() == 2) {
8652 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8657 // Load i64 elements as f64 values so that type legalization does not split
8658 // them up into i32 values.
8659 EVT VT = N->getValueType(0);
8660 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8663 SmallVector<SDValue, 8> Ops;
8664 unsigned NumElts = VT.getVectorNumElements();
8665 for (unsigned i = 0; i < NumElts; ++i) {
8666 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8668 // Make the DAGCombiner fold the bitcast.
8669 DCI.AddToWorklist(V.getNode());
8671 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8672 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8673 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8676 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8678 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8679 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8680 // At that time, we may have inserted bitcasts from integer to float.
8681 // If these bitcasts have survived DAGCombine, change the lowering of this
8682 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8683 // force to use floating point types.
8685 // Make sure we can change the type of the vector.
8686 // This is possible iff:
8687 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8688 // 1.1. Vector is used only once.
8689 // 1.2. Use is a bit convert to an integer type.
8690 // 2. The size of its operands are 32-bits (64-bits are not legal).
8691 EVT VT = N->getValueType(0);
8692 EVT EltVT = VT.getVectorElementType();
8694 // Check 1.1. and 2.
8695 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8698 // By construction, the input type must be float.
8699 assert(EltVT == MVT::f32 && "Unexpected type!");
8702 SDNode *Use = *N->use_begin();
8703 if (Use->getOpcode() != ISD::BITCAST ||
8704 Use->getValueType(0).isFloatingPoint())
8707 // Check profitability.
8708 // Model is, if more than half of the relevant operands are bitcast from
8709 // i32, turn the build_vector into a sequence of insert_vector_elt.
8710 // Relevant operands are everything that is not statically
8711 // (i.e., at compile time) bitcasted.
8712 unsigned NumOfBitCastedElts = 0;
8713 unsigned NumElts = VT.getVectorNumElements();
8714 unsigned NumOfRelevantElts = NumElts;
8715 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8716 SDValue Elt = N->getOperand(Idx);
8717 if (Elt->getOpcode() == ISD::BITCAST) {
8718 // Assume only bit cast to i32 will go away.
8719 if (Elt->getOperand(0).getValueType() == MVT::i32)
8720 ++NumOfBitCastedElts;
8721 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8722 // Constants are statically casted, thus do not count them as
8723 // relevant operands.
8724 --NumOfRelevantElts;
8727 // Check if more than half of the elements require a non-free bitcast.
8728 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8731 SelectionDAG &DAG = DCI.DAG;
8732 // Create the new vector type.
8733 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8734 // Check if the type is legal.
8735 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8736 if (!TLI.isTypeLegal(VecVT))
8740 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8741 // => BITCAST INSERT_VECTOR_ELT
8742 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8744 SDValue Vec = DAG.getUNDEF(VecVT);
8746 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8747 SDValue V = N->getOperand(Idx);
8748 if (V.getOpcode() == ISD::UNDEF)
8750 if (V.getOpcode() == ISD::BITCAST &&
8751 V->getOperand(0).getValueType() == MVT::i32)
8752 // Fold obvious case.
8753 V = V.getOperand(0);
8755 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8756 // Make the DAGCombiner fold the bitcasts.
8757 DCI.AddToWorklist(V.getNode());
8759 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
8760 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8762 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8763 // Make the DAGCombiner fold the bitcasts.
8764 DCI.AddToWorklist(Vec.getNode());
8768 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8769 /// ISD::INSERT_VECTOR_ELT.
8770 static SDValue PerformInsertEltCombine(SDNode *N,
8771 TargetLowering::DAGCombinerInfo &DCI) {
8772 // Bitcast an i64 load inserted into a vector to f64.
8773 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8774 EVT VT = N->getValueType(0);
8775 SDNode *Elt = N->getOperand(1).getNode();
8776 if (VT.getVectorElementType() != MVT::i64 ||
8777 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8780 SelectionDAG &DAG = DCI.DAG;
8782 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8783 VT.getVectorNumElements());
8784 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8785 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8786 // Make the DAGCombiner fold the bitcasts.
8787 DCI.AddToWorklist(Vec.getNode());
8788 DCI.AddToWorklist(V.getNode());
8789 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8790 Vec, V, N->getOperand(2));
8791 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8794 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8795 /// ISD::VECTOR_SHUFFLE.
8796 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8797 // The LLVM shufflevector instruction does not require the shuffle mask
8798 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8799 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8800 // operands do not match the mask length, they are extended by concatenating
8801 // them with undef vectors. That is probably the right thing for other
8802 // targets, but for NEON it is better to concatenate two double-register
8803 // size vector operands into a single quad-register size vector. Do that
8804 // transformation here:
8805 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8806 // shuffle(concat(v1, v2), undef)
8807 SDValue Op0 = N->getOperand(0);
8808 SDValue Op1 = N->getOperand(1);
8809 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8810 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8811 Op0.getNumOperands() != 2 ||
8812 Op1.getNumOperands() != 2)
8814 SDValue Concat0Op1 = Op0.getOperand(1);
8815 SDValue Concat1Op1 = Op1.getOperand(1);
8816 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8817 Concat1Op1.getOpcode() != ISD::UNDEF)
8819 // Skip the transformation if any of the types are illegal.
8820 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8821 EVT VT = N->getValueType(0);
8822 if (!TLI.isTypeLegal(VT) ||
8823 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8824 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8827 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8828 Op0.getOperand(0), Op1.getOperand(0));
8829 // Translate the shuffle mask.
8830 SmallVector<int, 16> NewMask;
8831 unsigned NumElts = VT.getVectorNumElements();
8832 unsigned HalfElts = NumElts/2;
8833 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8834 for (unsigned n = 0; n < NumElts; ++n) {
8835 int MaskElt = SVN->getMaskElt(n);
8837 if (MaskElt < (int)HalfElts)
8839 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8840 NewElt = HalfElts + MaskElt - NumElts;
8841 NewMask.push_back(NewElt);
8843 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8844 DAG.getUNDEF(VT), NewMask.data());
8847 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8848 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8849 /// base address updates.
8850 /// For generic load/stores, the memory type is assumed to be a vector.
8851 /// The caller is assumed to have checked legality.
8852 static SDValue CombineBaseUpdate(SDNode *N,
8853 TargetLowering::DAGCombinerInfo &DCI) {
8854 SelectionDAG &DAG = DCI.DAG;
8855 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8856 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8857 const bool isStore = N->getOpcode() == ISD::STORE;
8858 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8859 SDValue Addr = N->getOperand(AddrOpIdx);
8860 MemSDNode *MemN = cast<MemSDNode>(N);
8863 // Search for a use of the address operand that is an increment.
8864 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8865 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8867 if (User->getOpcode() != ISD::ADD ||
8868 UI.getUse().getResNo() != Addr.getResNo())
8871 // Check that the add is independent of the load/store. Otherwise, folding
8872 // it would create a cycle.
8873 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8876 // Find the new opcode for the updating load/store.
8877 bool isLoadOp = true;
8878 bool isLaneOp = false;
8879 unsigned NewOpc = 0;
8880 unsigned NumVecs = 0;
8882 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8884 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8885 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8887 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8889 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8891 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8893 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8894 NumVecs = 2; isLaneOp = true; break;
8895 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8896 NumVecs = 3; isLaneOp = true; break;
8897 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8898 NumVecs = 4; isLaneOp = true; break;
8899 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8900 NumVecs = 1; isLoadOp = false; break;
8901 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8902 NumVecs = 2; isLoadOp = false; break;
8903 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8904 NumVecs = 3; isLoadOp = false; break;
8905 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8906 NumVecs = 4; isLoadOp = false; break;
8907 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8908 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8909 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8910 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8911 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8912 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8916 switch (N->getOpcode()) {
8917 default: llvm_unreachable("unexpected opcode for Neon base update");
8918 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8919 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8920 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8921 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
8922 NumVecs = 1; isLaneOp = false; break;
8923 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
8924 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
8928 // Find the size of memory referenced by the load/store.
8931 VecTy = N->getValueType(0);
8932 } else if (isIntrinsic) {
8933 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8935 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
8936 VecTy = N->getOperand(1).getValueType();
8939 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8941 NumBytes /= VecTy.getVectorNumElements();
8943 // If the increment is a constant, it must match the memory ref size.
8944 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8945 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8946 uint64_t IncVal = CInc->getZExtValue();
8947 if (IncVal != NumBytes)
8949 } else if (NumBytes >= 3 * 16) {
8950 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8951 // separate instructions that make it harder to use a non-constant update.
8955 // OK, we found an ADD we can fold into the base update.
8956 // Now, create a _UPD node, taking care of not breaking alignment.
8958 EVT AlignedVecTy = VecTy;
8959 unsigned Alignment = MemN->getAlignment();
8961 // If this is a less-than-standard-aligned load/store, change the type to
8962 // match the standard alignment.
8963 // The alignment is overlooked when selecting _UPD variants; and it's
8964 // easier to introduce bitcasts here than fix that.
8965 // There are 3 ways to get to this base-update combine:
8966 // - intrinsics: they are assumed to be properly aligned (to the standard
8967 // alignment of the memory type), so we don't need to do anything.
8968 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
8969 // intrinsics, so, likewise, there's nothing to do.
8970 // - generic load/store instructions: the alignment is specified as an
8971 // explicit operand, rather than implicitly as the standard alignment
8972 // of the memory type (like the intrisics). We need to change the
8973 // memory type to match the explicit alignment. That way, we don't
8974 // generate non-standard-aligned ARMISD::VLDx nodes.
8975 if (isa<LSBaseSDNode>(N)) {
8978 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
8979 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
8980 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
8981 assert(!isLaneOp && "Unexpected generic load/store lane.");
8982 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
8983 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
8985 // Don't set an explicit alignment on regular load/stores that we want
8986 // to transform to VLD/VST 1_UPD nodes.
8987 // This matches the behavior of regular load/stores, which only get an
8988 // explicit alignment if the MMO alignment is larger than the standard
8989 // alignment of the memory type.
8990 // Intrinsics, however, always get an explicit alignment, set to the
8991 // alignment of the MMO.
8995 // Create the new updating load/store node.
8996 // First, create an SDVTList for the new updating node's results.
8998 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9000 for (n = 0; n < NumResultVecs; ++n)
9001 Tys[n] = AlignedVecTy;
9002 Tys[n++] = MVT::i32;
9003 Tys[n] = MVT::Other;
9004 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9006 // Then, gather the new node's operands.
9007 SmallVector<SDValue, 8> Ops;
9008 Ops.push_back(N->getOperand(0)); // incoming chain
9009 Ops.push_back(N->getOperand(AddrOpIdx));
9012 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9013 // Try to match the intrinsic's signature
9014 Ops.push_back(StN->getValue());
9016 // Loads (and of course intrinsics) match the intrinsics' signature,
9017 // so just add all but the alignment operand.
9018 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9019 Ops.push_back(N->getOperand(i));
9022 // For all node types, the alignment operand is always the last one.
9023 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9025 // If this is a non-standard-aligned STORE, the penultimate operand is the
9026 // stored value. Bitcast it to the aligned type.
9027 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9028 SDValue &StVal = Ops[Ops.size()-2];
9029 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9032 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9034 MemN->getMemOperand());
9037 SmallVector<SDValue, 5> NewResults;
9038 for (unsigned i = 0; i < NumResultVecs; ++i)
9039 NewResults.push_back(SDValue(UpdN.getNode(), i));
9041 // If this is an non-standard-aligned LOAD, the first result is the loaded
9042 // value. Bitcast it to the expected result type.
9043 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9044 SDValue &LdVal = NewResults[0];
9045 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9048 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9049 DCI.CombineTo(N, NewResults);
9050 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9057 static SDValue PerformVLDCombine(SDNode *N,
9058 TargetLowering::DAGCombinerInfo &DCI) {
9059 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9062 return CombineBaseUpdate(N, DCI);
9065 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9066 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9067 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9069 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9070 SelectionDAG &DAG = DCI.DAG;
9071 EVT VT = N->getValueType(0);
9072 // vldN-dup instructions only support 64-bit vectors for N > 1.
9073 if (!VT.is64BitVector())
9076 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9077 SDNode *VLD = N->getOperand(0).getNode();
9078 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9080 unsigned NumVecs = 0;
9081 unsigned NewOpc = 0;
9082 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9083 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9085 NewOpc = ARMISD::VLD2DUP;
9086 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9088 NewOpc = ARMISD::VLD3DUP;
9089 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9091 NewOpc = ARMISD::VLD4DUP;
9096 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9097 // numbers match the load.
9098 unsigned VLDLaneNo =
9099 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9100 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9102 // Ignore uses of the chain result.
9103 if (UI.getUse().getResNo() == NumVecs)
9106 if (User->getOpcode() != ARMISD::VDUPLANE ||
9107 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9111 // Create the vldN-dup node.
9114 for (n = 0; n < NumVecs; ++n)
9116 Tys[n] = MVT::Other;
9117 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9118 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9119 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9120 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9121 Ops, VLDMemInt->getMemoryVT(),
9122 VLDMemInt->getMemOperand());
9125 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9127 unsigned ResNo = UI.getUse().getResNo();
9128 // Ignore uses of the chain result.
9129 if (ResNo == NumVecs)
9132 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9135 // Now the vldN-lane intrinsic is dead except for its chain result.
9136 // Update uses of the chain.
9137 std::vector<SDValue> VLDDupResults;
9138 for (unsigned n = 0; n < NumVecs; ++n)
9139 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9140 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9141 DCI.CombineTo(VLD, VLDDupResults);
9146 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9147 /// ARMISD::VDUPLANE.
9148 static SDValue PerformVDUPLANECombine(SDNode *N,
9149 TargetLowering::DAGCombinerInfo &DCI) {
9150 SDValue Op = N->getOperand(0);
9152 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9153 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9154 if (CombineVLDDUP(N, DCI))
9155 return SDValue(N, 0);
9157 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9158 // redundant. Ignore bit_converts for now; element sizes are checked below.
9159 while (Op.getOpcode() == ISD::BITCAST)
9160 Op = Op.getOperand(0);
9161 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9164 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9165 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9166 // The canonical VMOV for a zero vector uses a 32-bit element size.
9167 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9169 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9171 EVT VT = N->getValueType(0);
9172 if (EltSize > VT.getVectorElementType().getSizeInBits())
9175 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9178 static SDValue PerformLOADCombine(SDNode *N,
9179 TargetLowering::DAGCombinerInfo &DCI) {
9180 EVT VT = N->getValueType(0);
9182 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9183 if (ISD::isNormalLoad(N) && VT.isVector() &&
9184 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9185 return CombineBaseUpdate(N, DCI);
9190 /// PerformSTORECombine - Target-specific dag combine xforms for
9192 static SDValue PerformSTORECombine(SDNode *N,
9193 TargetLowering::DAGCombinerInfo &DCI) {
9194 StoreSDNode *St = cast<StoreSDNode>(N);
9195 if (St->isVolatile())
9198 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9199 // pack all of the elements in one place. Next, store to memory in fewer
9201 SDValue StVal = St->getValue();
9202 EVT VT = StVal.getValueType();
9203 if (St->isTruncatingStore() && VT.isVector()) {
9204 SelectionDAG &DAG = DCI.DAG;
9205 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9206 EVT StVT = St->getMemoryVT();
9207 unsigned NumElems = VT.getVectorNumElements();
9208 assert(StVT != VT && "Cannot truncate to the same type");
9209 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9210 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9212 // From, To sizes and ElemCount must be pow of two
9213 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9215 // We are going to use the original vector elt for storing.
9216 // Accumulated smaller vector elements must be a multiple of the store size.
9217 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9219 unsigned SizeRatio = FromEltSz / ToEltSz;
9220 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9222 // Create a type on which we perform the shuffle.
9223 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9224 NumElems*SizeRatio);
9225 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9228 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9229 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9230 for (unsigned i = 0; i < NumElems; ++i)
9231 ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9233 // Can't shuffle using an illegal type.
9234 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9236 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9237 DAG.getUNDEF(WideVec.getValueType()),
9239 // At this point all of the data is stored at the bottom of the
9240 // register. We now need to save it to mem.
9242 // Find the largest store unit
9243 MVT StoreType = MVT::i8;
9244 for (MVT Tp : MVT::integer_valuetypes()) {
9245 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9248 // Didn't find a legal store type.
9249 if (!TLI.isTypeLegal(StoreType))
9252 // Bitcast the original vector into a vector of store-size units
9253 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9254 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9255 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9256 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9257 SmallVector<SDValue, 8> Chains;
9258 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, DL,
9259 TLI.getPointerTy());
9260 SDValue BasePtr = St->getBasePtr();
9262 // Perform one or more big stores into memory.
9263 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9264 for (unsigned I = 0; I < E; I++) {
9265 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9266 StoreType, ShuffWide,
9267 DAG.getIntPtrConstant(I, DL));
9268 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9269 St->getPointerInfo(), St->isVolatile(),
9270 St->isNonTemporal(), St->getAlignment());
9271 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9273 Chains.push_back(Ch);
9275 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9278 if (!ISD::isNormalStore(St))
9281 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9282 // ARM stores of arguments in the same cache line.
9283 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9284 StVal.getNode()->hasOneUse()) {
9285 SelectionDAG &DAG = DCI.DAG;
9286 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9288 SDValue BasePtr = St->getBasePtr();
9289 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9290 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9291 BasePtr, St->getPointerInfo(), St->isVolatile(),
9292 St->isNonTemporal(), St->getAlignment());
9294 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9295 DAG.getConstant(4, DL, MVT::i32));
9296 return DAG.getStore(NewST1.getValue(0), DL,
9297 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9298 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9299 St->isNonTemporal(),
9300 std::min(4U, St->getAlignment() / 2));
9303 if (StVal.getValueType() == MVT::i64 &&
9304 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9306 // Bitcast an i64 store extracted from a vector to f64.
9307 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9308 SelectionDAG &DAG = DCI.DAG;
9310 SDValue IntVec = StVal.getOperand(0);
9311 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9312 IntVec.getValueType().getVectorNumElements());
9313 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9314 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9315 Vec, StVal.getOperand(1));
9317 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9318 // Make the DAGCombiner fold the bitcasts.
9319 DCI.AddToWorklist(Vec.getNode());
9320 DCI.AddToWorklist(ExtElt.getNode());
9321 DCI.AddToWorklist(V.getNode());
9322 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9323 St->getPointerInfo(), St->isVolatile(),
9324 St->isNonTemporal(), St->getAlignment(),
9328 // If this is a legal vector store, try to combine it into a VST1_UPD.
9329 if (ISD::isNormalStore(N) && VT.isVector() &&
9330 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9331 return CombineBaseUpdate(N, DCI);
9336 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9337 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9338 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9342 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9344 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9349 APFloat APF = C->getValueAPF();
9350 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9351 != APFloat::opOK || !isExact)
9354 c0 = (I == 0) ? cN : c0;
9355 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9362 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9363 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9364 /// when the VMUL has a constant operand that is a power of 2.
9366 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9367 /// vmul.f32 d16, d17, d16
9368 /// vcvt.s32.f32 d16, d16
9370 /// vcvt.s32.f32 d16, d16, #3
9371 static SDValue PerformVCVTCombine(SDNode *N,
9372 TargetLowering::DAGCombinerInfo &DCI,
9373 const ARMSubtarget *Subtarget) {
9374 SelectionDAG &DAG = DCI.DAG;
9375 SDValue Op = N->getOperand(0);
9377 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9378 Op.getOpcode() != ISD::FMUL)
9382 SDValue N0 = Op->getOperand(0);
9383 SDValue ConstVec = Op->getOperand(1);
9384 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9386 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9387 !isConstVecPow2(ConstVec, isSigned, C))
9390 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9391 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9392 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9393 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9395 // These instructions only exist converting from f32 to i32. We can handle
9396 // smaller integers by generating an extra truncate, but larger ones would
9397 // be lossy. We also can't handle more then 4 lanes, since these intructions
9398 // only support v2i32/v4i32 types.
9403 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9404 Intrinsic::arm_neon_vcvtfp2fxu;
9405 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9406 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9407 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9409 DAG.getConstant(Log2_64(C), dl, MVT::i32));
9411 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9412 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9417 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9418 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9419 /// when the VDIV has a constant operand that is a power of 2.
9421 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9422 /// vcvt.f32.s32 d16, d16
9423 /// vdiv.f32 d16, d17, d16
9425 /// vcvt.f32.s32 d16, d16, #3
9426 static SDValue PerformVDIVCombine(SDNode *N,
9427 TargetLowering::DAGCombinerInfo &DCI,
9428 const ARMSubtarget *Subtarget) {
9429 SelectionDAG &DAG = DCI.DAG;
9430 SDValue Op = N->getOperand(0);
9431 unsigned OpOpcode = Op.getNode()->getOpcode();
9433 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9434 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9438 SDValue ConstVec = N->getOperand(1);
9439 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9441 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9442 !isConstVecPow2(ConstVec, isSigned, C))
9445 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9446 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9447 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9448 // These instructions only exist converting from i32 to f32. We can handle
9449 // smaller integers by generating an extra extend, but larger ones would
9455 SDValue ConvInput = Op.getOperand(0);
9456 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9457 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9458 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9459 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9462 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9463 Intrinsic::arm_neon_vcvtfxu2fp;
9464 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9466 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9467 ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9470 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9471 /// operand of a vector shift operation, where all the elements of the
9472 /// build_vector must have the same constant integer value.
9473 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9474 // Ignore bit_converts.
9475 while (Op.getOpcode() == ISD::BITCAST)
9476 Op = Op.getOperand(0);
9477 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9478 APInt SplatBits, SplatUndef;
9479 unsigned SplatBitSize;
9481 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9482 HasAnyUndefs, ElementBits) ||
9483 SplatBitSize > ElementBits)
9485 Cnt = SplatBits.getSExtValue();
9489 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9490 /// operand of a vector shift left operation. That value must be in the range:
9491 /// 0 <= Value < ElementBits for a left shift; or
9492 /// 0 <= Value <= ElementBits for a long left shift.
9493 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9494 assert(VT.isVector() && "vector shift count is not a vector type");
9495 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9496 if (! getVShiftImm(Op, ElementBits, Cnt))
9498 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9501 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9502 /// operand of a vector shift right operation. For a shift opcode, the value
9503 /// is positive, but for an intrinsic the value count must be negative. The
9504 /// absolute value must be in the range:
9505 /// 1 <= |Value| <= ElementBits for a right shift; or
9506 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9507 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9509 assert(VT.isVector() && "vector shift count is not a vector type");
9510 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9511 if (! getVShiftImm(Op, ElementBits, Cnt))
9515 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9518 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9519 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9520 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9523 // Don't do anything for most intrinsics.
9526 // Vector shifts: check for immediate versions and lower them.
9527 // Note: This is done during DAG combining instead of DAG legalizing because
9528 // the build_vectors for 64-bit vector element shift counts are generally
9529 // not legal, and it is hard to see their values after they get legalized to
9530 // loads from a constant pool.
9531 case Intrinsic::arm_neon_vshifts:
9532 case Intrinsic::arm_neon_vshiftu:
9533 case Intrinsic::arm_neon_vrshifts:
9534 case Intrinsic::arm_neon_vrshiftu:
9535 case Intrinsic::arm_neon_vrshiftn:
9536 case Intrinsic::arm_neon_vqshifts:
9537 case Intrinsic::arm_neon_vqshiftu:
9538 case Intrinsic::arm_neon_vqshiftsu:
9539 case Intrinsic::arm_neon_vqshiftns:
9540 case Intrinsic::arm_neon_vqshiftnu:
9541 case Intrinsic::arm_neon_vqshiftnsu:
9542 case Intrinsic::arm_neon_vqrshiftns:
9543 case Intrinsic::arm_neon_vqrshiftnu:
9544 case Intrinsic::arm_neon_vqrshiftnsu: {
9545 EVT VT = N->getOperand(1).getValueType();
9547 unsigned VShiftOpc = 0;
9550 case Intrinsic::arm_neon_vshifts:
9551 case Intrinsic::arm_neon_vshiftu:
9552 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9553 VShiftOpc = ARMISD::VSHL;
9556 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9557 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9558 ARMISD::VSHRs : ARMISD::VSHRu);
9563 case Intrinsic::arm_neon_vrshifts:
9564 case Intrinsic::arm_neon_vrshiftu:
9565 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9569 case Intrinsic::arm_neon_vqshifts:
9570 case Intrinsic::arm_neon_vqshiftu:
9571 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9575 case Intrinsic::arm_neon_vqshiftsu:
9576 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9578 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9580 case Intrinsic::arm_neon_vrshiftn:
9581 case Intrinsic::arm_neon_vqshiftns:
9582 case Intrinsic::arm_neon_vqshiftnu:
9583 case Intrinsic::arm_neon_vqshiftnsu:
9584 case Intrinsic::arm_neon_vqrshiftns:
9585 case Intrinsic::arm_neon_vqrshiftnu:
9586 case Intrinsic::arm_neon_vqrshiftnsu:
9587 // Narrowing shifts require an immediate right shift.
9588 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9590 llvm_unreachable("invalid shift count for narrowing vector shift "
9594 llvm_unreachable("unhandled vector shift");
9598 case Intrinsic::arm_neon_vshifts:
9599 case Intrinsic::arm_neon_vshiftu:
9600 // Opcode already set above.
9602 case Intrinsic::arm_neon_vrshifts:
9603 VShiftOpc = ARMISD::VRSHRs; break;
9604 case Intrinsic::arm_neon_vrshiftu:
9605 VShiftOpc = ARMISD::VRSHRu; break;
9606 case Intrinsic::arm_neon_vrshiftn:
9607 VShiftOpc = ARMISD::VRSHRN; break;
9608 case Intrinsic::arm_neon_vqshifts:
9609 VShiftOpc = ARMISD::VQSHLs; break;
9610 case Intrinsic::arm_neon_vqshiftu:
9611 VShiftOpc = ARMISD::VQSHLu; break;
9612 case Intrinsic::arm_neon_vqshiftsu:
9613 VShiftOpc = ARMISD::VQSHLsu; break;
9614 case Intrinsic::arm_neon_vqshiftns:
9615 VShiftOpc = ARMISD::VQSHRNs; break;
9616 case Intrinsic::arm_neon_vqshiftnu:
9617 VShiftOpc = ARMISD::VQSHRNu; break;
9618 case Intrinsic::arm_neon_vqshiftnsu:
9619 VShiftOpc = ARMISD::VQSHRNsu; break;
9620 case Intrinsic::arm_neon_vqrshiftns:
9621 VShiftOpc = ARMISD::VQRSHRNs; break;
9622 case Intrinsic::arm_neon_vqrshiftnu:
9623 VShiftOpc = ARMISD::VQRSHRNu; break;
9624 case Intrinsic::arm_neon_vqrshiftnsu:
9625 VShiftOpc = ARMISD::VQRSHRNsu; break;
9629 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9630 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9633 case Intrinsic::arm_neon_vshiftins: {
9634 EVT VT = N->getOperand(1).getValueType();
9636 unsigned VShiftOpc = 0;
9638 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9639 VShiftOpc = ARMISD::VSLI;
9640 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9641 VShiftOpc = ARMISD::VSRI;
9643 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9647 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9648 N->getOperand(1), N->getOperand(2),
9649 DAG.getConstant(Cnt, dl, MVT::i32));
9652 case Intrinsic::arm_neon_vqrshifts:
9653 case Intrinsic::arm_neon_vqrshiftu:
9654 // No immediate versions of these to check for.
9661 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9662 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9663 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9664 /// vector element shift counts are generally not legal, and it is hard to see
9665 /// their values after they get legalized to loads from a constant pool.
9666 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9667 const ARMSubtarget *ST) {
9668 EVT VT = N->getValueType(0);
9669 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9670 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9671 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9672 SDValue N1 = N->getOperand(1);
9673 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9674 SDValue N0 = N->getOperand(0);
9675 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9676 DAG.MaskedValueIsZero(N0.getOperand(0),
9677 APInt::getHighBitsSet(32, 16)))
9678 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9682 // Nothing to be done for scalar shifts.
9683 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9684 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9687 assert(ST->hasNEON() && "unexpected vector shift");
9690 switch (N->getOpcode()) {
9691 default: llvm_unreachable("unexpected shift opcode");
9694 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
9696 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
9697 DAG.getConstant(Cnt, dl, MVT::i32));
9703 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9704 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9705 ARMISD::VSHRs : ARMISD::VSHRu);
9707 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
9708 DAG.getConstant(Cnt, dl, MVT::i32));
9714 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9715 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9716 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9717 const ARMSubtarget *ST) {
9718 SDValue N0 = N->getOperand(0);
9720 // Check for sign- and zero-extensions of vector extract operations of 8-
9721 // and 16-bit vector elements. NEON supports these directly. They are
9722 // handled during DAG combining because type legalization will promote them
9723 // to 32-bit types and it is messy to recognize the operations after that.
9724 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9725 SDValue Vec = N0.getOperand(0);
9726 SDValue Lane = N0.getOperand(1);
9727 EVT VT = N->getValueType(0);
9728 EVT EltVT = N0.getValueType();
9729 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9731 if (VT == MVT::i32 &&
9732 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9733 TLI.isTypeLegal(Vec.getValueType()) &&
9734 isa<ConstantSDNode>(Lane)) {
9737 switch (N->getOpcode()) {
9738 default: llvm_unreachable("unexpected opcode");
9739 case ISD::SIGN_EXTEND:
9740 Opc = ARMISD::VGETLANEs;
9742 case ISD::ZERO_EXTEND:
9743 case ISD::ANY_EXTEND:
9744 Opc = ARMISD::VGETLANEu;
9747 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9754 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9755 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9756 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9757 const ARMSubtarget *ST) {
9758 // If the target supports NEON, try to use vmax/vmin instructions for f32
9759 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9760 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9761 // a NaN; only do the transformation when it matches that behavior.
9763 // For now only do this when using NEON for FP operations; if using VFP, it
9764 // is not obvious that the benefit outweighs the cost of switching to the
9766 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9767 N->getValueType(0) != MVT::f32)
9770 SDValue CondLHS = N->getOperand(0);
9771 SDValue CondRHS = N->getOperand(1);
9772 SDValue LHS = N->getOperand(2);
9773 SDValue RHS = N->getOperand(3);
9774 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9776 unsigned Opcode = 0;
9778 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9779 IsReversed = false; // x CC y ? x : y
9780 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9781 IsReversed = true ; // x CC y ? y : x
9795 // If LHS is NaN, an ordered comparison will be false and the result will
9796 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9797 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9798 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9799 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9801 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9802 // will return -0, so vmin can only be used for unsafe math or if one of
9803 // the operands is known to be nonzero.
9804 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9805 !DAG.getTarget().Options.UnsafeFPMath &&
9806 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9808 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9817 // If LHS is NaN, an ordered comparison will be false and the result will
9818 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9819 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9820 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9821 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9823 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9824 // will return +0, so vmax can only be used for unsafe math or if one of
9825 // the operands is known to be nonzero.
9826 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9827 !DAG.getTarget().Options.UnsafeFPMath &&
9828 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9830 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9836 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9839 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9841 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9842 SDValue Cmp = N->getOperand(4);
9843 if (Cmp.getOpcode() != ARMISD::CMPZ)
9844 // Only looking at EQ and NE cases.
9847 EVT VT = N->getValueType(0);
9849 SDValue LHS = Cmp.getOperand(0);
9850 SDValue RHS = Cmp.getOperand(1);
9851 SDValue FalseVal = N->getOperand(0);
9852 SDValue TrueVal = N->getOperand(1);
9853 SDValue ARMcc = N->getOperand(2);
9854 ARMCC::CondCodes CC =
9855 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9873 /// FIXME: Turn this into a target neutral optimization?
9875 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9876 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9877 N->getOperand(3), Cmp);
9878 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9880 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9881 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9882 N->getOperand(3), NewCmp);
9885 if (Res.getNode()) {
9886 APInt KnownZero, KnownOne;
9887 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9888 // Capture demanded bits information that would be otherwise lost.
9889 if (KnownZero == 0xfffffffe)
9890 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9891 DAG.getValueType(MVT::i1));
9892 else if (KnownZero == 0xffffff00)
9893 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9894 DAG.getValueType(MVT::i8));
9895 else if (KnownZero == 0xffff0000)
9896 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9897 DAG.getValueType(MVT::i16));
9903 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9904 DAGCombinerInfo &DCI) const {
9905 switch (N->getOpcode()) {
9907 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9908 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9909 case ISD::SUB: return PerformSUBCombine(N, DCI);
9910 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9911 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9912 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9913 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9914 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9915 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9916 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9917 case ISD::STORE: return PerformSTORECombine(N, DCI);
9918 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9919 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9920 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9921 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9922 case ISD::FP_TO_SINT:
9923 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9924 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9925 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9928 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9929 case ISD::SIGN_EXTEND:
9930 case ISD::ZERO_EXTEND:
9931 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9932 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9933 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9934 case ISD::LOAD: return PerformLOADCombine(N, DCI);
9935 case ARMISD::VLD2DUP:
9936 case ARMISD::VLD3DUP:
9937 case ARMISD::VLD4DUP:
9938 return PerformVLDCombine(N, DCI);
9939 case ARMISD::BUILD_VECTOR:
9940 return PerformARMBUILD_VECTORCombine(N, DCI);
9941 case ISD::INTRINSIC_VOID:
9942 case ISD::INTRINSIC_W_CHAIN:
9943 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9944 case Intrinsic::arm_neon_vld1:
9945 case Intrinsic::arm_neon_vld2:
9946 case Intrinsic::arm_neon_vld3:
9947 case Intrinsic::arm_neon_vld4:
9948 case Intrinsic::arm_neon_vld2lane:
9949 case Intrinsic::arm_neon_vld3lane:
9950 case Intrinsic::arm_neon_vld4lane:
9951 case Intrinsic::arm_neon_vst1:
9952 case Intrinsic::arm_neon_vst2:
9953 case Intrinsic::arm_neon_vst3:
9954 case Intrinsic::arm_neon_vst4:
9955 case Intrinsic::arm_neon_vst2lane:
9956 case Intrinsic::arm_neon_vst3lane:
9957 case Intrinsic::arm_neon_vst4lane:
9958 return PerformVLDCombine(N, DCI);
9966 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9968 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9971 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9975 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9976 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9978 switch (VT.getSimpleVT().SimpleTy) {
9984 // Unaligned access can use (for example) LRDB, LRDH, LDR
9985 if (AllowsUnaligned) {
9987 *Fast = Subtarget->hasV7Ops();
9994 // For any little-endian targets with neon, we can support unaligned ld/st
9995 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9996 // A big-endian target may also explicitly support unaligned accesses
9997 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10007 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10008 unsigned AlignCheck) {
10009 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10010 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10013 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10014 unsigned DstAlign, unsigned SrcAlign,
10015 bool IsMemset, bool ZeroMemset,
10017 MachineFunction &MF) const {
10018 const Function *F = MF.getFunction();
10020 // See if we can use NEON instructions for this...
10021 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10022 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10025 (memOpAlign(SrcAlign, DstAlign, 16) ||
10026 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10028 } else if (Size >= 8 &&
10029 (memOpAlign(SrcAlign, DstAlign, 8) ||
10030 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10036 // Lowering to i32/i16 if the size permits.
10039 else if (Size >= 2)
10042 // Let the target-independent logic figure it out.
10046 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10047 if (Val.getOpcode() != ISD::LOAD)
10050 EVT VT1 = Val.getValueType();
10051 if (!VT1.isSimple() || !VT1.isInteger() ||
10052 !VT2.isSimple() || !VT2.isInteger())
10055 switch (VT1.getSimpleVT().SimpleTy) {
10060 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10067 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10068 EVT VT = ExtVal.getValueType();
10070 if (!isTypeLegal(VT))
10073 // Don't create a loadext if we can fold the extension into a wide/long
10075 // If there's more than one user instruction, the loadext is desirable no
10076 // matter what. There can be two uses by the same instruction.
10077 if (ExtVal->use_empty() ||
10078 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10081 SDNode *U = *ExtVal->use_begin();
10082 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10083 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10089 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10090 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10093 if (!isTypeLegal(EVT::getEVT(Ty1)))
10096 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10098 // Assuming the caller doesn't have a zeroext or signext return parameter,
10099 // truncation all the way down to i1 is valid.
10104 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10108 unsigned Scale = 1;
10109 switch (VT.getSimpleVT().SimpleTy) {
10110 default: return false;
10125 if ((V & (Scale - 1)) != 0)
10128 return V == (V & ((1LL << 5) - 1));
10131 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10132 const ARMSubtarget *Subtarget) {
10133 bool isNeg = false;
10139 switch (VT.getSimpleVT().SimpleTy) {
10140 default: return false;
10145 // + imm12 or - imm8
10147 return V == (V & ((1LL << 8) - 1));
10148 return V == (V & ((1LL << 12) - 1));
10151 // Same as ARM mode. FIXME: NEON?
10152 if (!Subtarget->hasVFP2())
10157 return V == (V & ((1LL << 8) - 1));
10161 /// isLegalAddressImmediate - Return true if the integer value can be used
10162 /// as the offset of the target addressing mode for load / store of the
10164 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10165 const ARMSubtarget *Subtarget) {
10169 if (!VT.isSimple())
10172 if (Subtarget->isThumb1Only())
10173 return isLegalT1AddressImmediate(V, VT);
10174 else if (Subtarget->isThumb2())
10175 return isLegalT2AddressImmediate(V, VT, Subtarget);
10180 switch (VT.getSimpleVT().SimpleTy) {
10181 default: return false;
10186 return V == (V & ((1LL << 12) - 1));
10189 return V == (V & ((1LL << 8) - 1));
10192 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10197 return V == (V & ((1LL << 8) - 1));
10201 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10203 int Scale = AM.Scale;
10207 switch (VT.getSimpleVT().SimpleTy) {
10208 default: return false;
10216 Scale = Scale & ~1;
10217 return Scale == 2 || Scale == 4 || Scale == 8;
10220 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10224 // Note, we allow "void" uses (basically, uses that aren't loads or
10225 // stores), because arm allows folding a scale into many arithmetic
10226 // operations. This should be made more precise and revisited later.
10228 // Allow r << imm, but the imm has to be a multiple of two.
10229 if (Scale & 1) return false;
10230 return isPowerOf2_32(Scale);
10234 /// isLegalAddressingMode - Return true if the addressing mode represented
10235 /// by AM is legal for this target, for a load/store of the specified type.
10236 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10238 EVT VT = getValueType(Ty, true);
10239 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10242 // Can never fold addr of global into load/store.
10246 switch (AM.Scale) {
10247 case 0: // no scale reg, must be "r+i" or "r", or "i".
10250 if (Subtarget->isThumb1Only())
10254 // ARM doesn't support any R+R*scale+imm addr modes.
10258 if (!VT.isSimple())
10261 if (Subtarget->isThumb2())
10262 return isLegalT2ScaledAddressingMode(AM, VT);
10264 int Scale = AM.Scale;
10265 switch (VT.getSimpleVT().SimpleTy) {
10266 default: return false;
10270 if (Scale < 0) Scale = -Scale;
10274 return isPowerOf2_32(Scale & ~1);
10278 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10283 // Note, we allow "void" uses (basically, uses that aren't loads or
10284 // stores), because arm allows folding a scale into many arithmetic
10285 // operations. This should be made more precise and revisited later.
10287 // Allow r << imm, but the imm has to be a multiple of two.
10288 if (Scale & 1) return false;
10289 return isPowerOf2_32(Scale);
10295 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10296 /// icmp immediate, that is the target has icmp instructions which can compare
10297 /// a register against the immediate without having to materialize the
10298 /// immediate into a register.
10299 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10300 // Thumb2 and ARM modes can use cmn for negative immediates.
10301 if (!Subtarget->isThumb())
10302 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10303 if (Subtarget->isThumb2())
10304 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10305 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10306 return Imm >= 0 && Imm <= 255;
10309 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10310 /// *or sub* immediate, that is the target has add or sub instructions which can
10311 /// add a register with the immediate without having to materialize the
10312 /// immediate into a register.
10313 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10314 // Same encoding for add/sub, just flip the sign.
10315 int64_t AbsImm = std::abs(Imm);
10316 if (!Subtarget->isThumb())
10317 return ARM_AM::getSOImmVal(AbsImm) != -1;
10318 if (Subtarget->isThumb2())
10319 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10320 // Thumb1 only has 8-bit unsigned immediate.
10321 return AbsImm >= 0 && AbsImm <= 255;
10324 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10325 bool isSEXTLoad, SDValue &Base,
10326 SDValue &Offset, bool &isInc,
10327 SelectionDAG &DAG) {
10328 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10331 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10332 // AddressingMode 3
10333 Base = Ptr->getOperand(0);
10334 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10335 int RHSC = (int)RHS->getZExtValue();
10336 if (RHSC < 0 && RHSC > -256) {
10337 assert(Ptr->getOpcode() == ISD::ADD);
10339 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10343 isInc = (Ptr->getOpcode() == ISD::ADD);
10344 Offset = Ptr->getOperand(1);
10346 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10347 // AddressingMode 2
10348 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10349 int RHSC = (int)RHS->getZExtValue();
10350 if (RHSC < 0 && RHSC > -0x1000) {
10351 assert(Ptr->getOpcode() == ISD::ADD);
10353 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10354 Base = Ptr->getOperand(0);
10359 if (Ptr->getOpcode() == ISD::ADD) {
10361 ARM_AM::ShiftOpc ShOpcVal=
10362 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10363 if (ShOpcVal != ARM_AM::no_shift) {
10364 Base = Ptr->getOperand(1);
10365 Offset = Ptr->getOperand(0);
10367 Base = Ptr->getOperand(0);
10368 Offset = Ptr->getOperand(1);
10373 isInc = (Ptr->getOpcode() == ISD::ADD);
10374 Base = Ptr->getOperand(0);
10375 Offset = Ptr->getOperand(1);
10379 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10383 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10384 bool isSEXTLoad, SDValue &Base,
10385 SDValue &Offset, bool &isInc,
10386 SelectionDAG &DAG) {
10387 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10390 Base = Ptr->getOperand(0);
10391 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10392 int RHSC = (int)RHS->getZExtValue();
10393 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10394 assert(Ptr->getOpcode() == ISD::ADD);
10396 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10398 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10399 isInc = Ptr->getOpcode() == ISD::ADD;
10400 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10408 /// getPreIndexedAddressParts - returns true by value, base pointer and
10409 /// offset pointer and addressing mode by reference if the node's address
10410 /// can be legally represented as pre-indexed load / store address.
10412 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10414 ISD::MemIndexedMode &AM,
10415 SelectionDAG &DAG) const {
10416 if (Subtarget->isThumb1Only())
10421 bool isSEXTLoad = false;
10422 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10423 Ptr = LD->getBasePtr();
10424 VT = LD->getMemoryVT();
10425 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10426 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10427 Ptr = ST->getBasePtr();
10428 VT = ST->getMemoryVT();
10433 bool isLegal = false;
10434 if (Subtarget->isThumb2())
10435 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10436 Offset, isInc, DAG);
10438 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10439 Offset, isInc, DAG);
10443 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10447 /// getPostIndexedAddressParts - returns true by value, base pointer and
10448 /// offset pointer and addressing mode by reference if this node can be
10449 /// combined with a load / store to form a post-indexed load / store.
10450 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10453 ISD::MemIndexedMode &AM,
10454 SelectionDAG &DAG) const {
10455 if (Subtarget->isThumb1Only())
10460 bool isSEXTLoad = false;
10461 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10462 VT = LD->getMemoryVT();
10463 Ptr = LD->getBasePtr();
10464 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10465 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10466 VT = ST->getMemoryVT();
10467 Ptr = ST->getBasePtr();
10472 bool isLegal = false;
10473 if (Subtarget->isThumb2())
10474 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10477 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10483 // Swap base ptr and offset to catch more post-index load / store when
10484 // it's legal. In Thumb2 mode, offset must be an immediate.
10485 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10486 !Subtarget->isThumb2())
10487 std::swap(Base, Offset);
10489 // Post-indexed load / store update the base pointer.
10494 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10498 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10501 const SelectionDAG &DAG,
10502 unsigned Depth) const {
10503 unsigned BitWidth = KnownOne.getBitWidth();
10504 KnownZero = KnownOne = APInt(BitWidth, 0);
10505 switch (Op.getOpcode()) {
10511 // These nodes' second result is a boolean
10512 if (Op.getResNo() == 0)
10514 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10516 case ARMISD::CMOV: {
10517 // Bits are known zero/one if known on the LHS and RHS.
10518 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10519 if (KnownZero == 0 && KnownOne == 0) return;
10521 APInt KnownZeroRHS, KnownOneRHS;
10522 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10523 KnownZero &= KnownZeroRHS;
10524 KnownOne &= KnownOneRHS;
10527 case ISD::INTRINSIC_W_CHAIN: {
10528 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10529 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10532 case Intrinsic::arm_ldaex:
10533 case Intrinsic::arm_ldrex: {
10534 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10535 unsigned MemBits = VT.getScalarType().getSizeInBits();
10536 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10544 //===----------------------------------------------------------------------===//
10545 // ARM Inline Assembly Support
10546 //===----------------------------------------------------------------------===//
10548 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10549 // Looking for "rev" which is V6+.
10550 if (!Subtarget->hasV6Ops())
10553 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10554 std::string AsmStr = IA->getAsmString();
10555 SmallVector<StringRef, 4> AsmPieces;
10556 SplitString(AsmStr, AsmPieces, ";\n");
10558 switch (AsmPieces.size()) {
10559 default: return false;
10561 AsmStr = AsmPieces[0];
10563 SplitString(AsmStr, AsmPieces, " \t,");
10566 if (AsmPieces.size() == 3 &&
10567 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10568 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10569 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10570 if (Ty && Ty->getBitWidth() == 32)
10571 return IntrinsicLowering::LowerToByteSwap(CI);
10579 /// getConstraintType - Given a constraint letter, return the type of
10580 /// constraint it is for this target.
10581 ARMTargetLowering::ConstraintType
10582 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10583 if (Constraint.size() == 1) {
10584 switch (Constraint[0]) {
10586 case 'l': return C_RegisterClass;
10587 case 'w': return C_RegisterClass;
10588 case 'h': return C_RegisterClass;
10589 case 'x': return C_RegisterClass;
10590 case 't': return C_RegisterClass;
10591 case 'j': return C_Other; // Constant for movw.
10592 // An address with a single base register. Due to the way we
10593 // currently handle addresses it is the same as an 'r' memory constraint.
10594 case 'Q': return C_Memory;
10596 } else if (Constraint.size() == 2) {
10597 switch (Constraint[0]) {
10599 // All 'U+' constraints are addresses.
10600 case 'U': return C_Memory;
10603 return TargetLowering::getConstraintType(Constraint);
10606 /// Examine constraint type and operand type and determine a weight value.
10607 /// This object must already have been set up with the operand type
10608 /// and the current alternative constraint selected.
10609 TargetLowering::ConstraintWeight
10610 ARMTargetLowering::getSingleConstraintMatchWeight(
10611 AsmOperandInfo &info, const char *constraint) const {
10612 ConstraintWeight weight = CW_Invalid;
10613 Value *CallOperandVal = info.CallOperandVal;
10614 // If we don't have a value, we can't do a match,
10615 // but allow it at the lowest weight.
10616 if (!CallOperandVal)
10618 Type *type = CallOperandVal->getType();
10619 // Look at the constraint type.
10620 switch (*constraint) {
10622 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10625 if (type->isIntegerTy()) {
10626 if (Subtarget->isThumb())
10627 weight = CW_SpecificReg;
10629 weight = CW_Register;
10633 if (type->isFloatingPointTy())
10634 weight = CW_Register;
10640 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10642 ARMTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10643 const std::string &Constraint,
10645 if (Constraint.size() == 1) {
10646 // GCC ARM Constraint Letters
10647 switch (Constraint[0]) {
10648 case 'l': // Low regs or general regs.
10649 if (Subtarget->isThumb())
10650 return RCPair(0U, &ARM::tGPRRegClass);
10651 return RCPair(0U, &ARM::GPRRegClass);
10652 case 'h': // High regs or no regs.
10653 if (Subtarget->isThumb())
10654 return RCPair(0U, &ARM::hGPRRegClass);
10657 if (Subtarget->isThumb1Only())
10658 return RCPair(0U, &ARM::tGPRRegClass);
10659 return RCPair(0U, &ARM::GPRRegClass);
10661 if (VT == MVT::Other)
10663 if (VT == MVT::f32)
10664 return RCPair(0U, &ARM::SPRRegClass);
10665 if (VT.getSizeInBits() == 64)
10666 return RCPair(0U, &ARM::DPRRegClass);
10667 if (VT.getSizeInBits() == 128)
10668 return RCPair(0U, &ARM::QPRRegClass);
10671 if (VT == MVT::Other)
10673 if (VT == MVT::f32)
10674 return RCPair(0U, &ARM::SPR_8RegClass);
10675 if (VT.getSizeInBits() == 64)
10676 return RCPair(0U, &ARM::DPR_8RegClass);
10677 if (VT.getSizeInBits() == 128)
10678 return RCPair(0U, &ARM::QPR_8RegClass);
10681 if (VT == MVT::f32)
10682 return RCPair(0U, &ARM::SPRRegClass);
10686 if (StringRef("{cc}").equals_lower(Constraint))
10687 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10689 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10692 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10693 /// vector. If it is invalid, don't add anything to Ops.
10694 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10695 std::string &Constraint,
10696 std::vector<SDValue>&Ops,
10697 SelectionDAG &DAG) const {
10700 // Currently only support length 1 constraints.
10701 if (Constraint.length() != 1) return;
10703 char ConstraintLetter = Constraint[0];
10704 switch (ConstraintLetter) {
10707 case 'I': case 'J': case 'K': case 'L':
10708 case 'M': case 'N': case 'O':
10709 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10713 int64_t CVal64 = C->getSExtValue();
10714 int CVal = (int) CVal64;
10715 // None of these constraints allow values larger than 32 bits. Check
10716 // that the value fits in an int.
10717 if (CVal != CVal64)
10720 switch (ConstraintLetter) {
10722 // Constant suitable for movw, must be between 0 and
10724 if (Subtarget->hasV6T2Ops())
10725 if (CVal >= 0 && CVal <= 65535)
10729 if (Subtarget->isThumb1Only()) {
10730 // This must be a constant between 0 and 255, for ADD
10732 if (CVal >= 0 && CVal <= 255)
10734 } else if (Subtarget->isThumb2()) {
10735 // A constant that can be used as an immediate value in a
10736 // data-processing instruction.
10737 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10740 // A constant that can be used as an immediate value in a
10741 // data-processing instruction.
10742 if (ARM_AM::getSOImmVal(CVal) != -1)
10748 if (Subtarget->isThumb()) { // FIXME thumb2
10749 // This must be a constant between -255 and -1, for negated ADD
10750 // immediates. This can be used in GCC with an "n" modifier that
10751 // prints the negated value, for use with SUB instructions. It is
10752 // not useful otherwise but is implemented for compatibility.
10753 if (CVal >= -255 && CVal <= -1)
10756 // This must be a constant between -4095 and 4095. It is not clear
10757 // what this constraint is intended for. Implemented for
10758 // compatibility with GCC.
10759 if (CVal >= -4095 && CVal <= 4095)
10765 if (Subtarget->isThumb1Only()) {
10766 // A 32-bit value where only one byte has a nonzero value. Exclude
10767 // zero to match GCC. This constraint is used by GCC internally for
10768 // constants that can be loaded with a move/shift combination.
10769 // It is not useful otherwise but is implemented for compatibility.
10770 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10772 } else if (Subtarget->isThumb2()) {
10773 // A constant whose bitwise inverse can be used as an immediate
10774 // value in a data-processing instruction. This can be used in GCC
10775 // with a "B" modifier that prints the inverted value, for use with
10776 // BIC and MVN instructions. It is not useful otherwise but is
10777 // implemented for compatibility.
10778 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10781 // A constant whose bitwise inverse can be used as an immediate
10782 // value in a data-processing instruction. This can be used in GCC
10783 // with a "B" modifier that prints the inverted value, for use with
10784 // BIC and MVN instructions. It is not useful otherwise but is
10785 // implemented for compatibility.
10786 if (ARM_AM::getSOImmVal(~CVal) != -1)
10792 if (Subtarget->isThumb1Only()) {
10793 // This must be a constant between -7 and 7,
10794 // for 3-operand ADD/SUB immediate instructions.
10795 if (CVal >= -7 && CVal < 7)
10797 } else if (Subtarget->isThumb2()) {
10798 // A constant whose negation can be used as an immediate value in a
10799 // data-processing instruction. This can be used in GCC with an "n"
10800 // modifier that prints the negated value, for use with SUB
10801 // instructions. It is not useful otherwise but is implemented for
10803 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10806 // A constant whose negation can be used as an immediate value in a
10807 // data-processing instruction. This can be used in GCC with an "n"
10808 // modifier that prints the negated value, for use with SUB
10809 // instructions. It is not useful otherwise but is implemented for
10811 if (ARM_AM::getSOImmVal(-CVal) != -1)
10817 if (Subtarget->isThumb()) { // FIXME thumb2
10818 // This must be a multiple of 4 between 0 and 1020, for
10819 // ADD sp + immediate.
10820 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10823 // A power of two or a constant between 0 and 32. This is used in
10824 // GCC for the shift amount on shifted register operands, but it is
10825 // useful in general for any shift amounts.
10826 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10832 if (Subtarget->isThumb()) { // FIXME thumb2
10833 // This must be a constant between 0 and 31, for shift amounts.
10834 if (CVal >= 0 && CVal <= 31)
10840 if (Subtarget->isThumb()) { // FIXME thumb2
10841 // This must be a multiple of 4 between -508 and 508, for
10842 // ADD/SUB sp = sp + immediate.
10843 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10848 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
10852 if (Result.getNode()) {
10853 Ops.push_back(Result);
10856 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10859 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10860 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10861 unsigned Opcode = Op->getOpcode();
10862 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10863 "Invalid opcode for Div/Rem lowering");
10864 bool isSigned = (Opcode == ISD::SDIVREM);
10865 EVT VT = Op->getValueType(0);
10866 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10869 switch (VT.getSimpleVT().SimpleTy) {
10870 default: llvm_unreachable("Unexpected request for libcall!");
10871 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10872 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10873 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10874 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10877 SDValue InChain = DAG.getEntryNode();
10879 TargetLowering::ArgListTy Args;
10880 TargetLowering::ArgListEntry Entry;
10881 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10882 EVT ArgVT = Op->getOperand(i).getValueType();
10883 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10884 Entry.Node = Op->getOperand(i);
10886 Entry.isSExt = isSigned;
10887 Entry.isZExt = !isSigned;
10888 Args.push_back(Entry);
10891 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10894 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10897 TargetLowering::CallLoweringInfo CLI(DAG);
10898 CLI.setDebugLoc(dl).setChain(InChain)
10899 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10900 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10902 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10903 return CallInfo.first;
10907 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10908 assert(Subtarget->isTargetWindows() && "unsupported target platform");
10912 SDValue Chain = Op.getOperand(0);
10913 SDValue Size = Op.getOperand(1);
10915 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10916 DAG.getConstant(2, DL, MVT::i32));
10919 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10920 Flag = Chain.getValue(1);
10922 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10923 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10925 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10926 Chain = NewSP.getValue(1);
10928 SDValue Ops[2] = { NewSP, Chain };
10929 return DAG.getMergeValues(Ops, DL);
10932 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10933 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10934 "Unexpected type for custom-lowering FP_EXTEND");
10937 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10939 SDValue SrcVal = Op.getOperand(0);
10940 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10941 /*isSigned*/ false, SDLoc(Op)).first;
10944 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10945 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10946 Subtarget->isFPOnlySP() &&
10947 "Unexpected type for custom-lowering FP_ROUND");
10950 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10952 SDValue SrcVal = Op.getOperand(0);
10953 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10954 /*isSigned*/ false, SDLoc(Op)).first;
10958 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10959 // The ARM target isn't yet aware of offsets.
10963 bool ARM::isBitFieldInvertedMask(unsigned v) {
10964 if (v == 0xffffffff)
10967 // there can be 1's on either or both "outsides", all the "inside"
10968 // bits must be 0's
10969 return isShiftedMask_32(~v);
10972 /// isFPImmLegal - Returns true if the target can instruction select the
10973 /// specified FP immediate natively. If false, the legalizer will
10974 /// materialize the FP immediate as a load from a constant pool.
10975 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10976 if (!Subtarget->hasVFP3())
10978 if (VT == MVT::f32)
10979 return ARM_AM::getFP32Imm(Imm) != -1;
10980 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10981 return ARM_AM::getFP64Imm(Imm) != -1;
10985 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10986 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10987 /// specified in the intrinsic calls.
10988 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10990 unsigned Intrinsic) const {
10991 switch (Intrinsic) {
10992 case Intrinsic::arm_neon_vld1:
10993 case Intrinsic::arm_neon_vld2:
10994 case Intrinsic::arm_neon_vld3:
10995 case Intrinsic::arm_neon_vld4:
10996 case Intrinsic::arm_neon_vld2lane:
10997 case Intrinsic::arm_neon_vld3lane:
10998 case Intrinsic::arm_neon_vld4lane: {
10999 Info.opc = ISD::INTRINSIC_W_CHAIN;
11000 // Conservatively set memVT to the entire set of vectors loaded.
11001 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11002 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11003 Info.ptrVal = I.getArgOperand(0);
11005 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11006 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11007 Info.vol = false; // volatile loads with NEON intrinsics not supported
11008 Info.readMem = true;
11009 Info.writeMem = false;
11012 case Intrinsic::arm_neon_vst1:
11013 case Intrinsic::arm_neon_vst2:
11014 case Intrinsic::arm_neon_vst3:
11015 case Intrinsic::arm_neon_vst4:
11016 case Intrinsic::arm_neon_vst2lane:
11017 case Intrinsic::arm_neon_vst3lane:
11018 case Intrinsic::arm_neon_vst4lane: {
11019 Info.opc = ISD::INTRINSIC_VOID;
11020 // Conservatively set memVT to the entire set of vectors stored.
11021 unsigned NumElts = 0;
11022 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11023 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11024 if (!ArgTy->isVectorTy())
11026 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11028 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11029 Info.ptrVal = I.getArgOperand(0);
11031 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11032 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11033 Info.vol = false; // volatile stores with NEON intrinsics not supported
11034 Info.readMem = false;
11035 Info.writeMem = true;
11038 case Intrinsic::arm_ldaex:
11039 case Intrinsic::arm_ldrex: {
11040 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11041 Info.opc = ISD::INTRINSIC_W_CHAIN;
11042 Info.memVT = MVT::getVT(PtrTy->getElementType());
11043 Info.ptrVal = I.getArgOperand(0);
11045 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11047 Info.readMem = true;
11048 Info.writeMem = false;
11051 case Intrinsic::arm_stlex:
11052 case Intrinsic::arm_strex: {
11053 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11054 Info.opc = ISD::INTRINSIC_W_CHAIN;
11055 Info.memVT = MVT::getVT(PtrTy->getElementType());
11056 Info.ptrVal = I.getArgOperand(1);
11058 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11060 Info.readMem = false;
11061 Info.writeMem = true;
11064 case Intrinsic::arm_stlexd:
11065 case Intrinsic::arm_strexd: {
11066 Info.opc = ISD::INTRINSIC_W_CHAIN;
11067 Info.memVT = MVT::i64;
11068 Info.ptrVal = I.getArgOperand(2);
11072 Info.readMem = false;
11073 Info.writeMem = true;
11076 case Intrinsic::arm_ldaexd:
11077 case Intrinsic::arm_ldrexd: {
11078 Info.opc = ISD::INTRINSIC_W_CHAIN;
11079 Info.memVT = MVT::i64;
11080 Info.ptrVal = I.getArgOperand(0);
11084 Info.readMem = true;
11085 Info.writeMem = false;
11095 /// \brief Returns true if it is beneficial to convert a load of a constant
11096 /// to just the constant itself.
11097 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11099 assert(Ty->isIntegerTy());
11101 unsigned Bits = Ty->getPrimitiveSizeInBits();
11102 if (Bits == 0 || Bits > 32)
11107 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11109 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11110 ARM_MB::MemBOpt Domain) const {
11111 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11113 // First, if the target has no DMB, see what fallback we can use.
11114 if (!Subtarget->hasDataBarrier()) {
11115 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11116 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11118 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11119 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11120 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11121 Builder.getInt32(0), Builder.getInt32(7),
11122 Builder.getInt32(10), Builder.getInt32(5)};
11123 return Builder.CreateCall(MCR, args);
11125 // Instead of using barriers, atomic accesses on these subtargets use
11127 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11130 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11131 // Only a full system barrier exists in the M-class architectures.
11132 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11133 Constant *CDomain = Builder.getInt32(Domain);
11134 return Builder.CreateCall(DMB, CDomain);
11138 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11139 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11140 AtomicOrdering Ord, bool IsStore,
11141 bool IsLoad) const {
11142 if (!getInsertFencesForAtomic())
11148 llvm_unreachable("Invalid fence: unordered/non-atomic");
11151 return nullptr; // Nothing to do
11152 case SequentiallyConsistent:
11154 return nullptr; // Nothing to do
11157 case AcquireRelease:
11158 if (Subtarget->isSwift())
11159 return makeDMB(Builder, ARM_MB::ISHST);
11160 // FIXME: add a comment with a link to documentation justifying this.
11162 return makeDMB(Builder, ARM_MB::ISH);
11164 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11167 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11168 AtomicOrdering Ord, bool IsStore,
11169 bool IsLoad) const {
11170 if (!getInsertFencesForAtomic())
11176 llvm_unreachable("Invalid fence: unordered/not-atomic");
11179 return nullptr; // Nothing to do
11181 case AcquireRelease:
11182 case SequentiallyConsistent:
11183 return makeDMB(Builder, ARM_MB::ISH);
11185 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11188 // Loads and stores less than 64-bits are already atomic; ones above that
11189 // are doomed anyway, so defer to the default libcall and blame the OS when
11190 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11191 // anything for those.
11192 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11193 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11194 return (Size == 64) && !Subtarget->isMClass();
11197 // Loads and stores less than 64-bits are already atomic; ones above that
11198 // are doomed anyway, so defer to the default libcall and blame the OS when
11199 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11200 // anything for those.
11201 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11202 // guarantee, see DDI0406C ARM architecture reference manual,
11203 // sections A8.8.72-74 LDRD)
11204 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11205 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11206 return (Size == 64) && !Subtarget->isMClass();
11209 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11210 // and up to 64 bits on the non-M profiles
11211 TargetLoweringBase::AtomicRMWExpansionKind
11212 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11213 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11214 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11215 ? AtomicRMWExpansionKind::LLSC
11216 : AtomicRMWExpansionKind::None;
11219 // This has so far only been implemented for MachO.
11220 bool ARMTargetLowering::useLoadStackGuardNode() const {
11221 return Subtarget->isTargetMachO();
11224 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11225 unsigned &Cost) const {
11226 // If we do not have NEON, vector types are not natively supported.
11227 if (!Subtarget->hasNEON())
11230 // Floating point values and vector values map to the same register file.
11231 // Therefore, althought we could do a store extract of a vector type, this is
11232 // better to leave at float as we have more freedom in the addressing mode for
11234 if (VectorTy->isFPOrFPVectorTy())
11237 // If the index is unknown at compile time, this is very expensive to lower
11238 // and it is not possible to combine the store with the extract.
11239 if (!isa<ConstantInt>(Idx))
11242 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11243 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11244 // We can do a store + vector extract on any vector that fits perfectly in a D
11246 if (BitWidth == 64 || BitWidth == 128) {
11253 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11254 AtomicOrdering Ord) const {
11255 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11256 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11257 bool IsAcquire = isAtLeastAcquire(Ord);
11259 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11260 // intrinsic must return {i32, i32} and we have to recombine them into a
11261 // single i64 here.
11262 if (ValTy->getPrimitiveSizeInBits() == 64) {
11263 Intrinsic::ID Int =
11264 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11265 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11267 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11268 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11270 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11271 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11272 if (!Subtarget->isLittle())
11273 std::swap (Lo, Hi);
11274 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11275 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11276 return Builder.CreateOr(
11277 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11280 Type *Tys[] = { Addr->getType() };
11281 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11282 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11284 return Builder.CreateTruncOrBitCast(
11285 Builder.CreateCall(Ldrex, Addr),
11286 cast<PointerType>(Addr->getType())->getElementType());
11289 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11291 AtomicOrdering Ord) const {
11292 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11293 bool IsRelease = isAtLeastRelease(Ord);
11295 // Since the intrinsics must have legal type, the i64 intrinsics take two
11296 // parameters: "i32, i32". We must marshal Val into the appropriate form
11297 // before the call.
11298 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11299 Intrinsic::ID Int =
11300 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11301 Function *Strex = Intrinsic::getDeclaration(M, Int);
11302 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11304 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11305 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11306 if (!Subtarget->isLittle())
11307 std::swap (Lo, Hi);
11308 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11309 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11312 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11313 Type *Tys[] = { Addr->getType() };
11314 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11316 return Builder.CreateCall2(
11317 Strex, Builder.CreateZExtOrBitCast(
11318 Val, Strex->getFunctionType()->getParamType(0)),
11330 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11331 uint64_t &Members) {
11332 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11333 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11334 uint64_t SubMembers = 0;
11335 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11337 Members += SubMembers;
11339 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11340 uint64_t SubMembers = 0;
11341 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11343 Members += SubMembers * AT->getNumElements();
11344 } else if (Ty->isFloatTy()) {
11345 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11349 } else if (Ty->isDoubleTy()) {
11350 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11354 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11361 return VT->getBitWidth() == 64;
11363 return VT->getBitWidth() == 128;
11365 switch (VT->getBitWidth()) {
11378 return (Members > 0 && Members <= 4);
11381 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11382 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11383 /// passing according to AAPCS rules.
11384 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11385 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11386 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11387 CallingConv::ARM_AAPCS_VFP)
11390 HABaseType Base = HA_UNKNOWN;
11391 uint64_t Members = 0;
11392 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11393 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11395 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11396 return IsHA || IsIntArray;