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() && !TM.Options.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 (!TM.Options.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 (!TM.Options.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 (!TM.Options.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 (!TM.Options.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 (TM.Options.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 // FIXME: It might make sense to define the representative register class as the
960 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
961 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
962 // SPR's representative would be DPR_VFP2. This should work well if register
963 // pressure tracking were modified such that a register use would increment the
964 // pressure of the register class's representative and all of it's super
965 // classes' representatives transitively. We have not implemented this because
966 // of the difficulty prior to coalescing of modeling operand register classes
967 // due to the common occurrence of cross class copies and subregister insertions
969 std::pair<const TargetRegisterClass *, uint8_t>
970 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
972 const TargetRegisterClass *RRC = nullptr;
974 switch (VT.SimpleTy) {
976 return TargetLowering::findRepresentativeClass(TRI, VT);
977 // Use DPR as representative register class for all floating point
978 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
979 // the cost is 1 for both f32 and f64.
980 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
981 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
982 RRC = &ARM::DPRRegClass;
983 // When NEON is used for SP, only half of the register file is available
984 // because operations that define both SP and DP results will be constrained
985 // to the VFP2 class (D0-D15). We currently model this constraint prior to
986 // coalescing by double-counting the SP regs. See the FIXME above.
987 if (Subtarget->useNEONForSinglePrecisionFP())
990 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
991 case MVT::v4f32: case MVT::v2f64:
992 RRC = &ARM::DPRRegClass;
996 RRC = &ARM::DPRRegClass;
1000 RRC = &ARM::DPRRegClass;
1004 return std::make_pair(RRC, Cost);
1007 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1009 default: return nullptr;
1010 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1011 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1012 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1013 case ARMISD::CALL: return "ARMISD::CALL";
1014 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1015 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1016 case ARMISD::tCALL: return "ARMISD::tCALL";
1017 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1018 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1019 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1020 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1021 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1022 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1023 case ARMISD::CMP: return "ARMISD::CMP";
1024 case ARMISD::CMN: return "ARMISD::CMN";
1025 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1026 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1027 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1028 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1029 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1031 case ARMISD::CMOV: return "ARMISD::CMOV";
1033 case ARMISD::RBIT: return "ARMISD::RBIT";
1035 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1036 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1037 case ARMISD::RRX: return "ARMISD::RRX";
1039 case ARMISD::ADDC: return "ARMISD::ADDC";
1040 case ARMISD::ADDE: return "ARMISD::ADDE";
1041 case ARMISD::SUBC: return "ARMISD::SUBC";
1042 case ARMISD::SUBE: return "ARMISD::SUBE";
1044 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1045 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1047 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1048 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1050 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1052 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1054 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1056 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1058 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1060 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1062 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1063 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1064 case ARMISD::VCGE: return "ARMISD::VCGE";
1065 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1066 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1067 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1068 case ARMISD::VCGT: return "ARMISD::VCGT";
1069 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1070 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1071 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1072 case ARMISD::VTST: return "ARMISD::VTST";
1074 case ARMISD::VSHL: return "ARMISD::VSHL";
1075 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1076 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1077 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1078 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1079 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1080 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1081 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1082 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1083 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1084 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1085 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1086 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1087 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1088 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1089 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1090 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1091 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1092 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1093 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1094 case ARMISD::VDUP: return "ARMISD::VDUP";
1095 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1096 case ARMISD::VEXT: return "ARMISD::VEXT";
1097 case ARMISD::VREV64: return "ARMISD::VREV64";
1098 case ARMISD::VREV32: return "ARMISD::VREV32";
1099 case ARMISD::VREV16: return "ARMISD::VREV16";
1100 case ARMISD::VZIP: return "ARMISD::VZIP";
1101 case ARMISD::VUZP: return "ARMISD::VUZP";
1102 case ARMISD::VTRN: return "ARMISD::VTRN";
1103 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1104 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1105 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1106 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1107 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1108 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1109 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1110 case ARMISD::FMAX: return "ARMISD::FMAX";
1111 case ARMISD::FMIN: return "ARMISD::FMIN";
1112 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1113 case ARMISD::VMINNM: return "ARMISD::VMIN";
1114 case ARMISD::BFI: return "ARMISD::BFI";
1115 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1116 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1117 case ARMISD::VBSL: return "ARMISD::VBSL";
1118 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1119 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1120 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1121 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1122 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1123 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1124 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1125 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1126 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1127 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1128 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1129 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1130 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1131 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1132 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1133 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1134 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1135 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1136 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1137 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1141 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1142 if (!VT.isVector()) return getPointerTy();
1143 return VT.changeVectorElementTypeToInteger();
1146 /// getRegClassFor - Return the register class that should be used for the
1147 /// specified value type.
1148 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1149 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1150 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1151 // load / store 4 to 8 consecutive D registers.
1152 if (Subtarget->hasNEON()) {
1153 if (VT == MVT::v4i64)
1154 return &ARM::QQPRRegClass;
1155 if (VT == MVT::v8i64)
1156 return &ARM::QQQQPRRegClass;
1158 return TargetLowering::getRegClassFor(VT);
1161 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1162 // source/dest is aligned and the copy size is large enough. We therefore want
1163 // to align such objects passed to memory intrinsics.
1164 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1165 unsigned &PrefAlign) const {
1166 if (!isa<MemIntrinsic>(CI))
1169 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1170 // cycle faster than 4-byte aligned LDM.
1171 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1175 // Create a fast isel object.
1177 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1178 const TargetLibraryInfo *libInfo) const {
1179 return ARM::createFastISel(funcInfo, libInfo);
1182 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1183 unsigned NumVals = N->getNumValues();
1185 return Sched::RegPressure;
1187 for (unsigned i = 0; i != NumVals; ++i) {
1188 EVT VT = N->getValueType(i);
1189 if (VT == MVT::Glue || VT == MVT::Other)
1191 if (VT.isFloatingPoint() || VT.isVector())
1195 if (!N->isMachineOpcode())
1196 return Sched::RegPressure;
1198 // Load are scheduled for latency even if there instruction itinerary
1199 // is not available.
1200 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1201 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1203 if (MCID.getNumDefs() == 0)
1204 return Sched::RegPressure;
1205 if (!Itins->isEmpty() &&
1206 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1209 return Sched::RegPressure;
1212 //===----------------------------------------------------------------------===//
1214 //===----------------------------------------------------------------------===//
1216 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1217 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1219 default: llvm_unreachable("Unknown condition code!");
1220 case ISD::SETNE: return ARMCC::NE;
1221 case ISD::SETEQ: return ARMCC::EQ;
1222 case ISD::SETGT: return ARMCC::GT;
1223 case ISD::SETGE: return ARMCC::GE;
1224 case ISD::SETLT: return ARMCC::LT;
1225 case ISD::SETLE: return ARMCC::LE;
1226 case ISD::SETUGT: return ARMCC::HI;
1227 case ISD::SETUGE: return ARMCC::HS;
1228 case ISD::SETULT: return ARMCC::LO;
1229 case ISD::SETULE: return ARMCC::LS;
1233 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1234 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1235 ARMCC::CondCodes &CondCode2) {
1236 CondCode2 = ARMCC::AL;
1238 default: llvm_unreachable("Unknown FP condition!");
1240 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1242 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1244 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1245 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1246 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1247 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1248 case ISD::SETO: CondCode = ARMCC::VC; break;
1249 case ISD::SETUO: CondCode = ARMCC::VS; break;
1250 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1251 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1252 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1254 case ISD::SETULT: CondCode = ARMCC::LT; break;
1256 case ISD::SETULE: CondCode = ARMCC::LE; break;
1258 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1262 //===----------------------------------------------------------------------===//
1263 // Calling Convention Implementation
1264 //===----------------------------------------------------------------------===//
1266 #include "ARMGenCallingConv.inc"
1268 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1269 /// account presence of floating point hardware and calling convention
1270 /// limitations, such as support for variadic functions.
1272 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1273 bool isVarArg) const {
1276 llvm_unreachable("Unsupported calling convention");
1277 case CallingConv::ARM_AAPCS:
1278 case CallingConv::ARM_APCS:
1279 case CallingConv::GHC:
1281 case CallingConv::ARM_AAPCS_VFP:
1282 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1283 case CallingConv::C:
1284 if (!Subtarget->isAAPCS_ABI())
1285 return CallingConv::ARM_APCS;
1286 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1287 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1289 return CallingConv::ARM_AAPCS_VFP;
1291 return CallingConv::ARM_AAPCS;
1292 case CallingConv::Fast:
1293 if (!Subtarget->isAAPCS_ABI()) {
1294 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1295 return CallingConv::Fast;
1296 return CallingConv::ARM_APCS;
1297 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1298 return CallingConv::ARM_AAPCS_VFP;
1300 return CallingConv::ARM_AAPCS;
1304 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1305 /// CallingConvention.
1306 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1308 bool isVarArg) const {
1309 switch (getEffectiveCallingConv(CC, isVarArg)) {
1311 llvm_unreachable("Unsupported calling convention");
1312 case CallingConv::ARM_APCS:
1313 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1314 case CallingConv::ARM_AAPCS:
1315 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1316 case CallingConv::ARM_AAPCS_VFP:
1317 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1318 case CallingConv::Fast:
1319 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1320 case CallingConv::GHC:
1321 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1325 /// LowerCallResult - Lower the result values of a call into the
1326 /// appropriate copies out of appropriate physical registers.
1328 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1329 CallingConv::ID CallConv, bool isVarArg,
1330 const SmallVectorImpl<ISD::InputArg> &Ins,
1331 SDLoc dl, SelectionDAG &DAG,
1332 SmallVectorImpl<SDValue> &InVals,
1333 bool isThisReturn, SDValue ThisVal) const {
1335 // Assign locations to each value returned by this call.
1336 SmallVector<CCValAssign, 16> RVLocs;
1337 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1338 *DAG.getContext(), Call);
1339 CCInfo.AnalyzeCallResult(Ins,
1340 CCAssignFnForNode(CallConv, /* Return*/ true,
1343 // Copy all of the result registers out of their specified physreg.
1344 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1345 CCValAssign VA = RVLocs[i];
1347 // Pass 'this' value directly from the argument to return value, to avoid
1348 // reg unit interference
1349 if (i == 0 && isThisReturn) {
1350 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1351 "unexpected return calling convention register assignment");
1352 InVals.push_back(ThisVal);
1357 if (VA.needsCustom()) {
1358 // Handle f64 or half of a v2f64.
1359 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1361 Chain = Lo.getValue(1);
1362 InFlag = Lo.getValue(2);
1363 VA = RVLocs[++i]; // skip ahead to next loc
1364 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1366 Chain = Hi.getValue(1);
1367 InFlag = Hi.getValue(2);
1368 if (!Subtarget->isLittle())
1370 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1372 if (VA.getLocVT() == MVT::v2f64) {
1373 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1374 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1375 DAG.getConstant(0, MVT::i32));
1377 VA = RVLocs[++i]; // skip ahead to next loc
1378 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1379 Chain = Lo.getValue(1);
1380 InFlag = Lo.getValue(2);
1381 VA = RVLocs[++i]; // skip ahead to next loc
1382 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1383 Chain = Hi.getValue(1);
1384 InFlag = Hi.getValue(2);
1385 if (!Subtarget->isLittle())
1387 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1388 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1389 DAG.getConstant(1, MVT::i32));
1392 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1394 Chain = Val.getValue(1);
1395 InFlag = Val.getValue(2);
1398 switch (VA.getLocInfo()) {
1399 default: llvm_unreachable("Unknown loc info!");
1400 case CCValAssign::Full: break;
1401 case CCValAssign::BCvt:
1402 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1406 InVals.push_back(Val);
1412 /// LowerMemOpCallTo - Store the argument to the stack.
1414 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1415 SDValue StackPtr, SDValue Arg,
1416 SDLoc dl, SelectionDAG &DAG,
1417 const CCValAssign &VA,
1418 ISD::ArgFlagsTy Flags) const {
1419 unsigned LocMemOffset = VA.getLocMemOffset();
1420 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1421 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1422 return DAG.getStore(Chain, dl, Arg, PtrOff,
1423 MachinePointerInfo::getStack(LocMemOffset),
1427 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1428 SDValue Chain, SDValue &Arg,
1429 RegsToPassVector &RegsToPass,
1430 CCValAssign &VA, CCValAssign &NextVA,
1432 SmallVectorImpl<SDValue> &MemOpChains,
1433 ISD::ArgFlagsTy Flags) const {
1435 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1436 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1437 unsigned id = Subtarget->isLittle() ? 0 : 1;
1438 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1440 if (NextVA.isRegLoc())
1441 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1443 assert(NextVA.isMemLoc());
1444 if (!StackPtr.getNode())
1445 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1447 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1453 /// LowerCall - Lowering a call into a callseq_start <-
1454 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1457 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1458 SmallVectorImpl<SDValue> &InVals) const {
1459 SelectionDAG &DAG = CLI.DAG;
1461 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1462 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1463 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1464 SDValue Chain = CLI.Chain;
1465 SDValue Callee = CLI.Callee;
1466 bool &isTailCall = CLI.IsTailCall;
1467 CallingConv::ID CallConv = CLI.CallConv;
1468 bool doesNotRet = CLI.DoesNotReturn;
1469 bool isVarArg = CLI.IsVarArg;
1471 MachineFunction &MF = DAG.getMachineFunction();
1472 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1473 bool isThisReturn = false;
1474 bool isSibCall = false;
1476 // Disable tail calls if they're not supported.
1477 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1481 // Check if it's really possible to do a tail call.
1482 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1483 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1484 Outs, OutVals, Ins, DAG);
1485 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1486 report_fatal_error("failed to perform tail call elimination on a call "
1487 "site marked musttail");
1488 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1489 // detected sibcalls.
1496 // Analyze operands of the call, assigning locations to each operand.
1497 SmallVector<CCValAssign, 16> ArgLocs;
1498 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1499 *DAG.getContext(), Call);
1500 CCInfo.AnalyzeCallOperands(Outs,
1501 CCAssignFnForNode(CallConv, /* Return*/ false,
1504 // Get a count of how many bytes are to be pushed on the stack.
1505 unsigned NumBytes = CCInfo.getNextStackOffset();
1507 // For tail calls, memory operands are available in our caller's stack.
1511 // Adjust the stack pointer for the new arguments...
1512 // These operations are automatically eliminated by the prolog/epilog pass
1514 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1517 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1519 RegsToPassVector RegsToPass;
1520 SmallVector<SDValue, 8> MemOpChains;
1522 // Walk the register/memloc assignments, inserting copies/loads. In the case
1523 // of tail call optimization, arguments are handled later.
1524 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1526 ++i, ++realArgIdx) {
1527 CCValAssign &VA = ArgLocs[i];
1528 SDValue Arg = OutVals[realArgIdx];
1529 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1530 bool isByVal = Flags.isByVal();
1532 // Promote the value if needed.
1533 switch (VA.getLocInfo()) {
1534 default: llvm_unreachable("Unknown loc info!");
1535 case CCValAssign::Full: break;
1536 case CCValAssign::SExt:
1537 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1539 case CCValAssign::ZExt:
1540 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1542 case CCValAssign::AExt:
1543 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1545 case CCValAssign::BCvt:
1546 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1550 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1551 if (VA.needsCustom()) {
1552 if (VA.getLocVT() == MVT::v2f64) {
1553 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1554 DAG.getConstant(0, MVT::i32));
1555 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1556 DAG.getConstant(1, MVT::i32));
1558 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1559 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1561 VA = ArgLocs[++i]; // skip ahead to next loc
1562 if (VA.isRegLoc()) {
1563 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1564 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1566 assert(VA.isMemLoc());
1568 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1569 dl, DAG, VA, Flags));
1572 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1573 StackPtr, MemOpChains, Flags);
1575 } else if (VA.isRegLoc()) {
1576 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1577 assert(VA.getLocVT() == MVT::i32 &&
1578 "unexpected calling convention register assignment");
1579 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1580 "unexpected use of 'returned'");
1581 isThisReturn = true;
1583 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1584 } else if (isByVal) {
1585 assert(VA.isMemLoc());
1586 unsigned offset = 0;
1588 // True if this byval aggregate will be split between registers
1590 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1591 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1593 if (CurByValIdx < ByValArgsCount) {
1595 unsigned RegBegin, RegEnd;
1596 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1598 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1600 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1601 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1602 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1603 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1604 MachinePointerInfo(),
1605 false, false, false,
1606 DAG.InferPtrAlignment(AddArg));
1607 MemOpChains.push_back(Load.getValue(1));
1608 RegsToPass.push_back(std::make_pair(j, Load));
1611 // If parameter size outsides register area, "offset" value
1612 // helps us to calculate stack slot for remained part properly.
1613 offset = RegEnd - RegBegin;
1615 CCInfo.nextInRegsParam();
1618 if (Flags.getByValSize() > 4*offset) {
1619 unsigned LocMemOffset = VA.getLocMemOffset();
1620 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1621 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1623 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1624 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1625 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1627 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1629 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1630 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1631 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1634 } else if (!isSibCall) {
1635 assert(VA.isMemLoc());
1637 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1638 dl, DAG, VA, Flags));
1642 if (!MemOpChains.empty())
1643 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1645 // Build a sequence of copy-to-reg nodes chained together with token chain
1646 // and flag operands which copy the outgoing args into the appropriate regs.
1648 // Tail call byval lowering might overwrite argument registers so in case of
1649 // tail call optimization the copies to registers are lowered later.
1651 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1652 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1653 RegsToPass[i].second, InFlag);
1654 InFlag = Chain.getValue(1);
1657 // For tail calls lower the arguments to the 'real' stack slot.
1659 // Force all the incoming stack arguments to be loaded from the stack
1660 // before any new outgoing arguments are stored to the stack, because the
1661 // outgoing stack slots may alias the incoming argument stack slots, and
1662 // the alias isn't otherwise explicit. This is slightly more conservative
1663 // than necessary, because it means that each store effectively depends
1664 // on every argument instead of just those arguments it would clobber.
1666 // Do not flag preceding copytoreg stuff together with the following stuff.
1668 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1669 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1670 RegsToPass[i].second, InFlag);
1671 InFlag = Chain.getValue(1);
1676 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1677 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1678 // node so that legalize doesn't hack it.
1679 bool isDirect = false;
1680 bool isARMFunc = false;
1681 bool isLocalARMFunc = false;
1682 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1684 if (EnableARMLongCalls) {
1685 assert((Subtarget->isTargetWindows() ||
1686 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1687 "long-calls with non-static relocation model!");
1688 // Handle a global address or an external symbol. If it's not one of
1689 // those, the target's already in a register, so we don't need to do
1691 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1692 const GlobalValue *GV = G->getGlobal();
1693 // Create a constant pool entry for the callee address
1694 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1695 ARMConstantPoolValue *CPV =
1696 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1698 // Get the address of the callee into a register
1699 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1700 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1701 Callee = DAG.getLoad(getPointerTy(), dl,
1702 DAG.getEntryNode(), CPAddr,
1703 MachinePointerInfo::getConstantPool(),
1704 false, false, false, 0);
1705 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1706 const char *Sym = S->getSymbol();
1708 // Create a constant pool entry for the callee address
1709 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1710 ARMConstantPoolValue *CPV =
1711 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1712 ARMPCLabelIndex, 0);
1713 // Get the address of the callee into a register
1714 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1715 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1716 Callee = DAG.getLoad(getPointerTy(), dl,
1717 DAG.getEntryNode(), CPAddr,
1718 MachinePointerInfo::getConstantPool(),
1719 false, false, false, 0);
1721 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1722 const GlobalValue *GV = G->getGlobal();
1724 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1725 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1726 getTargetMachine().getRelocationModel() != Reloc::Static;
1727 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1728 // ARM call to a local ARM function is predicable.
1729 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1730 // tBX takes a register source operand.
1731 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1732 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1733 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1734 DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1735 0, ARMII::MO_NONLAZY));
1736 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1737 MachinePointerInfo::getGOT(), false, false, true, 0);
1738 } else if (Subtarget->isTargetCOFF()) {
1739 assert(Subtarget->isTargetWindows() &&
1740 "Windows is the only supported COFF target");
1741 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1742 ? ARMII::MO_DLLIMPORT
1743 : ARMII::MO_NO_FLAG;
1744 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1746 if (GV->hasDLLImportStorageClass())
1747 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1748 DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1749 Callee), MachinePointerInfo::getGOT(),
1750 false, false, false, 0);
1752 // On ELF targets for PIC code, direct calls should go through the PLT
1753 unsigned OpFlags = 0;
1754 if (Subtarget->isTargetELF() &&
1755 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1756 OpFlags = ARMII::MO_PLT;
1757 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1759 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1761 bool isStub = Subtarget->isTargetMachO() &&
1762 getTargetMachine().getRelocationModel() != Reloc::Static;
1763 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1764 // tBX takes a register source operand.
1765 const char *Sym = S->getSymbol();
1766 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1767 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1768 ARMConstantPoolValue *CPV =
1769 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1770 ARMPCLabelIndex, 4);
1771 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1772 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1773 Callee = DAG.getLoad(getPointerTy(), dl,
1774 DAG.getEntryNode(), CPAddr,
1775 MachinePointerInfo::getConstantPool(),
1776 false, false, false, 0);
1777 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1778 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1779 getPointerTy(), Callee, PICLabel);
1781 unsigned OpFlags = 0;
1782 // On ELF targets for PIC code, direct calls should go through the PLT
1783 if (Subtarget->isTargetELF() &&
1784 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1785 OpFlags = ARMII::MO_PLT;
1786 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1790 // FIXME: handle tail calls differently.
1792 bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1793 if (Subtarget->isThumb()) {
1794 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1795 CallOpc = ARMISD::CALL_NOLINK;
1797 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1799 if (!isDirect && !Subtarget->hasV5TOps())
1800 CallOpc = ARMISD::CALL_NOLINK;
1801 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1802 // Emit regular call when code size is the priority
1804 // "mov lr, pc; b _foo" to avoid confusing the RSP
1805 CallOpc = ARMISD::CALL_NOLINK;
1807 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1810 std::vector<SDValue> Ops;
1811 Ops.push_back(Chain);
1812 Ops.push_back(Callee);
1814 // Add argument registers to the end of the list so that they are known live
1816 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1817 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1818 RegsToPass[i].second.getValueType()));
1820 // Add a register mask operand representing the call-preserved registers.
1822 const uint32_t *Mask;
1823 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1825 // For 'this' returns, use the R0-preserving mask if applicable
1826 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1828 // Set isThisReturn to false if the calling convention is not one that
1829 // allows 'returned' to be modeled in this way, so LowerCallResult does
1830 // not try to pass 'this' straight through
1831 isThisReturn = false;
1832 Mask = ARI->getCallPreservedMask(MF, CallConv);
1835 Mask = ARI->getCallPreservedMask(MF, CallConv);
1837 assert(Mask && "Missing call preserved mask for calling convention");
1838 Ops.push_back(DAG.getRegisterMask(Mask));
1841 if (InFlag.getNode())
1842 Ops.push_back(InFlag);
1844 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1846 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1848 // Returns a chain and a flag for retval copy to use.
1849 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1850 InFlag = Chain.getValue(1);
1852 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1853 DAG.getIntPtrConstant(0, true), InFlag, dl);
1855 InFlag = Chain.getValue(1);
1857 // Handle result values, copying them out of physregs into vregs that we
1859 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1860 InVals, isThisReturn,
1861 isThisReturn ? OutVals[0] : SDValue());
1864 /// HandleByVal - Every parameter *after* a byval parameter is passed
1865 /// on the stack. Remember the next parameter register to allocate,
1866 /// and then confiscate the rest of the parameter registers to insure
1868 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1869 unsigned Align) const {
1870 assert((State->getCallOrPrologue() == Prologue ||
1871 State->getCallOrPrologue() == Call) &&
1872 "unhandled ParmContext");
1874 // Byval (as with any stack) slots are always at least 4 byte aligned.
1875 Align = std::max(Align, 4U);
1877 unsigned Reg = State->AllocateReg(GPRArgRegs);
1881 unsigned AlignInRegs = Align / 4;
1882 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1883 for (unsigned i = 0; i < Waste; ++i)
1884 Reg = State->AllocateReg(GPRArgRegs);
1889 unsigned Excess = 4 * (ARM::R4 - Reg);
1891 // Special case when NSAA != SP and parameter size greater than size of
1892 // all remained GPR regs. In that case we can't split parameter, we must
1893 // send it to stack. We also must set NCRN to R4, so waste all
1894 // remained registers.
1895 const unsigned NSAAOffset = State->getNextStackOffset();
1896 if (NSAAOffset != 0 && Size > Excess) {
1897 while (State->AllocateReg(GPRArgRegs))
1902 // First register for byval parameter is the first register that wasn't
1903 // allocated before this method call, so it would be "reg".
1904 // If parameter is small enough to be saved in range [reg, r4), then
1905 // the end (first after last) register would be reg + param-size-in-regs,
1906 // else parameter would be splitted between registers and stack,
1907 // end register would be r4 in this case.
1908 unsigned ByValRegBegin = Reg;
1909 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1910 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1911 // Note, first register is allocated in the beginning of function already,
1912 // allocate remained amount of registers we need.
1913 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1914 State->AllocateReg(GPRArgRegs);
1915 // A byval parameter that is split between registers and memory needs its
1916 // size truncated here.
1917 // In the case where the entire structure fits in registers, we set the
1918 // size in memory to zero.
1919 Size = std::max<int>(Size - Excess, 0);
1923 /// MatchingStackOffset - Return true if the given stack call argument is
1924 /// already available in the same position (relatively) of the caller's
1925 /// incoming argument stack.
1927 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1928 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1929 const TargetInstrInfo *TII) {
1930 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1932 if (Arg.getOpcode() == ISD::CopyFromReg) {
1933 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1934 if (!TargetRegisterInfo::isVirtualRegister(VR))
1936 MachineInstr *Def = MRI->getVRegDef(VR);
1939 if (!Flags.isByVal()) {
1940 if (!TII->isLoadFromStackSlot(Def, FI))
1945 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1946 if (Flags.isByVal())
1947 // ByVal argument is passed in as a pointer but it's now being
1948 // dereferenced. e.g.
1949 // define @foo(%struct.X* %A) {
1950 // tail call @bar(%struct.X* byval %A)
1953 SDValue Ptr = Ld->getBasePtr();
1954 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1957 FI = FINode->getIndex();
1961 assert(FI != INT_MAX);
1962 if (!MFI->isFixedObjectIndex(FI))
1964 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1967 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1968 /// for tail call optimization. Targets which want to do tail call
1969 /// optimization should implement this function.
1971 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1972 CallingConv::ID CalleeCC,
1974 bool isCalleeStructRet,
1975 bool isCallerStructRet,
1976 const SmallVectorImpl<ISD::OutputArg> &Outs,
1977 const SmallVectorImpl<SDValue> &OutVals,
1978 const SmallVectorImpl<ISD::InputArg> &Ins,
1979 SelectionDAG& DAG) const {
1980 const Function *CallerF = DAG.getMachineFunction().getFunction();
1981 CallingConv::ID CallerCC = CallerF->getCallingConv();
1982 bool CCMatch = CallerCC == CalleeCC;
1984 // Look for obvious safe cases to perform tail call optimization that do not
1985 // require ABI changes. This is what gcc calls sibcall.
1987 // Do not sibcall optimize vararg calls unless the call site is not passing
1989 if (isVarArg && !Outs.empty())
1992 // Exception-handling functions need a special set of instructions to indicate
1993 // a return to the hardware. Tail-calling another function would probably
1995 if (CallerF->hasFnAttribute("interrupt"))
1998 // Also avoid sibcall optimization if either caller or callee uses struct
1999 // return semantics.
2000 if (isCalleeStructRet || isCallerStructRet)
2003 // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2004 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2005 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2006 // support in the assembler and linker to be used. This would need to be
2007 // fixed to fully support tail calls in Thumb1.
2009 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2010 // LR. This means if we need to reload LR, it takes an extra instructions,
2011 // which outweighs the value of the tail call; but here we don't know yet
2012 // whether LR is going to be used. Probably the right approach is to
2013 // generate the tail call here and turn it back into CALL/RET in
2014 // emitEpilogue if LR is used.
2016 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2017 // but we need to make sure there are enough registers; the only valid
2018 // registers are the 4 used for parameters. We don't currently do this
2020 if (Subtarget->isThumb1Only())
2023 // Externally-defined functions with weak linkage should not be
2024 // tail-called on ARM when the OS does not support dynamic
2025 // pre-emption of symbols, as the AAELF spec requires normal calls
2026 // to undefined weak functions to be replaced with a NOP or jump to the
2027 // next instruction. The behaviour of branch instructions in this
2028 // situation (as used for tail calls) is implementation-defined, so we
2029 // cannot rely on the linker replacing the tail call with a return.
2030 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2031 const GlobalValue *GV = G->getGlobal();
2032 const Triple TT(getTargetMachine().getTargetTriple());
2033 if (GV->hasExternalWeakLinkage() &&
2034 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2038 // If the calling conventions do not match, then we'd better make sure the
2039 // results are returned in the same way as what the caller expects.
2041 SmallVector<CCValAssign, 16> RVLocs1;
2042 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2043 *DAG.getContext(), Call);
2044 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2046 SmallVector<CCValAssign, 16> RVLocs2;
2047 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2048 *DAG.getContext(), Call);
2049 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2051 if (RVLocs1.size() != RVLocs2.size())
2053 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2054 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2056 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2058 if (RVLocs1[i].isRegLoc()) {
2059 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2062 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2068 // If Caller's vararg or byval argument has been split between registers and
2069 // stack, do not perform tail call, since part of the argument is in caller's
2071 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2072 getInfo<ARMFunctionInfo>();
2073 if (AFI_Caller->getArgRegsSaveSize())
2076 // If the callee takes no arguments then go on to check the results of the
2078 if (!Outs.empty()) {
2079 // Check if stack adjustment is needed. For now, do not do this if any
2080 // argument is passed on the stack.
2081 SmallVector<CCValAssign, 16> ArgLocs;
2082 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2083 *DAG.getContext(), Call);
2084 CCInfo.AnalyzeCallOperands(Outs,
2085 CCAssignFnForNode(CalleeCC, false, isVarArg));
2086 if (CCInfo.getNextStackOffset()) {
2087 MachineFunction &MF = DAG.getMachineFunction();
2089 // Check if the arguments are already laid out in the right way as
2090 // the caller's fixed stack objects.
2091 MachineFrameInfo *MFI = MF.getFrameInfo();
2092 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2093 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2094 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2096 ++i, ++realArgIdx) {
2097 CCValAssign &VA = ArgLocs[i];
2098 EVT RegVT = VA.getLocVT();
2099 SDValue Arg = OutVals[realArgIdx];
2100 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2101 if (VA.getLocInfo() == CCValAssign::Indirect)
2103 if (VA.needsCustom()) {
2104 // f64 and vector types are split into multiple registers or
2105 // register/stack-slot combinations. The types will not match
2106 // the registers; give up on memory f64 refs until we figure
2107 // out what to do about this.
2110 if (!ArgLocs[++i].isRegLoc())
2112 if (RegVT == MVT::v2f64) {
2113 if (!ArgLocs[++i].isRegLoc())
2115 if (!ArgLocs[++i].isRegLoc())
2118 } else if (!VA.isRegLoc()) {
2119 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2131 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2132 MachineFunction &MF, bool isVarArg,
2133 const SmallVectorImpl<ISD::OutputArg> &Outs,
2134 LLVMContext &Context) const {
2135 SmallVector<CCValAssign, 16> RVLocs;
2136 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2137 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2141 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2142 SDLoc DL, SelectionDAG &DAG) {
2143 const MachineFunction &MF = DAG.getMachineFunction();
2144 const Function *F = MF.getFunction();
2146 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2148 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2149 // version of the "preferred return address". These offsets affect the return
2150 // instruction if this is a return from PL1 without hypervisor extensions.
2151 // IRQ/FIQ: +4 "subs pc, lr, #4"
2152 // SWI: 0 "subs pc, lr, #0"
2153 // ABORT: +4 "subs pc, lr, #4"
2154 // UNDEF: +4/+2 "subs pc, lr, #0"
2155 // UNDEF varies depending on where the exception came from ARM or Thumb
2156 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2159 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2162 else if (IntKind == "SWI" || IntKind == "UNDEF")
2165 report_fatal_error("Unsupported interrupt attribute. If present, value "
2166 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2168 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2170 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2174 ARMTargetLowering::LowerReturn(SDValue Chain,
2175 CallingConv::ID CallConv, bool isVarArg,
2176 const SmallVectorImpl<ISD::OutputArg> &Outs,
2177 const SmallVectorImpl<SDValue> &OutVals,
2178 SDLoc dl, SelectionDAG &DAG) const {
2180 // CCValAssign - represent the assignment of the return value to a location.
2181 SmallVector<CCValAssign, 16> RVLocs;
2183 // CCState - Info about the registers and stack slots.
2184 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2185 *DAG.getContext(), Call);
2187 // Analyze outgoing return values.
2188 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2192 SmallVector<SDValue, 4> RetOps;
2193 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2194 bool isLittleEndian = Subtarget->isLittle();
2196 MachineFunction &MF = DAG.getMachineFunction();
2197 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2198 AFI->setReturnRegsCount(RVLocs.size());
2200 // Copy the result values into the output registers.
2201 for (unsigned i = 0, realRVLocIdx = 0;
2203 ++i, ++realRVLocIdx) {
2204 CCValAssign &VA = RVLocs[i];
2205 assert(VA.isRegLoc() && "Can only return in registers!");
2207 SDValue Arg = OutVals[realRVLocIdx];
2209 switch (VA.getLocInfo()) {
2210 default: llvm_unreachable("Unknown loc info!");
2211 case CCValAssign::Full: break;
2212 case CCValAssign::BCvt:
2213 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2217 if (VA.needsCustom()) {
2218 if (VA.getLocVT() == MVT::v2f64) {
2219 // Extract the first half and return it in two registers.
2220 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2221 DAG.getConstant(0, MVT::i32));
2222 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2223 DAG.getVTList(MVT::i32, MVT::i32), Half);
2225 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2226 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2228 Flag = Chain.getValue(1);
2229 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2230 VA = RVLocs[++i]; // skip ahead to next loc
2231 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2232 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2234 Flag = Chain.getValue(1);
2235 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2236 VA = RVLocs[++i]; // skip ahead to next loc
2238 // Extract the 2nd half and fall through to handle it as an f64 value.
2239 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2240 DAG.getConstant(1, MVT::i32));
2242 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2244 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2245 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2246 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2247 fmrrd.getValue(isLittleEndian ? 0 : 1),
2249 Flag = Chain.getValue(1);
2250 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2251 VA = RVLocs[++i]; // skip ahead to next loc
2252 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2253 fmrrd.getValue(isLittleEndian ? 1 : 0),
2256 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2258 // Guarantee that all emitted copies are
2259 // stuck together, avoiding something bad.
2260 Flag = Chain.getValue(1);
2261 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2264 // Update chain and glue.
2267 RetOps.push_back(Flag);
2269 // CPUs which aren't M-class use a special sequence to return from
2270 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2271 // though we use "subs pc, lr, #N").
2273 // M-class CPUs actually use a normal return sequence with a special
2274 // (hardware-provided) value in LR, so the normal code path works.
2275 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2276 !Subtarget->isMClass()) {
2277 if (Subtarget->isThumb1Only())
2278 report_fatal_error("interrupt attribute is not supported in Thumb1");
2279 return LowerInterruptReturn(RetOps, dl, DAG);
2282 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2285 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2286 if (N->getNumValues() != 1)
2288 if (!N->hasNUsesOfValue(1, 0))
2291 SDValue TCChain = Chain;
2292 SDNode *Copy = *N->use_begin();
2293 if (Copy->getOpcode() == ISD::CopyToReg) {
2294 // If the copy has a glue operand, we conservatively assume it isn't safe to
2295 // perform a tail call.
2296 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2298 TCChain = Copy->getOperand(0);
2299 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2300 SDNode *VMov = Copy;
2301 // f64 returned in a pair of GPRs.
2302 SmallPtrSet<SDNode*, 2> Copies;
2303 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2305 if (UI->getOpcode() != ISD::CopyToReg)
2309 if (Copies.size() > 2)
2312 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2314 SDValue UseChain = UI->getOperand(0);
2315 if (Copies.count(UseChain.getNode()))
2319 // We are at the top of this chain.
2320 // If the copy has a glue operand, we conservatively assume it
2321 // isn't safe to perform a tail call.
2322 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2328 } else if (Copy->getOpcode() == ISD::BITCAST) {
2329 // f32 returned in a single GPR.
2330 if (!Copy->hasOneUse())
2332 Copy = *Copy->use_begin();
2333 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2335 // If the copy has a glue operand, we conservatively assume it isn't safe to
2336 // perform a tail call.
2337 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2339 TCChain = Copy->getOperand(0);
2344 bool HasRet = false;
2345 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2347 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2348 UI->getOpcode() != ARMISD::INTRET_FLAG)
2360 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2361 if (!Subtarget->supportsTailCall())
2364 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2367 return !Subtarget->isThumb1Only();
2370 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2371 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2372 // one of the above mentioned nodes. It has to be wrapped because otherwise
2373 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2374 // be used to form addressing mode. These wrapped nodes will be selected
2376 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2377 EVT PtrVT = Op.getValueType();
2378 // FIXME there is no actual debug info here
2380 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2382 if (CP->isMachineConstantPoolEntry())
2383 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2384 CP->getAlignment());
2386 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2387 CP->getAlignment());
2388 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2391 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2392 return MachineJumpTableInfo::EK_Inline;
2395 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2396 SelectionDAG &DAG) const {
2397 MachineFunction &MF = DAG.getMachineFunction();
2398 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2399 unsigned ARMPCLabelIndex = 0;
2401 EVT PtrVT = getPointerTy();
2402 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2403 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2405 if (RelocM == Reloc::Static) {
2406 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2408 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2409 ARMPCLabelIndex = AFI->createPICLabelUId();
2410 ARMConstantPoolValue *CPV =
2411 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2412 ARMCP::CPBlockAddress, PCAdj);
2413 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2415 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2416 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2417 MachinePointerInfo::getConstantPool(),
2418 false, false, false, 0);
2419 if (RelocM == Reloc::Static)
2421 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2422 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2425 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2427 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2428 SelectionDAG &DAG) const {
2430 EVT PtrVT = getPointerTy();
2431 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2432 MachineFunction &MF = DAG.getMachineFunction();
2433 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2434 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2435 ARMConstantPoolValue *CPV =
2436 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2437 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2438 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2439 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2440 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2441 MachinePointerInfo::getConstantPool(),
2442 false, false, false, 0);
2443 SDValue Chain = Argument.getValue(1);
2445 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2446 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2448 // call __tls_get_addr.
2451 Entry.Node = Argument;
2452 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2453 Args.push_back(Entry);
2455 // FIXME: is there useful debug info available here?
2456 TargetLowering::CallLoweringInfo CLI(DAG);
2457 CLI.setDebugLoc(dl).setChain(Chain)
2458 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2459 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2462 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2463 return CallResult.first;
2466 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2467 // "local exec" model.
2469 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2471 TLSModel::Model model) const {
2472 const GlobalValue *GV = GA->getGlobal();
2475 SDValue Chain = DAG.getEntryNode();
2476 EVT PtrVT = getPointerTy();
2477 // Get the Thread Pointer
2478 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2480 if (model == TLSModel::InitialExec) {
2481 MachineFunction &MF = DAG.getMachineFunction();
2482 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2483 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2484 // Initial exec model.
2485 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2486 ARMConstantPoolValue *CPV =
2487 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2488 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2490 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2491 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2492 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2493 MachinePointerInfo::getConstantPool(),
2494 false, false, false, 0);
2495 Chain = Offset.getValue(1);
2497 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2498 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2500 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2501 MachinePointerInfo::getConstantPool(),
2502 false, false, false, 0);
2505 assert(model == TLSModel::LocalExec);
2506 ARMConstantPoolValue *CPV =
2507 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2508 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2509 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2510 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2511 MachinePointerInfo::getConstantPool(),
2512 false, false, false, 0);
2515 // The address of the thread local variable is the add of the thread
2516 // pointer with the offset of the variable.
2517 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2521 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2522 // TODO: implement the "local dynamic" model
2523 assert(Subtarget->isTargetELF() &&
2524 "TLS not implemented for non-ELF targets");
2525 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2527 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2530 case TLSModel::GeneralDynamic:
2531 case TLSModel::LocalDynamic:
2532 return LowerToTLSGeneralDynamicModel(GA, DAG);
2533 case TLSModel::InitialExec:
2534 case TLSModel::LocalExec:
2535 return LowerToTLSExecModels(GA, DAG, model);
2537 llvm_unreachable("bogus TLS model");
2540 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2541 SelectionDAG &DAG) const {
2542 EVT PtrVT = getPointerTy();
2544 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2545 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2546 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2547 ARMConstantPoolValue *CPV =
2548 ARMConstantPoolConstant::Create(GV,
2549 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2550 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2551 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2552 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2554 MachinePointerInfo::getConstantPool(),
2555 false, false, false, 0);
2556 SDValue Chain = Result.getValue(1);
2557 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2558 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2560 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2561 MachinePointerInfo::getGOT(),
2562 false, false, false, 0);
2566 // If we have T2 ops, we can materialize the address directly via movt/movw
2567 // pair. This is always cheaper.
2568 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2570 // FIXME: Once remat is capable of dealing with instructions with register
2571 // operands, expand this into two nodes.
2572 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2573 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2575 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2576 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2577 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2578 MachinePointerInfo::getConstantPool(),
2579 false, false, false, 0);
2583 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2584 SelectionDAG &DAG) const {
2585 EVT PtrVT = getPointerTy();
2587 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2588 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2590 if (Subtarget->useMovt(DAG.getMachineFunction()))
2593 // FIXME: Once remat is capable of dealing with instructions with register
2594 // operands, expand this into multiple nodes
2596 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2598 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2599 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2601 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2602 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2603 MachinePointerInfo::getGOT(), false, false, false, 0);
2607 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2608 SelectionDAG &DAG) const {
2609 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2610 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2611 "Windows on ARM expects to use movw/movt");
2613 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2614 const ARMII::TOF TargetFlags =
2615 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2616 EVT PtrVT = getPointerTy();
2622 // FIXME: Once remat is capable of dealing with instructions with register
2623 // operands, expand this into two nodes.
2624 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2625 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2627 if (GV->hasDLLImportStorageClass())
2628 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2629 MachinePointerInfo::getGOT(), false, false, false, 0);
2633 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2634 SelectionDAG &DAG) const {
2635 assert(Subtarget->isTargetELF() &&
2636 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2637 MachineFunction &MF = DAG.getMachineFunction();
2638 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2639 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2640 EVT PtrVT = getPointerTy();
2642 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2643 ARMConstantPoolValue *CPV =
2644 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2645 ARMPCLabelIndex, PCAdj);
2646 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2647 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2648 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2649 MachinePointerInfo::getConstantPool(),
2650 false, false, false, 0);
2651 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2652 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2656 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2658 SDValue Val = DAG.getConstant(0, MVT::i32);
2659 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2660 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2661 Op.getOperand(1), Val);
2665 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2667 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2668 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2672 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2673 const ARMSubtarget *Subtarget) const {
2674 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2677 default: return SDValue(); // Don't custom lower most intrinsics.
2678 case Intrinsic::arm_rbit: {
2679 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2680 "RBIT intrinsic must have i32 type!");
2681 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2683 case Intrinsic::arm_thread_pointer: {
2684 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2685 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2687 case Intrinsic::eh_sjlj_lsda: {
2688 MachineFunction &MF = DAG.getMachineFunction();
2689 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2690 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2691 EVT PtrVT = getPointerTy();
2692 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2694 unsigned PCAdj = (RelocM != Reloc::PIC_)
2695 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2696 ARMConstantPoolValue *CPV =
2697 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2698 ARMCP::CPLSDA, PCAdj);
2699 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2700 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2702 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2703 MachinePointerInfo::getConstantPool(),
2704 false, false, false, 0);
2706 if (RelocM == Reloc::PIC_) {
2707 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2708 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2712 case Intrinsic::arm_neon_vmulls:
2713 case Intrinsic::arm_neon_vmullu: {
2714 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2715 ? ARMISD::VMULLs : ARMISD::VMULLu;
2716 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2717 Op.getOperand(1), Op.getOperand(2));
2722 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2723 const ARMSubtarget *Subtarget) {
2724 // FIXME: handle "fence singlethread" more efficiently.
2726 if (!Subtarget->hasDataBarrier()) {
2727 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2728 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2730 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2731 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2732 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2733 DAG.getConstant(0, MVT::i32));
2736 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2737 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2738 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2739 if (Subtarget->isMClass()) {
2740 // Only a full system barrier exists in the M-class architectures.
2741 Domain = ARM_MB::SY;
2742 } else if (Subtarget->isSwift() && Ord == Release) {
2743 // Swift happens to implement ISHST barriers in a way that's compatible with
2744 // Release semantics but weaker than ISH so we'd be fools not to use
2745 // it. Beware: other processors probably don't!
2746 Domain = ARM_MB::ISHST;
2749 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2750 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2751 DAG.getConstant(Domain, MVT::i32));
2754 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2755 const ARMSubtarget *Subtarget) {
2756 // ARM pre v5TE and Thumb1 does not have preload instructions.
2757 if (!(Subtarget->isThumb2() ||
2758 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2759 // Just preserve the chain.
2760 return Op.getOperand(0);
2763 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2765 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2766 // ARMv7 with MP extension has PLDW.
2767 return Op.getOperand(0);
2769 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2770 if (Subtarget->isThumb()) {
2772 isRead = ~isRead & 1;
2773 isData = ~isData & 1;
2776 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2777 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2778 DAG.getConstant(isData, MVT::i32));
2781 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2782 MachineFunction &MF = DAG.getMachineFunction();
2783 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2785 // vastart just stores the address of the VarArgsFrameIndex slot into the
2786 // memory location argument.
2788 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2789 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2790 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2791 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2792 MachinePointerInfo(SV), false, false, 0);
2796 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2797 SDValue &Root, SelectionDAG &DAG,
2799 MachineFunction &MF = DAG.getMachineFunction();
2800 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2802 const TargetRegisterClass *RC;
2803 if (AFI->isThumb1OnlyFunction())
2804 RC = &ARM::tGPRRegClass;
2806 RC = &ARM::GPRRegClass;
2808 // Transform the arguments stored in physical registers into virtual ones.
2809 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2810 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2813 if (NextVA.isMemLoc()) {
2814 MachineFrameInfo *MFI = MF.getFrameInfo();
2815 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2817 // Create load node to retrieve arguments from the stack.
2818 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2819 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2820 MachinePointerInfo::getFixedStack(FI),
2821 false, false, false, 0);
2823 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2824 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2826 if (!Subtarget->isLittle())
2827 std::swap (ArgValue, ArgValue2);
2828 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2831 // The remaining GPRs hold either the beginning of variable-argument
2832 // data, or the beginning of an aggregate passed by value (usually
2833 // byval). Either way, we allocate stack slots adjacent to the data
2834 // provided by our caller, and store the unallocated registers there.
2835 // If this is a variadic function, the va_list pointer will begin with
2836 // these values; otherwise, this reassembles a (byval) structure that
2837 // was split between registers and memory.
2838 // Return: The frame index registers were stored into.
2840 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2841 SDLoc dl, SDValue &Chain,
2842 const Value *OrigArg,
2843 unsigned InRegsParamRecordIdx,
2845 unsigned ArgSize) const {
2846 // Currently, two use-cases possible:
2847 // Case #1. Non-var-args function, and we meet first byval parameter.
2848 // Setup first unallocated register as first byval register;
2849 // eat all remained registers
2850 // (these two actions are performed by HandleByVal method).
2851 // Then, here, we initialize stack frame with
2852 // "store-reg" instructions.
2853 // Case #2. Var-args function, that doesn't contain byval parameters.
2854 // The same: eat all remained unallocated registers,
2855 // initialize stack frame.
2857 MachineFunction &MF = DAG.getMachineFunction();
2858 MachineFrameInfo *MFI = MF.getFrameInfo();
2859 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2860 unsigned RBegin, REnd;
2861 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2862 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2864 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2865 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2870 ArgOffset = -4 * (ARM::R4 - RBegin);
2872 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2873 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2875 SmallVector<SDValue, 4> MemOps;
2876 const TargetRegisterClass *RC =
2877 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2879 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2880 unsigned VReg = MF.addLiveIn(Reg, RC);
2881 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2883 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2884 MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2885 MemOps.push_back(Store);
2886 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2887 DAG.getConstant(4, getPointerTy()));
2890 if (!MemOps.empty())
2891 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2895 // Setup stack frame, the va_list pointer will start from.
2897 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2898 SDLoc dl, SDValue &Chain,
2900 unsigned TotalArgRegsSaveSize,
2901 bool ForceMutable) const {
2902 MachineFunction &MF = DAG.getMachineFunction();
2903 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2905 // Try to store any remaining integer argument regs
2906 // to their spots on the stack so that they may be loaded by deferencing
2907 // the result of va_next.
2908 // If there is no regs to be stored, just point address after last
2909 // argument passed via stack.
2910 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2911 CCInfo.getInRegsParamsCount(),
2912 CCInfo.getNextStackOffset(), 4);
2913 AFI->setVarArgsFrameIndex(FrameIndex);
2917 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2918 CallingConv::ID CallConv, bool isVarArg,
2919 const SmallVectorImpl<ISD::InputArg>
2921 SDLoc dl, SelectionDAG &DAG,
2922 SmallVectorImpl<SDValue> &InVals)
2924 MachineFunction &MF = DAG.getMachineFunction();
2925 MachineFrameInfo *MFI = MF.getFrameInfo();
2927 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2929 // Assign locations to all of the incoming arguments.
2930 SmallVector<CCValAssign, 16> ArgLocs;
2931 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2932 *DAG.getContext(), Prologue);
2933 CCInfo.AnalyzeFormalArguments(Ins,
2934 CCAssignFnForNode(CallConv, /* Return*/ false,
2937 SmallVector<SDValue, 16> ArgValues;
2939 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2940 unsigned CurArgIdx = 0;
2942 // Initially ArgRegsSaveSize is zero.
2943 // Then we increase this value each time we meet byval parameter.
2944 // We also increase this value in case of varargs function.
2945 AFI->setArgRegsSaveSize(0);
2947 // Calculate the amount of stack space that we need to allocate to store
2948 // byval and variadic arguments that are passed in registers.
2949 // We need to know this before we allocate the first byval or variadic
2950 // argument, as they will be allocated a stack slot below the CFA (Canonical
2951 // Frame Address, the stack pointer at entry to the function).
2952 unsigned ArgRegBegin = ARM::R4;
2953 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2954 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
2957 CCValAssign &VA = ArgLocs[i];
2958 unsigned Index = VA.getValNo();
2959 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
2960 if (!Flags.isByVal())
2963 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
2964 unsigned RBegin, REnd;
2965 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
2966 ArgRegBegin = std::min(ArgRegBegin, RBegin);
2968 CCInfo.nextInRegsParam();
2970 CCInfo.rewindByValRegsInfo();
2972 int lastInsIndex = -1;
2973 if (isVarArg && MFI->hasVAStart()) {
2974 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2975 if (RegIdx != array_lengthof(GPRArgRegs))
2976 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
2979 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
2980 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
2982 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2983 CCValAssign &VA = ArgLocs[i];
2984 if (Ins[VA.getValNo()].isOrigArg()) {
2985 std::advance(CurOrigArg,
2986 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
2987 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
2989 // Arguments stored in registers.
2990 if (VA.isRegLoc()) {
2991 EVT RegVT = VA.getLocVT();
2993 if (VA.needsCustom()) {
2994 // f64 and vector types are split up into multiple registers or
2995 // combinations of registers and stack slots.
2996 if (VA.getLocVT() == MVT::v2f64) {
2997 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2999 VA = ArgLocs[++i]; // skip ahead to next loc
3001 if (VA.isMemLoc()) {
3002 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3003 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3004 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3005 MachinePointerInfo::getFixedStack(FI),
3006 false, false, false, 0);
3008 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3011 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3012 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3013 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3014 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3015 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3017 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3020 const TargetRegisterClass *RC;
3022 if (RegVT == MVT::f32)
3023 RC = &ARM::SPRRegClass;
3024 else if (RegVT == MVT::f64)
3025 RC = &ARM::DPRRegClass;
3026 else if (RegVT == MVT::v2f64)
3027 RC = &ARM::QPRRegClass;
3028 else if (RegVT == MVT::i32)
3029 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3030 : &ARM::GPRRegClass;
3032 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3034 // Transform the arguments in physical registers into virtual ones.
3035 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3036 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3039 // If this is an 8 or 16-bit value, it is really passed promoted
3040 // to 32 bits. Insert an assert[sz]ext to capture this, then
3041 // truncate to the right size.
3042 switch (VA.getLocInfo()) {
3043 default: llvm_unreachable("Unknown loc info!");
3044 case CCValAssign::Full: break;
3045 case CCValAssign::BCvt:
3046 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3048 case CCValAssign::SExt:
3049 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3050 DAG.getValueType(VA.getValVT()));
3051 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3053 case CCValAssign::ZExt:
3054 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3055 DAG.getValueType(VA.getValVT()));
3056 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3060 InVals.push_back(ArgValue);
3062 } else { // VA.isRegLoc()
3065 assert(VA.isMemLoc());
3066 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3068 int index = VA.getValNo();
3070 // Some Ins[] entries become multiple ArgLoc[] entries.
3071 // Process them only once.
3072 if (index != lastInsIndex)
3074 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3075 // FIXME: For now, all byval parameter objects are marked mutable.
3076 // This can be changed with more analysis.
3077 // In case of tail call optimization mark all arguments mutable.
3078 // Since they could be overwritten by lowering of arguments in case of
3080 if (Flags.isByVal()) {
3081 assert(Ins[index].isOrigArg() &&
3082 "Byval arguments cannot be implicit");
3083 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3085 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3086 CurByValIndex, VA.getLocMemOffset(),
3087 Flags.getByValSize());
3088 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3089 CCInfo.nextInRegsParam();
3091 unsigned FIOffset = VA.getLocMemOffset();
3092 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3095 // Create load nodes to retrieve arguments from the stack.
3096 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3097 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3098 MachinePointerInfo::getFixedStack(FI),
3099 false, false, false, 0));
3101 lastInsIndex = index;
3107 if (isVarArg && MFI->hasVAStart())
3108 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3109 CCInfo.getNextStackOffset(),
3110 TotalArgRegsSaveSize);
3112 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3117 /// isFloatingPointZero - Return true if this is +0.0.
3118 static bool isFloatingPointZero(SDValue Op) {
3119 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3120 return CFP->getValueAPF().isPosZero();
3121 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3122 // Maybe this has already been legalized into the constant pool?
3123 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3124 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3125 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3126 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3127 return CFP->getValueAPF().isPosZero();
3129 } else if (Op->getOpcode() == ISD::BITCAST &&
3130 Op->getValueType(0) == MVT::f64) {
3131 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3132 // created by LowerConstantFP().
3133 SDValue BitcastOp = Op->getOperand(0);
3134 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3135 SDValue MoveOp = BitcastOp->getOperand(0);
3136 if (MoveOp->getOpcode() == ISD::TargetConstant &&
3137 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3145 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3146 /// the given operands.
3148 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3149 SDValue &ARMcc, SelectionDAG &DAG,
3151 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3152 unsigned C = RHSC->getZExtValue();
3153 if (!isLegalICmpImmediate(C)) {
3154 // Constant does not fit, try adjusting it by one?
3159 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3160 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3161 RHS = DAG.getConstant(C-1, MVT::i32);
3166 if (C != 0 && isLegalICmpImmediate(C-1)) {
3167 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3168 RHS = DAG.getConstant(C-1, MVT::i32);
3173 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3174 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3175 RHS = DAG.getConstant(C+1, MVT::i32);
3180 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3181 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3182 RHS = DAG.getConstant(C+1, MVT::i32);
3189 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3190 ARMISD::NodeType CompareType;
3193 CompareType = ARMISD::CMP;
3198 CompareType = ARMISD::CMPZ;
3201 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3202 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3205 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3207 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3209 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3211 if (!isFloatingPointZero(RHS))
3212 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3214 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3215 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3218 /// duplicateCmp - Glue values can have only one use, so this function
3219 /// duplicates a comparison node.
3221 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3222 unsigned Opc = Cmp.getOpcode();
3224 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3225 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3227 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3228 Cmp = Cmp.getOperand(0);
3229 Opc = Cmp.getOpcode();
3230 if (Opc == ARMISD::CMPFP)
3231 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3233 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3234 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3236 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3239 std::pair<SDValue, SDValue>
3240 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3241 SDValue &ARMcc) const {
3242 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3244 SDValue Value, OverflowCmp;
3245 SDValue LHS = Op.getOperand(0);
3246 SDValue RHS = Op.getOperand(1);
3249 // FIXME: We are currently always generating CMPs because we don't support
3250 // generating CMN through the backend. This is not as good as the natural
3251 // CMP case because it causes a register dependency and cannot be folded
3254 switch (Op.getOpcode()) {
3256 llvm_unreachable("Unknown overflow instruction!");
3258 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3259 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3260 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3263 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3264 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3265 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3268 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3269 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3270 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3273 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3274 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3275 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3279 return std::make_pair(Value, OverflowCmp);
3284 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3285 // Let legalize expand this if it isn't a legal type yet.
3286 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3289 SDValue Value, OverflowCmp;
3291 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3292 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3293 // We use 0 and 1 as false and true values.
3294 SDValue TVal = DAG.getConstant(1, MVT::i32);
3295 SDValue FVal = DAG.getConstant(0, MVT::i32);
3296 EVT VT = Op.getValueType();
3298 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3299 ARMcc, CCR, OverflowCmp);
3301 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3302 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3306 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3307 SDValue Cond = Op.getOperand(0);
3308 SDValue SelectTrue = Op.getOperand(1);
3309 SDValue SelectFalse = Op.getOperand(2);
3311 unsigned Opc = Cond.getOpcode();
3313 if (Cond.getResNo() == 1 &&
3314 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3315 Opc == ISD::USUBO)) {
3316 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3319 SDValue Value, OverflowCmp;
3321 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3322 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3323 EVT VT = Op.getValueType();
3325 return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3331 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3332 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3334 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3335 const ConstantSDNode *CMOVTrue =
3336 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3337 const ConstantSDNode *CMOVFalse =
3338 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3340 if (CMOVTrue && CMOVFalse) {
3341 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3342 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3346 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3348 False = SelectFalse;
3349 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3354 if (True.getNode() && False.getNode()) {
3355 EVT VT = Op.getValueType();
3356 SDValue ARMcc = Cond.getOperand(2);
3357 SDValue CCR = Cond.getOperand(3);
3358 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3359 assert(True.getValueType() == VT);
3360 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3365 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3366 // undefined bits before doing a full-word comparison with zero.
3367 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3368 DAG.getConstant(1, Cond.getValueType()));
3370 return DAG.getSelectCC(dl, Cond,
3371 DAG.getConstant(0, Cond.getValueType()),
3372 SelectTrue, SelectFalse, ISD::SETNE);
3375 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3376 if (CC == ISD::SETNE)
3378 return ISD::getSetCCInverse(CC, true);
3381 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3382 bool &swpCmpOps, bool &swpVselOps) {
3383 // Start by selecting the GE condition code for opcodes that return true for
3385 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3387 CondCode = ARMCC::GE;
3389 // and GT for opcodes that return false for 'equality'.
3390 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3392 CondCode = ARMCC::GT;
3394 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3395 // to swap the compare operands.
3396 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3400 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3401 // If we have an unordered opcode, we need to swap the operands to the VSEL
3402 // instruction (effectively negating the condition).
3404 // This also has the effect of swapping which one of 'less' or 'greater'
3405 // returns true, so we also swap the compare operands. It also switches
3406 // whether we return true for 'equality', so we compensate by picking the
3407 // opposite condition code to our original choice.
3408 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3409 CC == ISD::SETUGT) {
3410 swpCmpOps = !swpCmpOps;
3411 swpVselOps = !swpVselOps;
3412 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3415 // 'ordered' is 'anything but unordered', so use the VS condition code and
3416 // swap the VSEL operands.
3417 if (CC == ISD::SETO) {
3418 CondCode = ARMCC::VS;
3422 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3423 // code and swap the VSEL operands.
3424 if (CC == ISD::SETUNE) {
3425 CondCode = ARMCC::EQ;
3430 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3431 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3432 SDValue Cmp, SelectionDAG &DAG) const {
3433 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3434 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3435 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3436 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3437 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3439 SDValue TrueLow = TrueVal.getValue(0);
3440 SDValue TrueHigh = TrueVal.getValue(1);
3441 SDValue FalseLow = FalseVal.getValue(0);
3442 SDValue FalseHigh = FalseVal.getValue(1);
3444 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3446 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3447 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3449 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3451 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3456 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3457 EVT VT = Op.getValueType();
3458 SDValue LHS = Op.getOperand(0);
3459 SDValue RHS = Op.getOperand(1);
3460 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3461 SDValue TrueVal = Op.getOperand(2);
3462 SDValue FalseVal = Op.getOperand(3);
3465 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3466 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3469 // If softenSetCCOperands only returned one value, we should compare it to
3471 if (!RHS.getNode()) {
3472 RHS = DAG.getConstant(0, LHS.getValueType());
3477 if (LHS.getValueType() == MVT::i32) {
3478 // Try to generate VSEL on ARMv8.
3479 // The VSEL instruction can't use all the usual ARM condition
3480 // codes: it only has two bits to select the condition code, so it's
3481 // constrained to use only GE, GT, VS and EQ.
3483 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3484 // swap the operands of the previous compare instruction (effectively
3485 // inverting the compare condition, swapping 'less' and 'greater') and
3486 // sometimes need to swap the operands to the VSEL (which inverts the
3487 // condition in the sense of firing whenever the previous condition didn't)
3488 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3489 TrueVal.getValueType() == MVT::f64)) {
3490 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3491 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3492 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3493 CC = getInverseCCForVSEL(CC);
3494 std::swap(TrueVal, FalseVal);
3499 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3500 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3501 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3504 ARMCC::CondCodes CondCode, CondCode2;
3505 FPCCToARMCC(CC, CondCode, CondCode2);
3507 // Try to generate VSEL on ARMv8.
3508 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3509 TrueVal.getValueType() == MVT::f64)) {
3510 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3511 // same operands, as follows:
3512 // c = fcmp [ogt, olt, ugt, ult] a, b
3514 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3515 // handled differently than the original code sequence.
3516 if (getTargetMachine().Options.UnsafeFPMath) {
3517 if (LHS == TrueVal && RHS == FalseVal) {
3518 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3519 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3520 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3521 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3522 } else if (LHS == FalseVal && RHS == TrueVal) {
3523 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3524 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3525 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3526 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3530 bool swpCmpOps = false;
3531 bool swpVselOps = false;
3532 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3534 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3535 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3537 std::swap(LHS, RHS);
3539 std::swap(TrueVal, FalseVal);
3543 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3544 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3545 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3546 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3547 if (CondCode2 != ARMCC::AL) {
3548 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3549 // FIXME: Needs another CMP because flag can have but one use.
3550 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3551 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3556 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3557 /// to morph to an integer compare sequence.
3558 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3559 const ARMSubtarget *Subtarget) {
3560 SDNode *N = Op.getNode();
3561 if (!N->hasOneUse())
3562 // Otherwise it requires moving the value from fp to integer registers.
3564 if (!N->getNumValues())
3566 EVT VT = Op.getValueType();
3567 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3568 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3569 // vmrs are very slow, e.g. cortex-a8.
3572 if (isFloatingPointZero(Op)) {
3576 return ISD::isNormalLoad(N);
3579 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3580 if (isFloatingPointZero(Op))
3581 return DAG.getConstant(0, MVT::i32);
3583 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3584 return DAG.getLoad(MVT::i32, SDLoc(Op),
3585 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3586 Ld->isVolatile(), Ld->isNonTemporal(),
3587 Ld->isInvariant(), Ld->getAlignment());
3589 llvm_unreachable("Unknown VFP cmp argument!");
3592 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3593 SDValue &RetVal1, SDValue &RetVal2) {
3594 if (isFloatingPointZero(Op)) {
3595 RetVal1 = DAG.getConstant(0, MVT::i32);
3596 RetVal2 = DAG.getConstant(0, MVT::i32);
3600 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3601 SDValue Ptr = Ld->getBasePtr();
3602 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3603 Ld->getChain(), Ptr,
3604 Ld->getPointerInfo(),
3605 Ld->isVolatile(), Ld->isNonTemporal(),
3606 Ld->isInvariant(), Ld->getAlignment());
3608 EVT PtrType = Ptr.getValueType();
3609 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3610 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3611 PtrType, Ptr, DAG.getConstant(4, PtrType));
3612 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3613 Ld->getChain(), NewPtr,
3614 Ld->getPointerInfo().getWithOffset(4),
3615 Ld->isVolatile(), Ld->isNonTemporal(),
3616 Ld->isInvariant(), NewAlign);
3620 llvm_unreachable("Unknown VFP cmp argument!");
3623 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3624 /// f32 and even f64 comparisons to integer ones.
3626 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3627 SDValue Chain = Op.getOperand(0);
3628 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3629 SDValue LHS = Op.getOperand(2);
3630 SDValue RHS = Op.getOperand(3);
3631 SDValue Dest = Op.getOperand(4);
3634 bool LHSSeenZero = false;
3635 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3636 bool RHSSeenZero = false;
3637 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3638 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3639 // If unsafe fp math optimization is enabled and there are no other uses of
3640 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3641 // to an integer comparison.
3642 if (CC == ISD::SETOEQ)
3644 else if (CC == ISD::SETUNE)
3647 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3649 if (LHS.getValueType() == MVT::f32) {
3650 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3651 bitcastf32Toi32(LHS, DAG), Mask);
3652 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3653 bitcastf32Toi32(RHS, DAG), Mask);
3654 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3655 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3656 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3657 Chain, Dest, ARMcc, CCR, Cmp);
3662 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3663 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3664 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3665 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3666 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3667 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3668 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3669 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3670 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3676 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3677 SDValue Chain = Op.getOperand(0);
3678 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3679 SDValue LHS = Op.getOperand(2);
3680 SDValue RHS = Op.getOperand(3);
3681 SDValue Dest = Op.getOperand(4);
3684 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3685 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3688 // If softenSetCCOperands only returned one value, we should compare it to
3690 if (!RHS.getNode()) {
3691 RHS = DAG.getConstant(0, LHS.getValueType());
3696 if (LHS.getValueType() == MVT::i32) {
3698 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3699 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3700 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3701 Chain, Dest, ARMcc, CCR, Cmp);
3704 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3706 if (getTargetMachine().Options.UnsafeFPMath &&
3707 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3708 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3709 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3710 if (Result.getNode())
3714 ARMCC::CondCodes CondCode, CondCode2;
3715 FPCCToARMCC(CC, CondCode, CondCode2);
3717 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3718 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3719 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3720 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3721 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3722 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3723 if (CondCode2 != ARMCC::AL) {
3724 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3725 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3726 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3731 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3732 SDValue Chain = Op.getOperand(0);
3733 SDValue Table = Op.getOperand(1);
3734 SDValue Index = Op.getOperand(2);
3737 EVT PTy = getPointerTy();
3738 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3739 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3740 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3741 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3742 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3743 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3744 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3745 if (Subtarget->isThumb2()) {
3746 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3747 // which does another jump to the destination. This also makes it easier
3748 // to translate it to TBB / TBH later.
3749 // FIXME: This might not work if the function is extremely large.
3750 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3751 Addr, Op.getOperand(2), JTI, UId);
3753 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3754 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3755 MachinePointerInfo::getJumpTable(),
3756 false, false, false, 0);
3757 Chain = Addr.getValue(1);
3758 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3759 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3761 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3762 MachinePointerInfo::getJumpTable(),
3763 false, false, false, 0);
3764 Chain = Addr.getValue(1);
3765 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3769 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3770 EVT VT = Op.getValueType();
3773 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3774 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3776 return DAG.UnrollVectorOp(Op.getNode());
3779 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3780 "Invalid type for custom lowering!");
3781 if (VT != MVT::v4i16)
3782 return DAG.UnrollVectorOp(Op.getNode());
3784 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3785 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3788 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3789 EVT VT = Op.getValueType();
3791 return LowerVectorFP_TO_INT(Op, DAG);
3792 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3794 if (Op.getOpcode() == ISD::FP_TO_SINT)
3795 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3798 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3800 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3801 /*isSigned*/ false, SDLoc(Op)).first;
3807 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3808 EVT VT = Op.getValueType();
3811 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3812 if (VT.getVectorElementType() == MVT::f32)
3814 return DAG.UnrollVectorOp(Op.getNode());
3817 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3818 "Invalid type for custom lowering!");
3819 if (VT != MVT::v4f32)
3820 return DAG.UnrollVectorOp(Op.getNode());
3824 switch (Op.getOpcode()) {
3825 default: llvm_unreachable("Invalid opcode!");
3826 case ISD::SINT_TO_FP:
3827 CastOpc = ISD::SIGN_EXTEND;
3828 Opc = ISD::SINT_TO_FP;
3830 case ISD::UINT_TO_FP:
3831 CastOpc = ISD::ZERO_EXTEND;
3832 Opc = ISD::UINT_TO_FP;
3836 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3837 return DAG.getNode(Opc, dl, VT, Op);
3840 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3841 EVT VT = Op.getValueType();
3843 return LowerVectorINT_TO_FP(Op, DAG);
3844 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3846 if (Op.getOpcode() == ISD::SINT_TO_FP)
3847 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3850 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3852 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3853 /*isSigned*/ false, SDLoc(Op)).first;
3859 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3860 // Implement fcopysign with a fabs and a conditional fneg.
3861 SDValue Tmp0 = Op.getOperand(0);
3862 SDValue Tmp1 = Op.getOperand(1);
3864 EVT VT = Op.getValueType();
3865 EVT SrcVT = Tmp1.getValueType();
3866 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3867 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3868 bool UseNEON = !InGPR && Subtarget->hasNEON();
3871 // Use VBSL to copy the sign bit.
3872 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3873 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3874 DAG.getTargetConstant(EncodedVal, MVT::i32));
3875 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3877 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3878 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3879 DAG.getConstant(32, MVT::i32));
3880 else /*if (VT == MVT::f32)*/
3881 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3882 if (SrcVT == MVT::f32) {
3883 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3885 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3886 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3887 DAG.getConstant(32, MVT::i32));
3888 } else if (VT == MVT::f32)
3889 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3890 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3891 DAG.getConstant(32, MVT::i32));
3892 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3893 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3895 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3897 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3898 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3899 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3901 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3902 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3903 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3904 if (VT == MVT::f32) {
3905 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3906 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3907 DAG.getConstant(0, MVT::i32));
3909 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3915 // Bitcast operand 1 to i32.
3916 if (SrcVT == MVT::f64)
3917 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3919 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3921 // Or in the signbit with integer operations.
3922 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3923 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3924 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3925 if (VT == MVT::f32) {
3926 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3927 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3928 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3929 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3932 // f64: Or the high part with signbit and then combine two parts.
3933 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3935 SDValue Lo = Tmp0.getValue(0);
3936 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3937 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3938 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3941 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3942 MachineFunction &MF = DAG.getMachineFunction();
3943 MachineFrameInfo *MFI = MF.getFrameInfo();
3944 MFI->setReturnAddressIsTaken(true);
3946 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3949 EVT VT = Op.getValueType();
3951 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3953 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3954 SDValue Offset = DAG.getConstant(4, MVT::i32);
3955 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3956 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3957 MachinePointerInfo(), false, false, false, 0);
3960 // Return LR, which contains the return address. Mark it an implicit live-in.
3961 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3962 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3965 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3966 const ARMBaseRegisterInfo &ARI =
3967 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3968 MachineFunction &MF = DAG.getMachineFunction();
3969 MachineFrameInfo *MFI = MF.getFrameInfo();
3970 MFI->setFrameAddressIsTaken(true);
3972 EVT VT = Op.getValueType();
3973 SDLoc dl(Op); // FIXME probably not meaningful
3974 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3975 unsigned FrameReg = ARI.getFrameRegister(MF);
3976 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3978 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3979 MachinePointerInfo(),
3980 false, false, false, 0);
3984 // FIXME? Maybe this could be a TableGen attribute on some registers and
3985 // this table could be generated automatically from RegInfo.
3986 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3988 unsigned Reg = StringSwitch<unsigned>(RegName)
3989 .Case("sp", ARM::SP)
3993 report_fatal_error("Invalid register name global variable");
3996 /// ExpandBITCAST - If the target supports VFP, this function is called to
3997 /// expand a bit convert where either the source or destination type is i64 to
3998 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3999 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4000 /// vectors), since the legalizer won't know what to do with that.
4001 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4002 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4004 SDValue Op = N->getOperand(0);
4006 // This function is only supposed to be called for i64 types, either as the
4007 // source or destination of the bit convert.
4008 EVT SrcVT = Op.getValueType();
4009 EVT DstVT = N->getValueType(0);
4010 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4011 "ExpandBITCAST called for non-i64 type");
4013 // Turn i64->f64 into VMOVDRR.
4014 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4015 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4016 DAG.getConstant(0, MVT::i32));
4017 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4018 DAG.getConstant(1, MVT::i32));
4019 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4020 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4023 // Turn f64->i64 into VMOVRRD.
4024 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4026 if (TLI.isBigEndian() && SrcVT.isVector() &&
4027 SrcVT.getVectorNumElements() > 1)
4028 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4029 DAG.getVTList(MVT::i32, MVT::i32),
4030 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4032 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4033 DAG.getVTList(MVT::i32, MVT::i32), Op);
4034 // Merge the pieces into a single i64 value.
4035 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4041 /// getZeroVector - Returns a vector of specified type with all zero elements.
4042 /// Zero vectors are used to represent vector negation and in those cases
4043 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4044 /// not support i64 elements, so sometimes the zero vectors will need to be
4045 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4047 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4048 assert(VT.isVector() && "Expected a vector type");
4049 // The canonical modified immediate encoding of a zero vector is....0!
4050 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4051 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4052 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4053 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4056 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4057 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4058 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4059 SelectionDAG &DAG) const {
4060 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4061 EVT VT = Op.getValueType();
4062 unsigned VTBits = VT.getSizeInBits();
4064 SDValue ShOpLo = Op.getOperand(0);
4065 SDValue ShOpHi = Op.getOperand(1);
4066 SDValue ShAmt = Op.getOperand(2);
4068 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4070 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4072 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4073 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4074 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4075 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4076 DAG.getConstant(VTBits, MVT::i32));
4077 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4078 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4079 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4081 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4082 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4084 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4085 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4088 SDValue Ops[2] = { Lo, Hi };
4089 return DAG.getMergeValues(Ops, dl);
4092 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4093 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4094 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4095 SelectionDAG &DAG) const {
4096 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4097 EVT VT = Op.getValueType();
4098 unsigned VTBits = VT.getSizeInBits();
4100 SDValue ShOpLo = Op.getOperand(0);
4101 SDValue ShOpHi = Op.getOperand(1);
4102 SDValue ShAmt = Op.getOperand(2);
4105 assert(Op.getOpcode() == ISD::SHL_PARTS);
4106 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4107 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4108 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4109 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4110 DAG.getConstant(VTBits, MVT::i32));
4111 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4112 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4114 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4115 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4116 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4118 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4119 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4122 SDValue Ops[2] = { Lo, Hi };
4123 return DAG.getMergeValues(Ops, dl);
4126 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4127 SelectionDAG &DAG) const {
4128 // The rounding mode is in bits 23:22 of the FPSCR.
4129 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4130 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4131 // so that the shift + and get folded into a bitfield extract.
4133 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4134 DAG.getConstant(Intrinsic::arm_get_fpscr,
4136 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4137 DAG.getConstant(1U << 22, MVT::i32));
4138 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4139 DAG.getConstant(22, MVT::i32));
4140 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4141 DAG.getConstant(3, MVT::i32));
4144 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4145 const ARMSubtarget *ST) {
4146 EVT VT = N->getValueType(0);
4149 if (!ST->hasV6T2Ops())
4152 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4153 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4156 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4157 /// for each 16-bit element from operand, repeated. The basic idea is to
4158 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4160 /// Trace for v4i16:
4161 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4162 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4163 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4164 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4165 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4166 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4167 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4168 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4169 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4170 EVT VT = N->getValueType(0);
4173 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4174 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4175 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4176 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4177 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4178 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4181 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4182 /// bit-count for each 16-bit element from the operand. We need slightly
4183 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4184 /// 64/128-bit registers.
4186 /// Trace for v4i16:
4187 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4188 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4189 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4190 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4191 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4192 EVT VT = N->getValueType(0);
4195 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4196 if (VT.is64BitVector()) {
4197 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4198 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4199 DAG.getIntPtrConstant(0));
4201 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4202 BitCounts, DAG.getIntPtrConstant(0));
4203 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4207 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4208 /// bit-count for each 32-bit element from the operand. The idea here is
4209 /// to split the vector into 16-bit elements, leverage the 16-bit count
4210 /// routine, and then combine the results.
4212 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4213 /// input = [v0 v1 ] (vi: 32-bit elements)
4214 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4215 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4216 /// vrev: N0 = [k1 k0 k3 k2 ]
4218 /// N1 =+[k1 k0 k3 k2 ]
4220 /// N2 =+[k1 k3 k0 k2 ]
4222 /// Extended =+[k1 k3 k0 k2 ]
4224 /// Extracted=+[k1 k3 ]
4226 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4227 EVT VT = N->getValueType(0);
4230 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4232 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4233 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4234 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4235 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4236 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4238 if (VT.is64BitVector()) {
4239 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4240 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4241 DAG.getIntPtrConstant(0));
4243 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4244 DAG.getIntPtrConstant(0));
4245 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4249 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4250 const ARMSubtarget *ST) {
4251 EVT VT = N->getValueType(0);
4253 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4254 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4255 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4256 "Unexpected type for custom ctpop lowering");
4258 if (VT.getVectorElementType() == MVT::i32)
4259 return lowerCTPOP32BitElements(N, DAG);
4261 return lowerCTPOP16BitElements(N, DAG);
4264 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4265 const ARMSubtarget *ST) {
4266 EVT VT = N->getValueType(0);
4272 // Lower vector shifts on NEON to use VSHL.
4273 assert(ST->hasNEON() && "unexpected vector shift");
4275 // Left shifts translate directly to the vshiftu intrinsic.
4276 if (N->getOpcode() == ISD::SHL)
4277 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4278 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4279 N->getOperand(0), N->getOperand(1));
4281 assert((N->getOpcode() == ISD::SRA ||
4282 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4284 // NEON uses the same intrinsics for both left and right shifts. For
4285 // right shifts, the shift amounts are negative, so negate the vector of
4287 EVT ShiftVT = N->getOperand(1).getValueType();
4288 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4289 getZeroVector(ShiftVT, DAG, dl),
4291 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4292 Intrinsic::arm_neon_vshifts :
4293 Intrinsic::arm_neon_vshiftu);
4294 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4295 DAG.getConstant(vshiftInt, MVT::i32),
4296 N->getOperand(0), NegatedCount);
4299 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4300 const ARMSubtarget *ST) {
4301 EVT VT = N->getValueType(0);
4304 // We can get here for a node like i32 = ISD::SHL i32, i64
4308 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4309 "Unknown shift to lower!");
4311 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4312 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4313 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4316 // If we are in thumb mode, we don't have RRX.
4317 if (ST->isThumb1Only()) return SDValue();
4319 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4320 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4321 DAG.getConstant(0, MVT::i32));
4322 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4323 DAG.getConstant(1, MVT::i32));
4325 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4326 // captures the result into a carry flag.
4327 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4328 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4330 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4331 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4333 // Merge the pieces into a single i64 value.
4334 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4337 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4338 SDValue TmpOp0, TmpOp1;
4339 bool Invert = false;
4343 SDValue Op0 = Op.getOperand(0);
4344 SDValue Op1 = Op.getOperand(1);
4345 SDValue CC = Op.getOperand(2);
4346 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4347 EVT VT = Op.getValueType();
4348 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4351 if (Op1.getValueType().isFloatingPoint()) {
4352 switch (SetCCOpcode) {
4353 default: llvm_unreachable("Illegal FP comparison");
4355 case ISD::SETNE: Invert = true; // Fallthrough
4357 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4359 case ISD::SETLT: Swap = true; // Fallthrough
4361 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4363 case ISD::SETLE: Swap = true; // Fallthrough
4365 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4366 case ISD::SETUGE: Swap = true; // Fallthrough
4367 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4368 case ISD::SETUGT: Swap = true; // Fallthrough
4369 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4370 case ISD::SETUEQ: Invert = true; // Fallthrough
4372 // Expand this to (OLT | OGT).
4376 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4377 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4379 case ISD::SETUO: Invert = true; // Fallthrough
4381 // Expand this to (OLT | OGE).
4385 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4386 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4390 // Integer comparisons.
4391 switch (SetCCOpcode) {
4392 default: llvm_unreachable("Illegal integer comparison");
4393 case ISD::SETNE: Invert = true;
4394 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4395 case ISD::SETLT: Swap = true;
4396 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4397 case ISD::SETLE: Swap = true;
4398 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4399 case ISD::SETULT: Swap = true;
4400 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4401 case ISD::SETULE: Swap = true;
4402 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4405 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4406 if (Opc == ARMISD::VCEQ) {
4409 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4411 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4414 // Ignore bitconvert.
4415 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4416 AndOp = AndOp.getOperand(0);
4418 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4420 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4421 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4428 std::swap(Op0, Op1);
4430 // If one of the operands is a constant vector zero, attempt to fold the
4431 // comparison to a specialized compare-against-zero form.
4433 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4435 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4436 if (Opc == ARMISD::VCGE)
4437 Opc = ARMISD::VCLEZ;
4438 else if (Opc == ARMISD::VCGT)
4439 Opc = ARMISD::VCLTZ;
4444 if (SingleOp.getNode()) {
4447 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4449 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4451 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4453 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4455 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4457 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4460 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4463 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4466 Result = DAG.getNOT(dl, Result, VT);
4471 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4472 /// valid vector constant for a NEON instruction with a "modified immediate"
4473 /// operand (e.g., VMOV). If so, return the encoded value.
4474 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4475 unsigned SplatBitSize, SelectionDAG &DAG,
4476 EVT &VT, bool is128Bits, NEONModImmType type) {
4477 unsigned OpCmode, Imm;
4479 // SplatBitSize is set to the smallest size that splats the vector, so a
4480 // zero vector will always have SplatBitSize == 8. However, NEON modified
4481 // immediate instructions others than VMOV do not support the 8-bit encoding
4482 // of a zero vector, and the default encoding of zero is supposed to be the
4487 switch (SplatBitSize) {
4489 if (type != VMOVModImm)
4491 // Any 1-byte value is OK. Op=0, Cmode=1110.
4492 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4495 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4499 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4500 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4501 if ((SplatBits & ~0xff) == 0) {
4502 // Value = 0x00nn: Op=x, Cmode=100x.
4507 if ((SplatBits & ~0xff00) == 0) {
4508 // Value = 0xnn00: Op=x, Cmode=101x.
4510 Imm = SplatBits >> 8;
4516 // NEON's 32-bit VMOV supports splat values where:
4517 // * only one byte is nonzero, or
4518 // * the least significant byte is 0xff and the second byte is nonzero, or
4519 // * the least significant 2 bytes are 0xff and the third is nonzero.
4520 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4521 if ((SplatBits & ~0xff) == 0) {
4522 // Value = 0x000000nn: Op=x, Cmode=000x.
4527 if ((SplatBits & ~0xff00) == 0) {
4528 // Value = 0x0000nn00: Op=x, Cmode=001x.
4530 Imm = SplatBits >> 8;
4533 if ((SplatBits & ~0xff0000) == 0) {
4534 // Value = 0x00nn0000: Op=x, Cmode=010x.
4536 Imm = SplatBits >> 16;
4539 if ((SplatBits & ~0xff000000) == 0) {
4540 // Value = 0xnn000000: Op=x, Cmode=011x.
4542 Imm = SplatBits >> 24;
4546 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4547 if (type == OtherModImm) return SDValue();
4549 if ((SplatBits & ~0xffff) == 0 &&
4550 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4551 // Value = 0x0000nnff: Op=x, Cmode=1100.
4553 Imm = SplatBits >> 8;
4557 if ((SplatBits & ~0xffffff) == 0 &&
4558 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4559 // Value = 0x00nnffff: Op=x, Cmode=1101.
4561 Imm = SplatBits >> 16;
4565 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4566 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4567 // VMOV.I32. A (very) minor optimization would be to replicate the value
4568 // and fall through here to test for a valid 64-bit splat. But, then the
4569 // caller would also need to check and handle the change in size.
4573 if (type != VMOVModImm)
4575 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4576 uint64_t BitMask = 0xff;
4578 unsigned ImmMask = 1;
4580 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4581 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4584 } else if ((SplatBits & BitMask) != 0) {
4591 if (DAG.getTargetLoweringInfo().isBigEndian())
4592 // swap higher and lower 32 bit word
4593 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4595 // Op=1, Cmode=1110.
4597 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4602 llvm_unreachable("unexpected size for isNEONModifiedImm");
4605 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4606 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4609 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4610 const ARMSubtarget *ST) const {
4614 bool IsDouble = Op.getValueType() == MVT::f64;
4615 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4617 // Use the default (constant pool) lowering for double constants when we have
4619 if (IsDouble && Subtarget->isFPOnlySP())
4622 // Try splatting with a VMOV.f32...
4623 APFloat FPVal = CFP->getValueAPF();
4624 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4627 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4628 // We have code in place to select a valid ConstantFP already, no need to
4633 // It's a float and we are trying to use NEON operations where
4634 // possible. Lower it to a splat followed by an extract.
4636 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4637 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4639 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4640 DAG.getConstant(0, MVT::i32));
4643 // The rest of our options are NEON only, make sure that's allowed before
4645 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4649 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4651 // It wouldn't really be worth bothering for doubles except for one very
4652 // important value, which does happen to match: 0.0. So make sure we don't do
4654 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4657 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4658 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4660 if (NewVal != SDValue()) {
4662 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4665 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4667 // It's a float: cast and extract a vector element.
4668 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4670 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4671 DAG.getConstant(0, MVT::i32));
4674 // Finally, try a VMVN.i32
4675 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4677 if (NewVal != SDValue()) {
4679 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4682 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4684 // It's a float: cast and extract a vector element.
4685 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4687 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4688 DAG.getConstant(0, MVT::i32));
4694 // check if an VEXT instruction can handle the shuffle mask when the
4695 // vector sources of the shuffle are the same.
4696 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4697 unsigned NumElts = VT.getVectorNumElements();
4699 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4705 // If this is a VEXT shuffle, the immediate value is the index of the first
4706 // element. The other shuffle indices must be the successive elements after
4708 unsigned ExpectedElt = Imm;
4709 for (unsigned i = 1; i < NumElts; ++i) {
4710 // Increment the expected index. If it wraps around, just follow it
4711 // back to index zero and keep going.
4713 if (ExpectedElt == NumElts)
4716 if (M[i] < 0) continue; // ignore UNDEF indices
4717 if (ExpectedElt != static_cast<unsigned>(M[i]))
4725 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4726 bool &ReverseVEXT, unsigned &Imm) {
4727 unsigned NumElts = VT.getVectorNumElements();
4728 ReverseVEXT = false;
4730 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4736 // If this is a VEXT shuffle, the immediate value is the index of the first
4737 // element. The other shuffle indices must be the successive elements after
4739 unsigned ExpectedElt = Imm;
4740 for (unsigned i = 1; i < NumElts; ++i) {
4741 // Increment the expected index. If it wraps around, it may still be
4742 // a VEXT but the source vectors must be swapped.
4744 if (ExpectedElt == NumElts * 2) {
4749 if (M[i] < 0) continue; // ignore UNDEF indices
4750 if (ExpectedElt != static_cast<unsigned>(M[i]))
4754 // Adjust the index value if the source operands will be swapped.
4761 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4762 /// instruction with the specified blocksize. (The order of the elements
4763 /// within each block of the vector is reversed.)
4764 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4765 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4766 "Only possible block sizes for VREV are: 16, 32, 64");
4768 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4772 unsigned NumElts = VT.getVectorNumElements();
4773 unsigned BlockElts = M[0] + 1;
4774 // If the first shuffle index is UNDEF, be optimistic.
4776 BlockElts = BlockSize / EltSz;
4778 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4781 for (unsigned i = 0; i < NumElts; ++i) {
4782 if (M[i] < 0) continue; // ignore UNDEF indices
4783 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4790 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4791 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4792 // range, then 0 is placed into the resulting vector. So pretty much any mask
4793 // of 8 elements can work here.
4794 return VT == MVT::v8i8 && M.size() == 8;
4797 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4798 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4802 unsigned NumElts = VT.getVectorNumElements();
4803 WhichResult = (M[0] == 0 ? 0 : 1);
4804 for (unsigned i = 0; i < NumElts; i += 2) {
4805 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4806 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4812 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4813 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4814 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4815 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4816 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4820 unsigned NumElts = VT.getVectorNumElements();
4821 WhichResult = (M[0] == 0 ? 0 : 1);
4822 for (unsigned i = 0; i < NumElts; i += 2) {
4823 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4824 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4830 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4831 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4835 unsigned NumElts = VT.getVectorNumElements();
4836 WhichResult = (M[0] == 0 ? 0 : 1);
4837 for (unsigned i = 0; i != NumElts; ++i) {
4838 if (M[i] < 0) continue; // ignore UNDEF indices
4839 if ((unsigned) M[i] != 2 * i + WhichResult)
4843 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4844 if (VT.is64BitVector() && EltSz == 32)
4850 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4851 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4852 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4853 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4854 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4858 unsigned Half = VT.getVectorNumElements() / 2;
4859 WhichResult = (M[0] == 0 ? 0 : 1);
4860 for (unsigned j = 0; j != 2; ++j) {
4861 unsigned Idx = WhichResult;
4862 for (unsigned i = 0; i != Half; ++i) {
4863 int MIdx = M[i + j * Half];
4864 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4870 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4871 if (VT.is64BitVector() && EltSz == 32)
4877 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4878 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4882 unsigned NumElts = VT.getVectorNumElements();
4883 WhichResult = (M[0] == 0 ? 0 : 1);
4884 unsigned Idx = WhichResult * NumElts / 2;
4885 for (unsigned i = 0; i != NumElts; i += 2) {
4886 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4887 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4892 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4893 if (VT.is64BitVector() && EltSz == 32)
4899 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4900 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4901 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4902 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4903 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4907 unsigned NumElts = VT.getVectorNumElements();
4908 WhichResult = (M[0] == 0 ? 0 : 1);
4909 unsigned Idx = WhichResult * NumElts / 2;
4910 for (unsigned i = 0; i != NumElts; i += 2) {
4911 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4912 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4917 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4918 if (VT.is64BitVector() && EltSz == 32)
4924 /// \return true if this is a reverse operation on an vector.
4925 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4926 unsigned NumElts = VT.getVectorNumElements();
4927 // Make sure the mask has the right size.
4928 if (NumElts != M.size())
4931 // Look for <15, ..., 3, -1, 1, 0>.
4932 for (unsigned i = 0; i != NumElts; ++i)
4933 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4939 // If N is an integer constant that can be moved into a register in one
4940 // instruction, return an SDValue of such a constant (will become a MOV
4941 // instruction). Otherwise return null.
4942 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4943 const ARMSubtarget *ST, SDLoc dl) {
4945 if (!isa<ConstantSDNode>(N))
4947 Val = cast<ConstantSDNode>(N)->getZExtValue();
4949 if (ST->isThumb1Only()) {
4950 if (Val <= 255 || ~Val <= 255)
4951 return DAG.getConstant(Val, MVT::i32);
4953 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4954 return DAG.getConstant(Val, MVT::i32);
4959 // If this is a case we can't handle, return null and let the default
4960 // expansion code take care of it.
4961 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4962 const ARMSubtarget *ST) const {
4963 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4965 EVT VT = Op.getValueType();
4967 APInt SplatBits, SplatUndef;
4968 unsigned SplatBitSize;
4970 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4971 if (SplatBitSize <= 64) {
4972 // Check if an immediate VMOV works.
4974 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4975 SplatUndef.getZExtValue(), SplatBitSize,
4976 DAG, VmovVT, VT.is128BitVector(),
4978 if (Val.getNode()) {
4979 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4980 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4983 // Try an immediate VMVN.
4984 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4985 Val = isNEONModifiedImm(NegatedImm,
4986 SplatUndef.getZExtValue(), SplatBitSize,
4987 DAG, VmovVT, VT.is128BitVector(),
4989 if (Val.getNode()) {
4990 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4991 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4994 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4995 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4996 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4998 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4999 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5005 // Scan through the operands to see if only one value is used.
5007 // As an optimisation, even if more than one value is used it may be more
5008 // profitable to splat with one value then change some lanes.
5010 // Heuristically we decide to do this if the vector has a "dominant" value,
5011 // defined as splatted to more than half of the lanes.
5012 unsigned NumElts = VT.getVectorNumElements();
5013 bool isOnlyLowElement = true;
5014 bool usesOnlyOneValue = true;
5015 bool hasDominantValue = false;
5016 bool isConstant = true;
5018 // Map of the number of times a particular SDValue appears in the
5020 DenseMap<SDValue, unsigned> ValueCounts;
5022 for (unsigned i = 0; i < NumElts; ++i) {
5023 SDValue V = Op.getOperand(i);
5024 if (V.getOpcode() == ISD::UNDEF)
5027 isOnlyLowElement = false;
5028 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5031 ValueCounts.insert(std::make_pair(V, 0));
5032 unsigned &Count = ValueCounts[V];
5034 // Is this value dominant? (takes up more than half of the lanes)
5035 if (++Count > (NumElts / 2)) {
5036 hasDominantValue = true;
5040 if (ValueCounts.size() != 1)
5041 usesOnlyOneValue = false;
5042 if (!Value.getNode() && ValueCounts.size() > 0)
5043 Value = ValueCounts.begin()->first;
5045 if (ValueCounts.size() == 0)
5046 return DAG.getUNDEF(VT);
5048 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5049 // Keep going if we are hitting this case.
5050 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5051 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5053 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5055 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5056 // i32 and try again.
5057 if (hasDominantValue && EltSize <= 32) {
5061 // If we are VDUPing a value that comes directly from a vector, that will
5062 // cause an unnecessary move to and from a GPR, where instead we could
5063 // just use VDUPLANE. We can only do this if the lane being extracted
5064 // is at a constant index, as the VDUP from lane instructions only have
5065 // constant-index forms.
5066 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5067 isa<ConstantSDNode>(Value->getOperand(1))) {
5068 // We need to create a new undef vector to use for the VDUPLANE if the
5069 // size of the vector from which we get the value is different than the
5070 // size of the vector that we need to create. We will insert the element
5071 // such that the register coalescer will remove unnecessary copies.
5072 if (VT != Value->getOperand(0).getValueType()) {
5073 ConstantSDNode *constIndex;
5074 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5075 assert(constIndex && "The index is not a constant!");
5076 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5077 VT.getVectorNumElements();
5078 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5079 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5080 Value, DAG.getConstant(index, MVT::i32)),
5081 DAG.getConstant(index, MVT::i32));
5083 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5084 Value->getOperand(0), Value->getOperand(1));
5086 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5088 if (!usesOnlyOneValue) {
5089 // The dominant value was splatted as 'N', but we now have to insert
5090 // all differing elements.
5091 for (unsigned I = 0; I < NumElts; ++I) {
5092 if (Op.getOperand(I) == Value)
5094 SmallVector<SDValue, 3> Ops;
5096 Ops.push_back(Op.getOperand(I));
5097 Ops.push_back(DAG.getConstant(I, MVT::i32));
5098 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5103 if (VT.getVectorElementType().isFloatingPoint()) {
5104 SmallVector<SDValue, 8> Ops;
5105 for (unsigned i = 0; i < NumElts; ++i)
5106 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5108 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5109 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5110 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5112 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5114 if (usesOnlyOneValue) {
5115 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5116 if (isConstant && Val.getNode())
5117 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5121 // If all elements are constants and the case above didn't get hit, fall back
5122 // to the default expansion, which will generate a load from the constant
5127 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5129 SDValue shuffle = ReconstructShuffle(Op, DAG);
5130 if (shuffle != SDValue())
5134 // Vectors with 32- or 64-bit elements can be built by directly assigning
5135 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5136 // will be legalized.
5137 if (EltSize >= 32) {
5138 // Do the expansion with floating-point types, since that is what the VFP
5139 // registers are defined to use, and since i64 is not legal.
5140 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5141 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5142 SmallVector<SDValue, 8> Ops;
5143 for (unsigned i = 0; i < NumElts; ++i)
5144 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5145 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5146 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5149 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5150 // know the default expansion would otherwise fall back on something even
5151 // worse. For a vector with one or two non-undef values, that's
5152 // scalar_to_vector for the elements followed by a shuffle (provided the
5153 // shuffle is valid for the target) and materialization element by element
5154 // on the stack followed by a load for everything else.
5155 if (!isConstant && !usesOnlyOneValue) {
5156 SDValue Vec = DAG.getUNDEF(VT);
5157 for (unsigned i = 0 ; i < NumElts; ++i) {
5158 SDValue V = Op.getOperand(i);
5159 if (V.getOpcode() == ISD::UNDEF)
5161 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5162 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5170 // Gather data to see if the operation can be modelled as a
5171 // shuffle in combination with VEXTs.
5172 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5173 SelectionDAG &DAG) const {
5175 EVT VT = Op.getValueType();
5176 unsigned NumElts = VT.getVectorNumElements();
5178 SmallVector<SDValue, 2> SourceVecs;
5179 SmallVector<unsigned, 2> MinElts;
5180 SmallVector<unsigned, 2> MaxElts;
5182 for (unsigned i = 0; i < NumElts; ++i) {
5183 SDValue V = Op.getOperand(i);
5184 if (V.getOpcode() == ISD::UNDEF)
5186 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5187 // A shuffle can only come from building a vector from various
5188 // elements of other vectors.
5190 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5191 VT.getVectorElementType()) {
5192 // This code doesn't know how to handle shuffles where the vector
5193 // element types do not match (this happens because type legalization
5194 // promotes the return type of EXTRACT_VECTOR_ELT).
5195 // FIXME: It might be appropriate to extend this code to handle
5196 // mismatched types.
5200 // Record this extraction against the appropriate vector if possible...
5201 SDValue SourceVec = V.getOperand(0);
5202 // If the element number isn't a constant, we can't effectively
5203 // analyze what's going on.
5204 if (!isa<ConstantSDNode>(V.getOperand(1)))
5206 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5207 bool FoundSource = false;
5208 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5209 if (SourceVecs[j] == SourceVec) {
5210 if (MinElts[j] > EltNo)
5212 if (MaxElts[j] < EltNo)
5219 // Or record a new source if not...
5221 SourceVecs.push_back(SourceVec);
5222 MinElts.push_back(EltNo);
5223 MaxElts.push_back(EltNo);
5227 // Currently only do something sane when at most two source vectors
5229 if (SourceVecs.size() > 2)
5232 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5233 int VEXTOffsets[2] = {0, 0};
5235 // This loop extracts the usage patterns of the source vectors
5236 // and prepares appropriate SDValues for a shuffle if possible.
5237 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5238 if (SourceVecs[i].getValueType() == VT) {
5239 // No VEXT necessary
5240 ShuffleSrcs[i] = SourceVecs[i];
5243 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5244 // It probably isn't worth padding out a smaller vector just to
5245 // break it down again in a shuffle.
5249 // Since only 64-bit and 128-bit vectors are legal on ARM and
5250 // we've eliminated the other cases...
5251 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5252 "unexpected vector sizes in ReconstructShuffle");
5254 if (MaxElts[i] - MinElts[i] >= NumElts) {
5255 // Span too large for a VEXT to cope
5259 if (MinElts[i] >= NumElts) {
5260 // The extraction can just take the second half
5261 VEXTOffsets[i] = NumElts;
5262 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5264 DAG.getIntPtrConstant(NumElts));
5265 } else if (MaxElts[i] < NumElts) {
5266 // The extraction can just take the first half
5268 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5270 DAG.getIntPtrConstant(0));
5272 // An actual VEXT is needed
5273 VEXTOffsets[i] = MinElts[i];
5274 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5276 DAG.getIntPtrConstant(0));
5277 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5279 DAG.getIntPtrConstant(NumElts));
5280 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5281 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5285 SmallVector<int, 8> Mask;
5287 for (unsigned i = 0; i < NumElts; ++i) {
5288 SDValue Entry = Op.getOperand(i);
5289 if (Entry.getOpcode() == ISD::UNDEF) {
5294 SDValue ExtractVec = Entry.getOperand(0);
5295 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5296 .getOperand(1))->getSExtValue();
5297 if (ExtractVec == SourceVecs[0]) {
5298 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5300 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5304 // Final check before we try to produce nonsense...
5305 if (isShuffleMaskLegal(Mask, VT))
5306 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5312 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5313 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5314 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5315 /// are assumed to be legal.
5317 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5319 if (VT.getVectorNumElements() == 4 &&
5320 (VT.is128BitVector() || VT.is64BitVector())) {
5321 unsigned PFIndexes[4];
5322 for (unsigned i = 0; i != 4; ++i) {
5326 PFIndexes[i] = M[i];
5329 // Compute the index in the perfect shuffle table.
5330 unsigned PFTableIndex =
5331 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5332 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5333 unsigned Cost = (PFEntry >> 30);
5340 unsigned Imm, WhichResult;
5342 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5343 return (EltSize >= 32 ||
5344 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5345 isVREVMask(M, VT, 64) ||
5346 isVREVMask(M, VT, 32) ||
5347 isVREVMask(M, VT, 16) ||
5348 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5349 isVTBLMask(M, VT) ||
5350 isVTRNMask(M, VT, WhichResult) ||
5351 isVUZPMask(M, VT, WhichResult) ||
5352 isVZIPMask(M, VT, WhichResult) ||
5353 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5354 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5355 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5356 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5359 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5360 /// the specified operations to build the shuffle.
5361 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5362 SDValue RHS, SelectionDAG &DAG,
5364 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5365 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5366 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5369 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5378 OP_VUZPL, // VUZP, left result
5379 OP_VUZPR, // VUZP, right result
5380 OP_VZIPL, // VZIP, left result
5381 OP_VZIPR, // VZIP, right result
5382 OP_VTRNL, // VTRN, left result
5383 OP_VTRNR // VTRN, right result
5386 if (OpNum == OP_COPY) {
5387 if (LHSID == (1*9+2)*9+3) return LHS;
5388 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5392 SDValue OpLHS, OpRHS;
5393 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5394 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5395 EVT VT = OpLHS.getValueType();
5398 default: llvm_unreachable("Unknown shuffle opcode!");
5400 // VREV divides the vector in half and swaps within the half.
5401 if (VT.getVectorElementType() == MVT::i32 ||
5402 VT.getVectorElementType() == MVT::f32)
5403 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5404 // vrev <4 x i16> -> VREV32
5405 if (VT.getVectorElementType() == MVT::i16)
5406 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5407 // vrev <4 x i8> -> VREV16
5408 assert(VT.getVectorElementType() == MVT::i8);
5409 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5414 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5415 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5419 return DAG.getNode(ARMISD::VEXT, dl, VT,
5421 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5424 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5425 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5428 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5429 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5432 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5433 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5437 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5438 ArrayRef<int> ShuffleMask,
5439 SelectionDAG &DAG) {
5440 // Check to see if we can use the VTBL instruction.
5441 SDValue V1 = Op.getOperand(0);
5442 SDValue V2 = Op.getOperand(1);
5445 SmallVector<SDValue, 8> VTBLMask;
5446 for (ArrayRef<int>::iterator
5447 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5448 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5450 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5451 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5452 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5454 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5455 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5458 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5459 SelectionDAG &DAG) {
5461 SDValue OpLHS = Op.getOperand(0);
5462 EVT VT = OpLHS.getValueType();
5464 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5465 "Expect an v8i16/v16i8 type");
5466 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5467 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5468 // extract the first 8 bytes into the top double word and the last 8 bytes
5469 // into the bottom double word. The v8i16 case is similar.
5470 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5471 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5472 DAG.getConstant(ExtractNum, MVT::i32));
5475 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5476 SDValue V1 = Op.getOperand(0);
5477 SDValue V2 = Op.getOperand(1);
5479 EVT VT = Op.getValueType();
5480 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5482 // Convert shuffles that are directly supported on NEON to target-specific
5483 // DAG nodes, instead of keeping them as shuffles and matching them again
5484 // during code selection. This is more efficient and avoids the possibility
5485 // of inconsistencies between legalization and selection.
5486 // FIXME: floating-point vectors should be canonicalized to integer vectors
5487 // of the same time so that they get CSEd properly.
5488 ArrayRef<int> ShuffleMask = SVN->getMask();
5490 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5491 if (EltSize <= 32) {
5492 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5493 int Lane = SVN->getSplatIndex();
5494 // If this is undef splat, generate it via "just" vdup, if possible.
5495 if (Lane == -1) Lane = 0;
5497 // Test if V1 is a SCALAR_TO_VECTOR.
5498 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5499 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5501 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5502 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5504 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5505 !isa<ConstantSDNode>(V1.getOperand(0))) {
5506 bool IsScalarToVector = true;
5507 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5508 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5509 IsScalarToVector = false;
5512 if (IsScalarToVector)
5513 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5515 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5516 DAG.getConstant(Lane, MVT::i32));
5521 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5524 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5525 DAG.getConstant(Imm, MVT::i32));
5528 if (isVREVMask(ShuffleMask, VT, 64))
5529 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5530 if (isVREVMask(ShuffleMask, VT, 32))
5531 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5532 if (isVREVMask(ShuffleMask, VT, 16))
5533 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5535 if (V2->getOpcode() == ISD::UNDEF &&
5536 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5537 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5538 DAG.getConstant(Imm, MVT::i32));
5541 // Check for Neon shuffles that modify both input vectors in place.
5542 // If both results are used, i.e., if there are two shuffles with the same
5543 // source operands and with masks corresponding to both results of one of
5544 // these operations, DAG memoization will ensure that a single node is
5545 // used for both shuffles.
5546 unsigned WhichResult;
5547 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5548 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5549 V1, V2).getValue(WhichResult);
5550 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5551 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5552 V1, V2).getValue(WhichResult);
5553 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5554 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5555 V1, V2).getValue(WhichResult);
5557 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5558 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5559 V1, V1).getValue(WhichResult);
5560 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5561 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5562 V1, V1).getValue(WhichResult);
5563 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5564 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5565 V1, V1).getValue(WhichResult);
5568 // If the shuffle is not directly supported and it has 4 elements, use
5569 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5570 unsigned NumElts = VT.getVectorNumElements();
5572 unsigned PFIndexes[4];
5573 for (unsigned i = 0; i != 4; ++i) {
5574 if (ShuffleMask[i] < 0)
5577 PFIndexes[i] = ShuffleMask[i];
5580 // Compute the index in the perfect shuffle table.
5581 unsigned PFTableIndex =
5582 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5583 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5584 unsigned Cost = (PFEntry >> 30);
5587 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5590 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5591 if (EltSize >= 32) {
5592 // Do the expansion with floating-point types, since that is what the VFP
5593 // registers are defined to use, and since i64 is not legal.
5594 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5595 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5596 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5597 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5598 SmallVector<SDValue, 8> Ops;
5599 for (unsigned i = 0; i < NumElts; ++i) {
5600 if (ShuffleMask[i] < 0)
5601 Ops.push_back(DAG.getUNDEF(EltVT));
5603 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5604 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5605 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5608 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5609 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5612 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5613 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5615 if (VT == MVT::v8i8) {
5616 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5617 if (NewOp.getNode())
5624 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5625 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5626 SDValue Lane = Op.getOperand(2);
5627 if (!isa<ConstantSDNode>(Lane))
5633 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5634 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5635 SDValue Lane = Op.getOperand(1);
5636 if (!isa<ConstantSDNode>(Lane))
5639 SDValue Vec = Op.getOperand(0);
5640 if (Op.getValueType() == MVT::i32 &&
5641 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5643 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5649 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5650 // The only time a CONCAT_VECTORS operation can have legal types is when
5651 // two 64-bit vectors are concatenated to a 128-bit vector.
5652 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5653 "unexpected CONCAT_VECTORS");
5655 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5656 SDValue Op0 = Op.getOperand(0);
5657 SDValue Op1 = Op.getOperand(1);
5658 if (Op0.getOpcode() != ISD::UNDEF)
5659 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5660 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5661 DAG.getIntPtrConstant(0));
5662 if (Op1.getOpcode() != ISD::UNDEF)
5663 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5664 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5665 DAG.getIntPtrConstant(1));
5666 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5669 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5670 /// element has been zero/sign-extended, depending on the isSigned parameter,
5671 /// from an integer type half its size.
5672 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5674 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5675 EVT VT = N->getValueType(0);
5676 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5677 SDNode *BVN = N->getOperand(0).getNode();
5678 if (BVN->getValueType(0) != MVT::v4i32 ||
5679 BVN->getOpcode() != ISD::BUILD_VECTOR)
5681 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5682 unsigned HiElt = 1 - LoElt;
5683 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5684 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5685 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5686 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5687 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5690 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5691 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5694 if (Hi0->isNullValue() && Hi1->isNullValue())
5700 if (N->getOpcode() != ISD::BUILD_VECTOR)
5703 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5704 SDNode *Elt = N->getOperand(i).getNode();
5705 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5706 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5707 unsigned HalfSize = EltSize / 2;
5709 if (!isIntN(HalfSize, C->getSExtValue()))
5712 if (!isUIntN(HalfSize, C->getZExtValue()))
5723 /// isSignExtended - Check if a node is a vector value that is sign-extended
5724 /// or a constant BUILD_VECTOR with sign-extended elements.
5725 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5726 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5728 if (isExtendedBUILD_VECTOR(N, DAG, true))
5733 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5734 /// or a constant BUILD_VECTOR with zero-extended elements.
5735 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5736 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5738 if (isExtendedBUILD_VECTOR(N, DAG, false))
5743 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5744 if (OrigVT.getSizeInBits() >= 64)
5747 assert(OrigVT.isSimple() && "Expecting a simple value type");
5749 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5750 switch (OrigSimpleTy) {
5751 default: llvm_unreachable("Unexpected Vector Type");
5760 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5761 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5762 /// We insert the required extension here to get the vector to fill a D register.
5763 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5766 unsigned ExtOpcode) {
5767 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5768 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5769 // 64-bits we need to insert a new extension so that it will be 64-bits.
5770 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5771 if (OrigTy.getSizeInBits() >= 64)
5774 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5775 EVT NewVT = getExtensionTo64Bits(OrigTy);
5777 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5780 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5781 /// does not do any sign/zero extension. If the original vector is less
5782 /// than 64 bits, an appropriate extension will be added after the load to
5783 /// reach a total size of 64 bits. We have to add the extension separately
5784 /// because ARM does not have a sign/zero extending load for vectors.
5785 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5786 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5788 // The load already has the right type.
5789 if (ExtendedTy == LD->getMemoryVT())
5790 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5791 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5792 LD->isNonTemporal(), LD->isInvariant(),
5793 LD->getAlignment());
5795 // We need to create a zextload/sextload. We cannot just create a load
5796 // followed by a zext/zext node because LowerMUL is also run during normal
5797 // operation legalization where we can't create illegal types.
5798 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5799 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5800 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5801 LD->isNonTemporal(), LD->getAlignment());
5804 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5805 /// extending load, or BUILD_VECTOR with extended elements, return the
5806 /// unextended value. The unextended vector should be 64 bits so that it can
5807 /// be used as an operand to a VMULL instruction. If the original vector size
5808 /// before extension is less than 64 bits we add a an extension to resize
5809 /// the vector to 64 bits.
5810 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5811 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5812 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5813 N->getOperand(0)->getValueType(0),
5817 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5818 return SkipLoadExtensionForVMULL(LD, DAG);
5820 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5821 // have been legalized as a BITCAST from v4i32.
5822 if (N->getOpcode() == ISD::BITCAST) {
5823 SDNode *BVN = N->getOperand(0).getNode();
5824 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5825 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5826 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5827 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5828 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5830 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5831 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5832 EVT VT = N->getValueType(0);
5833 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5834 unsigned NumElts = VT.getVectorNumElements();
5835 MVT TruncVT = MVT::getIntegerVT(EltSize);
5836 SmallVector<SDValue, 8> Ops;
5837 for (unsigned i = 0; i != NumElts; ++i) {
5838 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5839 const APInt &CInt = C->getAPIntValue();
5840 // Element types smaller than 32 bits are not legal, so use i32 elements.
5841 // The values are implicitly truncated so sext vs. zext doesn't matter.
5842 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5844 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5845 MVT::getVectorVT(TruncVT, NumElts), Ops);
5848 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5849 unsigned Opcode = N->getOpcode();
5850 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5851 SDNode *N0 = N->getOperand(0).getNode();
5852 SDNode *N1 = N->getOperand(1).getNode();
5853 return N0->hasOneUse() && N1->hasOneUse() &&
5854 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5859 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5860 unsigned Opcode = N->getOpcode();
5861 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5862 SDNode *N0 = N->getOperand(0).getNode();
5863 SDNode *N1 = N->getOperand(1).getNode();
5864 return N0->hasOneUse() && N1->hasOneUse() &&
5865 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5870 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5871 // Multiplications are only custom-lowered for 128-bit vectors so that
5872 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5873 EVT VT = Op.getValueType();
5874 assert(VT.is128BitVector() && VT.isInteger() &&
5875 "unexpected type for custom-lowering ISD::MUL");
5876 SDNode *N0 = Op.getOperand(0).getNode();
5877 SDNode *N1 = Op.getOperand(1).getNode();
5878 unsigned NewOpc = 0;
5880 bool isN0SExt = isSignExtended(N0, DAG);
5881 bool isN1SExt = isSignExtended(N1, DAG);
5882 if (isN0SExt && isN1SExt)
5883 NewOpc = ARMISD::VMULLs;
5885 bool isN0ZExt = isZeroExtended(N0, DAG);
5886 bool isN1ZExt = isZeroExtended(N1, DAG);
5887 if (isN0ZExt && isN1ZExt)
5888 NewOpc = ARMISD::VMULLu;
5889 else if (isN1SExt || isN1ZExt) {
5890 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5891 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5892 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5893 NewOpc = ARMISD::VMULLs;
5895 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5896 NewOpc = ARMISD::VMULLu;
5898 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5900 NewOpc = ARMISD::VMULLu;
5906 if (VT == MVT::v2i64)
5907 // Fall through to expand this. It is not legal.
5910 // Other vector multiplications are legal.
5915 // Legalize to a VMULL instruction.
5918 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5920 Op0 = SkipExtensionForVMULL(N0, DAG);
5921 assert(Op0.getValueType().is64BitVector() &&
5922 Op1.getValueType().is64BitVector() &&
5923 "unexpected types for extended operands to VMULL");
5924 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5927 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5928 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5935 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5936 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5937 EVT Op1VT = Op1.getValueType();
5938 return DAG.getNode(N0->getOpcode(), DL, VT,
5939 DAG.getNode(NewOpc, DL, VT,
5940 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5941 DAG.getNode(NewOpc, DL, VT,
5942 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5946 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5948 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5949 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5950 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5951 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5952 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5953 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5954 // Get reciprocal estimate.
5955 // float4 recip = vrecpeq_f32(yf);
5956 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5957 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5958 // Because char has a smaller range than uchar, we can actually get away
5959 // without any newton steps. This requires that we use a weird bias
5960 // of 0xb000, however (again, this has been exhaustively tested).
5961 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5962 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5963 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5964 Y = DAG.getConstant(0xb000, MVT::i32);
5965 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5966 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5967 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5968 // Convert back to short.
5969 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5970 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5975 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5977 // Convert to float.
5978 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5979 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5980 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5981 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5982 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5983 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5985 // Use reciprocal estimate and one refinement step.
5986 // float4 recip = vrecpeq_f32(yf);
5987 // recip *= vrecpsq_f32(yf, recip);
5988 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5989 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5990 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5991 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5993 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5994 // Because short has a smaller range than ushort, we can actually get away
5995 // with only a single newton step. This requires that we use a weird bias
5996 // of 89, however (again, this has been exhaustively tested).
5997 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5998 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5999 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6000 N1 = DAG.getConstant(0x89, MVT::i32);
6001 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6002 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6003 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6004 // Convert back to integer and return.
6005 // return vmovn_s32(vcvt_s32_f32(result));
6006 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6007 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6011 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6012 EVT VT = Op.getValueType();
6013 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6014 "unexpected type for custom-lowering ISD::SDIV");
6017 SDValue N0 = Op.getOperand(0);
6018 SDValue N1 = Op.getOperand(1);
6021 if (VT == MVT::v8i8) {
6022 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6023 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6025 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6026 DAG.getIntPtrConstant(4));
6027 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6028 DAG.getIntPtrConstant(4));
6029 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6030 DAG.getIntPtrConstant(0));
6031 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6032 DAG.getIntPtrConstant(0));
6034 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6035 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6037 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6038 N0 = LowerCONCAT_VECTORS(N0, DAG);
6040 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6043 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6046 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6047 EVT VT = Op.getValueType();
6048 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6049 "unexpected type for custom-lowering ISD::UDIV");
6052 SDValue N0 = Op.getOperand(0);
6053 SDValue N1 = Op.getOperand(1);
6056 if (VT == MVT::v8i8) {
6057 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6058 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6060 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6061 DAG.getIntPtrConstant(4));
6062 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6063 DAG.getIntPtrConstant(4));
6064 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6065 DAG.getIntPtrConstant(0));
6066 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6067 DAG.getIntPtrConstant(0));
6069 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6070 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6072 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6073 N0 = LowerCONCAT_VECTORS(N0, DAG);
6075 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6076 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6081 // v4i16 sdiv ... Convert to float.
6082 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6083 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6084 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6085 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6086 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6087 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6089 // Use reciprocal estimate and two refinement steps.
6090 // float4 recip = vrecpeq_f32(yf);
6091 // recip *= vrecpsq_f32(yf, recip);
6092 // recip *= vrecpsq_f32(yf, recip);
6093 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6094 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6095 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6096 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6098 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6099 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6100 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6102 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6103 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6104 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6105 // and that it will never cause us to return an answer too large).
6106 // float4 result = as_float4(as_int4(xf*recip) + 2);
6107 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6108 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6109 N1 = DAG.getConstant(2, MVT::i32);
6110 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6111 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6112 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6113 // Convert back to integer and return.
6114 // return vmovn_u32(vcvt_s32_f32(result));
6115 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6116 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6120 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6121 EVT VT = Op.getNode()->getValueType(0);
6122 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6125 bool ExtraOp = false;
6126 switch (Op.getOpcode()) {
6127 default: llvm_unreachable("Invalid code");
6128 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6129 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6130 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6131 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6135 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6137 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6138 Op.getOperand(1), Op.getOperand(2));
6141 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6142 assert(Subtarget->isTargetDarwin());
6144 // For iOS, we want to call an alternative entry point: __sincos_stret,
6145 // return values are passed via sret.
6147 SDValue Arg = Op.getOperand(0);
6148 EVT ArgVT = Arg.getValueType();
6149 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6151 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6152 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6154 // Pair of floats / doubles used to pass the result.
6155 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6157 // Create stack object for sret.
6158 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6159 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6160 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6161 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6167 Entry.Ty = RetTy->getPointerTo();
6168 Entry.isSExt = false;
6169 Entry.isZExt = false;
6170 Entry.isSRet = true;
6171 Args.push_back(Entry);
6175 Entry.isSExt = false;
6176 Entry.isZExt = false;
6177 Args.push_back(Entry);
6179 const char *LibcallName = (ArgVT == MVT::f64)
6180 ? "__sincos_stret" : "__sincosf_stret";
6181 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6183 TargetLowering::CallLoweringInfo CLI(DAG);
6184 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6185 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6187 .setDiscardResult();
6189 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6191 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6192 MachinePointerInfo(), false, false, false, 0);
6194 // Address of cos field.
6195 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6196 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6197 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6198 MachinePointerInfo(), false, false, false, 0);
6200 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6201 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6202 LoadSin.getValue(0), LoadCos.getValue(0));
6205 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6206 // Monotonic load/store is legal for all targets
6207 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6210 // Acquire/Release load/store is not legal for targets without a
6211 // dmb or equivalent available.
6215 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6216 SmallVectorImpl<SDValue> &Results,
6218 const ARMSubtarget *Subtarget) {
6220 SDValue Cycles32, OutChain;
6222 if (Subtarget->hasPerfMon()) {
6223 // Under Power Management extensions, the cycle-count is:
6224 // mrc p15, #0, <Rt>, c9, c13, #0
6225 SDValue Ops[] = { N->getOperand(0), // Chain
6226 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6227 DAG.getConstant(15, MVT::i32),
6228 DAG.getConstant(0, MVT::i32),
6229 DAG.getConstant(9, MVT::i32),
6230 DAG.getConstant(13, MVT::i32),
6231 DAG.getConstant(0, MVT::i32)
6234 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6235 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6236 OutChain = Cycles32.getValue(1);
6238 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6239 // there are older ARM CPUs that have implementation-specific ways of
6240 // obtaining this information (FIXME!).
6241 Cycles32 = DAG.getConstant(0, MVT::i32);
6242 OutChain = DAG.getEntryNode();
6246 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6247 Cycles32, DAG.getConstant(0, MVT::i32));
6248 Results.push_back(Cycles64);
6249 Results.push_back(OutChain);
6252 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6253 switch (Op.getOpcode()) {
6254 default: llvm_unreachable("Don't know how to custom lower this!");
6255 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6256 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6257 case ISD::GlobalAddress:
6258 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6259 default: llvm_unreachable("unknown object format");
6261 return LowerGlobalAddressWindows(Op, DAG);
6263 return LowerGlobalAddressELF(Op, DAG);
6265 return LowerGlobalAddressDarwin(Op, DAG);
6267 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6268 case ISD::SELECT: return LowerSELECT(Op, DAG);
6269 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6270 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6271 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6272 case ISD::VASTART: return LowerVASTART(Op, DAG);
6273 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6274 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6275 case ISD::SINT_TO_FP:
6276 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6277 case ISD::FP_TO_SINT:
6278 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6279 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6280 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6281 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6282 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6283 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6284 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6285 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6287 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6290 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6291 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6292 case ISD::SRL_PARTS:
6293 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6294 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6295 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6296 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6297 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6298 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6299 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6300 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6301 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6302 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6303 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6304 case ISD::MUL: return LowerMUL(Op, DAG);
6305 case ISD::SDIV: return LowerSDIV(Op, DAG);
6306 case ISD::UDIV: return LowerUDIV(Op, DAG);
6310 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6315 return LowerXALUO(Op, DAG);
6316 case ISD::ATOMIC_LOAD:
6317 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6318 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6320 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6321 case ISD::DYNAMIC_STACKALLOC:
6322 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6323 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6324 llvm_unreachable("Don't know how to custom lower this!");
6325 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6326 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6330 /// ReplaceNodeResults - Replace the results of node with an illegal result
6331 /// type with new values built out of custom code.
6332 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6333 SmallVectorImpl<SDValue>&Results,
6334 SelectionDAG &DAG) const {
6336 switch (N->getOpcode()) {
6338 llvm_unreachable("Don't know how to custom expand this!");
6340 Res = ExpandBITCAST(N, DAG);
6344 Res = Expand64BitShift(N, DAG, Subtarget);
6346 case ISD::READCYCLECOUNTER:
6347 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6351 Results.push_back(Res);
6354 //===----------------------------------------------------------------------===//
6355 // ARM Scheduler Hooks
6356 //===----------------------------------------------------------------------===//
6358 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6359 /// registers the function context.
6360 void ARMTargetLowering::
6361 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6362 MachineBasicBlock *DispatchBB, int FI) const {
6363 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6364 DebugLoc dl = MI->getDebugLoc();
6365 MachineFunction *MF = MBB->getParent();
6366 MachineRegisterInfo *MRI = &MF->getRegInfo();
6367 MachineConstantPool *MCP = MF->getConstantPool();
6368 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6369 const Function *F = MF->getFunction();
6371 bool isThumb = Subtarget->isThumb();
6372 bool isThumb2 = Subtarget->isThumb2();
6374 unsigned PCLabelId = AFI->createPICLabelUId();
6375 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6376 ARMConstantPoolValue *CPV =
6377 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6378 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6380 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6381 : &ARM::GPRRegClass;
6383 // Grab constant pool and fixed stack memory operands.
6384 MachineMemOperand *CPMMO =
6385 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6386 MachineMemOperand::MOLoad, 4, 4);
6388 MachineMemOperand *FIMMOSt =
6389 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6390 MachineMemOperand::MOStore, 4, 4);
6392 // Load the address of the dispatch MBB into the jump buffer.
6394 // Incoming value: jbuf
6395 // ldr.n r5, LCPI1_1
6398 // str r5, [$jbuf, #+4] ; &jbuf[1]
6399 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6400 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6401 .addConstantPoolIndex(CPI)
6402 .addMemOperand(CPMMO));
6403 // Set the low bit because of thumb mode.
6404 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6406 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6407 .addReg(NewVReg1, RegState::Kill)
6409 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6410 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6411 .addReg(NewVReg2, RegState::Kill)
6413 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6414 .addReg(NewVReg3, RegState::Kill)
6416 .addImm(36) // &jbuf[1] :: pc
6417 .addMemOperand(FIMMOSt));
6418 } else if (isThumb) {
6419 // Incoming value: jbuf
6420 // ldr.n r1, LCPI1_4
6424 // add r2, $jbuf, #+4 ; &jbuf[1]
6426 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6427 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6428 .addConstantPoolIndex(CPI)
6429 .addMemOperand(CPMMO));
6430 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6431 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6432 .addReg(NewVReg1, RegState::Kill)
6434 // Set the low bit because of thumb mode.
6435 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6436 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6437 .addReg(ARM::CPSR, RegState::Define)
6439 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6440 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6441 .addReg(ARM::CPSR, RegState::Define)
6442 .addReg(NewVReg2, RegState::Kill)
6443 .addReg(NewVReg3, RegState::Kill));
6444 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6445 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6447 .addImm(36); // &jbuf[1] :: pc
6448 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6449 .addReg(NewVReg4, RegState::Kill)
6450 .addReg(NewVReg5, RegState::Kill)
6452 .addMemOperand(FIMMOSt));
6454 // Incoming value: jbuf
6457 // str r1, [$jbuf, #+4] ; &jbuf[1]
6458 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6459 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6460 .addConstantPoolIndex(CPI)
6462 .addMemOperand(CPMMO));
6463 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6464 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6465 .addReg(NewVReg1, RegState::Kill)
6466 .addImm(PCLabelId));
6467 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6468 .addReg(NewVReg2, RegState::Kill)
6470 .addImm(36) // &jbuf[1] :: pc
6471 .addMemOperand(FIMMOSt));
6475 MachineBasicBlock *ARMTargetLowering::
6476 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6477 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6478 DebugLoc dl = MI->getDebugLoc();
6479 MachineFunction *MF = MBB->getParent();
6480 MachineRegisterInfo *MRI = &MF->getRegInfo();
6481 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6482 MachineFrameInfo *MFI = MF->getFrameInfo();
6483 int FI = MFI->getFunctionContextIndex();
6485 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6486 : &ARM::GPRnopcRegClass;
6488 // Get a mapping of the call site numbers to all of the landing pads they're
6490 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6491 unsigned MaxCSNum = 0;
6492 MachineModuleInfo &MMI = MF->getMMI();
6493 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6495 if (!BB->isLandingPad()) continue;
6497 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6499 for (MachineBasicBlock::iterator
6500 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6501 if (!II->isEHLabel()) continue;
6503 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6504 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6506 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6507 for (SmallVectorImpl<unsigned>::iterator
6508 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6509 CSI != CSE; ++CSI) {
6510 CallSiteNumToLPad[*CSI].push_back(BB);
6511 MaxCSNum = std::max(MaxCSNum, *CSI);
6517 // Get an ordered list of the machine basic blocks for the jump table.
6518 std::vector<MachineBasicBlock*> LPadList;
6519 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6520 LPadList.reserve(CallSiteNumToLPad.size());
6521 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6522 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6523 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6524 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6525 LPadList.push_back(*II);
6526 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6530 assert(!LPadList.empty() &&
6531 "No landing pad destinations for the dispatch jump table!");
6533 // Create the jump table and associated information.
6534 MachineJumpTableInfo *JTI =
6535 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6536 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6537 unsigned UId = AFI->createJumpTableUId();
6538 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6540 // Create the MBBs for the dispatch code.
6542 // Shove the dispatch's address into the return slot in the function context.
6543 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6544 DispatchBB->setIsLandingPad();
6546 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6547 unsigned trap_opcode;
6548 if (Subtarget->isThumb())
6549 trap_opcode = ARM::tTRAP;
6551 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6553 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6554 DispatchBB->addSuccessor(TrapBB);
6556 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6557 DispatchBB->addSuccessor(DispContBB);
6560 MF->insert(MF->end(), DispatchBB);
6561 MF->insert(MF->end(), DispContBB);
6562 MF->insert(MF->end(), TrapBB);
6564 // Insert code into the entry block that creates and registers the function
6566 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6568 MachineMemOperand *FIMMOLd =
6569 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6570 MachineMemOperand::MOLoad |
6571 MachineMemOperand::MOVolatile, 4, 4);
6573 MachineInstrBuilder MIB;
6574 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6576 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6577 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6579 // Add a register mask with no preserved registers. This results in all
6580 // registers being marked as clobbered.
6581 MIB.addRegMask(RI.getNoPreservedMask());
6583 unsigned NumLPads = LPadList.size();
6584 if (Subtarget->isThumb2()) {
6585 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6586 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6589 .addMemOperand(FIMMOLd));
6591 if (NumLPads < 256) {
6592 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6594 .addImm(LPadList.size()));
6596 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6597 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6598 .addImm(NumLPads & 0xFFFF));
6600 unsigned VReg2 = VReg1;
6601 if ((NumLPads & 0xFFFF0000) != 0) {
6602 VReg2 = MRI->createVirtualRegister(TRC);
6603 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6605 .addImm(NumLPads >> 16));
6608 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6613 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6618 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6619 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6620 .addJumpTableIndex(MJTI)
6623 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6626 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6627 .addReg(NewVReg3, RegState::Kill)
6629 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6631 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6632 .addReg(NewVReg4, RegState::Kill)
6634 .addJumpTableIndex(MJTI)
6636 } else if (Subtarget->isThumb()) {
6637 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6638 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6641 .addMemOperand(FIMMOLd));
6643 if (NumLPads < 256) {
6644 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6648 MachineConstantPool *ConstantPool = MF->getConstantPool();
6649 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6650 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6652 // MachineConstantPool wants an explicit alignment.
6653 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6655 Align = getDataLayout()->getTypeAllocSize(C->getType());
6656 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6658 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6659 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6660 .addReg(VReg1, RegState::Define)
6661 .addConstantPoolIndex(Idx));
6662 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6667 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6672 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6673 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6674 .addReg(ARM::CPSR, RegState::Define)
6678 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6679 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6680 .addJumpTableIndex(MJTI)
6683 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6684 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6685 .addReg(ARM::CPSR, RegState::Define)
6686 .addReg(NewVReg2, RegState::Kill)
6689 MachineMemOperand *JTMMOLd =
6690 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6691 MachineMemOperand::MOLoad, 4, 4);
6693 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6694 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6695 .addReg(NewVReg4, RegState::Kill)
6697 .addMemOperand(JTMMOLd));
6699 unsigned NewVReg6 = NewVReg5;
6700 if (RelocM == Reloc::PIC_) {
6701 NewVReg6 = MRI->createVirtualRegister(TRC);
6702 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6703 .addReg(ARM::CPSR, RegState::Define)
6704 .addReg(NewVReg5, RegState::Kill)
6708 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6709 .addReg(NewVReg6, RegState::Kill)
6710 .addJumpTableIndex(MJTI)
6713 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6714 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6717 .addMemOperand(FIMMOLd));
6719 if (NumLPads < 256) {
6720 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6723 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6724 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6725 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6726 .addImm(NumLPads & 0xFFFF));
6728 unsigned VReg2 = VReg1;
6729 if ((NumLPads & 0xFFFF0000) != 0) {
6730 VReg2 = MRI->createVirtualRegister(TRC);
6731 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6733 .addImm(NumLPads >> 16));
6736 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6740 MachineConstantPool *ConstantPool = MF->getConstantPool();
6741 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6742 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6744 // MachineConstantPool wants an explicit alignment.
6745 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6747 Align = getDataLayout()->getTypeAllocSize(C->getType());
6748 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6750 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6751 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6752 .addReg(VReg1, RegState::Define)
6753 .addConstantPoolIndex(Idx)
6755 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6757 .addReg(VReg1, RegState::Kill));
6760 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6765 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6767 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6769 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6770 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6771 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6772 .addJumpTableIndex(MJTI)
6775 MachineMemOperand *JTMMOLd =
6776 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6777 MachineMemOperand::MOLoad, 4, 4);
6778 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6780 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6781 .addReg(NewVReg3, RegState::Kill)
6784 .addMemOperand(JTMMOLd));
6786 if (RelocM == Reloc::PIC_) {
6787 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6788 .addReg(NewVReg5, RegState::Kill)
6790 .addJumpTableIndex(MJTI)
6793 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6794 .addReg(NewVReg5, RegState::Kill)
6795 .addJumpTableIndex(MJTI)
6800 // Add the jump table entries as successors to the MBB.
6801 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6802 for (std::vector<MachineBasicBlock*>::iterator
6803 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6804 MachineBasicBlock *CurMBB = *I;
6805 if (SeenMBBs.insert(CurMBB).second)
6806 DispContBB->addSuccessor(CurMBB);
6809 // N.B. the order the invoke BBs are processed in doesn't matter here.
6810 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6811 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6812 for (MachineBasicBlock *BB : InvokeBBs) {
6814 // Remove the landing pad successor from the invoke block and replace it
6815 // with the new dispatch block.
6816 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6818 while (!Successors.empty()) {
6819 MachineBasicBlock *SMBB = Successors.pop_back_val();
6820 if (SMBB->isLandingPad()) {
6821 BB->removeSuccessor(SMBB);
6822 MBBLPads.push_back(SMBB);
6826 BB->addSuccessor(DispatchBB);
6828 // Find the invoke call and mark all of the callee-saved registers as
6829 // 'implicit defined' so that they're spilled. This prevents code from
6830 // moving instructions to before the EH block, where they will never be
6832 for (MachineBasicBlock::reverse_iterator
6833 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6834 if (!II->isCall()) continue;
6836 DenseMap<unsigned, bool> DefRegs;
6837 for (MachineInstr::mop_iterator
6838 OI = II->operands_begin(), OE = II->operands_end();
6840 if (!OI->isReg()) continue;
6841 DefRegs[OI->getReg()] = true;
6844 MachineInstrBuilder MIB(*MF, &*II);
6846 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6847 unsigned Reg = SavedRegs[i];
6848 if (Subtarget->isThumb2() &&
6849 !ARM::tGPRRegClass.contains(Reg) &&
6850 !ARM::hGPRRegClass.contains(Reg))
6852 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6854 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6857 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6864 // Mark all former landing pads as non-landing pads. The dispatch is the only
6866 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6867 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6868 (*I)->setIsLandingPad(false);
6870 // The instruction is gone now.
6871 MI->eraseFromParent();
6877 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6878 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6879 E = MBB->succ_end(); I != E; ++I)
6882 llvm_unreachable("Expecting a BB with two successors!");
6885 /// Return the load opcode for a given load size. If load size >= 8,
6886 /// neon opcode will be returned.
6887 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6889 return LdSize == 16 ? ARM::VLD1q32wb_fixed
6890 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6892 return LdSize == 4 ? ARM::tLDRi
6893 : LdSize == 2 ? ARM::tLDRHi
6894 : LdSize == 1 ? ARM::tLDRBi : 0;
6896 return LdSize == 4 ? ARM::t2LDR_POST
6897 : LdSize == 2 ? ARM::t2LDRH_POST
6898 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6899 return LdSize == 4 ? ARM::LDR_POST_IMM
6900 : LdSize == 2 ? ARM::LDRH_POST
6901 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6904 /// Return the store opcode for a given store size. If store size >= 8,
6905 /// neon opcode will be returned.
6906 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6908 return StSize == 16 ? ARM::VST1q32wb_fixed
6909 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6911 return StSize == 4 ? ARM::tSTRi
6912 : StSize == 2 ? ARM::tSTRHi
6913 : StSize == 1 ? ARM::tSTRBi : 0;
6915 return StSize == 4 ? ARM::t2STR_POST
6916 : StSize == 2 ? ARM::t2STRH_POST
6917 : StSize == 1 ? ARM::t2STRB_POST : 0;
6918 return StSize == 4 ? ARM::STR_POST_IMM
6919 : StSize == 2 ? ARM::STRH_POST
6920 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6923 /// Emit a post-increment load operation with given size. The instructions
6924 /// will be added to BB at Pos.
6925 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6926 const TargetInstrInfo *TII, DebugLoc dl,
6927 unsigned LdSize, unsigned Data, unsigned AddrIn,
6928 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6929 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6930 assert(LdOpc != 0 && "Should have a load opcode");
6932 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6933 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6935 } else if (IsThumb1) {
6936 // load + update AddrIn
6937 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6938 .addReg(AddrIn).addImm(0));
6939 MachineInstrBuilder MIB =
6940 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6941 MIB = AddDefaultT1CC(MIB);
6942 MIB.addReg(AddrIn).addImm(LdSize);
6943 AddDefaultPred(MIB);
6944 } else if (IsThumb2) {
6945 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6946 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6949 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6950 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6951 .addReg(0).addImm(LdSize));
6955 /// Emit a post-increment store operation with given size. The instructions
6956 /// will be added to BB at Pos.
6957 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6958 const TargetInstrInfo *TII, DebugLoc dl,
6959 unsigned StSize, unsigned Data, unsigned AddrIn,
6960 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6961 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6962 assert(StOpc != 0 && "Should have a store opcode");
6964 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6965 .addReg(AddrIn).addImm(0).addReg(Data));
6966 } else if (IsThumb1) {
6967 // store + update AddrIn
6968 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6969 .addReg(AddrIn).addImm(0));
6970 MachineInstrBuilder MIB =
6971 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6972 MIB = AddDefaultT1CC(MIB);
6973 MIB.addReg(AddrIn).addImm(StSize);
6974 AddDefaultPred(MIB);
6975 } else if (IsThumb2) {
6976 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6977 .addReg(Data).addReg(AddrIn).addImm(StSize));
6979 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6980 .addReg(Data).addReg(AddrIn).addReg(0)
6986 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6987 MachineBasicBlock *BB) const {
6988 // This pseudo instruction has 3 operands: dst, src, size
6989 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6990 // Otherwise, we will generate unrolled scalar copies.
6991 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6992 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6993 MachineFunction::iterator It = BB;
6996 unsigned dest = MI->getOperand(0).getReg();
6997 unsigned src = MI->getOperand(1).getReg();
6998 unsigned SizeVal = MI->getOperand(2).getImm();
6999 unsigned Align = MI->getOperand(3).getImm();
7000 DebugLoc dl = MI->getDebugLoc();
7002 MachineFunction *MF = BB->getParent();
7003 MachineRegisterInfo &MRI = MF->getRegInfo();
7004 unsigned UnitSize = 0;
7005 const TargetRegisterClass *TRC = nullptr;
7006 const TargetRegisterClass *VecTRC = nullptr;
7008 bool IsThumb1 = Subtarget->isThumb1Only();
7009 bool IsThumb2 = Subtarget->isThumb2();
7013 } else if (Align & 2) {
7016 // Check whether we can use NEON instructions.
7017 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7018 Subtarget->hasNEON()) {
7019 if ((Align % 16 == 0) && SizeVal >= 16)
7021 else if ((Align % 8 == 0) && SizeVal >= 8)
7024 // Can't use NEON instructions.
7029 // Select the correct opcode and register class for unit size load/store
7030 bool IsNeon = UnitSize >= 8;
7031 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7033 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7034 : UnitSize == 8 ? &ARM::DPRRegClass
7037 unsigned BytesLeft = SizeVal % UnitSize;
7038 unsigned LoopSize = SizeVal - BytesLeft;
7040 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7041 // Use LDR and STR to copy.
7042 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7043 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7044 unsigned srcIn = src;
7045 unsigned destIn = dest;
7046 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7047 unsigned srcOut = MRI.createVirtualRegister(TRC);
7048 unsigned destOut = MRI.createVirtualRegister(TRC);
7049 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7050 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7051 IsThumb1, IsThumb2);
7052 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7053 IsThumb1, IsThumb2);
7058 // Handle the leftover bytes with LDRB and STRB.
7059 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7060 // [destOut] = STRB_POST(scratch, destIn, 1)
7061 for (unsigned i = 0; i < BytesLeft; i++) {
7062 unsigned srcOut = MRI.createVirtualRegister(TRC);
7063 unsigned destOut = MRI.createVirtualRegister(TRC);
7064 unsigned scratch = MRI.createVirtualRegister(TRC);
7065 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7066 IsThumb1, IsThumb2);
7067 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7068 IsThumb1, IsThumb2);
7072 MI->eraseFromParent(); // The instruction is gone now.
7076 // Expand the pseudo op to a loop.
7079 // movw varEnd, # --> with thumb2
7081 // ldrcp varEnd, idx --> without thumb2
7082 // fallthrough --> loopMBB
7084 // PHI varPhi, varEnd, varLoop
7085 // PHI srcPhi, src, srcLoop
7086 // PHI destPhi, dst, destLoop
7087 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7088 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7089 // subs varLoop, varPhi, #UnitSize
7091 // fallthrough --> exitMBB
7093 // epilogue to handle left-over bytes
7094 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7095 // [destOut] = STRB_POST(scratch, destLoop, 1)
7096 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7097 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7098 MF->insert(It, loopMBB);
7099 MF->insert(It, exitMBB);
7101 // Transfer the remainder of BB and its successor edges to exitMBB.
7102 exitMBB->splice(exitMBB->begin(), BB,
7103 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7104 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7106 // Load an immediate to varEnd.
7107 unsigned varEnd = MRI.createVirtualRegister(TRC);
7109 unsigned Vtmp = varEnd;
7110 if ((LoopSize & 0xFFFF0000) != 0)
7111 Vtmp = MRI.createVirtualRegister(TRC);
7112 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7113 .addImm(LoopSize & 0xFFFF));
7115 if ((LoopSize & 0xFFFF0000) != 0)
7116 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7117 .addReg(Vtmp).addImm(LoopSize >> 16));
7119 MachineConstantPool *ConstantPool = MF->getConstantPool();
7120 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7121 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7123 // MachineConstantPool wants an explicit alignment.
7124 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7126 Align = getDataLayout()->getTypeAllocSize(C->getType());
7127 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7130 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7131 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7133 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7134 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7136 BB->addSuccessor(loopMBB);
7138 // Generate the loop body:
7139 // varPhi = PHI(varLoop, varEnd)
7140 // srcPhi = PHI(srcLoop, src)
7141 // destPhi = PHI(destLoop, dst)
7142 MachineBasicBlock *entryBB = BB;
7144 unsigned varLoop = MRI.createVirtualRegister(TRC);
7145 unsigned varPhi = MRI.createVirtualRegister(TRC);
7146 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7147 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7148 unsigned destLoop = MRI.createVirtualRegister(TRC);
7149 unsigned destPhi = MRI.createVirtualRegister(TRC);
7151 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7152 .addReg(varLoop).addMBB(loopMBB)
7153 .addReg(varEnd).addMBB(entryBB);
7154 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7155 .addReg(srcLoop).addMBB(loopMBB)
7156 .addReg(src).addMBB(entryBB);
7157 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7158 .addReg(destLoop).addMBB(loopMBB)
7159 .addReg(dest).addMBB(entryBB);
7161 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7162 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7163 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7164 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7165 IsThumb1, IsThumb2);
7166 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7167 IsThumb1, IsThumb2);
7169 // Decrement loop variable by UnitSize.
7171 MachineInstrBuilder MIB =
7172 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7173 MIB = AddDefaultT1CC(MIB);
7174 MIB.addReg(varPhi).addImm(UnitSize);
7175 AddDefaultPred(MIB);
7177 MachineInstrBuilder MIB =
7178 BuildMI(*BB, BB->end(), dl,
7179 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7180 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7181 MIB->getOperand(5).setReg(ARM::CPSR);
7182 MIB->getOperand(5).setIsDef(true);
7184 BuildMI(*BB, BB->end(), dl,
7185 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7186 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7188 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7189 BB->addSuccessor(loopMBB);
7190 BB->addSuccessor(exitMBB);
7192 // Add epilogue to handle BytesLeft.
7194 MachineInstr *StartOfExit = exitMBB->begin();
7196 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7197 // [destOut] = STRB_POST(scratch, destLoop, 1)
7198 unsigned srcIn = srcLoop;
7199 unsigned destIn = destLoop;
7200 for (unsigned i = 0; i < BytesLeft; i++) {
7201 unsigned srcOut = MRI.createVirtualRegister(TRC);
7202 unsigned destOut = MRI.createVirtualRegister(TRC);
7203 unsigned scratch = MRI.createVirtualRegister(TRC);
7204 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7205 IsThumb1, IsThumb2);
7206 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7207 IsThumb1, IsThumb2);
7212 MI->eraseFromParent(); // The instruction is gone now.
7217 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7218 MachineBasicBlock *MBB) const {
7219 const TargetMachine &TM = getTargetMachine();
7220 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7221 DebugLoc DL = MI->getDebugLoc();
7223 assert(Subtarget->isTargetWindows() &&
7224 "__chkstk is only supported on Windows");
7225 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7227 // __chkstk takes the number of words to allocate on the stack in R4, and
7228 // returns the stack adjustment in number of bytes in R4. This will not
7229 // clober any other registers (other than the obvious lr).
7231 // Although, technically, IP should be considered a register which may be
7232 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7233 // thumb-2 environment, so there is no interworking required. As a result, we
7234 // do not expect a veneer to be emitted by the linker, clobbering IP.
7236 // Each module receives its own copy of __chkstk, so no import thunk is
7237 // required, again, ensuring that IP is not clobbered.
7239 // Finally, although some linkers may theoretically provide a trampoline for
7240 // out of range calls (which is quite common due to a 32M range limitation of
7241 // branches for Thumb), we can generate the long-call version via
7242 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7245 switch (TM.getCodeModel()) {
7246 case CodeModel::Small:
7247 case CodeModel::Medium:
7248 case CodeModel::Default:
7249 case CodeModel::Kernel:
7250 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7251 .addImm((unsigned)ARMCC::AL).addReg(0)
7252 .addExternalSymbol("__chkstk")
7253 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7254 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7255 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7257 case CodeModel::Large:
7258 case CodeModel::JITDefault: {
7259 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7260 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7262 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7263 .addExternalSymbol("__chkstk");
7264 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7265 .addImm((unsigned)ARMCC::AL).addReg(0)
7266 .addReg(Reg, RegState::Kill)
7267 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7268 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7269 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7274 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7276 .addReg(ARM::SP).addReg(ARM::R4)));
7278 MI->eraseFromParent();
7283 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7284 MachineBasicBlock *BB) const {
7285 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7286 DebugLoc dl = MI->getDebugLoc();
7287 bool isThumb2 = Subtarget->isThumb2();
7288 switch (MI->getOpcode()) {
7291 llvm_unreachable("Unexpected instr type to insert");
7293 // The Thumb2 pre-indexed stores have the same MI operands, they just
7294 // define them differently in the .td files from the isel patterns, so
7295 // they need pseudos.
7296 case ARM::t2STR_preidx:
7297 MI->setDesc(TII->get(ARM::t2STR_PRE));
7299 case ARM::t2STRB_preidx:
7300 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7302 case ARM::t2STRH_preidx:
7303 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7306 case ARM::STRi_preidx:
7307 case ARM::STRBi_preidx: {
7308 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7309 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7310 // Decode the offset.
7311 unsigned Offset = MI->getOperand(4).getImm();
7312 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7313 Offset = ARM_AM::getAM2Offset(Offset);
7317 MachineMemOperand *MMO = *MI->memoperands_begin();
7318 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7319 .addOperand(MI->getOperand(0)) // Rn_wb
7320 .addOperand(MI->getOperand(1)) // Rt
7321 .addOperand(MI->getOperand(2)) // Rn
7322 .addImm(Offset) // offset (skip GPR==zero_reg)
7323 .addOperand(MI->getOperand(5)) // pred
7324 .addOperand(MI->getOperand(6))
7325 .addMemOperand(MMO);
7326 MI->eraseFromParent();
7329 case ARM::STRr_preidx:
7330 case ARM::STRBr_preidx:
7331 case ARM::STRH_preidx: {
7333 switch (MI->getOpcode()) {
7334 default: llvm_unreachable("unexpected opcode!");
7335 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7336 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7337 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7339 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7340 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7341 MIB.addOperand(MI->getOperand(i));
7342 MI->eraseFromParent();
7346 case ARM::tMOVCCr_pseudo: {
7347 // To "insert" a SELECT_CC instruction, we actually have to insert the
7348 // diamond control-flow pattern. The incoming instruction knows the
7349 // destination vreg to set, the condition code register to branch on, the
7350 // true/false values to select between, and a branch opcode to use.
7351 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7352 MachineFunction::iterator It = BB;
7358 // cmpTY ccX, r1, r2
7360 // fallthrough --> copy0MBB
7361 MachineBasicBlock *thisMBB = BB;
7362 MachineFunction *F = BB->getParent();
7363 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7364 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7365 F->insert(It, copy0MBB);
7366 F->insert(It, sinkMBB);
7368 // Transfer the remainder of BB and its successor edges to sinkMBB.
7369 sinkMBB->splice(sinkMBB->begin(), BB,
7370 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7371 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7373 BB->addSuccessor(copy0MBB);
7374 BB->addSuccessor(sinkMBB);
7376 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7377 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7380 // %FalseValue = ...
7381 // # fallthrough to sinkMBB
7384 // Update machine-CFG edges
7385 BB->addSuccessor(sinkMBB);
7388 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7391 BuildMI(*BB, BB->begin(), dl,
7392 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7393 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7394 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7396 MI->eraseFromParent(); // The pseudo instruction is gone now.
7401 case ARM::BCCZi64: {
7402 // If there is an unconditional branch to the other successor, remove it.
7403 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7405 // Compare both parts that make up the double comparison separately for
7407 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7409 unsigned LHS1 = MI->getOperand(1).getReg();
7410 unsigned LHS2 = MI->getOperand(2).getReg();
7412 AddDefaultPred(BuildMI(BB, dl,
7413 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7414 .addReg(LHS1).addImm(0));
7415 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7416 .addReg(LHS2).addImm(0)
7417 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7419 unsigned RHS1 = MI->getOperand(3).getReg();
7420 unsigned RHS2 = MI->getOperand(4).getReg();
7421 AddDefaultPred(BuildMI(BB, dl,
7422 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7423 .addReg(LHS1).addReg(RHS1));
7424 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7425 .addReg(LHS2).addReg(RHS2)
7426 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7429 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7430 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7431 if (MI->getOperand(0).getImm() == ARMCC::NE)
7432 std::swap(destMBB, exitMBB);
7434 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7435 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7437 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7439 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7441 MI->eraseFromParent(); // The pseudo instruction is gone now.
7445 case ARM::Int_eh_sjlj_setjmp:
7446 case ARM::Int_eh_sjlj_setjmp_nofp:
7447 case ARM::tInt_eh_sjlj_setjmp:
7448 case ARM::t2Int_eh_sjlj_setjmp:
7449 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7450 EmitSjLjDispatchBlock(MI, BB);
7455 // To insert an ABS instruction, we have to insert the
7456 // diamond control-flow pattern. The incoming instruction knows the
7457 // source vreg to test against 0, the destination vreg to set,
7458 // the condition code register to branch on, the
7459 // true/false values to select between, and a branch opcode to use.
7464 // BCC (branch to SinkBB if V0 >= 0)
7465 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7466 // SinkBB: V1 = PHI(V2, V3)
7467 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7468 MachineFunction::iterator BBI = BB;
7470 MachineFunction *Fn = BB->getParent();
7471 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7472 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7473 Fn->insert(BBI, RSBBB);
7474 Fn->insert(BBI, SinkBB);
7476 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7477 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7478 bool isThumb2 = Subtarget->isThumb2();
7479 MachineRegisterInfo &MRI = Fn->getRegInfo();
7480 // In Thumb mode S must not be specified if source register is the SP or
7481 // PC and if destination register is the SP, so restrict register class
7482 unsigned NewRsbDstReg =
7483 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7485 // Transfer the remainder of BB and its successor edges to sinkMBB.
7486 SinkBB->splice(SinkBB->begin(), BB,
7487 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7488 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7490 BB->addSuccessor(RSBBB);
7491 BB->addSuccessor(SinkBB);
7493 // fall through to SinkMBB
7494 RSBBB->addSuccessor(SinkBB);
7496 // insert a cmp at the end of BB
7497 AddDefaultPred(BuildMI(BB, dl,
7498 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7499 .addReg(ABSSrcReg).addImm(0));
7501 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7503 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7504 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7506 // insert rsbri in RSBBB
7507 // Note: BCC and rsbri will be converted into predicated rsbmi
7508 // by if-conversion pass
7509 BuildMI(*RSBBB, RSBBB->begin(), dl,
7510 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7511 .addReg(ABSSrcReg, RegState::Kill)
7512 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7514 // insert PHI in SinkBB,
7515 // reuse ABSDstReg to not change uses of ABS instruction
7516 BuildMI(*SinkBB, SinkBB->begin(), dl,
7517 TII->get(ARM::PHI), ABSDstReg)
7518 .addReg(NewRsbDstReg).addMBB(RSBBB)
7519 .addReg(ABSSrcReg).addMBB(BB);
7521 // remove ABS instruction
7522 MI->eraseFromParent();
7524 // return last added BB
7527 case ARM::COPY_STRUCT_BYVAL_I32:
7529 return EmitStructByval(MI, BB);
7530 case ARM::WIN__CHKSTK:
7531 return EmitLowered__chkstk(MI, BB);
7535 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7536 SDNode *Node) const {
7537 const MCInstrDesc *MCID = &MI->getDesc();
7538 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7539 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7540 // operand is still set to noreg. If needed, set the optional operand's
7541 // register to CPSR, and remove the redundant implicit def.
7543 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7545 // Rename pseudo opcodes.
7546 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7548 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7549 MCID = &TII->get(NewOpc);
7551 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7552 "converted opcode should be the same except for cc_out");
7556 // Add the optional cc_out operand
7557 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7559 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7561 // Any ARM instruction that sets the 's' bit should specify an optional
7562 // "cc_out" operand in the last operand position.
7563 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7564 assert(!NewOpc && "Optional cc_out operand required");
7567 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7568 // since we already have an optional CPSR def.
7569 bool definesCPSR = false;
7570 bool deadCPSR = false;
7571 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7573 const MachineOperand &MO = MI->getOperand(i);
7574 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7578 MI->RemoveOperand(i);
7583 assert(!NewOpc && "Optional cc_out operand required");
7586 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7588 assert(!MI->getOperand(ccOutIdx).getReg() &&
7589 "expect uninitialized optional cc_out operand");
7593 // If this instruction was defined with an optional CPSR def and its dag node
7594 // had a live implicit CPSR def, then activate the optional CPSR def.
7595 MachineOperand &MO = MI->getOperand(ccOutIdx);
7596 MO.setReg(ARM::CPSR);
7600 //===----------------------------------------------------------------------===//
7601 // ARM Optimization Hooks
7602 //===----------------------------------------------------------------------===//
7604 // Helper function that checks if N is a null or all ones constant.
7605 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7606 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7609 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7612 // Return true if N is conditionally 0 or all ones.
7613 // Detects these expressions where cc is an i1 value:
7615 // (select cc 0, y) [AllOnes=0]
7616 // (select cc y, 0) [AllOnes=0]
7617 // (zext cc) [AllOnes=0]
7618 // (sext cc) [AllOnes=0/1]
7619 // (select cc -1, y) [AllOnes=1]
7620 // (select cc y, -1) [AllOnes=1]
7622 // Invert is set when N is the null/all ones constant when CC is false.
7623 // OtherOp is set to the alternative value of N.
7624 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7625 SDValue &CC, bool &Invert,
7627 SelectionDAG &DAG) {
7628 switch (N->getOpcode()) {
7629 default: return false;
7631 CC = N->getOperand(0);
7632 SDValue N1 = N->getOperand(1);
7633 SDValue N2 = N->getOperand(2);
7634 if (isZeroOrAllOnes(N1, AllOnes)) {
7639 if (isZeroOrAllOnes(N2, AllOnes)) {
7646 case ISD::ZERO_EXTEND:
7647 // (zext cc) can never be the all ones value.
7651 case ISD::SIGN_EXTEND: {
7652 EVT VT = N->getValueType(0);
7653 CC = N->getOperand(0);
7654 if (CC.getValueType() != MVT::i1)
7658 // When looking for an AllOnes constant, N is an sext, and the 'other'
7660 OtherOp = DAG.getConstant(0, VT);
7661 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7662 // When looking for a 0 constant, N can be zext or sext.
7663 OtherOp = DAG.getConstant(1, VT);
7665 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7671 // Combine a constant select operand into its use:
7673 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7674 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7675 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7676 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7677 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7679 // The transform is rejected if the select doesn't have a constant operand that
7680 // is null, or all ones when AllOnes is set.
7682 // Also recognize sext/zext from i1:
7684 // (add (zext cc), x) -> (select cc (add x, 1), x)
7685 // (add (sext cc), x) -> (select cc (add x, -1), x)
7687 // These transformations eventually create predicated instructions.
7689 // @param N The node to transform.
7690 // @param Slct The N operand that is a select.
7691 // @param OtherOp The other N operand (x above).
7692 // @param DCI Context.
7693 // @param AllOnes Require the select constant to be all ones instead of null.
7694 // @returns The new node, or SDValue() on failure.
7696 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7697 TargetLowering::DAGCombinerInfo &DCI,
7698 bool AllOnes = false) {
7699 SelectionDAG &DAG = DCI.DAG;
7700 EVT VT = N->getValueType(0);
7701 SDValue NonConstantVal;
7704 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7705 NonConstantVal, DAG))
7708 // Slct is now know to be the desired identity constant when CC is true.
7709 SDValue TrueVal = OtherOp;
7710 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7711 OtherOp, NonConstantVal);
7712 // Unless SwapSelectOps says CC should be false.
7714 std::swap(TrueVal, FalseVal);
7716 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7717 CCOp, TrueVal, FalseVal);
7720 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7722 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7723 TargetLowering::DAGCombinerInfo &DCI) {
7724 SDValue N0 = N->getOperand(0);
7725 SDValue N1 = N->getOperand(1);
7726 if (N0.getNode()->hasOneUse()) {
7727 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7728 if (Result.getNode())
7731 if (N1.getNode()->hasOneUse()) {
7732 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7733 if (Result.getNode())
7739 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7740 // (only after legalization).
7741 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7742 TargetLowering::DAGCombinerInfo &DCI,
7743 const ARMSubtarget *Subtarget) {
7745 // Only perform optimization if after legalize, and if NEON is available. We
7746 // also expected both operands to be BUILD_VECTORs.
7747 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7748 || N0.getOpcode() != ISD::BUILD_VECTOR
7749 || N1.getOpcode() != ISD::BUILD_VECTOR)
7752 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7753 EVT VT = N->getValueType(0);
7754 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7757 // Check that the vector operands are of the right form.
7758 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7759 // operands, where N is the size of the formed vector.
7760 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7761 // index such that we have a pair wise add pattern.
7763 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7764 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7766 SDValue Vec = N0->getOperand(0)->getOperand(0);
7767 SDNode *V = Vec.getNode();
7768 unsigned nextIndex = 0;
7770 // For each operands to the ADD which are BUILD_VECTORs,
7771 // check to see if each of their operands are an EXTRACT_VECTOR with
7772 // the same vector and appropriate index.
7773 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7774 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7775 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7777 SDValue ExtVec0 = N0->getOperand(i);
7778 SDValue ExtVec1 = N1->getOperand(i);
7780 // First operand is the vector, verify its the same.
7781 if (V != ExtVec0->getOperand(0).getNode() ||
7782 V != ExtVec1->getOperand(0).getNode())
7785 // Second is the constant, verify its correct.
7786 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7787 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7789 // For the constant, we want to see all the even or all the odd.
7790 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7791 || C1->getZExtValue() != nextIndex+1)
7800 // Create VPADDL node.
7801 SelectionDAG &DAG = DCI.DAG;
7802 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7804 // Build operand list.
7805 SmallVector<SDValue, 8> Ops;
7806 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7807 TLI.getPointerTy()));
7809 // Input is the vector.
7812 // Get widened type and narrowed type.
7814 unsigned numElem = VT.getVectorNumElements();
7816 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7817 switch (inputLaneType.getSimpleVT().SimpleTy) {
7818 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7819 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7820 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7822 llvm_unreachable("Invalid vector element type for padd optimization.");
7825 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7826 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7827 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7830 static SDValue findMUL_LOHI(SDValue V) {
7831 if (V->getOpcode() == ISD::UMUL_LOHI ||
7832 V->getOpcode() == ISD::SMUL_LOHI)
7837 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7838 TargetLowering::DAGCombinerInfo &DCI,
7839 const ARMSubtarget *Subtarget) {
7841 if (Subtarget->isThumb1Only()) return SDValue();
7843 // Only perform the checks after legalize when the pattern is available.
7844 if (DCI.isBeforeLegalize()) return SDValue();
7846 // Look for multiply add opportunities.
7847 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7848 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7849 // a glue link from the first add to the second add.
7850 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7851 // a S/UMLAL instruction.
7854 // \ / \ [no multiline comment]
7860 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7861 SDValue AddcOp0 = AddcNode->getOperand(0);
7862 SDValue AddcOp1 = AddcNode->getOperand(1);
7864 // Check if the two operands are from the same mul_lohi node.
7865 if (AddcOp0.getNode() == AddcOp1.getNode())
7868 assert(AddcNode->getNumValues() == 2 &&
7869 AddcNode->getValueType(0) == MVT::i32 &&
7870 "Expect ADDC with two result values. First: i32");
7872 // Check that we have a glued ADDC node.
7873 if (AddcNode->getValueType(1) != MVT::Glue)
7876 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7877 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7878 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7879 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7880 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7883 // Look for the glued ADDE.
7884 SDNode* AddeNode = AddcNode->getGluedUser();
7888 // Make sure it is really an ADDE.
7889 if (AddeNode->getOpcode() != ISD::ADDE)
7892 assert(AddeNode->getNumOperands() == 3 &&
7893 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7894 "ADDE node has the wrong inputs");
7896 // Check for the triangle shape.
7897 SDValue AddeOp0 = AddeNode->getOperand(0);
7898 SDValue AddeOp1 = AddeNode->getOperand(1);
7900 // Make sure that the ADDE operands are not coming from the same node.
7901 if (AddeOp0.getNode() == AddeOp1.getNode())
7904 // Find the MUL_LOHI node walking up ADDE's operands.
7905 bool IsLeftOperandMUL = false;
7906 SDValue MULOp = findMUL_LOHI(AddeOp0);
7907 if (MULOp == SDValue())
7908 MULOp = findMUL_LOHI(AddeOp1);
7910 IsLeftOperandMUL = true;
7911 if (MULOp == SDValue())
7914 // Figure out the right opcode.
7915 unsigned Opc = MULOp->getOpcode();
7916 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7918 // Figure out the high and low input values to the MLAL node.
7919 SDValue* HiAdd = nullptr;
7920 SDValue* LoMul = nullptr;
7921 SDValue* LowAdd = nullptr;
7923 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
7924 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
7927 if (IsLeftOperandMUL)
7933 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
7934 // whose low result is fed to the ADDC we are checking.
7936 if (AddcOp0 == MULOp.getValue(0)) {
7940 if (AddcOp1 == MULOp.getValue(0)) {
7948 // Create the merged node.
7949 SelectionDAG &DAG = DCI.DAG;
7951 // Build operand list.
7952 SmallVector<SDValue, 8> Ops;
7953 Ops.push_back(LoMul->getOperand(0));
7954 Ops.push_back(LoMul->getOperand(1));
7955 Ops.push_back(*LowAdd);
7956 Ops.push_back(*HiAdd);
7958 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
7959 DAG.getVTList(MVT::i32, MVT::i32), Ops);
7961 // Replace the ADDs' nodes uses by the MLA node's values.
7962 SDValue HiMLALResult(MLALNode.getNode(), 1);
7963 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7965 SDValue LoMLALResult(MLALNode.getNode(), 0);
7966 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7968 // Return original node to notify the driver to stop replacing.
7969 SDValue resNode(AddcNode, 0);
7973 /// PerformADDCCombine - Target-specific dag combine transform from
7974 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7975 static SDValue PerformADDCCombine(SDNode *N,
7976 TargetLowering::DAGCombinerInfo &DCI,
7977 const ARMSubtarget *Subtarget) {
7979 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7983 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7984 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7985 /// called with the default operands, and if that fails, with commuted
7987 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7988 TargetLowering::DAGCombinerInfo &DCI,
7989 const ARMSubtarget *Subtarget){
7991 // Attempt to create vpaddl for this add.
7992 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7993 if (Result.getNode())
7996 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7997 if (N0.getNode()->hasOneUse()) {
7998 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7999 if (Result.getNode()) return Result;
8004 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8006 static SDValue PerformADDCombine(SDNode *N,
8007 TargetLowering::DAGCombinerInfo &DCI,
8008 const ARMSubtarget *Subtarget) {
8009 SDValue N0 = N->getOperand(0);
8010 SDValue N1 = N->getOperand(1);
8012 // First try with the default operand order.
8013 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8014 if (Result.getNode())
8017 // If that didn't work, try again with the operands commuted.
8018 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8021 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8023 static SDValue PerformSUBCombine(SDNode *N,
8024 TargetLowering::DAGCombinerInfo &DCI) {
8025 SDValue N0 = N->getOperand(0);
8026 SDValue N1 = N->getOperand(1);
8028 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8029 if (N1.getNode()->hasOneUse()) {
8030 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8031 if (Result.getNode()) return Result;
8037 /// PerformVMULCombine
8038 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8039 /// special multiplier accumulator forwarding.
8045 // However, for (A + B) * (A + B),
8052 static SDValue PerformVMULCombine(SDNode *N,
8053 TargetLowering::DAGCombinerInfo &DCI,
8054 const ARMSubtarget *Subtarget) {
8055 if (!Subtarget->hasVMLxForwarding())
8058 SelectionDAG &DAG = DCI.DAG;
8059 SDValue N0 = N->getOperand(0);
8060 SDValue N1 = N->getOperand(1);
8061 unsigned Opcode = N0.getOpcode();
8062 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8063 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8064 Opcode = N1.getOpcode();
8065 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8066 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8074 EVT VT = N->getValueType(0);
8076 SDValue N00 = N0->getOperand(0);
8077 SDValue N01 = N0->getOperand(1);
8078 return DAG.getNode(Opcode, DL, VT,
8079 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8080 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8083 static SDValue PerformMULCombine(SDNode *N,
8084 TargetLowering::DAGCombinerInfo &DCI,
8085 const ARMSubtarget *Subtarget) {
8086 SelectionDAG &DAG = DCI.DAG;
8088 if (Subtarget->isThumb1Only())
8091 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8094 EVT VT = N->getValueType(0);
8095 if (VT.is64BitVector() || VT.is128BitVector())
8096 return PerformVMULCombine(N, DCI, Subtarget);
8100 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8104 int64_t MulAmt = C->getSExtValue();
8105 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8107 ShiftAmt = ShiftAmt & (32 - 1);
8108 SDValue V = N->getOperand(0);
8112 MulAmt >>= ShiftAmt;
8115 if (isPowerOf2_32(MulAmt - 1)) {
8116 // (mul x, 2^N + 1) => (add (shl x, N), x)
8117 Res = DAG.getNode(ISD::ADD, DL, VT,
8119 DAG.getNode(ISD::SHL, DL, VT,
8121 DAG.getConstant(Log2_32(MulAmt - 1),
8123 } else if (isPowerOf2_32(MulAmt + 1)) {
8124 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8125 Res = DAG.getNode(ISD::SUB, DL, VT,
8126 DAG.getNode(ISD::SHL, DL, VT,
8128 DAG.getConstant(Log2_32(MulAmt + 1),
8134 uint64_t MulAmtAbs = -MulAmt;
8135 if (isPowerOf2_32(MulAmtAbs + 1)) {
8136 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8137 Res = DAG.getNode(ISD::SUB, DL, VT,
8139 DAG.getNode(ISD::SHL, DL, VT,
8141 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8143 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8144 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8145 Res = DAG.getNode(ISD::ADD, DL, VT,
8147 DAG.getNode(ISD::SHL, DL, VT,
8149 DAG.getConstant(Log2_32(MulAmtAbs-1),
8151 Res = DAG.getNode(ISD::SUB, DL, VT,
8152 DAG.getConstant(0, MVT::i32),Res);
8159 Res = DAG.getNode(ISD::SHL, DL, VT,
8160 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8162 // Do not add new nodes to DAG combiner worklist.
8163 DCI.CombineTo(N, Res, false);
8167 static SDValue PerformANDCombine(SDNode *N,
8168 TargetLowering::DAGCombinerInfo &DCI,
8169 const ARMSubtarget *Subtarget) {
8171 // Attempt to use immediate-form VBIC
8172 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8174 EVT VT = N->getValueType(0);
8175 SelectionDAG &DAG = DCI.DAG;
8177 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8180 APInt SplatBits, SplatUndef;
8181 unsigned SplatBitSize;
8184 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8185 if (SplatBitSize <= 64) {
8187 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8188 SplatUndef.getZExtValue(), SplatBitSize,
8189 DAG, VbicVT, VT.is128BitVector(),
8191 if (Val.getNode()) {
8193 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8194 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8195 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8200 if (!Subtarget->isThumb1Only()) {
8201 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8202 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8203 if (Result.getNode())
8210 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8211 static SDValue PerformORCombine(SDNode *N,
8212 TargetLowering::DAGCombinerInfo &DCI,
8213 const ARMSubtarget *Subtarget) {
8214 // Attempt to use immediate-form VORR
8215 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8217 EVT VT = N->getValueType(0);
8218 SelectionDAG &DAG = DCI.DAG;
8220 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8223 APInt SplatBits, SplatUndef;
8224 unsigned SplatBitSize;
8226 if (BVN && Subtarget->hasNEON() &&
8227 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8228 if (SplatBitSize <= 64) {
8230 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8231 SplatUndef.getZExtValue(), SplatBitSize,
8232 DAG, VorrVT, VT.is128BitVector(),
8234 if (Val.getNode()) {
8236 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8237 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8238 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8243 if (!Subtarget->isThumb1Only()) {
8244 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8245 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8246 if (Result.getNode())
8250 // The code below optimizes (or (and X, Y), Z).
8251 // The AND operand needs to have a single user to make these optimizations
8253 SDValue N0 = N->getOperand(0);
8254 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8256 SDValue N1 = N->getOperand(1);
8258 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8259 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8260 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8262 unsigned SplatBitSize;
8265 APInt SplatBits0, SplatBits1;
8266 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8267 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8268 // Ensure that the second operand of both ands are constants
8269 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8270 HasAnyUndefs) && !HasAnyUndefs) {
8271 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8272 HasAnyUndefs) && !HasAnyUndefs) {
8273 // Ensure that the bit width of the constants are the same and that
8274 // the splat arguments are logical inverses as per the pattern we
8275 // are trying to simplify.
8276 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8277 SplatBits0 == ~SplatBits1) {
8278 // Canonicalize the vector type to make instruction selection
8280 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8281 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8285 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8291 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8294 // BFI is only available on V6T2+
8295 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8299 // 1) or (and A, mask), val => ARMbfi A, val, mask
8300 // iff (val & mask) == val
8302 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8303 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8304 // && mask == ~mask2
8305 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8306 // && ~mask == mask2
8307 // (i.e., copy a bitfield value into another bitfield of the same width)
8312 SDValue N00 = N0.getOperand(0);
8314 // The value and the mask need to be constants so we can verify this is
8315 // actually a bitfield set. If the mask is 0xffff, we can do better
8316 // via a movt instruction, so don't use BFI in that case.
8317 SDValue MaskOp = N0.getOperand(1);
8318 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8321 unsigned Mask = MaskC->getZExtValue();
8325 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8326 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8328 unsigned Val = N1C->getZExtValue();
8329 if ((Val & ~Mask) != Val)
8332 if (ARM::isBitFieldInvertedMask(Mask)) {
8333 Val >>= countTrailingZeros(~Mask);
8335 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8336 DAG.getConstant(Val, MVT::i32),
8337 DAG.getConstant(Mask, MVT::i32));
8339 // Do not add new nodes to DAG combiner worklist.
8340 DCI.CombineTo(N, Res, false);
8343 } else if (N1.getOpcode() == ISD::AND) {
8344 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8345 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8348 unsigned Mask2 = N11C->getZExtValue();
8350 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8352 if (ARM::isBitFieldInvertedMask(Mask) &&
8354 // The pack halfword instruction works better for masks that fit it,
8355 // so use that when it's available.
8356 if (Subtarget->hasT2ExtractPack() &&
8357 (Mask == 0xffff || Mask == 0xffff0000))
8360 unsigned amt = countTrailingZeros(Mask2);
8361 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8362 DAG.getConstant(amt, MVT::i32));
8363 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8364 DAG.getConstant(Mask, MVT::i32));
8365 // Do not add new nodes to DAG combiner worklist.
8366 DCI.CombineTo(N, Res, false);
8368 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8370 // The pack halfword instruction works better for masks that fit it,
8371 // so use that when it's available.
8372 if (Subtarget->hasT2ExtractPack() &&
8373 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8376 unsigned lsb = countTrailingZeros(Mask);
8377 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8378 DAG.getConstant(lsb, MVT::i32));
8379 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8380 DAG.getConstant(Mask2, MVT::i32));
8381 // Do not add new nodes to DAG combiner worklist.
8382 DCI.CombineTo(N, Res, false);
8387 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8388 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8389 ARM::isBitFieldInvertedMask(~Mask)) {
8390 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8391 // where lsb(mask) == #shamt and masked bits of B are known zero.
8392 SDValue ShAmt = N00.getOperand(1);
8393 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8394 unsigned LSB = countTrailingZeros(Mask);
8398 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8399 DAG.getConstant(~Mask, MVT::i32));
8401 // Do not add new nodes to DAG combiner worklist.
8402 DCI.CombineTo(N, Res, false);
8408 static SDValue PerformXORCombine(SDNode *N,
8409 TargetLowering::DAGCombinerInfo &DCI,
8410 const ARMSubtarget *Subtarget) {
8411 EVT VT = N->getValueType(0);
8412 SelectionDAG &DAG = DCI.DAG;
8414 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8417 if (!Subtarget->isThumb1Only()) {
8418 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8419 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8420 if (Result.getNode())
8427 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8428 /// the bits being cleared by the AND are not demanded by the BFI.
8429 static SDValue PerformBFICombine(SDNode *N,
8430 TargetLowering::DAGCombinerInfo &DCI) {
8431 SDValue N1 = N->getOperand(1);
8432 if (N1.getOpcode() == ISD::AND) {
8433 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8436 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8437 unsigned LSB = countTrailingZeros(~InvMask);
8438 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8440 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8441 "undefined behavior");
8442 unsigned Mask = (1u << Width) - 1;
8443 unsigned Mask2 = N11C->getZExtValue();
8444 if ((Mask & (~Mask2)) == 0)
8445 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8446 N->getOperand(0), N1.getOperand(0),
8452 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8453 /// ARMISD::VMOVRRD.
8454 static SDValue PerformVMOVRRDCombine(SDNode *N,
8455 TargetLowering::DAGCombinerInfo &DCI,
8456 const ARMSubtarget *Subtarget) {
8457 // vmovrrd(vmovdrr x, y) -> x,y
8458 SDValue InDouble = N->getOperand(0);
8459 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8460 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8462 // vmovrrd(load f64) -> (load i32), (load i32)
8463 SDNode *InNode = InDouble.getNode();
8464 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8465 InNode->getValueType(0) == MVT::f64 &&
8466 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8467 !cast<LoadSDNode>(InNode)->isVolatile()) {
8468 // TODO: Should this be done for non-FrameIndex operands?
8469 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8471 SelectionDAG &DAG = DCI.DAG;
8473 SDValue BasePtr = LD->getBasePtr();
8474 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8475 LD->getPointerInfo(), LD->isVolatile(),
8476 LD->isNonTemporal(), LD->isInvariant(),
8477 LD->getAlignment());
8479 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8480 DAG.getConstant(4, MVT::i32));
8481 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8482 LD->getPointerInfo(), LD->isVolatile(),
8483 LD->isNonTemporal(), LD->isInvariant(),
8484 std::min(4U, LD->getAlignment() / 2));
8486 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8487 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8488 std::swap (NewLD1, NewLD2);
8489 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8496 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8497 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8498 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8499 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8500 SDValue Op0 = N->getOperand(0);
8501 SDValue Op1 = N->getOperand(1);
8502 if (Op0.getOpcode() == ISD::BITCAST)
8503 Op0 = Op0.getOperand(0);
8504 if (Op1.getOpcode() == ISD::BITCAST)
8505 Op1 = Op1.getOperand(0);
8506 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8507 Op0.getNode() == Op1.getNode() &&
8508 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8509 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8510 N->getValueType(0), Op0.getOperand(0));
8514 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8515 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8516 /// i64 vector to have f64 elements, since the value can then be loaded
8517 /// directly into a VFP register.
8518 static bool hasNormalLoadOperand(SDNode *N) {
8519 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8520 for (unsigned i = 0; i < NumElts; ++i) {
8521 SDNode *Elt = N->getOperand(i).getNode();
8522 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8528 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8529 /// ISD::BUILD_VECTOR.
8530 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8531 TargetLowering::DAGCombinerInfo &DCI,
8532 const ARMSubtarget *Subtarget) {
8533 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8534 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8535 // into a pair of GPRs, which is fine when the value is used as a scalar,
8536 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8537 SelectionDAG &DAG = DCI.DAG;
8538 if (N->getNumOperands() == 2) {
8539 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8544 // Load i64 elements as f64 values so that type legalization does not split
8545 // them up into i32 values.
8546 EVT VT = N->getValueType(0);
8547 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8550 SmallVector<SDValue, 8> Ops;
8551 unsigned NumElts = VT.getVectorNumElements();
8552 for (unsigned i = 0; i < NumElts; ++i) {
8553 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8555 // Make the DAGCombiner fold the bitcast.
8556 DCI.AddToWorklist(V.getNode());
8558 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8559 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8560 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8563 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8565 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8566 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8567 // At that time, we may have inserted bitcasts from integer to float.
8568 // If these bitcasts have survived DAGCombine, change the lowering of this
8569 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8570 // force to use floating point types.
8572 // Make sure we can change the type of the vector.
8573 // This is possible iff:
8574 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8575 // 1.1. Vector is used only once.
8576 // 1.2. Use is a bit convert to an integer type.
8577 // 2. The size of its operands are 32-bits (64-bits are not legal).
8578 EVT VT = N->getValueType(0);
8579 EVT EltVT = VT.getVectorElementType();
8581 // Check 1.1. and 2.
8582 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8585 // By construction, the input type must be float.
8586 assert(EltVT == MVT::f32 && "Unexpected type!");
8589 SDNode *Use = *N->use_begin();
8590 if (Use->getOpcode() != ISD::BITCAST ||
8591 Use->getValueType(0).isFloatingPoint())
8594 // Check profitability.
8595 // Model is, if more than half of the relevant operands are bitcast from
8596 // i32, turn the build_vector into a sequence of insert_vector_elt.
8597 // Relevant operands are everything that is not statically
8598 // (i.e., at compile time) bitcasted.
8599 unsigned NumOfBitCastedElts = 0;
8600 unsigned NumElts = VT.getVectorNumElements();
8601 unsigned NumOfRelevantElts = NumElts;
8602 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8603 SDValue Elt = N->getOperand(Idx);
8604 if (Elt->getOpcode() == ISD::BITCAST) {
8605 // Assume only bit cast to i32 will go away.
8606 if (Elt->getOperand(0).getValueType() == MVT::i32)
8607 ++NumOfBitCastedElts;
8608 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8609 // Constants are statically casted, thus do not count them as
8610 // relevant operands.
8611 --NumOfRelevantElts;
8614 // Check if more than half of the elements require a non-free bitcast.
8615 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8618 SelectionDAG &DAG = DCI.DAG;
8619 // Create the new vector type.
8620 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8621 // Check if the type is legal.
8622 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8623 if (!TLI.isTypeLegal(VecVT))
8627 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8628 // => BITCAST INSERT_VECTOR_ELT
8629 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8631 SDValue Vec = DAG.getUNDEF(VecVT);
8633 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8634 SDValue V = N->getOperand(Idx);
8635 if (V.getOpcode() == ISD::UNDEF)
8637 if (V.getOpcode() == ISD::BITCAST &&
8638 V->getOperand(0).getValueType() == MVT::i32)
8639 // Fold obvious case.
8640 V = V.getOperand(0);
8642 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8643 // Make the DAGCombiner fold the bitcasts.
8644 DCI.AddToWorklist(V.getNode());
8646 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8647 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8649 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8650 // Make the DAGCombiner fold the bitcasts.
8651 DCI.AddToWorklist(Vec.getNode());
8655 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8656 /// ISD::INSERT_VECTOR_ELT.
8657 static SDValue PerformInsertEltCombine(SDNode *N,
8658 TargetLowering::DAGCombinerInfo &DCI) {
8659 // Bitcast an i64 load inserted into a vector to f64.
8660 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8661 EVT VT = N->getValueType(0);
8662 SDNode *Elt = N->getOperand(1).getNode();
8663 if (VT.getVectorElementType() != MVT::i64 ||
8664 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8667 SelectionDAG &DAG = DCI.DAG;
8669 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8670 VT.getVectorNumElements());
8671 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8672 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8673 // Make the DAGCombiner fold the bitcasts.
8674 DCI.AddToWorklist(Vec.getNode());
8675 DCI.AddToWorklist(V.getNode());
8676 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8677 Vec, V, N->getOperand(2));
8678 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8681 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8682 /// ISD::VECTOR_SHUFFLE.
8683 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8684 // The LLVM shufflevector instruction does not require the shuffle mask
8685 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8686 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8687 // operands do not match the mask length, they are extended by concatenating
8688 // them with undef vectors. That is probably the right thing for other
8689 // targets, but for NEON it is better to concatenate two double-register
8690 // size vector operands into a single quad-register size vector. Do that
8691 // transformation here:
8692 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8693 // shuffle(concat(v1, v2), undef)
8694 SDValue Op0 = N->getOperand(0);
8695 SDValue Op1 = N->getOperand(1);
8696 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8697 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8698 Op0.getNumOperands() != 2 ||
8699 Op1.getNumOperands() != 2)
8701 SDValue Concat0Op1 = Op0.getOperand(1);
8702 SDValue Concat1Op1 = Op1.getOperand(1);
8703 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8704 Concat1Op1.getOpcode() != ISD::UNDEF)
8706 // Skip the transformation if any of the types are illegal.
8707 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8708 EVT VT = N->getValueType(0);
8709 if (!TLI.isTypeLegal(VT) ||
8710 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8711 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8714 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8715 Op0.getOperand(0), Op1.getOperand(0));
8716 // Translate the shuffle mask.
8717 SmallVector<int, 16> NewMask;
8718 unsigned NumElts = VT.getVectorNumElements();
8719 unsigned HalfElts = NumElts/2;
8720 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8721 for (unsigned n = 0; n < NumElts; ++n) {
8722 int MaskElt = SVN->getMaskElt(n);
8724 if (MaskElt < (int)HalfElts)
8726 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8727 NewElt = HalfElts + MaskElt - NumElts;
8728 NewMask.push_back(NewElt);
8730 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8731 DAG.getUNDEF(VT), NewMask.data());
8734 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8735 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8736 /// base address updates.
8737 /// For generic load/stores, the memory type is assumed to be a vector.
8738 /// The caller is assumed to have checked legality.
8739 static SDValue CombineBaseUpdate(SDNode *N,
8740 TargetLowering::DAGCombinerInfo &DCI) {
8741 SelectionDAG &DAG = DCI.DAG;
8742 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8743 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8744 const bool isStore = N->getOpcode() == ISD::STORE;
8745 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8746 SDValue Addr = N->getOperand(AddrOpIdx);
8747 MemSDNode *MemN = cast<MemSDNode>(N);
8749 // Search for a use of the address operand that is an increment.
8750 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8751 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8753 if (User->getOpcode() != ISD::ADD ||
8754 UI.getUse().getResNo() != Addr.getResNo())
8757 // Check that the add is independent of the load/store. Otherwise, folding
8758 // it would create a cycle.
8759 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8762 // Find the new opcode for the updating load/store.
8763 bool isLoadOp = true;
8764 bool isLaneOp = false;
8765 unsigned NewOpc = 0;
8766 unsigned NumVecs = 0;
8768 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8770 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8771 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8773 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8775 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8777 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8779 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8780 NumVecs = 2; isLaneOp = true; break;
8781 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8782 NumVecs = 3; isLaneOp = true; break;
8783 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8784 NumVecs = 4; isLaneOp = true; break;
8785 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8786 NumVecs = 1; isLoadOp = false; break;
8787 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8788 NumVecs = 2; isLoadOp = false; break;
8789 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8790 NumVecs = 3; isLoadOp = false; break;
8791 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8792 NumVecs = 4; isLoadOp = false; break;
8793 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8794 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8795 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8796 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8797 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8798 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8802 switch (N->getOpcode()) {
8803 default: llvm_unreachable("unexpected opcode for Neon base update");
8804 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8805 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8806 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8807 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
8808 NumVecs = 1; isLaneOp = false; break;
8809 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
8810 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
8814 // Find the size of memory referenced by the load/store.
8817 VecTy = N->getValueType(0);
8818 } else if (isIntrinsic) {
8819 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8821 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
8822 VecTy = N->getOperand(1).getValueType();
8825 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8827 NumBytes /= VecTy.getVectorNumElements();
8829 // If the increment is a constant, it must match the memory ref size.
8830 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8831 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8832 uint64_t IncVal = CInc->getZExtValue();
8833 if (IncVal != NumBytes)
8835 } else if (NumBytes >= 3 * 16) {
8836 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8837 // separate instructions that make it harder to use a non-constant update.
8841 // OK, we found an ADD we can fold into the base update.
8842 // Now, create a _UPD node, taking care of not breaking alignment.
8844 EVT AlignedVecTy = VecTy;
8845 unsigned Alignment = MemN->getAlignment();
8847 // If this is a less-than-standard-aligned load/store, change the type to
8848 // match the standard alignment.
8849 // The alignment is overlooked when selecting _UPD variants; and it's
8850 // easier to introduce bitcasts here than fix that.
8851 // There are 3 ways to get to this base-update combine:
8852 // - intrinsics: they are assumed to be properly aligned (to the standard
8853 // alignment of the memory type), so we don't need to do anything.
8854 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
8855 // intrinsics, so, likewise, there's nothing to do.
8856 // - generic load/store instructions: the alignment is specified as an
8857 // explicit operand, rather than implicitly as the standard alignment
8858 // of the memory type (like the intrisics). We need to change the
8859 // memory type to match the explicit alignment. That way, we don't
8860 // generate non-standard-aligned ARMISD::VLDx nodes.
8861 if (isa<LSBaseSDNode>(N)) {
8864 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
8865 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
8866 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
8867 assert(!isLaneOp && "Unexpected generic load/store lane.");
8868 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
8869 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
8871 // Don't set an explicit alignment on regular load/stores that we want
8872 // to transform to VLD/VST 1_UPD nodes.
8873 // This matches the behavior of regular load/stores, which only get an
8874 // explicit alignment if the MMO alignment is larger than the standard
8875 // alignment of the memory type.
8876 // Intrinsics, however, always get an explicit alignment, set to the
8877 // alignment of the MMO.
8881 // Create the new updating load/store node.
8882 // First, create an SDVTList for the new updating node's results.
8884 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
8886 for (n = 0; n < NumResultVecs; ++n)
8887 Tys[n] = AlignedVecTy;
8888 Tys[n++] = MVT::i32;
8889 Tys[n] = MVT::Other;
8890 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
8892 // Then, gather the new node's operands.
8893 SmallVector<SDValue, 8> Ops;
8894 Ops.push_back(N->getOperand(0)); // incoming chain
8895 Ops.push_back(N->getOperand(AddrOpIdx));
8898 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
8899 // Try to match the intrinsic's signature
8900 Ops.push_back(StN->getValue());
8902 // Loads (and of course intrinsics) match the intrinsics' signature,
8903 // so just add all but the alignment operand.
8904 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
8905 Ops.push_back(N->getOperand(i));
8908 // For all node types, the alignment operand is always the last one.
8909 Ops.push_back(DAG.getConstant(Alignment, MVT::i32));
8911 // If this is a non-standard-aligned STORE, the penultimate operand is the
8912 // stored value. Bitcast it to the aligned type.
8913 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
8914 SDValue &StVal = Ops[Ops.size()-2];
8915 StVal = DAG.getNode(ISD::BITCAST, SDLoc(N), AlignedVecTy, StVal);
8918 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8920 MemN->getMemOperand());
8923 SmallVector<SDValue, 5> NewResults;
8924 for (unsigned i = 0; i < NumResultVecs; ++i)
8925 NewResults.push_back(SDValue(UpdN.getNode(), i));
8927 // If this is an non-standard-aligned LOAD, the first result is the loaded
8928 // value. Bitcast it to the expected result type.
8929 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
8930 SDValue &LdVal = NewResults[0];
8931 LdVal = DAG.getNode(ISD::BITCAST, SDLoc(N), VecTy, LdVal);
8934 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8935 DCI.CombineTo(N, NewResults);
8936 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8943 static SDValue PerformVLDCombine(SDNode *N,
8944 TargetLowering::DAGCombinerInfo &DCI) {
8945 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8948 return CombineBaseUpdate(N, DCI);
8951 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8952 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8953 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8955 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8956 SelectionDAG &DAG = DCI.DAG;
8957 EVT VT = N->getValueType(0);
8958 // vldN-dup instructions only support 64-bit vectors for N > 1.
8959 if (!VT.is64BitVector())
8962 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8963 SDNode *VLD = N->getOperand(0).getNode();
8964 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8966 unsigned NumVecs = 0;
8967 unsigned NewOpc = 0;
8968 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8969 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8971 NewOpc = ARMISD::VLD2DUP;
8972 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8974 NewOpc = ARMISD::VLD3DUP;
8975 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8977 NewOpc = ARMISD::VLD4DUP;
8982 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8983 // numbers match the load.
8984 unsigned VLDLaneNo =
8985 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8986 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8988 // Ignore uses of the chain result.
8989 if (UI.getUse().getResNo() == NumVecs)
8992 if (User->getOpcode() != ARMISD::VDUPLANE ||
8993 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8997 // Create the vldN-dup node.
9000 for (n = 0; n < NumVecs; ++n)
9002 Tys[n] = MVT::Other;
9003 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9004 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9005 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9006 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9007 Ops, VLDMemInt->getMemoryVT(),
9008 VLDMemInt->getMemOperand());
9011 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9013 unsigned ResNo = UI.getUse().getResNo();
9014 // Ignore uses of the chain result.
9015 if (ResNo == NumVecs)
9018 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9021 // Now the vldN-lane intrinsic is dead except for its chain result.
9022 // Update uses of the chain.
9023 std::vector<SDValue> VLDDupResults;
9024 for (unsigned n = 0; n < NumVecs; ++n)
9025 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9026 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9027 DCI.CombineTo(VLD, VLDDupResults);
9032 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9033 /// ARMISD::VDUPLANE.
9034 static SDValue PerformVDUPLANECombine(SDNode *N,
9035 TargetLowering::DAGCombinerInfo &DCI) {
9036 SDValue Op = N->getOperand(0);
9038 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9039 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9040 if (CombineVLDDUP(N, DCI))
9041 return SDValue(N, 0);
9043 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9044 // redundant. Ignore bit_converts for now; element sizes are checked below.
9045 while (Op.getOpcode() == ISD::BITCAST)
9046 Op = Op.getOperand(0);
9047 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9050 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9051 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9052 // The canonical VMOV for a zero vector uses a 32-bit element size.
9053 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9055 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9057 EVT VT = N->getValueType(0);
9058 if (EltSize > VT.getVectorElementType().getSizeInBits())
9061 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9064 static SDValue PerformLOADCombine(SDNode *N,
9065 TargetLowering::DAGCombinerInfo &DCI) {
9066 EVT VT = N->getValueType(0);
9068 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9069 if (ISD::isNormalLoad(N) && VT.isVector() &&
9070 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9071 return CombineBaseUpdate(N, DCI);
9076 /// PerformSTORECombine - Target-specific dag combine xforms for
9078 static SDValue PerformSTORECombine(SDNode *N,
9079 TargetLowering::DAGCombinerInfo &DCI) {
9080 StoreSDNode *St = cast<StoreSDNode>(N);
9081 if (St->isVolatile())
9084 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9085 // pack all of the elements in one place. Next, store to memory in fewer
9087 SDValue StVal = St->getValue();
9088 EVT VT = StVal.getValueType();
9089 if (St->isTruncatingStore() && VT.isVector()) {
9090 SelectionDAG &DAG = DCI.DAG;
9091 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9092 EVT StVT = St->getMemoryVT();
9093 unsigned NumElems = VT.getVectorNumElements();
9094 assert(StVT != VT && "Cannot truncate to the same type");
9095 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9096 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9098 // From, To sizes and ElemCount must be pow of two
9099 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9101 // We are going to use the original vector elt for storing.
9102 // Accumulated smaller vector elements must be a multiple of the store size.
9103 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9105 unsigned SizeRatio = FromEltSz / ToEltSz;
9106 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9108 // Create a type on which we perform the shuffle.
9109 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9110 NumElems*SizeRatio);
9111 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9114 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9115 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9116 for (unsigned i = 0; i < NumElems; ++i)
9117 ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9119 // Can't shuffle using an illegal type.
9120 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9122 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9123 DAG.getUNDEF(WideVec.getValueType()),
9125 // At this point all of the data is stored at the bottom of the
9126 // register. We now need to save it to mem.
9128 // Find the largest store unit
9129 MVT StoreType = MVT::i8;
9130 for (MVT Tp : MVT::integer_valuetypes()) {
9131 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9134 // Didn't find a legal store type.
9135 if (!TLI.isTypeLegal(StoreType))
9138 // Bitcast the original vector into a vector of store-size units
9139 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9140 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9141 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9142 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9143 SmallVector<SDValue, 8> Chains;
9144 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9145 TLI.getPointerTy());
9146 SDValue BasePtr = St->getBasePtr();
9148 // Perform one or more big stores into memory.
9149 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9150 for (unsigned I = 0; I < E; I++) {
9151 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9152 StoreType, ShuffWide,
9153 DAG.getIntPtrConstant(I));
9154 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9155 St->getPointerInfo(), St->isVolatile(),
9156 St->isNonTemporal(), St->getAlignment());
9157 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9159 Chains.push_back(Ch);
9161 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9164 if (!ISD::isNormalStore(St))
9167 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9168 // ARM stores of arguments in the same cache line.
9169 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9170 StVal.getNode()->hasOneUse()) {
9171 SelectionDAG &DAG = DCI.DAG;
9172 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9174 SDValue BasePtr = St->getBasePtr();
9175 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9176 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9177 BasePtr, St->getPointerInfo(), St->isVolatile(),
9178 St->isNonTemporal(), St->getAlignment());
9180 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9181 DAG.getConstant(4, MVT::i32));
9182 return DAG.getStore(NewST1.getValue(0), DL,
9183 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9184 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9185 St->isNonTemporal(),
9186 std::min(4U, St->getAlignment() / 2));
9189 if (StVal.getValueType() == MVT::i64 &&
9190 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9192 // Bitcast an i64 store extracted from a vector to f64.
9193 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9194 SelectionDAG &DAG = DCI.DAG;
9196 SDValue IntVec = StVal.getOperand(0);
9197 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9198 IntVec.getValueType().getVectorNumElements());
9199 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9200 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9201 Vec, StVal.getOperand(1));
9203 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9204 // Make the DAGCombiner fold the bitcasts.
9205 DCI.AddToWorklist(Vec.getNode());
9206 DCI.AddToWorklist(ExtElt.getNode());
9207 DCI.AddToWorklist(V.getNode());
9208 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9209 St->getPointerInfo(), St->isVolatile(),
9210 St->isNonTemporal(), St->getAlignment(),
9214 // If this is a legal vector store, try to combine it into a VST1_UPD.
9215 if (ISD::isNormalStore(N) && VT.isVector() &&
9216 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9217 return CombineBaseUpdate(N, DCI);
9222 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9223 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9224 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9228 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9230 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9235 APFloat APF = C->getValueAPF();
9236 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9237 != APFloat::opOK || !isExact)
9240 c0 = (I == 0) ? cN : c0;
9241 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9248 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9249 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9250 /// when the VMUL has a constant operand that is a power of 2.
9252 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9253 /// vmul.f32 d16, d17, d16
9254 /// vcvt.s32.f32 d16, d16
9256 /// vcvt.s32.f32 d16, d16, #3
9257 static SDValue PerformVCVTCombine(SDNode *N,
9258 TargetLowering::DAGCombinerInfo &DCI,
9259 const ARMSubtarget *Subtarget) {
9260 SelectionDAG &DAG = DCI.DAG;
9261 SDValue Op = N->getOperand(0);
9263 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9264 Op.getOpcode() != ISD::FMUL)
9268 SDValue N0 = Op->getOperand(0);
9269 SDValue ConstVec = Op->getOperand(1);
9270 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9272 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9273 !isConstVecPow2(ConstVec, isSigned, C))
9276 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9277 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9278 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9279 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9281 // These instructions only exist converting from f32 to i32. We can handle
9282 // smaller integers by generating an extra truncate, but larger ones would
9283 // be lossy. We also can't handle more then 4 lanes, since these intructions
9284 // only support v2i32/v4i32 types.
9288 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9289 Intrinsic::arm_neon_vcvtfp2fxu;
9290 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9291 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9292 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9293 DAG.getConstant(Log2_64(C), MVT::i32));
9295 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9296 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9301 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9302 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9303 /// when the VDIV has a constant operand that is a power of 2.
9305 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9306 /// vcvt.f32.s32 d16, d16
9307 /// vdiv.f32 d16, d17, d16
9309 /// vcvt.f32.s32 d16, d16, #3
9310 static SDValue PerformVDIVCombine(SDNode *N,
9311 TargetLowering::DAGCombinerInfo &DCI,
9312 const ARMSubtarget *Subtarget) {
9313 SelectionDAG &DAG = DCI.DAG;
9314 SDValue Op = N->getOperand(0);
9315 unsigned OpOpcode = Op.getNode()->getOpcode();
9317 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9318 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9322 SDValue ConstVec = N->getOperand(1);
9323 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9325 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9326 !isConstVecPow2(ConstVec, isSigned, C))
9329 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9330 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9331 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9332 // These instructions only exist converting from i32 to f32. We can handle
9333 // smaller integers by generating an extra extend, but larger ones would
9338 SDValue ConvInput = Op.getOperand(0);
9339 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9340 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9341 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9342 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9345 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9346 Intrinsic::arm_neon_vcvtfxu2fp;
9347 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9349 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9350 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9353 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9354 /// operand of a vector shift operation, where all the elements of the
9355 /// build_vector must have the same constant integer value.
9356 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9357 // Ignore bit_converts.
9358 while (Op.getOpcode() == ISD::BITCAST)
9359 Op = Op.getOperand(0);
9360 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9361 APInt SplatBits, SplatUndef;
9362 unsigned SplatBitSize;
9364 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9365 HasAnyUndefs, ElementBits) ||
9366 SplatBitSize > ElementBits)
9368 Cnt = SplatBits.getSExtValue();
9372 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9373 /// operand of a vector shift left operation. That value must be in the range:
9374 /// 0 <= Value < ElementBits for a left shift; or
9375 /// 0 <= Value <= ElementBits for a long left shift.
9376 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9377 assert(VT.isVector() && "vector shift count is not a vector type");
9378 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9379 if (! getVShiftImm(Op, ElementBits, Cnt))
9381 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9384 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9385 /// operand of a vector shift right operation. For a shift opcode, the value
9386 /// is positive, but for an intrinsic the value count must be negative. The
9387 /// absolute value must be in the range:
9388 /// 1 <= |Value| <= ElementBits for a right shift; or
9389 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9390 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9392 assert(VT.isVector() && "vector shift count is not a vector type");
9393 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9394 if (! getVShiftImm(Op, ElementBits, Cnt))
9398 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9401 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9402 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9403 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9406 // Don't do anything for most intrinsics.
9409 // Vector shifts: check for immediate versions and lower them.
9410 // Note: This is done during DAG combining instead of DAG legalizing because
9411 // the build_vectors for 64-bit vector element shift counts are generally
9412 // not legal, and it is hard to see their values after they get legalized to
9413 // loads from a constant pool.
9414 case Intrinsic::arm_neon_vshifts:
9415 case Intrinsic::arm_neon_vshiftu:
9416 case Intrinsic::arm_neon_vrshifts:
9417 case Intrinsic::arm_neon_vrshiftu:
9418 case Intrinsic::arm_neon_vrshiftn:
9419 case Intrinsic::arm_neon_vqshifts:
9420 case Intrinsic::arm_neon_vqshiftu:
9421 case Intrinsic::arm_neon_vqshiftsu:
9422 case Intrinsic::arm_neon_vqshiftns:
9423 case Intrinsic::arm_neon_vqshiftnu:
9424 case Intrinsic::arm_neon_vqshiftnsu:
9425 case Intrinsic::arm_neon_vqrshiftns:
9426 case Intrinsic::arm_neon_vqrshiftnu:
9427 case Intrinsic::arm_neon_vqrshiftnsu: {
9428 EVT VT = N->getOperand(1).getValueType();
9430 unsigned VShiftOpc = 0;
9433 case Intrinsic::arm_neon_vshifts:
9434 case Intrinsic::arm_neon_vshiftu:
9435 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9436 VShiftOpc = ARMISD::VSHL;
9439 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9440 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9441 ARMISD::VSHRs : ARMISD::VSHRu);
9446 case Intrinsic::arm_neon_vrshifts:
9447 case Intrinsic::arm_neon_vrshiftu:
9448 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9452 case Intrinsic::arm_neon_vqshifts:
9453 case Intrinsic::arm_neon_vqshiftu:
9454 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9458 case Intrinsic::arm_neon_vqshiftsu:
9459 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9461 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9463 case Intrinsic::arm_neon_vrshiftn:
9464 case Intrinsic::arm_neon_vqshiftns:
9465 case Intrinsic::arm_neon_vqshiftnu:
9466 case Intrinsic::arm_neon_vqshiftnsu:
9467 case Intrinsic::arm_neon_vqrshiftns:
9468 case Intrinsic::arm_neon_vqrshiftnu:
9469 case Intrinsic::arm_neon_vqrshiftnsu:
9470 // Narrowing shifts require an immediate right shift.
9471 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9473 llvm_unreachable("invalid shift count for narrowing vector shift "
9477 llvm_unreachable("unhandled vector shift");
9481 case Intrinsic::arm_neon_vshifts:
9482 case Intrinsic::arm_neon_vshiftu:
9483 // Opcode already set above.
9485 case Intrinsic::arm_neon_vrshifts:
9486 VShiftOpc = ARMISD::VRSHRs; break;
9487 case Intrinsic::arm_neon_vrshiftu:
9488 VShiftOpc = ARMISD::VRSHRu; break;
9489 case Intrinsic::arm_neon_vrshiftn:
9490 VShiftOpc = ARMISD::VRSHRN; break;
9491 case Intrinsic::arm_neon_vqshifts:
9492 VShiftOpc = ARMISD::VQSHLs; break;
9493 case Intrinsic::arm_neon_vqshiftu:
9494 VShiftOpc = ARMISD::VQSHLu; break;
9495 case Intrinsic::arm_neon_vqshiftsu:
9496 VShiftOpc = ARMISD::VQSHLsu; break;
9497 case Intrinsic::arm_neon_vqshiftns:
9498 VShiftOpc = ARMISD::VQSHRNs; break;
9499 case Intrinsic::arm_neon_vqshiftnu:
9500 VShiftOpc = ARMISD::VQSHRNu; break;
9501 case Intrinsic::arm_neon_vqshiftnsu:
9502 VShiftOpc = ARMISD::VQSHRNsu; break;
9503 case Intrinsic::arm_neon_vqrshiftns:
9504 VShiftOpc = ARMISD::VQRSHRNs; break;
9505 case Intrinsic::arm_neon_vqrshiftnu:
9506 VShiftOpc = ARMISD::VQRSHRNu; break;
9507 case Intrinsic::arm_neon_vqrshiftnsu:
9508 VShiftOpc = ARMISD::VQRSHRNsu; break;
9511 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9512 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9515 case Intrinsic::arm_neon_vshiftins: {
9516 EVT VT = N->getOperand(1).getValueType();
9518 unsigned VShiftOpc = 0;
9520 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9521 VShiftOpc = ARMISD::VSLI;
9522 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9523 VShiftOpc = ARMISD::VSRI;
9525 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9528 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9529 N->getOperand(1), N->getOperand(2),
9530 DAG.getConstant(Cnt, MVT::i32));
9533 case Intrinsic::arm_neon_vqrshifts:
9534 case Intrinsic::arm_neon_vqrshiftu:
9535 // No immediate versions of these to check for.
9542 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9543 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9544 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9545 /// vector element shift counts are generally not legal, and it is hard to see
9546 /// their values after they get legalized to loads from a constant pool.
9547 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9548 const ARMSubtarget *ST) {
9549 EVT VT = N->getValueType(0);
9550 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9551 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9552 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9553 SDValue N1 = N->getOperand(1);
9554 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9555 SDValue N0 = N->getOperand(0);
9556 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9557 DAG.MaskedValueIsZero(N0.getOperand(0),
9558 APInt::getHighBitsSet(32, 16)))
9559 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9563 // Nothing to be done for scalar shifts.
9564 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9565 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9568 assert(ST->hasNEON() && "unexpected vector shift");
9571 switch (N->getOpcode()) {
9572 default: llvm_unreachable("unexpected shift opcode");
9575 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9576 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9577 DAG.getConstant(Cnt, MVT::i32));
9582 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9583 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9584 ARMISD::VSHRs : ARMISD::VSHRu);
9585 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9586 DAG.getConstant(Cnt, MVT::i32));
9592 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9593 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9594 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9595 const ARMSubtarget *ST) {
9596 SDValue N0 = N->getOperand(0);
9598 // Check for sign- and zero-extensions of vector extract operations of 8-
9599 // and 16-bit vector elements. NEON supports these directly. They are
9600 // handled during DAG combining because type legalization will promote them
9601 // to 32-bit types and it is messy to recognize the operations after that.
9602 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9603 SDValue Vec = N0.getOperand(0);
9604 SDValue Lane = N0.getOperand(1);
9605 EVT VT = N->getValueType(0);
9606 EVT EltVT = N0.getValueType();
9607 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9609 if (VT == MVT::i32 &&
9610 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9611 TLI.isTypeLegal(Vec.getValueType()) &&
9612 isa<ConstantSDNode>(Lane)) {
9615 switch (N->getOpcode()) {
9616 default: llvm_unreachable("unexpected opcode");
9617 case ISD::SIGN_EXTEND:
9618 Opc = ARMISD::VGETLANEs;
9620 case ISD::ZERO_EXTEND:
9621 case ISD::ANY_EXTEND:
9622 Opc = ARMISD::VGETLANEu;
9625 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9632 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9633 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9634 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9635 const ARMSubtarget *ST) {
9636 // If the target supports NEON, try to use vmax/vmin instructions for f32
9637 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9638 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9639 // a NaN; only do the transformation when it matches that behavior.
9641 // For now only do this when using NEON for FP operations; if using VFP, it
9642 // is not obvious that the benefit outweighs the cost of switching to the
9644 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9645 N->getValueType(0) != MVT::f32)
9648 SDValue CondLHS = N->getOperand(0);
9649 SDValue CondRHS = N->getOperand(1);
9650 SDValue LHS = N->getOperand(2);
9651 SDValue RHS = N->getOperand(3);
9652 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9654 unsigned Opcode = 0;
9656 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9657 IsReversed = false; // x CC y ? x : y
9658 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9659 IsReversed = true ; // x CC y ? y : x
9673 // If LHS is NaN, an ordered comparison will be false and the result will
9674 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9675 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9676 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9677 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9679 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9680 // will return -0, so vmin can only be used for unsafe math or if one of
9681 // the operands is known to be nonzero.
9682 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9683 !DAG.getTarget().Options.UnsafeFPMath &&
9684 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9686 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9695 // If LHS is NaN, an ordered comparison will be false and the result will
9696 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9697 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9698 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9699 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9701 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9702 // will return +0, so vmax can only be used for unsafe math or if one of
9703 // the operands is known to be nonzero.
9704 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9705 !DAG.getTarget().Options.UnsafeFPMath &&
9706 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9708 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9714 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9717 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9719 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9720 SDValue Cmp = N->getOperand(4);
9721 if (Cmp.getOpcode() != ARMISD::CMPZ)
9722 // Only looking at EQ and NE cases.
9725 EVT VT = N->getValueType(0);
9727 SDValue LHS = Cmp.getOperand(0);
9728 SDValue RHS = Cmp.getOperand(1);
9729 SDValue FalseVal = N->getOperand(0);
9730 SDValue TrueVal = N->getOperand(1);
9731 SDValue ARMcc = N->getOperand(2);
9732 ARMCC::CondCodes CC =
9733 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9751 /// FIXME: Turn this into a target neutral optimization?
9753 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9754 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9755 N->getOperand(3), Cmp);
9756 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9758 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9759 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9760 N->getOperand(3), NewCmp);
9763 if (Res.getNode()) {
9764 APInt KnownZero, KnownOne;
9765 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9766 // Capture demanded bits information that would be otherwise lost.
9767 if (KnownZero == 0xfffffffe)
9768 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9769 DAG.getValueType(MVT::i1));
9770 else if (KnownZero == 0xffffff00)
9771 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9772 DAG.getValueType(MVT::i8));
9773 else if (KnownZero == 0xffff0000)
9774 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9775 DAG.getValueType(MVT::i16));
9781 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9782 DAGCombinerInfo &DCI) const {
9783 switch (N->getOpcode()) {
9785 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9786 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9787 case ISD::SUB: return PerformSUBCombine(N, DCI);
9788 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9789 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9790 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9791 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9792 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9793 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9794 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9795 case ISD::STORE: return PerformSTORECombine(N, DCI);
9796 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9797 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9798 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9799 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9800 case ISD::FP_TO_SINT:
9801 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9802 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9803 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9806 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9807 case ISD::SIGN_EXTEND:
9808 case ISD::ZERO_EXTEND:
9809 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9810 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9811 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9812 case ISD::LOAD: return PerformLOADCombine(N, DCI);
9813 case ARMISD::VLD2DUP:
9814 case ARMISD::VLD3DUP:
9815 case ARMISD::VLD4DUP:
9816 return PerformVLDCombine(N, DCI);
9817 case ARMISD::BUILD_VECTOR:
9818 return PerformARMBUILD_VECTORCombine(N, DCI);
9819 case ISD::INTRINSIC_VOID:
9820 case ISD::INTRINSIC_W_CHAIN:
9821 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9822 case Intrinsic::arm_neon_vld1:
9823 case Intrinsic::arm_neon_vld2:
9824 case Intrinsic::arm_neon_vld3:
9825 case Intrinsic::arm_neon_vld4:
9826 case Intrinsic::arm_neon_vld2lane:
9827 case Intrinsic::arm_neon_vld3lane:
9828 case Intrinsic::arm_neon_vld4lane:
9829 case Intrinsic::arm_neon_vst1:
9830 case Intrinsic::arm_neon_vst2:
9831 case Intrinsic::arm_neon_vst3:
9832 case Intrinsic::arm_neon_vst4:
9833 case Intrinsic::arm_neon_vst2lane:
9834 case Intrinsic::arm_neon_vst3lane:
9835 case Intrinsic::arm_neon_vst4lane:
9836 return PerformVLDCombine(N, DCI);
9844 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9846 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9849 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9853 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9854 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9856 switch (VT.getSimpleVT().SimpleTy) {
9862 // Unaligned access can use (for example) LRDB, LRDH, LDR
9863 if (AllowsUnaligned) {
9865 *Fast = Subtarget->hasV7Ops();
9872 // For any little-endian targets with neon, we can support unaligned ld/st
9873 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9874 // A big-endian target may also explicitly support unaligned accesses
9875 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9885 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9886 unsigned AlignCheck) {
9887 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9888 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9891 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9892 unsigned DstAlign, unsigned SrcAlign,
9893 bool IsMemset, bool ZeroMemset,
9895 MachineFunction &MF) const {
9896 const Function *F = MF.getFunction();
9898 // See if we can use NEON instructions for this...
9899 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
9900 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
9903 (memOpAlign(SrcAlign, DstAlign, 16) ||
9904 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9906 } else if (Size >= 8 &&
9907 (memOpAlign(SrcAlign, DstAlign, 8) ||
9908 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9914 // Lowering to i32/i16 if the size permits.
9920 // Let the target-independent logic figure it out.
9924 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9925 if (Val.getOpcode() != ISD::LOAD)
9928 EVT VT1 = Val.getValueType();
9929 if (!VT1.isSimple() || !VT1.isInteger() ||
9930 !VT2.isSimple() || !VT2.isInteger())
9933 switch (VT1.getSimpleVT().SimpleTy) {
9938 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9945 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
9946 EVT VT = ExtVal.getValueType();
9948 if (!isTypeLegal(VT))
9951 // Don't create a loadext if we can fold the extension into a wide/long
9953 // If there's more than one user instruction, the loadext is desirable no
9954 // matter what. There can be two uses by the same instruction.
9955 if (ExtVal->use_empty() ||
9956 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
9959 SDNode *U = *ExtVal->use_begin();
9960 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
9961 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
9967 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9968 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9971 if (!isTypeLegal(EVT::getEVT(Ty1)))
9974 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9976 // Assuming the caller doesn't have a zeroext or signext return parameter,
9977 // truncation all the way down to i1 is valid.
9982 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9987 switch (VT.getSimpleVT().SimpleTy) {
9988 default: return false;
10003 if ((V & (Scale - 1)) != 0)
10006 return V == (V & ((1LL << 5) - 1));
10009 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10010 const ARMSubtarget *Subtarget) {
10011 bool isNeg = false;
10017 switch (VT.getSimpleVT().SimpleTy) {
10018 default: return false;
10023 // + imm12 or - imm8
10025 return V == (V & ((1LL << 8) - 1));
10026 return V == (V & ((1LL << 12) - 1));
10029 // Same as ARM mode. FIXME: NEON?
10030 if (!Subtarget->hasVFP2())
10035 return V == (V & ((1LL << 8) - 1));
10039 /// isLegalAddressImmediate - Return true if the integer value can be used
10040 /// as the offset of the target addressing mode for load / store of the
10042 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10043 const ARMSubtarget *Subtarget) {
10047 if (!VT.isSimple())
10050 if (Subtarget->isThumb1Only())
10051 return isLegalT1AddressImmediate(V, VT);
10052 else if (Subtarget->isThumb2())
10053 return isLegalT2AddressImmediate(V, VT, Subtarget);
10058 switch (VT.getSimpleVT().SimpleTy) {
10059 default: return false;
10064 return V == (V & ((1LL << 12) - 1));
10067 return V == (V & ((1LL << 8) - 1));
10070 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10075 return V == (V & ((1LL << 8) - 1));
10079 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10081 int Scale = AM.Scale;
10085 switch (VT.getSimpleVT().SimpleTy) {
10086 default: return false;
10094 Scale = Scale & ~1;
10095 return Scale == 2 || Scale == 4 || Scale == 8;
10098 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10102 // Note, we allow "void" uses (basically, uses that aren't loads or
10103 // stores), because arm allows folding a scale into many arithmetic
10104 // operations. This should be made more precise and revisited later.
10106 // Allow r << imm, but the imm has to be a multiple of two.
10107 if (Scale & 1) return false;
10108 return isPowerOf2_32(Scale);
10112 /// isLegalAddressingMode - Return true if the addressing mode represented
10113 /// by AM is legal for this target, for a load/store of the specified type.
10114 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10116 EVT VT = getValueType(Ty, true);
10117 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10120 // Can never fold addr of global into load/store.
10124 switch (AM.Scale) {
10125 case 0: // no scale reg, must be "r+i" or "r", or "i".
10128 if (Subtarget->isThumb1Only())
10132 // ARM doesn't support any R+R*scale+imm addr modes.
10136 if (!VT.isSimple())
10139 if (Subtarget->isThumb2())
10140 return isLegalT2ScaledAddressingMode(AM, VT);
10142 int Scale = AM.Scale;
10143 switch (VT.getSimpleVT().SimpleTy) {
10144 default: return false;
10148 if (Scale < 0) Scale = -Scale;
10152 return isPowerOf2_32(Scale & ~1);
10156 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10161 // Note, we allow "void" uses (basically, uses that aren't loads or
10162 // stores), because arm allows folding a scale into many arithmetic
10163 // operations. This should be made more precise and revisited later.
10165 // Allow r << imm, but the imm has to be a multiple of two.
10166 if (Scale & 1) return false;
10167 return isPowerOf2_32(Scale);
10173 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10174 /// icmp immediate, that is the target has icmp instructions which can compare
10175 /// a register against the immediate without having to materialize the
10176 /// immediate into a register.
10177 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10178 // Thumb2 and ARM modes can use cmn for negative immediates.
10179 if (!Subtarget->isThumb())
10180 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10181 if (Subtarget->isThumb2())
10182 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10183 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10184 return Imm >= 0 && Imm <= 255;
10187 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10188 /// *or sub* immediate, that is the target has add or sub instructions which can
10189 /// add a register with the immediate without having to materialize the
10190 /// immediate into a register.
10191 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10192 // Same encoding for add/sub, just flip the sign.
10193 int64_t AbsImm = std::abs(Imm);
10194 if (!Subtarget->isThumb())
10195 return ARM_AM::getSOImmVal(AbsImm) != -1;
10196 if (Subtarget->isThumb2())
10197 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10198 // Thumb1 only has 8-bit unsigned immediate.
10199 return AbsImm >= 0 && AbsImm <= 255;
10202 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10203 bool isSEXTLoad, SDValue &Base,
10204 SDValue &Offset, bool &isInc,
10205 SelectionDAG &DAG) {
10206 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10209 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10210 // AddressingMode 3
10211 Base = Ptr->getOperand(0);
10212 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10213 int RHSC = (int)RHS->getZExtValue();
10214 if (RHSC < 0 && RHSC > -256) {
10215 assert(Ptr->getOpcode() == ISD::ADD);
10217 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10221 isInc = (Ptr->getOpcode() == ISD::ADD);
10222 Offset = Ptr->getOperand(1);
10224 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10225 // AddressingMode 2
10226 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10227 int RHSC = (int)RHS->getZExtValue();
10228 if (RHSC < 0 && RHSC > -0x1000) {
10229 assert(Ptr->getOpcode() == ISD::ADD);
10231 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10232 Base = Ptr->getOperand(0);
10237 if (Ptr->getOpcode() == ISD::ADD) {
10239 ARM_AM::ShiftOpc ShOpcVal=
10240 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10241 if (ShOpcVal != ARM_AM::no_shift) {
10242 Base = Ptr->getOperand(1);
10243 Offset = Ptr->getOperand(0);
10245 Base = Ptr->getOperand(0);
10246 Offset = Ptr->getOperand(1);
10251 isInc = (Ptr->getOpcode() == ISD::ADD);
10252 Base = Ptr->getOperand(0);
10253 Offset = Ptr->getOperand(1);
10257 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10261 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10262 bool isSEXTLoad, SDValue &Base,
10263 SDValue &Offset, bool &isInc,
10264 SelectionDAG &DAG) {
10265 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10268 Base = Ptr->getOperand(0);
10269 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10270 int RHSC = (int)RHS->getZExtValue();
10271 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10272 assert(Ptr->getOpcode() == ISD::ADD);
10274 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10276 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10277 isInc = Ptr->getOpcode() == ISD::ADD;
10278 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10286 /// getPreIndexedAddressParts - returns true by value, base pointer and
10287 /// offset pointer and addressing mode by reference if the node's address
10288 /// can be legally represented as pre-indexed load / store address.
10290 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10292 ISD::MemIndexedMode &AM,
10293 SelectionDAG &DAG) const {
10294 if (Subtarget->isThumb1Only())
10299 bool isSEXTLoad = false;
10300 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10301 Ptr = LD->getBasePtr();
10302 VT = LD->getMemoryVT();
10303 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10304 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10305 Ptr = ST->getBasePtr();
10306 VT = ST->getMemoryVT();
10311 bool isLegal = false;
10312 if (Subtarget->isThumb2())
10313 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10314 Offset, isInc, DAG);
10316 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10317 Offset, isInc, DAG);
10321 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10325 /// getPostIndexedAddressParts - returns true by value, base pointer and
10326 /// offset pointer and addressing mode by reference if this node can be
10327 /// combined with a load / store to form a post-indexed load / store.
10328 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10331 ISD::MemIndexedMode &AM,
10332 SelectionDAG &DAG) const {
10333 if (Subtarget->isThumb1Only())
10338 bool isSEXTLoad = false;
10339 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10340 VT = LD->getMemoryVT();
10341 Ptr = LD->getBasePtr();
10342 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10343 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10344 VT = ST->getMemoryVT();
10345 Ptr = ST->getBasePtr();
10350 bool isLegal = false;
10351 if (Subtarget->isThumb2())
10352 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10355 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10361 // Swap base ptr and offset to catch more post-index load / store when
10362 // it's legal. In Thumb2 mode, offset must be an immediate.
10363 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10364 !Subtarget->isThumb2())
10365 std::swap(Base, Offset);
10367 // Post-indexed load / store update the base pointer.
10372 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10376 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10379 const SelectionDAG &DAG,
10380 unsigned Depth) const {
10381 unsigned BitWidth = KnownOne.getBitWidth();
10382 KnownZero = KnownOne = APInt(BitWidth, 0);
10383 switch (Op.getOpcode()) {
10389 // These nodes' second result is a boolean
10390 if (Op.getResNo() == 0)
10392 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10394 case ARMISD::CMOV: {
10395 // Bits are known zero/one if known on the LHS and RHS.
10396 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10397 if (KnownZero == 0 && KnownOne == 0) return;
10399 APInt KnownZeroRHS, KnownOneRHS;
10400 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10401 KnownZero &= KnownZeroRHS;
10402 KnownOne &= KnownOneRHS;
10405 case ISD::INTRINSIC_W_CHAIN: {
10406 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10407 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10410 case Intrinsic::arm_ldaex:
10411 case Intrinsic::arm_ldrex: {
10412 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10413 unsigned MemBits = VT.getScalarType().getSizeInBits();
10414 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10422 //===----------------------------------------------------------------------===//
10423 // ARM Inline Assembly Support
10424 //===----------------------------------------------------------------------===//
10426 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10427 // Looking for "rev" which is V6+.
10428 if (!Subtarget->hasV6Ops())
10431 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10432 std::string AsmStr = IA->getAsmString();
10433 SmallVector<StringRef, 4> AsmPieces;
10434 SplitString(AsmStr, AsmPieces, ";\n");
10436 switch (AsmPieces.size()) {
10437 default: return false;
10439 AsmStr = AsmPieces[0];
10441 SplitString(AsmStr, AsmPieces, " \t,");
10444 if (AsmPieces.size() == 3 &&
10445 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10446 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10447 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10448 if (Ty && Ty->getBitWidth() == 32)
10449 return IntrinsicLowering::LowerToByteSwap(CI);
10457 /// getConstraintType - Given a constraint letter, return the type of
10458 /// constraint it is for this target.
10459 ARMTargetLowering::ConstraintType
10460 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10461 if (Constraint.size() == 1) {
10462 switch (Constraint[0]) {
10464 case 'l': return C_RegisterClass;
10465 case 'w': return C_RegisterClass;
10466 case 'h': return C_RegisterClass;
10467 case 'x': return C_RegisterClass;
10468 case 't': return C_RegisterClass;
10469 case 'j': return C_Other; // Constant for movw.
10470 // An address with a single base register. Due to the way we
10471 // currently handle addresses it is the same as an 'r' memory constraint.
10472 case 'Q': return C_Memory;
10474 } else if (Constraint.size() == 2) {
10475 switch (Constraint[0]) {
10477 // All 'U+' constraints are addresses.
10478 case 'U': return C_Memory;
10481 return TargetLowering::getConstraintType(Constraint);
10484 /// Examine constraint type and operand type and determine a weight value.
10485 /// This object must already have been set up with the operand type
10486 /// and the current alternative constraint selected.
10487 TargetLowering::ConstraintWeight
10488 ARMTargetLowering::getSingleConstraintMatchWeight(
10489 AsmOperandInfo &info, const char *constraint) const {
10490 ConstraintWeight weight = CW_Invalid;
10491 Value *CallOperandVal = info.CallOperandVal;
10492 // If we don't have a value, we can't do a match,
10493 // but allow it at the lowest weight.
10494 if (!CallOperandVal)
10496 Type *type = CallOperandVal->getType();
10497 // Look at the constraint type.
10498 switch (*constraint) {
10500 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10503 if (type->isIntegerTy()) {
10504 if (Subtarget->isThumb())
10505 weight = CW_SpecificReg;
10507 weight = CW_Register;
10511 if (type->isFloatingPointTy())
10512 weight = CW_Register;
10518 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10520 ARMTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10521 const std::string &Constraint,
10523 if (Constraint.size() == 1) {
10524 // GCC ARM Constraint Letters
10525 switch (Constraint[0]) {
10526 case 'l': // Low regs or general regs.
10527 if (Subtarget->isThumb())
10528 return RCPair(0U, &ARM::tGPRRegClass);
10529 return RCPair(0U, &ARM::GPRRegClass);
10530 case 'h': // High regs or no regs.
10531 if (Subtarget->isThumb())
10532 return RCPair(0U, &ARM::hGPRRegClass);
10535 if (Subtarget->isThumb1Only())
10536 return RCPair(0U, &ARM::tGPRRegClass);
10537 return RCPair(0U, &ARM::GPRRegClass);
10539 if (VT == MVT::Other)
10541 if (VT == MVT::f32)
10542 return RCPair(0U, &ARM::SPRRegClass);
10543 if (VT.getSizeInBits() == 64)
10544 return RCPair(0U, &ARM::DPRRegClass);
10545 if (VT.getSizeInBits() == 128)
10546 return RCPair(0U, &ARM::QPRRegClass);
10549 if (VT == MVT::Other)
10551 if (VT == MVT::f32)
10552 return RCPair(0U, &ARM::SPR_8RegClass);
10553 if (VT.getSizeInBits() == 64)
10554 return RCPair(0U, &ARM::DPR_8RegClass);
10555 if (VT.getSizeInBits() == 128)
10556 return RCPair(0U, &ARM::QPR_8RegClass);
10559 if (VT == MVT::f32)
10560 return RCPair(0U, &ARM::SPRRegClass);
10564 if (StringRef("{cc}").equals_lower(Constraint))
10565 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10567 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10570 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10571 /// vector. If it is invalid, don't add anything to Ops.
10572 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10573 std::string &Constraint,
10574 std::vector<SDValue>&Ops,
10575 SelectionDAG &DAG) const {
10578 // Currently only support length 1 constraints.
10579 if (Constraint.length() != 1) return;
10581 char ConstraintLetter = Constraint[0];
10582 switch (ConstraintLetter) {
10585 case 'I': case 'J': case 'K': case 'L':
10586 case 'M': case 'N': case 'O':
10587 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10591 int64_t CVal64 = C->getSExtValue();
10592 int CVal = (int) CVal64;
10593 // None of these constraints allow values larger than 32 bits. Check
10594 // that the value fits in an int.
10595 if (CVal != CVal64)
10598 switch (ConstraintLetter) {
10600 // Constant suitable for movw, must be between 0 and
10602 if (Subtarget->hasV6T2Ops())
10603 if (CVal >= 0 && CVal <= 65535)
10607 if (Subtarget->isThumb1Only()) {
10608 // This must be a constant between 0 and 255, for ADD
10610 if (CVal >= 0 && CVal <= 255)
10612 } else if (Subtarget->isThumb2()) {
10613 // A constant that can be used as an immediate value in a
10614 // data-processing instruction.
10615 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10618 // A constant that can be used as an immediate value in a
10619 // data-processing instruction.
10620 if (ARM_AM::getSOImmVal(CVal) != -1)
10626 if (Subtarget->isThumb()) { // FIXME thumb2
10627 // This must be a constant between -255 and -1, for negated ADD
10628 // immediates. This can be used in GCC with an "n" modifier that
10629 // prints the negated value, for use with SUB instructions. It is
10630 // not useful otherwise but is implemented for compatibility.
10631 if (CVal >= -255 && CVal <= -1)
10634 // This must be a constant between -4095 and 4095. It is not clear
10635 // what this constraint is intended for. Implemented for
10636 // compatibility with GCC.
10637 if (CVal >= -4095 && CVal <= 4095)
10643 if (Subtarget->isThumb1Only()) {
10644 // A 32-bit value where only one byte has a nonzero value. Exclude
10645 // zero to match GCC. This constraint is used by GCC internally for
10646 // constants that can be loaded with a move/shift combination.
10647 // It is not useful otherwise but is implemented for compatibility.
10648 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10650 } else if (Subtarget->isThumb2()) {
10651 // A constant whose bitwise inverse can be used as an immediate
10652 // value in a data-processing instruction. This can be used in GCC
10653 // with a "B" modifier that prints the inverted value, for use with
10654 // BIC and MVN instructions. It is not useful otherwise but is
10655 // implemented for compatibility.
10656 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10659 // A constant whose bitwise inverse can be used as an immediate
10660 // value in a data-processing instruction. This can be used in GCC
10661 // with a "B" modifier that prints the inverted value, for use with
10662 // BIC and MVN instructions. It is not useful otherwise but is
10663 // implemented for compatibility.
10664 if (ARM_AM::getSOImmVal(~CVal) != -1)
10670 if (Subtarget->isThumb1Only()) {
10671 // This must be a constant between -7 and 7,
10672 // for 3-operand ADD/SUB immediate instructions.
10673 if (CVal >= -7 && CVal < 7)
10675 } else if (Subtarget->isThumb2()) {
10676 // A constant whose negation can be used as an immediate value in a
10677 // data-processing instruction. This can be used in GCC with an "n"
10678 // modifier that prints the negated value, for use with SUB
10679 // instructions. It is not useful otherwise but is implemented for
10681 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10684 // A constant whose negation can be used as an immediate value in a
10685 // data-processing instruction. This can be used in GCC with an "n"
10686 // modifier that prints the negated value, for use with SUB
10687 // instructions. It is not useful otherwise but is implemented for
10689 if (ARM_AM::getSOImmVal(-CVal) != -1)
10695 if (Subtarget->isThumb()) { // FIXME thumb2
10696 // This must be a multiple of 4 between 0 and 1020, for
10697 // ADD sp + immediate.
10698 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10701 // A power of two or a constant between 0 and 32. This is used in
10702 // GCC for the shift amount on shifted register operands, but it is
10703 // useful in general for any shift amounts.
10704 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10710 if (Subtarget->isThumb()) { // FIXME thumb2
10711 // This must be a constant between 0 and 31, for shift amounts.
10712 if (CVal >= 0 && CVal <= 31)
10718 if (Subtarget->isThumb()) { // FIXME thumb2
10719 // This must be a multiple of 4 between -508 and 508, for
10720 // ADD/SUB sp = sp + immediate.
10721 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10726 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10730 if (Result.getNode()) {
10731 Ops.push_back(Result);
10734 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10737 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10738 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10739 unsigned Opcode = Op->getOpcode();
10740 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10741 "Invalid opcode for Div/Rem lowering");
10742 bool isSigned = (Opcode == ISD::SDIVREM);
10743 EVT VT = Op->getValueType(0);
10744 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10747 switch (VT.getSimpleVT().SimpleTy) {
10748 default: llvm_unreachable("Unexpected request for libcall!");
10749 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10750 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10751 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10752 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10755 SDValue InChain = DAG.getEntryNode();
10757 TargetLowering::ArgListTy Args;
10758 TargetLowering::ArgListEntry Entry;
10759 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10760 EVT ArgVT = Op->getOperand(i).getValueType();
10761 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10762 Entry.Node = Op->getOperand(i);
10764 Entry.isSExt = isSigned;
10765 Entry.isZExt = !isSigned;
10766 Args.push_back(Entry);
10769 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10772 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10775 TargetLowering::CallLoweringInfo CLI(DAG);
10776 CLI.setDebugLoc(dl).setChain(InChain)
10777 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10778 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10780 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10781 return CallInfo.first;
10785 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10786 assert(Subtarget->isTargetWindows() && "unsupported target platform");
10790 SDValue Chain = Op.getOperand(0);
10791 SDValue Size = Op.getOperand(1);
10793 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10794 DAG.getConstant(2, MVT::i32));
10797 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10798 Flag = Chain.getValue(1);
10800 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10801 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10803 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10804 Chain = NewSP.getValue(1);
10806 SDValue Ops[2] = { NewSP, Chain };
10807 return DAG.getMergeValues(Ops, DL);
10810 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10811 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10812 "Unexpected type for custom-lowering FP_EXTEND");
10815 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10817 SDValue SrcVal = Op.getOperand(0);
10818 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10819 /*isSigned*/ false, SDLoc(Op)).first;
10822 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10823 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10824 Subtarget->isFPOnlySP() &&
10825 "Unexpected type for custom-lowering FP_ROUND");
10828 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10830 SDValue SrcVal = Op.getOperand(0);
10831 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10832 /*isSigned*/ false, SDLoc(Op)).first;
10836 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10837 // The ARM target isn't yet aware of offsets.
10841 bool ARM::isBitFieldInvertedMask(unsigned v) {
10842 if (v == 0xffffffff)
10845 // there can be 1's on either or both "outsides", all the "inside"
10846 // bits must be 0's
10847 return isShiftedMask_32(~v);
10850 /// isFPImmLegal - Returns true if the target can instruction select the
10851 /// specified FP immediate natively. If false, the legalizer will
10852 /// materialize the FP immediate as a load from a constant pool.
10853 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10854 if (!Subtarget->hasVFP3())
10856 if (VT == MVT::f32)
10857 return ARM_AM::getFP32Imm(Imm) != -1;
10858 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10859 return ARM_AM::getFP64Imm(Imm) != -1;
10863 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10864 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10865 /// specified in the intrinsic calls.
10866 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10868 unsigned Intrinsic) const {
10869 switch (Intrinsic) {
10870 case Intrinsic::arm_neon_vld1:
10871 case Intrinsic::arm_neon_vld2:
10872 case Intrinsic::arm_neon_vld3:
10873 case Intrinsic::arm_neon_vld4:
10874 case Intrinsic::arm_neon_vld2lane:
10875 case Intrinsic::arm_neon_vld3lane:
10876 case Intrinsic::arm_neon_vld4lane: {
10877 Info.opc = ISD::INTRINSIC_W_CHAIN;
10878 // Conservatively set memVT to the entire set of vectors loaded.
10879 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10880 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10881 Info.ptrVal = I.getArgOperand(0);
10883 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10884 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10885 Info.vol = false; // volatile loads with NEON intrinsics not supported
10886 Info.readMem = true;
10887 Info.writeMem = false;
10890 case Intrinsic::arm_neon_vst1:
10891 case Intrinsic::arm_neon_vst2:
10892 case Intrinsic::arm_neon_vst3:
10893 case Intrinsic::arm_neon_vst4:
10894 case Intrinsic::arm_neon_vst2lane:
10895 case Intrinsic::arm_neon_vst3lane:
10896 case Intrinsic::arm_neon_vst4lane: {
10897 Info.opc = ISD::INTRINSIC_VOID;
10898 // Conservatively set memVT to the entire set of vectors stored.
10899 unsigned NumElts = 0;
10900 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10901 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10902 if (!ArgTy->isVectorTy())
10904 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10906 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10907 Info.ptrVal = I.getArgOperand(0);
10909 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10910 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10911 Info.vol = false; // volatile stores with NEON intrinsics not supported
10912 Info.readMem = false;
10913 Info.writeMem = true;
10916 case Intrinsic::arm_ldaex:
10917 case Intrinsic::arm_ldrex: {
10918 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10919 Info.opc = ISD::INTRINSIC_W_CHAIN;
10920 Info.memVT = MVT::getVT(PtrTy->getElementType());
10921 Info.ptrVal = I.getArgOperand(0);
10923 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10925 Info.readMem = true;
10926 Info.writeMem = false;
10929 case Intrinsic::arm_stlex:
10930 case Intrinsic::arm_strex: {
10931 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10932 Info.opc = ISD::INTRINSIC_W_CHAIN;
10933 Info.memVT = MVT::getVT(PtrTy->getElementType());
10934 Info.ptrVal = I.getArgOperand(1);
10936 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10938 Info.readMem = false;
10939 Info.writeMem = true;
10942 case Intrinsic::arm_stlexd:
10943 case Intrinsic::arm_strexd: {
10944 Info.opc = ISD::INTRINSIC_W_CHAIN;
10945 Info.memVT = MVT::i64;
10946 Info.ptrVal = I.getArgOperand(2);
10950 Info.readMem = false;
10951 Info.writeMem = true;
10954 case Intrinsic::arm_ldaexd:
10955 case Intrinsic::arm_ldrexd: {
10956 Info.opc = ISD::INTRINSIC_W_CHAIN;
10957 Info.memVT = MVT::i64;
10958 Info.ptrVal = I.getArgOperand(0);
10962 Info.readMem = true;
10963 Info.writeMem = false;
10973 /// \brief Returns true if it is beneficial to convert a load of a constant
10974 /// to just the constant itself.
10975 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10977 assert(Ty->isIntegerTy());
10979 unsigned Bits = Ty->getPrimitiveSizeInBits();
10980 if (Bits == 0 || Bits > 32)
10985 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
10987 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
10988 ARM_MB::MemBOpt Domain) const {
10989 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10991 // First, if the target has no DMB, see what fallback we can use.
10992 if (!Subtarget->hasDataBarrier()) {
10993 // Some ARMv6 cpus can support data barriers with an mcr instruction.
10994 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
10996 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
10997 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
10998 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
10999 Builder.getInt32(0), Builder.getInt32(7),
11000 Builder.getInt32(10), Builder.getInt32(5)};
11001 return Builder.CreateCall(MCR, args);
11003 // Instead of using barriers, atomic accesses on these subtargets use
11005 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11008 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11009 // Only a full system barrier exists in the M-class architectures.
11010 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11011 Constant *CDomain = Builder.getInt32(Domain);
11012 return Builder.CreateCall(DMB, CDomain);
11016 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11017 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11018 AtomicOrdering Ord, bool IsStore,
11019 bool IsLoad) const {
11020 if (!getInsertFencesForAtomic())
11026 llvm_unreachable("Invalid fence: unordered/non-atomic");
11029 return nullptr; // Nothing to do
11030 case SequentiallyConsistent:
11032 return nullptr; // Nothing to do
11035 case AcquireRelease:
11036 if (Subtarget->isSwift())
11037 return makeDMB(Builder, ARM_MB::ISHST);
11038 // FIXME: add a comment with a link to documentation justifying this.
11040 return makeDMB(Builder, ARM_MB::ISH);
11042 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11045 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11046 AtomicOrdering Ord, bool IsStore,
11047 bool IsLoad) const {
11048 if (!getInsertFencesForAtomic())
11054 llvm_unreachable("Invalid fence: unordered/not-atomic");
11057 return nullptr; // Nothing to do
11059 case AcquireRelease:
11060 case SequentiallyConsistent:
11061 return makeDMB(Builder, ARM_MB::ISH);
11063 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11066 // Loads and stores less than 64-bits are already atomic; ones above that
11067 // are doomed anyway, so defer to the default libcall and blame the OS when
11068 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11069 // anything for those.
11070 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11071 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11072 return (Size == 64) && !Subtarget->isMClass();
11075 // Loads and stores less than 64-bits are already atomic; ones above that
11076 // are doomed anyway, so defer to the default libcall and blame the OS when
11077 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11078 // anything for those.
11079 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11080 // guarantee, see DDI0406C ARM architecture reference manual,
11081 // sections A8.8.72-74 LDRD)
11082 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11083 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11084 return (Size == 64) && !Subtarget->isMClass();
11087 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11088 // and up to 64 bits on the non-M profiles
11089 TargetLoweringBase::AtomicRMWExpansionKind
11090 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11091 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11092 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11093 ? AtomicRMWExpansionKind::LLSC
11094 : AtomicRMWExpansionKind::None;
11097 // This has so far only been implemented for MachO.
11098 bool ARMTargetLowering::useLoadStackGuardNode() const {
11099 return Subtarget->isTargetMachO();
11102 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11103 unsigned &Cost) const {
11104 // If we do not have NEON, vector types are not natively supported.
11105 if (!Subtarget->hasNEON())
11108 // Floating point values and vector values map to the same register file.
11109 // Therefore, althought we could do a store extract of a vector type, this is
11110 // better to leave at float as we have more freedom in the addressing mode for
11112 if (VectorTy->isFPOrFPVectorTy())
11115 // If the index is unknown at compile time, this is very expensive to lower
11116 // and it is not possible to combine the store with the extract.
11117 if (!isa<ConstantInt>(Idx))
11120 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11121 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11122 // We can do a store + vector extract on any vector that fits perfectly in a D
11124 if (BitWidth == 64 || BitWidth == 128) {
11131 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11132 AtomicOrdering Ord) const {
11133 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11134 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11135 bool IsAcquire = isAtLeastAcquire(Ord);
11137 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11138 // intrinsic must return {i32, i32} and we have to recombine them into a
11139 // single i64 here.
11140 if (ValTy->getPrimitiveSizeInBits() == 64) {
11141 Intrinsic::ID Int =
11142 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11143 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11145 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11146 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11148 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11149 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11150 if (!Subtarget->isLittle())
11151 std::swap (Lo, Hi);
11152 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11153 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11154 return Builder.CreateOr(
11155 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11158 Type *Tys[] = { Addr->getType() };
11159 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11160 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11162 return Builder.CreateTruncOrBitCast(
11163 Builder.CreateCall(Ldrex, Addr),
11164 cast<PointerType>(Addr->getType())->getElementType());
11167 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11169 AtomicOrdering Ord) const {
11170 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11171 bool IsRelease = isAtLeastRelease(Ord);
11173 // Since the intrinsics must have legal type, the i64 intrinsics take two
11174 // parameters: "i32, i32". We must marshal Val into the appropriate form
11175 // before the call.
11176 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11177 Intrinsic::ID Int =
11178 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11179 Function *Strex = Intrinsic::getDeclaration(M, Int);
11180 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11182 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11183 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11184 if (!Subtarget->isLittle())
11185 std::swap (Lo, Hi);
11186 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11187 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11190 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11191 Type *Tys[] = { Addr->getType() };
11192 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11194 return Builder.CreateCall2(
11195 Strex, Builder.CreateZExtOrBitCast(
11196 Val, Strex->getFunctionType()->getParamType(0)),
11208 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11209 uint64_t &Members) {
11210 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11211 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11212 uint64_t SubMembers = 0;
11213 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11215 Members += SubMembers;
11217 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11218 uint64_t SubMembers = 0;
11219 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11221 Members += SubMembers * AT->getNumElements();
11222 } else if (Ty->isFloatTy()) {
11223 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11227 } else if (Ty->isDoubleTy()) {
11228 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11232 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11239 return VT->getBitWidth() == 64;
11241 return VT->getBitWidth() == 128;
11243 switch (VT->getBitWidth()) {
11256 return (Members > 0 && Members <= 4);
11259 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11260 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11261 /// passing according to AAPCS rules.
11262 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11263 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11264 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11265 CallingConv::ARM_AAPCS_VFP)
11268 HABaseType Base = HA_UNKNOWN;
11269 uint64_t Members = 0;
11270 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11271 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11273 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11274 return IsHA || IsIntArray;