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/Intrinsics.h"
45 #include "llvm/IR/Type.h"
46 #include "llvm/MC/MCSectionMachO.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
55 #define DEBUG_TYPE "arm-isel"
57 STATISTIC(NumTailCalls, "Number of tail calls");
58 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
59 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
62 EnableARMLongCalls("arm-long-calls", cl::Hidden,
63 cl::desc("Generate calls via indirect call instructions"),
67 ARMInterworking("arm-interworking", cl::Hidden,
68 cl::desc("Enable / disable ARM interworking (for debugging only)"),
72 class ARMCCState : public CCState {
74 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
75 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
77 : CCState(CC, isVarArg, MF, locs, C) {
78 assert(((PC == Call) || (PC == Prologue)) &&
79 "ARMCCState users must specify whether their context is call"
80 "or prologue generation.");
86 // The APCS parameter registers.
87 static const MCPhysReg GPRArgRegs[] = {
88 ARM::R0, ARM::R1, ARM::R2, ARM::R3
91 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
92 MVT PromotedBitwiseVT) {
93 if (VT != PromotedLdStVT) {
94 setOperationAction(ISD::LOAD, VT, Promote);
95 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
97 setOperationAction(ISD::STORE, VT, Promote);
98 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
101 MVT ElemTy = VT.getVectorElementType();
102 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
103 setOperationAction(ISD::SETCC, VT, Custom);
104 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
105 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
106 if (ElemTy == MVT::i32) {
107 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
108 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
109 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
110 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
112 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
113 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
114 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
115 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
117 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
118 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
119 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
120 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
121 setOperationAction(ISD::SELECT, VT, Expand);
122 setOperationAction(ISD::SELECT_CC, VT, Expand);
123 setOperationAction(ISD::VSELECT, VT, Expand);
124 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
125 if (VT.isInteger()) {
126 setOperationAction(ISD::SHL, VT, Custom);
127 setOperationAction(ISD::SRA, VT, Custom);
128 setOperationAction(ISD::SRL, VT, Custom);
131 // Promote all bit-wise operations.
132 if (VT.isInteger() && VT != PromotedBitwiseVT) {
133 setOperationAction(ISD::AND, VT, Promote);
134 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
135 setOperationAction(ISD::OR, VT, Promote);
136 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
137 setOperationAction(ISD::XOR, VT, Promote);
138 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
141 // Neon does not support vector divide/remainder operations.
142 setOperationAction(ISD::SDIV, VT, Expand);
143 setOperationAction(ISD::UDIV, VT, Expand);
144 setOperationAction(ISD::FDIV, VT, Expand);
145 setOperationAction(ISD::SREM, VT, Expand);
146 setOperationAction(ISD::UREM, VT, Expand);
147 setOperationAction(ISD::FREM, VT, Expand);
150 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
151 addRegisterClass(VT, &ARM::DPRRegClass);
152 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
156 addRegisterClass(VT, &ARM::DPairRegClass);
157 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
161 const ARMSubtarget &STI)
162 : TargetLowering(TM), Subtarget(&STI) {
163 RegInfo = Subtarget->getRegisterInfo();
164 Itins = Subtarget->getInstrItineraryData();
166 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
168 if (Subtarget->isTargetMachO()) {
169 // Uses VFP for Thumb libfuncs if available.
170 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
171 Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
172 // Single-precision floating-point arithmetic.
173 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
174 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
175 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
176 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
178 // Double-precision floating-point arithmetic.
179 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
180 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
181 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
182 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
184 // Single-precision comparisons.
185 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
186 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
187 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
188 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
189 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
190 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
191 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
192 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
194 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
195 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
196 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
197 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
198 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
199 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
200 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
201 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
203 // Double-precision comparisons.
204 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
205 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
206 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
207 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
208 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
209 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
210 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
211 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
213 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
214 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
215 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
216 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
217 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
218 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
219 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
220 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
222 // Floating-point to integer conversions.
223 // i64 conversions are done via library routines even when generating VFP
224 // instructions, so use the same ones.
225 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
226 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
227 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
228 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
230 // Conversions between floating types.
231 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
232 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
234 // Integer to floating-point conversions.
235 // i64 conversions are done via library routines even when generating VFP
236 // instructions, so use the same ones.
237 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
238 // e.g., __floatunsidf vs. __floatunssidfvfp.
239 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
240 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
241 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
242 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
246 // These libcalls are not available in 32-bit.
247 setLibcallName(RTLIB::SHL_I128, nullptr);
248 setLibcallName(RTLIB::SRL_I128, nullptr);
249 setLibcallName(RTLIB::SRA_I128, nullptr);
251 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
252 !Subtarget->isTargetWindows()) {
253 static const struct {
254 const RTLIB::Libcall Op;
255 const char * const Name;
256 const CallingConv::ID CC;
257 const ISD::CondCode Cond;
259 // Double-precision floating-point arithmetic helper functions
260 // RTABI chapter 4.1.2, Table 2
261 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
262 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
263 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
266 // Double-precision floating-point comparison helper functions
267 // RTABI chapter 4.1.2, Table 3
268 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
269 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
270 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
271 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
272 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
273 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
274 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
275 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
277 // Single-precision floating-point arithmetic helper functions
278 // RTABI chapter 4.1.2, Table 4
279 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
280 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
281 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
284 // Single-precision floating-point comparison helper functions
285 // RTABI chapter 4.1.2, Table 5
286 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
287 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
288 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
289 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
290 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
291 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
292 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
293 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
295 // Floating-point to integer conversions.
296 // RTABI chapter 4.1.2, Table 6
297 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
298 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306 // Conversions between floating types.
307 // RTABI chapter 4.1.2, Table 7
308 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312 // Integer to floating-point conversions.
313 // RTABI chapter 4.1.2, Table 8
314 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323 // Long long helper functions
324 // RTABI chapter 4.2, Table 9
325 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330 // Integer division functions
331 // RTABI chapter 4.3.1
332 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342 // RTABI chapter 4.3.4
343 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348 for (const auto &LC : LibraryCalls) {
349 setLibcallName(LC.Op, LC.Name);
350 setLibcallCallingConv(LC.Op, LC.CC);
351 if (LC.Cond != ISD::SETCC_INVALID)
352 setCmpLibcallCC(LC.Op, LC.Cond);
356 if (Subtarget->isTargetWindows()) {
357 static const struct {
358 const RTLIB::Libcall Op;
359 const char * const Name;
360 const CallingConv::ID CC;
362 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
363 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
364 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
365 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
366 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
367 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
368 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
369 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
372 for (const auto &LC : LibraryCalls) {
373 setLibcallName(LC.Op, LC.Name);
374 setLibcallCallingConv(LC.Op, LC.CC);
378 // Use divmod compiler-rt calls for iOS 5.0 and later.
379 if (Subtarget->getTargetTriple().isiOS() &&
380 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
381 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
382 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
385 // The half <-> float conversion functions are always soft-float, but are
386 // needed for some targets which use a hard-float calling convention by
388 if (Subtarget->isAAPCS_ABI()) {
389 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
390 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
393 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
394 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
395 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
398 if (Subtarget->isThumb1Only())
399 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
401 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
402 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
403 !Subtarget->isThumb1Only()) {
404 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
405 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
408 for (MVT VT : MVT::vector_valuetypes()) {
409 for (MVT InnerVT : MVT::vector_valuetypes()) {
410 setTruncStoreAction(VT, InnerVT, Expand);
411 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
412 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
413 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
416 setOperationAction(ISD::MULHS, VT, Expand);
417 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
418 setOperationAction(ISD::MULHU, VT, Expand);
419 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
421 setOperationAction(ISD::BSWAP, VT, Expand);
424 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
425 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
427 if (Subtarget->hasNEON()) {
428 addDRTypeForNEON(MVT::v2f32);
429 addDRTypeForNEON(MVT::v8i8);
430 addDRTypeForNEON(MVT::v4i16);
431 addDRTypeForNEON(MVT::v2i32);
432 addDRTypeForNEON(MVT::v1i64);
434 addQRTypeForNEON(MVT::v4f32);
435 addQRTypeForNEON(MVT::v2f64);
436 addQRTypeForNEON(MVT::v16i8);
437 addQRTypeForNEON(MVT::v8i16);
438 addQRTypeForNEON(MVT::v4i32);
439 addQRTypeForNEON(MVT::v2i64);
441 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
442 // neither Neon nor VFP support any arithmetic operations on it.
443 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
444 // supported for v4f32.
445 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
446 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
447 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
448 // FIXME: Code duplication: FDIV and FREM are expanded always, see
449 // ARMTargetLowering::addTypeForNEON method for details.
450 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
451 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
452 // FIXME: Create unittest.
453 // In another words, find a way when "copysign" appears in DAG with vector
455 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
456 // FIXME: Code duplication: SETCC has custom operation action, see
457 // ARMTargetLowering::addTypeForNEON method for details.
458 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
459 // FIXME: Create unittest for FNEG and for FABS.
460 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
461 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
462 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
463 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
464 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
465 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
466 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
467 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
468 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
469 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
470 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
471 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
472 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
473 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
474 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
475 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
476 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
477 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
478 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
480 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
481 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
482 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
483 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
484 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
485 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
486 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
487 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
488 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
489 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
490 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
491 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
492 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
493 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
494 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
496 // Mark v2f32 intrinsics.
497 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
498 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
499 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
500 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
501 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
502 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
503 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
504 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
505 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
506 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
507 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
508 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
509 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
510 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
511 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
513 // Neon does not support some operations on v1i64 and v2i64 types.
514 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
515 // Custom handling for some quad-vector types to detect VMULL.
516 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
517 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
518 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
519 // Custom handling for some vector types to avoid expensive expansions
520 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
521 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
522 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
523 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
524 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
525 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
526 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
527 // a destination type that is wider than the source, and nor does
528 // it have a FP_TO_[SU]INT instruction with a narrower destination than
530 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
531 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
532 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
533 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
535 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
536 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
538 // NEON does not have single instruction CTPOP for vectors with element
539 // types wider than 8-bits. However, custom lowering can leverage the
540 // v8i8/v16i8 vcnt instruction.
541 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
542 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
543 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
544 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
546 // NEON only has FMA instructions as of VFP4.
547 if (!Subtarget->hasVFP4()) {
548 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
549 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
552 setTargetDAGCombine(ISD::INTRINSIC_VOID);
553 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
554 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
555 setTargetDAGCombine(ISD::SHL);
556 setTargetDAGCombine(ISD::SRL);
557 setTargetDAGCombine(ISD::SRA);
558 setTargetDAGCombine(ISD::SIGN_EXTEND);
559 setTargetDAGCombine(ISD::ZERO_EXTEND);
560 setTargetDAGCombine(ISD::ANY_EXTEND);
561 setTargetDAGCombine(ISD::SELECT_CC);
562 setTargetDAGCombine(ISD::BUILD_VECTOR);
563 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
564 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
565 setTargetDAGCombine(ISD::STORE);
566 setTargetDAGCombine(ISD::FP_TO_SINT);
567 setTargetDAGCombine(ISD::FP_TO_UINT);
568 setTargetDAGCombine(ISD::FDIV);
569 setTargetDAGCombine(ISD::LOAD);
571 // It is legal to extload from v4i8 to v4i16 or v4i32.
572 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
573 MVT::v4i16, MVT::v2i16,
575 for (unsigned i = 0; i < 6; ++i) {
576 for (MVT VT : MVT::integer_vector_valuetypes()) {
577 setLoadExtAction(ISD::EXTLOAD, VT, Tys[i], Legal);
578 setLoadExtAction(ISD::ZEXTLOAD, VT, Tys[i], Legal);
579 setLoadExtAction(ISD::SEXTLOAD, VT, Tys[i], 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::FP_ROUND, MVT::f32, Custom);
619 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
622 computeRegisterProperties(Subtarget->getRegisterInfo());
624 // ARM does not have floating-point extending loads.
625 for (MVT VT : MVT::fp_valuetypes()) {
626 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
627 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
630 // ... or truncating stores
631 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
632 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
633 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
635 // ARM does not have i1 sign extending load.
636 for (MVT VT : MVT::integer_valuetypes())
637 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
639 // ARM supports all 4 flavors of integer indexed load / store.
640 if (!Subtarget->isThumb1Only()) {
641 for (unsigned im = (unsigned)ISD::PRE_INC;
642 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
643 setIndexedLoadAction(im, MVT::i1, Legal);
644 setIndexedLoadAction(im, MVT::i8, Legal);
645 setIndexedLoadAction(im, MVT::i16, Legal);
646 setIndexedLoadAction(im, MVT::i32, Legal);
647 setIndexedStoreAction(im, MVT::i1, Legal);
648 setIndexedStoreAction(im, MVT::i8, Legal);
649 setIndexedStoreAction(im, MVT::i16, Legal);
650 setIndexedStoreAction(im, MVT::i32, Legal);
654 setOperationAction(ISD::SADDO, MVT::i32, Custom);
655 setOperationAction(ISD::UADDO, MVT::i32, Custom);
656 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
657 setOperationAction(ISD::USUBO, MVT::i32, Custom);
659 // i64 operation support.
660 setOperationAction(ISD::MUL, MVT::i64, Expand);
661 setOperationAction(ISD::MULHU, MVT::i32, Expand);
662 if (Subtarget->isThumb1Only()) {
663 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
664 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
666 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
667 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
668 setOperationAction(ISD::MULHS, MVT::i32, Expand);
670 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
671 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
672 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
673 setOperationAction(ISD::SRL, MVT::i64, Custom);
674 setOperationAction(ISD::SRA, MVT::i64, Custom);
676 if (!Subtarget->isThumb1Only()) {
677 // FIXME: We should do this for Thumb1 as well.
678 setOperationAction(ISD::ADDC, MVT::i32, Custom);
679 setOperationAction(ISD::ADDE, MVT::i32, Custom);
680 setOperationAction(ISD::SUBC, MVT::i32, Custom);
681 setOperationAction(ISD::SUBE, MVT::i32, Custom);
684 // ARM does not have ROTL.
685 setOperationAction(ISD::ROTL, MVT::i32, Expand);
686 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
687 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
688 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
689 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
691 // These just redirect to CTTZ and CTLZ on ARM.
692 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
693 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
695 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
697 // Only ARMv6 has BSWAP.
698 if (!Subtarget->hasV6Ops())
699 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
701 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
702 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
703 // These are expanded into libcalls if the cpu doesn't have HW divider.
704 setOperationAction(ISD::SDIV, MVT::i32, Expand);
705 setOperationAction(ISD::UDIV, MVT::i32, Expand);
708 // FIXME: Also set divmod for SREM on EABI
709 setOperationAction(ISD::SREM, MVT::i32, Expand);
710 setOperationAction(ISD::UREM, MVT::i32, Expand);
711 // Register based DivRem for AEABI (RTABI 4.2)
712 if (Subtarget->isTargetAEABI()) {
713 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
714 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
715 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
716 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
717 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
718 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
719 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
720 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
722 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
723 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
724 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
725 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
726 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
727 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
728 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
729 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
731 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
732 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
734 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
735 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
738 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
739 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
740 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
741 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
742 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
744 setOperationAction(ISD::TRAP, MVT::Other, Legal);
746 // Use the default implementation.
747 setOperationAction(ISD::VASTART, MVT::Other, Custom);
748 setOperationAction(ISD::VAARG, MVT::Other, Expand);
749 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
750 setOperationAction(ISD::VAEND, MVT::Other, Expand);
751 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
752 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
754 if (!Subtarget->isTargetMachO()) {
755 // Non-MachO platforms may return values in these registers via the
756 // personality function.
757 setExceptionPointerRegister(ARM::R0);
758 setExceptionSelectorRegister(ARM::R1);
761 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
762 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
764 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
766 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
767 // the default expansion. If we are targeting a single threaded system,
768 // then set them all for expand so we can lower them later into their
770 if (TM.Options.ThreadModel == ThreadModel::Single)
771 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
772 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
773 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
774 // to ldrex/strex loops already.
775 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
777 // On v8, we have particularly efficient implementations of atomic fences
778 // if they can be combined with nearby atomic loads and stores.
779 if (!Subtarget->hasV8Ops()) {
780 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
781 setInsertFencesForAtomic(true);
784 // If there's anything we can use as a barrier, go through custom lowering
786 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
787 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
789 // Set them all for expansion, which will force libcalls.
790 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
791 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
792 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
793 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
794 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
795 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
796 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
797 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
798 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
799 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
800 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
801 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
802 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
803 // Unordered/Monotonic case.
804 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
805 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
808 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
810 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
811 if (!Subtarget->hasV6Ops()) {
812 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
813 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
815 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
817 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
818 !Subtarget->isThumb1Only()) {
819 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
820 // iff target supports vfp2.
821 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
822 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
825 // We want to custom lower some of our intrinsics.
826 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
827 if (Subtarget->isTargetDarwin()) {
828 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
829 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
830 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
833 setOperationAction(ISD::SETCC, MVT::i32, Expand);
834 setOperationAction(ISD::SETCC, MVT::f32, Expand);
835 setOperationAction(ISD::SETCC, MVT::f64, Expand);
836 setOperationAction(ISD::SELECT, MVT::i32, Custom);
837 setOperationAction(ISD::SELECT, MVT::f32, Custom);
838 setOperationAction(ISD::SELECT, MVT::f64, Custom);
839 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
840 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
841 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
843 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
844 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
845 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
846 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
847 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
849 // We don't support sin/cos/fmod/copysign/pow
850 setOperationAction(ISD::FSIN, MVT::f64, Expand);
851 setOperationAction(ISD::FSIN, MVT::f32, Expand);
852 setOperationAction(ISD::FCOS, MVT::f32, Expand);
853 setOperationAction(ISD::FCOS, MVT::f64, Expand);
854 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
855 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
856 setOperationAction(ISD::FREM, MVT::f64, Expand);
857 setOperationAction(ISD::FREM, MVT::f32, Expand);
858 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
859 !Subtarget->isThumb1Only()) {
860 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
861 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
863 setOperationAction(ISD::FPOW, MVT::f64, Expand);
864 setOperationAction(ISD::FPOW, MVT::f32, Expand);
866 if (!Subtarget->hasVFP4()) {
867 setOperationAction(ISD::FMA, MVT::f64, Expand);
868 setOperationAction(ISD::FMA, MVT::f32, Expand);
871 // Various VFP goodness
872 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
873 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
874 if (Subtarget->hasVFP2()) {
875 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
876 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
877 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
878 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
881 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
882 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
883 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
884 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
887 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
888 if (!Subtarget->hasFP16()) {
889 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
890 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
894 // Combine sin / cos into one node or libcall if possible.
895 if (Subtarget->hasSinCos()) {
896 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
897 setLibcallName(RTLIB::SINCOS_F64, "sincos");
898 if (Subtarget->getTargetTriple().isiOS()) {
899 // For iOS, we don't want to the normal expansion of a libcall to
900 // sincos. We want to issue a libcall to __sincos_stret.
901 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
902 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
906 // FP-ARMv8 implements a lot of rounding-like FP operations.
907 if (Subtarget->hasFPARMv8()) {
908 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
909 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
910 setOperationAction(ISD::FROUND, MVT::f32, Legal);
911 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
912 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
913 setOperationAction(ISD::FRINT, MVT::f32, Legal);
914 if (!Subtarget->isFPOnlySP()) {
915 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
916 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
917 setOperationAction(ISD::FROUND, MVT::f64, Legal);
918 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
919 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
920 setOperationAction(ISD::FRINT, MVT::f64, Legal);
923 // We have target-specific dag combine patterns for the following nodes:
924 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
925 setTargetDAGCombine(ISD::ADD);
926 setTargetDAGCombine(ISD::SUB);
927 setTargetDAGCombine(ISD::MUL);
928 setTargetDAGCombine(ISD::AND);
929 setTargetDAGCombine(ISD::OR);
930 setTargetDAGCombine(ISD::XOR);
932 if (Subtarget->hasV6Ops())
933 setTargetDAGCombine(ISD::SRL);
935 setStackPointerRegisterToSaveRestore(ARM::SP);
937 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
938 !Subtarget->hasVFP2())
939 setSchedulingPreference(Sched::RegPressure);
941 setSchedulingPreference(Sched::Hybrid);
943 //// temporary - rewrite interface to use type
944 MaxStoresPerMemset = 8;
945 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
946 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
947 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
948 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
949 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
951 // On ARM arguments smaller than 4 bytes are extended, so all arguments
952 // are at least 4 bytes aligned.
953 setMinStackArgumentAlignment(4);
955 // Prefer likely predicted branches to selects on out-of-order cores.
956 PredictableSelectIsExpensive = Subtarget->isLikeA9();
958 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
961 // FIXME: It might make sense to define the representative register class as the
962 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
963 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
964 // SPR's representative would be DPR_VFP2. This should work well if register
965 // pressure tracking were modified such that a register use would increment the
966 // pressure of the register class's representative and all of it's super
967 // classes' representatives transitively. We have not implemented this because
968 // of the difficulty prior to coalescing of modeling operand register classes
969 // due to the common occurrence of cross class copies and subregister insertions
971 std::pair<const TargetRegisterClass *, uint8_t>
972 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
974 const TargetRegisterClass *RRC = nullptr;
976 switch (VT.SimpleTy) {
978 return TargetLowering::findRepresentativeClass(TRI, VT);
979 // Use DPR as representative register class for all floating point
980 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
981 // the cost is 1 for both f32 and f64.
982 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
983 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
984 RRC = &ARM::DPRRegClass;
985 // When NEON is used for SP, only half of the register file is available
986 // because operations that define both SP and DP results will be constrained
987 // to the VFP2 class (D0-D15). We currently model this constraint prior to
988 // coalescing by double-counting the SP regs. See the FIXME above.
989 if (Subtarget->useNEONForSinglePrecisionFP())
992 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
993 case MVT::v4f32: case MVT::v2f64:
994 RRC = &ARM::DPRRegClass;
998 RRC = &ARM::DPRRegClass;
1002 RRC = &ARM::DPRRegClass;
1006 return std::make_pair(RRC, Cost);
1009 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1011 default: return nullptr;
1012 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1013 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1014 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1015 case ARMISD::CALL: return "ARMISD::CALL";
1016 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1017 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1018 case ARMISD::tCALL: return "ARMISD::tCALL";
1019 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1020 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1021 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1022 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1023 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1024 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1025 case ARMISD::CMP: return "ARMISD::CMP";
1026 case ARMISD::CMN: return "ARMISD::CMN";
1027 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1028 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1029 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1030 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1031 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1033 case ARMISD::CMOV: return "ARMISD::CMOV";
1035 case ARMISD::RBIT: return "ARMISD::RBIT";
1037 case ARMISD::FTOSI: return "ARMISD::FTOSI";
1038 case ARMISD::FTOUI: return "ARMISD::FTOUI";
1039 case ARMISD::SITOF: return "ARMISD::SITOF";
1040 case ARMISD::UITOF: return "ARMISD::UITOF";
1042 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1043 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1044 case ARMISD::RRX: return "ARMISD::RRX";
1046 case ARMISD::ADDC: return "ARMISD::ADDC";
1047 case ARMISD::ADDE: return "ARMISD::ADDE";
1048 case ARMISD::SUBC: return "ARMISD::SUBC";
1049 case ARMISD::SUBE: return "ARMISD::SUBE";
1051 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1052 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1054 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1055 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1057 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1059 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1061 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1063 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1065 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1067 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1069 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1070 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1071 case ARMISD::VCGE: return "ARMISD::VCGE";
1072 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1073 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1074 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1075 case ARMISD::VCGT: return "ARMISD::VCGT";
1076 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1077 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1078 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1079 case ARMISD::VTST: return "ARMISD::VTST";
1081 case ARMISD::VSHL: return "ARMISD::VSHL";
1082 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1083 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1084 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1085 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1086 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1087 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1088 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1089 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1090 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1091 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1092 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1093 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1094 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1095 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1096 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1097 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1098 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1099 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1100 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1101 case ARMISD::VDUP: return "ARMISD::VDUP";
1102 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1103 case ARMISD::VEXT: return "ARMISD::VEXT";
1104 case ARMISD::VREV64: return "ARMISD::VREV64";
1105 case ARMISD::VREV32: return "ARMISD::VREV32";
1106 case ARMISD::VREV16: return "ARMISD::VREV16";
1107 case ARMISD::VZIP: return "ARMISD::VZIP";
1108 case ARMISD::VUZP: return "ARMISD::VUZP";
1109 case ARMISD::VTRN: return "ARMISD::VTRN";
1110 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1111 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1112 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1113 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1114 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1115 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1116 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1117 case ARMISD::FMAX: return "ARMISD::FMAX";
1118 case ARMISD::FMIN: return "ARMISD::FMIN";
1119 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1120 case ARMISD::VMINNM: return "ARMISD::VMIN";
1121 case ARMISD::BFI: return "ARMISD::BFI";
1122 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1123 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1124 case ARMISD::VBSL: return "ARMISD::VBSL";
1125 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1126 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1127 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1128 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1129 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1130 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1131 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1132 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1133 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1134 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1135 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1136 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1137 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1138 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1139 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1140 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1141 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1142 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1143 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1144 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1148 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1149 if (!VT.isVector()) return getPointerTy();
1150 return VT.changeVectorElementTypeToInteger();
1153 /// getRegClassFor - Return the register class that should be used for the
1154 /// specified value type.
1155 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1156 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1157 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1158 // load / store 4 to 8 consecutive D registers.
1159 if (Subtarget->hasNEON()) {
1160 if (VT == MVT::v4i64)
1161 return &ARM::QQPRRegClass;
1162 if (VT == MVT::v8i64)
1163 return &ARM::QQQQPRRegClass;
1165 return TargetLowering::getRegClassFor(VT);
1168 // Create a fast isel object.
1170 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1171 const TargetLibraryInfo *libInfo) const {
1172 return ARM::createFastISel(funcInfo, libInfo);
1175 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1176 unsigned NumVals = N->getNumValues();
1178 return Sched::RegPressure;
1180 for (unsigned i = 0; i != NumVals; ++i) {
1181 EVT VT = N->getValueType(i);
1182 if (VT == MVT::Glue || VT == MVT::Other)
1184 if (VT.isFloatingPoint() || VT.isVector())
1188 if (!N->isMachineOpcode())
1189 return Sched::RegPressure;
1191 // Load are scheduled for latency even if there instruction itinerary
1192 // is not available.
1193 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1194 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1196 if (MCID.getNumDefs() == 0)
1197 return Sched::RegPressure;
1198 if (!Itins->isEmpty() &&
1199 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1202 return Sched::RegPressure;
1205 //===----------------------------------------------------------------------===//
1207 //===----------------------------------------------------------------------===//
1209 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1210 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1212 default: llvm_unreachable("Unknown condition code!");
1213 case ISD::SETNE: return ARMCC::NE;
1214 case ISD::SETEQ: return ARMCC::EQ;
1215 case ISD::SETGT: return ARMCC::GT;
1216 case ISD::SETGE: return ARMCC::GE;
1217 case ISD::SETLT: return ARMCC::LT;
1218 case ISD::SETLE: return ARMCC::LE;
1219 case ISD::SETUGT: return ARMCC::HI;
1220 case ISD::SETUGE: return ARMCC::HS;
1221 case ISD::SETULT: return ARMCC::LO;
1222 case ISD::SETULE: return ARMCC::LS;
1226 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1227 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1228 ARMCC::CondCodes &CondCode2) {
1229 CondCode2 = ARMCC::AL;
1231 default: llvm_unreachable("Unknown FP condition!");
1233 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1235 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1237 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1238 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1239 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1240 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1241 case ISD::SETO: CondCode = ARMCC::VC; break;
1242 case ISD::SETUO: CondCode = ARMCC::VS; break;
1243 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1244 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1245 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1247 case ISD::SETULT: CondCode = ARMCC::LT; break;
1249 case ISD::SETULE: CondCode = ARMCC::LE; break;
1251 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1255 //===----------------------------------------------------------------------===//
1256 // Calling Convention Implementation
1257 //===----------------------------------------------------------------------===//
1259 #include "ARMGenCallingConv.inc"
1261 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1262 /// account presence of floating point hardware and calling convention
1263 /// limitations, such as support for variadic functions.
1265 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1266 bool isVarArg) const {
1269 llvm_unreachable("Unsupported calling convention");
1270 case CallingConv::ARM_AAPCS:
1271 case CallingConv::ARM_APCS:
1272 case CallingConv::GHC:
1274 case CallingConv::ARM_AAPCS_VFP:
1275 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1276 case CallingConv::C:
1277 if (!Subtarget->isAAPCS_ABI())
1278 return CallingConv::ARM_APCS;
1279 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1280 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1282 return CallingConv::ARM_AAPCS_VFP;
1284 return CallingConv::ARM_AAPCS;
1285 case CallingConv::Fast:
1286 if (!Subtarget->isAAPCS_ABI()) {
1287 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1288 return CallingConv::Fast;
1289 return CallingConv::ARM_APCS;
1290 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1291 return CallingConv::ARM_AAPCS_VFP;
1293 return CallingConv::ARM_AAPCS;
1297 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1298 /// CallingConvention.
1299 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1301 bool isVarArg) const {
1302 switch (getEffectiveCallingConv(CC, isVarArg)) {
1304 llvm_unreachable("Unsupported calling convention");
1305 case CallingConv::ARM_APCS:
1306 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1307 case CallingConv::ARM_AAPCS:
1308 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1309 case CallingConv::ARM_AAPCS_VFP:
1310 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1311 case CallingConv::Fast:
1312 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1313 case CallingConv::GHC:
1314 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1318 /// LowerCallResult - Lower the result values of a call into the
1319 /// appropriate copies out of appropriate physical registers.
1321 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1322 CallingConv::ID CallConv, bool isVarArg,
1323 const SmallVectorImpl<ISD::InputArg> &Ins,
1324 SDLoc dl, SelectionDAG &DAG,
1325 SmallVectorImpl<SDValue> &InVals,
1326 bool isThisReturn, SDValue ThisVal) const {
1328 // Assign locations to each value returned by this call.
1329 SmallVector<CCValAssign, 16> RVLocs;
1330 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1331 *DAG.getContext(), Call);
1332 CCInfo.AnalyzeCallResult(Ins,
1333 CCAssignFnForNode(CallConv, /* Return*/ true,
1336 // Copy all of the result registers out of their specified physreg.
1337 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1338 CCValAssign VA = RVLocs[i];
1340 // Pass 'this' value directly from the argument to return value, to avoid
1341 // reg unit interference
1342 if (i == 0 && isThisReturn) {
1343 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1344 "unexpected return calling convention register assignment");
1345 InVals.push_back(ThisVal);
1350 if (VA.needsCustom()) {
1351 // Handle f64 or half of a v2f64.
1352 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1354 Chain = Lo.getValue(1);
1355 InFlag = Lo.getValue(2);
1356 VA = RVLocs[++i]; // skip ahead to next loc
1357 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1359 Chain = Hi.getValue(1);
1360 InFlag = Hi.getValue(2);
1361 if (!Subtarget->isLittle())
1363 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1365 if (VA.getLocVT() == MVT::v2f64) {
1366 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1367 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1368 DAG.getConstant(0, MVT::i32));
1370 VA = RVLocs[++i]; // skip ahead to next loc
1371 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1372 Chain = Lo.getValue(1);
1373 InFlag = Lo.getValue(2);
1374 VA = RVLocs[++i]; // skip ahead to next loc
1375 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1376 Chain = Hi.getValue(1);
1377 InFlag = Hi.getValue(2);
1378 if (!Subtarget->isLittle())
1380 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1381 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1382 DAG.getConstant(1, MVT::i32));
1385 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1387 Chain = Val.getValue(1);
1388 InFlag = Val.getValue(2);
1391 switch (VA.getLocInfo()) {
1392 default: llvm_unreachable("Unknown loc info!");
1393 case CCValAssign::Full: break;
1394 case CCValAssign::BCvt:
1395 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1399 InVals.push_back(Val);
1405 /// LowerMemOpCallTo - Store the argument to the stack.
1407 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1408 SDValue StackPtr, SDValue Arg,
1409 SDLoc dl, SelectionDAG &DAG,
1410 const CCValAssign &VA,
1411 ISD::ArgFlagsTy Flags) const {
1412 unsigned LocMemOffset = VA.getLocMemOffset();
1413 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1414 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1415 return DAG.getStore(Chain, dl, Arg, PtrOff,
1416 MachinePointerInfo::getStack(LocMemOffset),
1420 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1421 SDValue Chain, SDValue &Arg,
1422 RegsToPassVector &RegsToPass,
1423 CCValAssign &VA, CCValAssign &NextVA,
1425 SmallVectorImpl<SDValue> &MemOpChains,
1426 ISD::ArgFlagsTy Flags) const {
1428 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1429 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1430 unsigned id = Subtarget->isLittle() ? 0 : 1;
1431 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1433 if (NextVA.isRegLoc())
1434 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1436 assert(NextVA.isMemLoc());
1437 if (!StackPtr.getNode())
1438 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1440 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1446 /// LowerCall - Lowering a call into a callseq_start <-
1447 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1450 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1451 SmallVectorImpl<SDValue> &InVals) const {
1452 SelectionDAG &DAG = CLI.DAG;
1454 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1455 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1456 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1457 SDValue Chain = CLI.Chain;
1458 SDValue Callee = CLI.Callee;
1459 bool &isTailCall = CLI.IsTailCall;
1460 CallingConv::ID CallConv = CLI.CallConv;
1461 bool doesNotRet = CLI.DoesNotReturn;
1462 bool isVarArg = CLI.IsVarArg;
1464 MachineFunction &MF = DAG.getMachineFunction();
1465 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1466 bool isThisReturn = false;
1467 bool isSibCall = false;
1469 // Disable tail calls if they're not supported.
1470 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1474 // Check if it's really possible to do a tail call.
1475 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1476 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1477 Outs, OutVals, Ins, DAG);
1478 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1479 report_fatal_error("failed to perform tail call elimination on a call "
1480 "site marked musttail");
1481 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1482 // detected sibcalls.
1489 // Analyze operands of the call, assigning locations to each operand.
1490 SmallVector<CCValAssign, 16> ArgLocs;
1491 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1492 *DAG.getContext(), Call);
1493 CCInfo.AnalyzeCallOperands(Outs,
1494 CCAssignFnForNode(CallConv, /* Return*/ false,
1497 // Get a count of how many bytes are to be pushed on the stack.
1498 unsigned NumBytes = CCInfo.getNextStackOffset();
1500 // For tail calls, memory operands are available in our caller's stack.
1504 // Adjust the stack pointer for the new arguments...
1505 // These operations are automatically eliminated by the prolog/epilog pass
1507 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1510 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1512 RegsToPassVector RegsToPass;
1513 SmallVector<SDValue, 8> MemOpChains;
1515 // Walk the register/memloc assignments, inserting copies/loads. In the case
1516 // of tail call optimization, arguments are handled later.
1517 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1519 ++i, ++realArgIdx) {
1520 CCValAssign &VA = ArgLocs[i];
1521 SDValue Arg = OutVals[realArgIdx];
1522 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1523 bool isByVal = Flags.isByVal();
1525 // Promote the value if needed.
1526 switch (VA.getLocInfo()) {
1527 default: llvm_unreachable("Unknown loc info!");
1528 case CCValAssign::Full: break;
1529 case CCValAssign::SExt:
1530 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1532 case CCValAssign::ZExt:
1533 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1535 case CCValAssign::AExt:
1536 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1538 case CCValAssign::BCvt:
1539 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1543 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1544 if (VA.needsCustom()) {
1545 if (VA.getLocVT() == MVT::v2f64) {
1546 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1547 DAG.getConstant(0, MVT::i32));
1548 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1549 DAG.getConstant(1, MVT::i32));
1551 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1552 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1554 VA = ArgLocs[++i]; // skip ahead to next loc
1555 if (VA.isRegLoc()) {
1556 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1557 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1559 assert(VA.isMemLoc());
1561 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1562 dl, DAG, VA, Flags));
1565 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1566 StackPtr, MemOpChains, Flags);
1568 } else if (VA.isRegLoc()) {
1569 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1570 assert(VA.getLocVT() == MVT::i32 &&
1571 "unexpected calling convention register assignment");
1572 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1573 "unexpected use of 'returned'");
1574 isThisReturn = true;
1576 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1577 } else if (isByVal) {
1578 assert(VA.isMemLoc());
1579 unsigned offset = 0;
1581 // True if this byval aggregate will be split between registers
1583 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1584 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1586 if (CurByValIdx < ByValArgsCount) {
1588 unsigned RegBegin, RegEnd;
1589 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1591 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1593 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1594 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1595 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1596 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1597 MachinePointerInfo(),
1598 false, false, false,
1599 DAG.InferPtrAlignment(AddArg));
1600 MemOpChains.push_back(Load.getValue(1));
1601 RegsToPass.push_back(std::make_pair(j, Load));
1604 // If parameter size outsides register area, "offset" value
1605 // helps us to calculate stack slot for remained part properly.
1606 offset = RegEnd - RegBegin;
1608 CCInfo.nextInRegsParam();
1611 if (Flags.getByValSize() > 4*offset) {
1612 unsigned LocMemOffset = VA.getLocMemOffset();
1613 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1614 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1616 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1617 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1618 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1620 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1622 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1623 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1624 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1627 } else if (!isSibCall) {
1628 assert(VA.isMemLoc());
1630 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1631 dl, DAG, VA, Flags));
1635 if (!MemOpChains.empty())
1636 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1638 // Build a sequence of copy-to-reg nodes chained together with token chain
1639 // and flag operands which copy the outgoing args into the appropriate regs.
1641 // Tail call byval lowering might overwrite argument registers so in case of
1642 // tail call optimization the copies to registers are lowered later.
1644 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1645 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1646 RegsToPass[i].second, InFlag);
1647 InFlag = Chain.getValue(1);
1650 // For tail calls lower the arguments to the 'real' stack slot.
1652 // Force all the incoming stack arguments to be loaded from the stack
1653 // before any new outgoing arguments are stored to the stack, because the
1654 // outgoing stack slots may alias the incoming argument stack slots, and
1655 // the alias isn't otherwise explicit. This is slightly more conservative
1656 // than necessary, because it means that each store effectively depends
1657 // on every argument instead of just those arguments it would clobber.
1659 // Do not flag preceding copytoreg stuff together with the following stuff.
1661 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1662 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1663 RegsToPass[i].second, InFlag);
1664 InFlag = Chain.getValue(1);
1669 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1670 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1671 // node so that legalize doesn't hack it.
1672 bool isDirect = false;
1673 bool isARMFunc = false;
1674 bool isLocalARMFunc = false;
1675 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1677 if (EnableARMLongCalls) {
1678 assert((Subtarget->isTargetWindows() ||
1679 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1680 "long-calls with non-static relocation model!");
1681 // Handle a global address or an external symbol. If it's not one of
1682 // those, the target's already in a register, so we don't need to do
1684 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1685 const GlobalValue *GV = G->getGlobal();
1686 // Create a constant pool entry for the callee address
1687 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1688 ARMConstantPoolValue *CPV =
1689 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1691 // Get the address of the callee into a register
1692 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1693 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1694 Callee = DAG.getLoad(getPointerTy(), dl,
1695 DAG.getEntryNode(), CPAddr,
1696 MachinePointerInfo::getConstantPool(),
1697 false, false, false, 0);
1698 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1699 const char *Sym = S->getSymbol();
1701 // Create a constant pool entry for the callee address
1702 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1703 ARMConstantPoolValue *CPV =
1704 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1705 ARMPCLabelIndex, 0);
1706 // Get the address of the callee into a register
1707 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1708 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1709 Callee = DAG.getLoad(getPointerTy(), dl,
1710 DAG.getEntryNode(), CPAddr,
1711 MachinePointerInfo::getConstantPool(),
1712 false, false, false, 0);
1714 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1715 const GlobalValue *GV = G->getGlobal();
1717 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1718 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1719 getTargetMachine().getRelocationModel() != Reloc::Static;
1720 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1721 // ARM call to a local ARM function is predicable.
1722 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1723 // tBX takes a register source operand.
1724 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1725 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1726 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1727 DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1728 0, ARMII::MO_NONLAZY));
1729 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1730 MachinePointerInfo::getGOT(), false, false, true, 0);
1731 } else if (Subtarget->isTargetCOFF()) {
1732 assert(Subtarget->isTargetWindows() &&
1733 "Windows is the only supported COFF target");
1734 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1735 ? ARMII::MO_DLLIMPORT
1736 : ARMII::MO_NO_FLAG;
1737 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1739 if (GV->hasDLLImportStorageClass())
1740 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1741 DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1742 Callee), MachinePointerInfo::getGOT(),
1743 false, false, false, 0);
1745 // On ELF targets for PIC code, direct calls should go through the PLT
1746 unsigned OpFlags = 0;
1747 if (Subtarget->isTargetELF() &&
1748 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1749 OpFlags = ARMII::MO_PLT;
1750 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1752 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1754 bool isStub = Subtarget->isTargetMachO() &&
1755 getTargetMachine().getRelocationModel() != Reloc::Static;
1756 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1757 // tBX takes a register source operand.
1758 const char *Sym = S->getSymbol();
1759 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1760 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1761 ARMConstantPoolValue *CPV =
1762 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1763 ARMPCLabelIndex, 4);
1764 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1765 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1766 Callee = DAG.getLoad(getPointerTy(), dl,
1767 DAG.getEntryNode(), CPAddr,
1768 MachinePointerInfo::getConstantPool(),
1769 false, false, false, 0);
1770 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1771 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1772 getPointerTy(), Callee, PICLabel);
1774 unsigned OpFlags = 0;
1775 // On ELF targets for PIC code, direct calls should go through the PLT
1776 if (Subtarget->isTargetELF() &&
1777 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1778 OpFlags = ARMII::MO_PLT;
1779 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1783 // FIXME: handle tail calls differently.
1785 bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1786 if (Subtarget->isThumb()) {
1787 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1788 CallOpc = ARMISD::CALL_NOLINK;
1790 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1792 if (!isDirect && !Subtarget->hasV5TOps())
1793 CallOpc = ARMISD::CALL_NOLINK;
1794 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1795 // Emit regular call when code size is the priority
1797 // "mov lr, pc; b _foo" to avoid confusing the RSP
1798 CallOpc = ARMISD::CALL_NOLINK;
1800 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1803 std::vector<SDValue> Ops;
1804 Ops.push_back(Chain);
1805 Ops.push_back(Callee);
1807 // Add argument registers to the end of the list so that they are known live
1809 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1810 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1811 RegsToPass[i].second.getValueType()));
1813 // Add a register mask operand representing the call-preserved registers.
1815 const uint32_t *Mask;
1816 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1818 // For 'this' returns, use the R0-preserving mask if applicable
1819 Mask = ARI->getThisReturnPreservedMask(CallConv);
1821 // Set isThisReturn to false if the calling convention is not one that
1822 // allows 'returned' to be modeled in this way, so LowerCallResult does
1823 // not try to pass 'this' straight through
1824 isThisReturn = false;
1825 Mask = ARI->getCallPreservedMask(CallConv);
1828 Mask = ARI->getCallPreservedMask(CallConv);
1830 assert(Mask && "Missing call preserved mask for calling convention");
1831 Ops.push_back(DAG.getRegisterMask(Mask));
1834 if (InFlag.getNode())
1835 Ops.push_back(InFlag);
1837 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1839 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1841 // Returns a chain and a flag for retval copy to use.
1842 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1843 InFlag = Chain.getValue(1);
1845 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1846 DAG.getIntPtrConstant(0, true), InFlag, dl);
1848 InFlag = Chain.getValue(1);
1850 // Handle result values, copying them out of physregs into vregs that we
1852 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1853 InVals, isThisReturn,
1854 isThisReturn ? OutVals[0] : SDValue());
1857 /// HandleByVal - Every parameter *after* a byval parameter is passed
1858 /// on the stack. Remember the next parameter register to allocate,
1859 /// and then confiscate the rest of the parameter registers to insure
1862 ARMTargetLowering::HandleByVal(
1863 CCState *State, unsigned &size, unsigned Align) const {
1864 unsigned reg = State->AllocateReg(GPRArgRegs);
1865 assert((State->getCallOrPrologue() == Prologue ||
1866 State->getCallOrPrologue() == Call) &&
1867 "unhandled ParmContext");
1869 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1870 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1871 unsigned AlignInRegs = Align / 4;
1872 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1873 for (unsigned i = 0; i < Waste; ++i)
1874 reg = State->AllocateReg(GPRArgRegs);
1877 unsigned excess = 4 * (ARM::R4 - reg);
1879 // Special case when NSAA != SP and parameter size greater than size of
1880 // all remained GPR regs. In that case we can't split parameter, we must
1881 // send it to stack. We also must set NCRN to R4, so waste all
1882 // remained registers.
1883 const unsigned NSAAOffset = State->getNextStackOffset();
1884 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1885 while (State->AllocateReg(GPRArgRegs))
1890 // First register for byval parameter is the first register that wasn't
1891 // allocated before this method call, so it would be "reg".
1892 // If parameter is small enough to be saved in range [reg, r4), then
1893 // the end (first after last) register would be reg + param-size-in-regs,
1894 // else parameter would be splitted between registers and stack,
1895 // end register would be r4 in this case.
1896 unsigned ByValRegBegin = reg;
1897 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1898 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1899 // Note, first register is allocated in the beginning of function already,
1900 // allocate remained amount of registers we need.
1901 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1902 State->AllocateReg(GPRArgRegs);
1903 // A byval parameter that is split between registers and memory needs its
1904 // size truncated here.
1905 // In the case where the entire structure fits in registers, we set the
1906 // size in memory to zero.
1915 /// MatchingStackOffset - Return true if the given stack call argument is
1916 /// already available in the same position (relatively) of the caller's
1917 /// incoming argument stack.
1919 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1920 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1921 const TargetInstrInfo *TII) {
1922 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1924 if (Arg.getOpcode() == ISD::CopyFromReg) {
1925 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1926 if (!TargetRegisterInfo::isVirtualRegister(VR))
1928 MachineInstr *Def = MRI->getVRegDef(VR);
1931 if (!Flags.isByVal()) {
1932 if (!TII->isLoadFromStackSlot(Def, FI))
1937 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1938 if (Flags.isByVal())
1939 // ByVal argument is passed in as a pointer but it's now being
1940 // dereferenced. e.g.
1941 // define @foo(%struct.X* %A) {
1942 // tail call @bar(%struct.X* byval %A)
1945 SDValue Ptr = Ld->getBasePtr();
1946 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1949 FI = FINode->getIndex();
1953 assert(FI != INT_MAX);
1954 if (!MFI->isFixedObjectIndex(FI))
1956 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1959 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1960 /// for tail call optimization. Targets which want to do tail call
1961 /// optimization should implement this function.
1963 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1964 CallingConv::ID CalleeCC,
1966 bool isCalleeStructRet,
1967 bool isCallerStructRet,
1968 const SmallVectorImpl<ISD::OutputArg> &Outs,
1969 const SmallVectorImpl<SDValue> &OutVals,
1970 const SmallVectorImpl<ISD::InputArg> &Ins,
1971 SelectionDAG& DAG) const {
1972 const Function *CallerF = DAG.getMachineFunction().getFunction();
1973 CallingConv::ID CallerCC = CallerF->getCallingConv();
1974 bool CCMatch = CallerCC == CalleeCC;
1976 // Look for obvious safe cases to perform tail call optimization that do not
1977 // require ABI changes. This is what gcc calls sibcall.
1979 // Do not sibcall optimize vararg calls unless the call site is not passing
1981 if (isVarArg && !Outs.empty())
1984 // Exception-handling functions need a special set of instructions to indicate
1985 // a return to the hardware. Tail-calling another function would probably
1987 if (CallerF->hasFnAttribute("interrupt"))
1990 // Also avoid sibcall optimization if either caller or callee uses struct
1991 // return semantics.
1992 if (isCalleeStructRet || isCallerStructRet)
1995 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1996 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1997 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1998 // support in the assembler and linker to be used. This would need to be
1999 // fixed to fully support tail calls in Thumb1.
2001 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2002 // LR. This means if we need to reload LR, it takes an extra instructions,
2003 // which outweighs the value of the tail call; but here we don't know yet
2004 // whether LR is going to be used. Probably the right approach is to
2005 // generate the tail call here and turn it back into CALL/RET in
2006 // emitEpilogue if LR is used.
2008 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2009 // but we need to make sure there are enough registers; the only valid
2010 // registers are the 4 used for parameters. We don't currently do this
2012 if (Subtarget->isThumb1Only())
2015 // Externally-defined functions with weak linkage should not be
2016 // tail-called on ARM when the OS does not support dynamic
2017 // pre-emption of symbols, as the AAELF spec requires normal calls
2018 // to undefined weak functions to be replaced with a NOP or jump to the
2019 // next instruction. The behaviour of branch instructions in this
2020 // situation (as used for tail calls) is implementation-defined, so we
2021 // cannot rely on the linker replacing the tail call with a return.
2022 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2023 const GlobalValue *GV = G->getGlobal();
2024 const Triple TT(getTargetMachine().getTargetTriple());
2025 if (GV->hasExternalWeakLinkage() &&
2026 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2030 // If the calling conventions do not match, then we'd better make sure the
2031 // results are returned in the same way as what the caller expects.
2033 SmallVector<CCValAssign, 16> RVLocs1;
2034 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2035 *DAG.getContext(), Call);
2036 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2038 SmallVector<CCValAssign, 16> RVLocs2;
2039 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2040 *DAG.getContext(), Call);
2041 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2043 if (RVLocs1.size() != RVLocs2.size())
2045 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2046 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2048 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2050 if (RVLocs1[i].isRegLoc()) {
2051 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2054 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2060 // If Caller's vararg or byval argument has been split between registers and
2061 // stack, do not perform tail call, since part of the argument is in caller's
2063 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2064 getInfo<ARMFunctionInfo>();
2065 if (AFI_Caller->getArgRegsSaveSize())
2068 // If the callee takes no arguments then go on to check the results of the
2070 if (!Outs.empty()) {
2071 // Check if stack adjustment is needed. For now, do not do this if any
2072 // argument is passed on the stack.
2073 SmallVector<CCValAssign, 16> ArgLocs;
2074 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2075 *DAG.getContext(), Call);
2076 CCInfo.AnalyzeCallOperands(Outs,
2077 CCAssignFnForNode(CalleeCC, false, isVarArg));
2078 if (CCInfo.getNextStackOffset()) {
2079 MachineFunction &MF = DAG.getMachineFunction();
2081 // Check if the arguments are already laid out in the right way as
2082 // the caller's fixed stack objects.
2083 MachineFrameInfo *MFI = MF.getFrameInfo();
2084 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2085 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2086 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2088 ++i, ++realArgIdx) {
2089 CCValAssign &VA = ArgLocs[i];
2090 EVT RegVT = VA.getLocVT();
2091 SDValue Arg = OutVals[realArgIdx];
2092 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2093 if (VA.getLocInfo() == CCValAssign::Indirect)
2095 if (VA.needsCustom()) {
2096 // f64 and vector types are split into multiple registers or
2097 // register/stack-slot combinations. The types will not match
2098 // the registers; give up on memory f64 refs until we figure
2099 // out what to do about this.
2102 if (!ArgLocs[++i].isRegLoc())
2104 if (RegVT == MVT::v2f64) {
2105 if (!ArgLocs[++i].isRegLoc())
2107 if (!ArgLocs[++i].isRegLoc())
2110 } else if (!VA.isRegLoc()) {
2111 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2123 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2124 MachineFunction &MF, bool isVarArg,
2125 const SmallVectorImpl<ISD::OutputArg> &Outs,
2126 LLVMContext &Context) const {
2127 SmallVector<CCValAssign, 16> RVLocs;
2128 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2129 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2133 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2134 SDLoc DL, SelectionDAG &DAG) {
2135 const MachineFunction &MF = DAG.getMachineFunction();
2136 const Function *F = MF.getFunction();
2138 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2140 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2141 // version of the "preferred return address". These offsets affect the return
2142 // instruction if this is a return from PL1 without hypervisor extensions.
2143 // IRQ/FIQ: +4 "subs pc, lr, #4"
2144 // SWI: 0 "subs pc, lr, #0"
2145 // ABORT: +4 "subs pc, lr, #4"
2146 // UNDEF: +4/+2 "subs pc, lr, #0"
2147 // UNDEF varies depending on where the exception came from ARM or Thumb
2148 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2151 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2154 else if (IntKind == "SWI" || IntKind == "UNDEF")
2157 report_fatal_error("Unsupported interrupt attribute. If present, value "
2158 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2160 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2162 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2166 ARMTargetLowering::LowerReturn(SDValue Chain,
2167 CallingConv::ID CallConv, bool isVarArg,
2168 const SmallVectorImpl<ISD::OutputArg> &Outs,
2169 const SmallVectorImpl<SDValue> &OutVals,
2170 SDLoc dl, SelectionDAG &DAG) const {
2172 // CCValAssign - represent the assignment of the return value to a location.
2173 SmallVector<CCValAssign, 16> RVLocs;
2175 // CCState - Info about the registers and stack slots.
2176 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2177 *DAG.getContext(), Call);
2179 // Analyze outgoing return values.
2180 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2184 SmallVector<SDValue, 4> RetOps;
2185 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2186 bool isLittleEndian = Subtarget->isLittle();
2188 MachineFunction &MF = DAG.getMachineFunction();
2189 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2190 AFI->setReturnRegsCount(RVLocs.size());
2192 // Copy the result values into the output registers.
2193 for (unsigned i = 0, realRVLocIdx = 0;
2195 ++i, ++realRVLocIdx) {
2196 CCValAssign &VA = RVLocs[i];
2197 assert(VA.isRegLoc() && "Can only return in registers!");
2199 SDValue Arg = OutVals[realRVLocIdx];
2201 switch (VA.getLocInfo()) {
2202 default: llvm_unreachable("Unknown loc info!");
2203 case CCValAssign::Full: break;
2204 case CCValAssign::BCvt:
2205 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2209 if (VA.needsCustom()) {
2210 if (VA.getLocVT() == MVT::v2f64) {
2211 // Extract the first half and return it in two registers.
2212 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2213 DAG.getConstant(0, MVT::i32));
2214 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2215 DAG.getVTList(MVT::i32, MVT::i32), Half);
2217 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2218 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2220 Flag = Chain.getValue(1);
2221 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2222 VA = RVLocs[++i]; // skip ahead to next loc
2223 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2224 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2226 Flag = Chain.getValue(1);
2227 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2228 VA = RVLocs[++i]; // skip ahead to next loc
2230 // Extract the 2nd half and fall through to handle it as an f64 value.
2231 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2232 DAG.getConstant(1, MVT::i32));
2234 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2236 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2237 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2238 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2239 fmrrd.getValue(isLittleEndian ? 0 : 1),
2241 Flag = Chain.getValue(1);
2242 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2243 VA = RVLocs[++i]; // skip ahead to next loc
2244 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2245 fmrrd.getValue(isLittleEndian ? 1 : 0),
2248 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2250 // Guarantee that all emitted copies are
2251 // stuck together, avoiding something bad.
2252 Flag = Chain.getValue(1);
2253 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2256 // Update chain and glue.
2259 RetOps.push_back(Flag);
2261 // CPUs which aren't M-class use a special sequence to return from
2262 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2263 // though we use "subs pc, lr, #N").
2265 // M-class CPUs actually use a normal return sequence with a special
2266 // (hardware-provided) value in LR, so the normal code path works.
2267 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2268 !Subtarget->isMClass()) {
2269 if (Subtarget->isThumb1Only())
2270 report_fatal_error("interrupt attribute is not supported in Thumb1");
2271 return LowerInterruptReturn(RetOps, dl, DAG);
2274 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2277 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2278 if (N->getNumValues() != 1)
2280 if (!N->hasNUsesOfValue(1, 0))
2283 SDValue TCChain = Chain;
2284 SDNode *Copy = *N->use_begin();
2285 if (Copy->getOpcode() == ISD::CopyToReg) {
2286 // If the copy has a glue operand, we conservatively assume it isn't safe to
2287 // perform a tail call.
2288 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2290 TCChain = Copy->getOperand(0);
2291 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2292 SDNode *VMov = Copy;
2293 // f64 returned in a pair of GPRs.
2294 SmallPtrSet<SDNode*, 2> Copies;
2295 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2297 if (UI->getOpcode() != ISD::CopyToReg)
2301 if (Copies.size() > 2)
2304 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2306 SDValue UseChain = UI->getOperand(0);
2307 if (Copies.count(UseChain.getNode()))
2311 // We are at the top of this chain.
2312 // If the copy has a glue operand, we conservatively assume it
2313 // isn't safe to perform a tail call.
2314 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2320 } else if (Copy->getOpcode() == ISD::BITCAST) {
2321 // f32 returned in a single GPR.
2322 if (!Copy->hasOneUse())
2324 Copy = *Copy->use_begin();
2325 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2327 // If the copy has a glue operand, we conservatively assume it isn't safe to
2328 // perform a tail call.
2329 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2331 TCChain = Copy->getOperand(0);
2336 bool HasRet = false;
2337 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2339 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2340 UI->getOpcode() != ARMISD::INTRET_FLAG)
2352 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2353 if (!Subtarget->supportsTailCall())
2356 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2359 return !Subtarget->isThumb1Only();
2362 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2363 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2364 // one of the above mentioned nodes. It has to be wrapped because otherwise
2365 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2366 // be used to form addressing mode. These wrapped nodes will be selected
2368 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2369 EVT PtrVT = Op.getValueType();
2370 // FIXME there is no actual debug info here
2372 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2374 if (CP->isMachineConstantPoolEntry())
2375 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2376 CP->getAlignment());
2378 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2379 CP->getAlignment());
2380 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2383 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2384 return MachineJumpTableInfo::EK_Inline;
2387 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2388 SelectionDAG &DAG) const {
2389 MachineFunction &MF = DAG.getMachineFunction();
2390 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2391 unsigned ARMPCLabelIndex = 0;
2393 EVT PtrVT = getPointerTy();
2394 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2395 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2397 if (RelocM == Reloc::Static) {
2398 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2400 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2401 ARMPCLabelIndex = AFI->createPICLabelUId();
2402 ARMConstantPoolValue *CPV =
2403 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2404 ARMCP::CPBlockAddress, PCAdj);
2405 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2407 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2408 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2409 MachinePointerInfo::getConstantPool(),
2410 false, false, false, 0);
2411 if (RelocM == Reloc::Static)
2413 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2414 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2417 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2419 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2420 SelectionDAG &DAG) const {
2422 EVT PtrVT = getPointerTy();
2423 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2424 MachineFunction &MF = DAG.getMachineFunction();
2425 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2426 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2427 ARMConstantPoolValue *CPV =
2428 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2429 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2430 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2431 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2432 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2433 MachinePointerInfo::getConstantPool(),
2434 false, false, false, 0);
2435 SDValue Chain = Argument.getValue(1);
2437 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2438 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2440 // call __tls_get_addr.
2443 Entry.Node = Argument;
2444 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2445 Args.push_back(Entry);
2447 // FIXME: is there useful debug info available here?
2448 TargetLowering::CallLoweringInfo CLI(DAG);
2449 CLI.setDebugLoc(dl).setChain(Chain)
2450 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2451 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2454 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2455 return CallResult.first;
2458 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2459 // "local exec" model.
2461 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2463 TLSModel::Model model) const {
2464 const GlobalValue *GV = GA->getGlobal();
2467 SDValue Chain = DAG.getEntryNode();
2468 EVT PtrVT = getPointerTy();
2469 // Get the Thread Pointer
2470 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2472 if (model == TLSModel::InitialExec) {
2473 MachineFunction &MF = DAG.getMachineFunction();
2474 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2475 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2476 // Initial exec model.
2477 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2478 ARMConstantPoolValue *CPV =
2479 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2480 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2482 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2483 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2484 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2485 MachinePointerInfo::getConstantPool(),
2486 false, false, false, 0);
2487 Chain = Offset.getValue(1);
2489 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2490 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2492 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2493 MachinePointerInfo::getConstantPool(),
2494 false, false, false, 0);
2497 assert(model == TLSModel::LocalExec);
2498 ARMConstantPoolValue *CPV =
2499 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2500 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2501 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2502 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2503 MachinePointerInfo::getConstantPool(),
2504 false, false, false, 0);
2507 // The address of the thread local variable is the add of the thread
2508 // pointer with the offset of the variable.
2509 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2513 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2514 // TODO: implement the "local dynamic" model
2515 assert(Subtarget->isTargetELF() &&
2516 "TLS not implemented for non-ELF targets");
2517 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2519 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2522 case TLSModel::GeneralDynamic:
2523 case TLSModel::LocalDynamic:
2524 return LowerToTLSGeneralDynamicModel(GA, DAG);
2525 case TLSModel::InitialExec:
2526 case TLSModel::LocalExec:
2527 return LowerToTLSExecModels(GA, DAG, model);
2529 llvm_unreachable("bogus TLS model");
2532 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2533 SelectionDAG &DAG) const {
2534 EVT PtrVT = getPointerTy();
2536 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2537 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2538 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2539 ARMConstantPoolValue *CPV =
2540 ARMConstantPoolConstant::Create(GV,
2541 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2542 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2543 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2544 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2546 MachinePointerInfo::getConstantPool(),
2547 false, false, false, 0);
2548 SDValue Chain = Result.getValue(1);
2549 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2550 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2552 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2553 MachinePointerInfo::getGOT(),
2554 false, false, false, 0);
2558 // If we have T2 ops, we can materialize the address directly via movt/movw
2559 // pair. This is always cheaper.
2560 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2562 // FIXME: Once remat is capable of dealing with instructions with register
2563 // operands, expand this into two nodes.
2564 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2565 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2567 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2568 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2569 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2570 MachinePointerInfo::getConstantPool(),
2571 false, false, false, 0);
2575 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2576 SelectionDAG &DAG) const {
2577 EVT PtrVT = getPointerTy();
2579 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2580 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2582 if (Subtarget->useMovt(DAG.getMachineFunction()))
2585 // FIXME: Once remat is capable of dealing with instructions with register
2586 // operands, expand this into multiple nodes
2588 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2590 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2591 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2593 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2594 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2595 MachinePointerInfo::getGOT(), false, false, false, 0);
2599 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2600 SelectionDAG &DAG) const {
2601 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2602 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2603 "Windows on ARM expects to use movw/movt");
2605 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2606 const ARMII::TOF TargetFlags =
2607 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2608 EVT PtrVT = getPointerTy();
2614 // FIXME: Once remat is capable of dealing with instructions with register
2615 // operands, expand this into two nodes.
2616 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2617 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2619 if (GV->hasDLLImportStorageClass())
2620 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2621 MachinePointerInfo::getGOT(), false, false, false, 0);
2625 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2626 SelectionDAG &DAG) const {
2627 assert(Subtarget->isTargetELF() &&
2628 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2629 MachineFunction &MF = DAG.getMachineFunction();
2630 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2631 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2632 EVT PtrVT = getPointerTy();
2634 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2635 ARMConstantPoolValue *CPV =
2636 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2637 ARMPCLabelIndex, PCAdj);
2638 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2639 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2640 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2641 MachinePointerInfo::getConstantPool(),
2642 false, false, false, 0);
2643 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2644 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2648 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2650 SDValue Val = DAG.getConstant(0, MVT::i32);
2651 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2652 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2653 Op.getOperand(1), Val);
2657 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2659 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2660 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2664 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2665 const ARMSubtarget *Subtarget) const {
2666 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2669 default: return SDValue(); // Don't custom lower most intrinsics.
2670 case Intrinsic::arm_rbit: {
2671 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2672 "RBIT intrinsic must have i32 type!");
2673 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2675 case Intrinsic::arm_thread_pointer: {
2676 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2677 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2679 case Intrinsic::eh_sjlj_lsda: {
2680 MachineFunction &MF = DAG.getMachineFunction();
2681 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2682 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2683 EVT PtrVT = getPointerTy();
2684 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2686 unsigned PCAdj = (RelocM != Reloc::PIC_)
2687 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2688 ARMConstantPoolValue *CPV =
2689 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2690 ARMCP::CPLSDA, PCAdj);
2691 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2692 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2694 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2695 MachinePointerInfo::getConstantPool(),
2696 false, false, false, 0);
2698 if (RelocM == Reloc::PIC_) {
2699 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2700 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2704 case Intrinsic::arm_neon_vmulls:
2705 case Intrinsic::arm_neon_vmullu: {
2706 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2707 ? ARMISD::VMULLs : ARMISD::VMULLu;
2708 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2709 Op.getOperand(1), Op.getOperand(2));
2714 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2715 const ARMSubtarget *Subtarget) {
2716 // FIXME: handle "fence singlethread" more efficiently.
2718 if (!Subtarget->hasDataBarrier()) {
2719 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2720 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2722 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2723 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2724 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2725 DAG.getConstant(0, MVT::i32));
2728 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2729 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2730 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2731 if (Subtarget->isMClass()) {
2732 // Only a full system barrier exists in the M-class architectures.
2733 Domain = ARM_MB::SY;
2734 } else if (Subtarget->isSwift() && Ord == Release) {
2735 // Swift happens to implement ISHST barriers in a way that's compatible with
2736 // Release semantics but weaker than ISH so we'd be fools not to use
2737 // it. Beware: other processors probably don't!
2738 Domain = ARM_MB::ISHST;
2741 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2742 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2743 DAG.getConstant(Domain, MVT::i32));
2746 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2747 const ARMSubtarget *Subtarget) {
2748 // ARM pre v5TE and Thumb1 does not have preload instructions.
2749 if (!(Subtarget->isThumb2() ||
2750 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2751 // Just preserve the chain.
2752 return Op.getOperand(0);
2755 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2757 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2758 // ARMv7 with MP extension has PLDW.
2759 return Op.getOperand(0);
2761 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2762 if (Subtarget->isThumb()) {
2764 isRead = ~isRead & 1;
2765 isData = ~isData & 1;
2768 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2769 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2770 DAG.getConstant(isData, MVT::i32));
2773 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2774 MachineFunction &MF = DAG.getMachineFunction();
2775 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2777 // vastart just stores the address of the VarArgsFrameIndex slot into the
2778 // memory location argument.
2780 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2781 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2782 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2783 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2784 MachinePointerInfo(SV), false, false, 0);
2788 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2789 SDValue &Root, SelectionDAG &DAG,
2791 MachineFunction &MF = DAG.getMachineFunction();
2792 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2794 const TargetRegisterClass *RC;
2795 if (AFI->isThumb1OnlyFunction())
2796 RC = &ARM::tGPRRegClass;
2798 RC = &ARM::GPRRegClass;
2800 // Transform the arguments stored in physical registers into virtual ones.
2801 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2802 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2805 if (NextVA.isMemLoc()) {
2806 MachineFrameInfo *MFI = MF.getFrameInfo();
2807 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2809 // Create load node to retrieve arguments from the stack.
2810 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2811 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2812 MachinePointerInfo::getFixedStack(FI),
2813 false, false, false, 0);
2815 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2816 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2818 if (!Subtarget->isLittle())
2819 std::swap (ArgValue, ArgValue2);
2820 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2824 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2825 unsigned InRegsParamRecordIdx,
2827 unsigned &ArgRegsSize,
2828 unsigned &ArgRegsSaveSize)
2831 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2832 unsigned RBegin, REnd;
2833 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2834 NumGPRs = REnd - RBegin;
2836 unsigned int firstUnalloced;
2837 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs);
2838 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2841 unsigned Align = Subtarget->getFrameLowering()->getStackAlignment();
2842 ArgRegsSize = NumGPRs * 4;
2844 // If parameter is split between stack and GPRs...
2845 if (NumGPRs && Align > 4 &&
2846 (ArgRegsSize < ArgSize ||
2847 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2848 // Add padding for part of param recovered from GPRs. For example,
2849 // if Align == 8, its last byte must be at address K*8 - 1.
2850 // We need to do it, since remained (stack) part of parameter has
2851 // stack alignment, and we need to "attach" "GPRs head" without gaps
2854 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2855 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2857 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2859 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2860 ArgRegsSaveSize = ArgRegsSize + Padding;
2862 // We don't need to extend regs save size for byval parameters if they
2863 // are passed via GPRs only.
2864 ArgRegsSaveSize = ArgRegsSize;
2867 // The remaining GPRs hold either the beginning of variable-argument
2868 // data, or the beginning of an aggregate passed by value (usually
2869 // byval). Either way, we allocate stack slots adjacent to the data
2870 // provided by our caller, and store the unallocated registers there.
2871 // If this is a variadic function, the va_list pointer will begin with
2872 // these values; otherwise, this reassembles a (byval) structure that
2873 // was split between registers and memory.
2874 // Return: The frame index registers were stored into.
2876 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2877 SDLoc dl, SDValue &Chain,
2878 const Value *OrigArg,
2879 unsigned InRegsParamRecordIdx,
2880 unsigned OffsetFromOrigArg,
2884 unsigned ByValStoreOffset,
2885 unsigned TotalArgRegsSaveSize) const {
2887 // Currently, two use-cases possible:
2888 // Case #1. Non-var-args function, and we meet first byval parameter.
2889 // Setup first unallocated register as first byval register;
2890 // eat all remained registers
2891 // (these two actions are performed by HandleByVal method).
2892 // Then, here, we initialize stack frame with
2893 // "store-reg" instructions.
2894 // Case #2. Var-args function, that doesn't contain byval parameters.
2895 // The same: eat all remained unallocated registers,
2896 // initialize stack frame.
2898 MachineFunction &MF = DAG.getMachineFunction();
2899 MachineFrameInfo *MFI = MF.getFrameInfo();
2900 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2901 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2902 unsigned RBegin, REnd;
2903 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2904 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2905 firstRegToSaveIndex = RBegin - ARM::R0;
2906 lastRegToSaveIndex = REnd - ARM::R0;
2908 firstRegToSaveIndex = CCInfo.getFirstUnallocated(GPRArgRegs);
2909 lastRegToSaveIndex = 4;
2912 unsigned ArgRegsSize, ArgRegsSaveSize;
2913 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2914 ArgRegsSize, ArgRegsSaveSize);
2916 // Store any by-val regs to their spots on the stack so that they may be
2917 // loaded by deferencing the result of formal parameter pointer or va_next.
2918 // Note: once stack area for byval/varargs registers
2919 // was initialized, it can't be initialized again.
2920 if (ArgRegsSaveSize) {
2921 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2924 assert(AFI->getStoredByValParamsPadding() == 0 &&
2925 "The only parameter may be padded.");
2926 AFI->setStoredByValParamsPadding(Padding);
2929 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2932 (int64_t)TotalArgRegsSaveSize,
2934 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2936 MFI->CreateFixedObject(Padding,
2937 ArgOffset + ByValStoreOffset -
2938 (int64_t)ArgRegsSaveSize,
2942 SmallVector<SDValue, 4> MemOps;
2943 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2944 ++firstRegToSaveIndex, ++i) {
2945 const TargetRegisterClass *RC;
2946 if (AFI->isThumb1OnlyFunction())
2947 RC = &ARM::tGPRRegClass;
2949 RC = &ARM::GPRRegClass;
2951 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2952 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2954 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2955 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2957 MemOps.push_back(Store);
2958 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2959 DAG.getConstant(4, getPointerTy()));
2962 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2964 if (!MemOps.empty())
2965 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2969 // We cannot allocate a zero-byte object for the first variadic argument,
2970 // so just make up a size.
2973 // This will point to the next argument passed via stack.
2974 return MFI->CreateFixedObject(
2975 ArgSize, ArgOffset, !ForceMutable);
2979 // Setup stack frame, the va_list pointer will start from.
2981 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2982 SDLoc dl, SDValue &Chain,
2984 unsigned TotalArgRegsSaveSize,
2985 bool ForceMutable) const {
2986 MachineFunction &MF = DAG.getMachineFunction();
2987 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2989 // Try to store any remaining integer argument regs
2990 // to their spots on the stack so that they may be loaded by deferencing
2991 // the result of va_next.
2992 // If there is no regs to be stored, just point address after last
2993 // argument passed via stack.
2995 StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2996 CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2997 0, TotalArgRegsSaveSize);
2999 AFI->setVarArgsFrameIndex(FrameIndex);
3003 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3004 CallingConv::ID CallConv, bool isVarArg,
3005 const SmallVectorImpl<ISD::InputArg>
3007 SDLoc dl, SelectionDAG &DAG,
3008 SmallVectorImpl<SDValue> &InVals)
3010 MachineFunction &MF = DAG.getMachineFunction();
3011 MachineFrameInfo *MFI = MF.getFrameInfo();
3013 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3015 // Assign locations to all of the incoming arguments.
3016 SmallVector<CCValAssign, 16> ArgLocs;
3017 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3018 *DAG.getContext(), Prologue);
3019 CCInfo.AnalyzeFormalArguments(Ins,
3020 CCAssignFnForNode(CallConv, /* Return*/ false,
3023 SmallVector<SDValue, 16> ArgValues;
3024 int lastInsIndex = -1;
3026 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3027 unsigned CurArgIdx = 0;
3029 // Initially ArgRegsSaveSize is zero.
3030 // Then we increase this value each time we meet byval parameter.
3031 // We also increase this value in case of varargs function.
3032 AFI->setArgRegsSaveSize(0);
3034 unsigned ByValStoreOffset = 0;
3035 unsigned TotalArgRegsSaveSize = 0;
3036 unsigned ArgRegsSaveSizeMaxAlign = 4;
3038 // Calculate the amount of stack space that we need to allocate to store
3039 // byval and variadic arguments that are passed in registers.
3040 // We need to know this before we allocate the first byval or variadic
3041 // argument, as they will be allocated a stack slot below the CFA (Canonical
3042 // Frame Address, the stack pointer at entry to the function).
3043 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3044 CCValAssign &VA = ArgLocs[i];
3045 if (VA.isMemLoc()) {
3046 int index = VA.getValNo();
3047 if (index != lastInsIndex) {
3048 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3049 if (Flags.isByVal()) {
3050 unsigned ExtraArgRegsSize;
3051 unsigned ExtraArgRegsSaveSize;
3052 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProcessed(),
3053 Flags.getByValSize(),
3054 ExtraArgRegsSize, ExtraArgRegsSaveSize);
3056 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3057 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3058 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3059 CCInfo.nextInRegsParam();
3061 lastInsIndex = index;
3065 CCInfo.rewindByValRegsInfo();
3067 if (isVarArg && MFI->hasVAStart()) {
3068 unsigned ExtraArgRegsSize;
3069 unsigned ExtraArgRegsSaveSize;
3070 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3071 ExtraArgRegsSize, ExtraArgRegsSaveSize);
3072 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3074 // If the arg regs save area contains N-byte aligned values, the
3075 // bottom of it must be at least N-byte aligned.
3076 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3077 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3079 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3080 CCValAssign &VA = ArgLocs[i];
3081 if (Ins[VA.getValNo()].isOrigArg()) {
3082 std::advance(CurOrigArg,
3083 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3084 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3086 // Arguments stored in registers.
3087 if (VA.isRegLoc()) {
3088 EVT RegVT = VA.getLocVT();
3090 if (VA.needsCustom()) {
3091 // f64 and vector types are split up into multiple registers or
3092 // combinations of registers and stack slots.
3093 if (VA.getLocVT() == MVT::v2f64) {
3094 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3096 VA = ArgLocs[++i]; // skip ahead to next loc
3098 if (VA.isMemLoc()) {
3099 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3100 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3101 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3102 MachinePointerInfo::getFixedStack(FI),
3103 false, false, false, 0);
3105 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3108 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3109 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3110 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3111 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3112 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3114 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3117 const TargetRegisterClass *RC;
3119 if (RegVT == MVT::f32)
3120 RC = &ARM::SPRRegClass;
3121 else if (RegVT == MVT::f64)
3122 RC = &ARM::DPRRegClass;
3123 else if (RegVT == MVT::v2f64)
3124 RC = &ARM::QPRRegClass;
3125 else if (RegVT == MVT::i32)
3126 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3127 : &ARM::GPRRegClass;
3129 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3131 // Transform the arguments in physical registers into virtual ones.
3132 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3133 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3136 // If this is an 8 or 16-bit value, it is really passed promoted
3137 // to 32 bits. Insert an assert[sz]ext to capture this, then
3138 // truncate to the right size.
3139 switch (VA.getLocInfo()) {
3140 default: llvm_unreachable("Unknown loc info!");
3141 case CCValAssign::Full: break;
3142 case CCValAssign::BCvt:
3143 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3145 case CCValAssign::SExt:
3146 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3147 DAG.getValueType(VA.getValVT()));
3148 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3150 case CCValAssign::ZExt:
3151 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3152 DAG.getValueType(VA.getValVT()));
3153 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3157 InVals.push_back(ArgValue);
3159 } else { // VA.isRegLoc()
3162 assert(VA.isMemLoc());
3163 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3165 int index = VA.getValNo();
3167 // Some Ins[] entries become multiple ArgLoc[] entries.
3168 // Process them only once.
3169 if (index != lastInsIndex)
3171 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3172 // FIXME: For now, all byval parameter objects are marked mutable.
3173 // This can be changed with more analysis.
3174 // In case of tail call optimization mark all arguments mutable.
3175 // Since they could be overwritten by lowering of arguments in case of
3177 if (Flags.isByVal()) {
3178 assert(Ins[index].isOrigArg() &&
3179 "Byval arguments cannot be implicit");
3180 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3182 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3183 int FrameIndex = StoreByValRegs(
3184 CCInfo, DAG, dl, Chain, CurOrigArg,
3186 Ins[VA.getValNo()].PartOffset,
3187 VA.getLocMemOffset(),
3188 Flags.getByValSize(),
3189 true /*force mutable frames*/,
3191 TotalArgRegsSaveSize);
3192 ByValStoreOffset += Flags.getByValSize();
3193 ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3194 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3195 CCInfo.nextInRegsParam();
3197 unsigned FIOffset = VA.getLocMemOffset();
3198 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3201 // Create load nodes to retrieve arguments from the stack.
3202 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3203 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3204 MachinePointerInfo::getFixedStack(FI),
3205 false, false, false, 0));
3207 lastInsIndex = index;
3213 if (isVarArg && MFI->hasVAStart())
3214 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3215 CCInfo.getNextStackOffset(),
3216 TotalArgRegsSaveSize);
3218 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3223 /// isFloatingPointZero - Return true if this is +0.0.
3224 static bool isFloatingPointZero(SDValue Op) {
3225 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3226 return CFP->getValueAPF().isPosZero();
3227 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3228 // Maybe this has already been legalized into the constant pool?
3229 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3230 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3231 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3232 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3233 return CFP->getValueAPF().isPosZero();
3235 } else if (Op->getOpcode() == ISD::BITCAST &&
3236 Op->getValueType(0) == MVT::f64) {
3237 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3238 // created by LowerConstantFP().
3239 SDValue BitcastOp = Op->getOperand(0);
3240 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3241 SDValue MoveOp = BitcastOp->getOperand(0);
3242 if (MoveOp->getOpcode() == ISD::TargetConstant &&
3243 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3251 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3252 /// the given operands.
3254 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3255 SDValue &ARMcc, SelectionDAG &DAG,
3257 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3258 unsigned C = RHSC->getZExtValue();
3259 if (!isLegalICmpImmediate(C)) {
3260 // Constant does not fit, try adjusting it by one?
3265 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3266 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3267 RHS = DAG.getConstant(C-1, MVT::i32);
3272 if (C != 0 && isLegalICmpImmediate(C-1)) {
3273 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3274 RHS = DAG.getConstant(C-1, MVT::i32);
3279 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3280 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3281 RHS = DAG.getConstant(C+1, MVT::i32);
3286 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3287 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3288 RHS = DAG.getConstant(C+1, MVT::i32);
3295 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3296 ARMISD::NodeType CompareType;
3299 CompareType = ARMISD::CMP;
3304 CompareType = ARMISD::CMPZ;
3307 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3308 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3311 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3313 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3315 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3317 if (!isFloatingPointZero(RHS))
3318 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3320 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3321 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3324 /// duplicateCmp - Glue values can have only one use, so this function
3325 /// duplicates a comparison node.
3327 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3328 unsigned Opc = Cmp.getOpcode();
3330 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3331 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3333 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3334 Cmp = Cmp.getOperand(0);
3335 Opc = Cmp.getOpcode();
3336 if (Opc == ARMISD::CMPFP)
3337 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3339 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3340 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3342 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3345 std::pair<SDValue, SDValue>
3346 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3347 SDValue &ARMcc) const {
3348 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3350 SDValue Value, OverflowCmp;
3351 SDValue LHS = Op.getOperand(0);
3352 SDValue RHS = Op.getOperand(1);
3355 // FIXME: We are currently always generating CMPs because we don't support
3356 // generating CMN through the backend. This is not as good as the natural
3357 // CMP case because it causes a register dependency and cannot be folded
3360 switch (Op.getOpcode()) {
3362 llvm_unreachable("Unknown overflow instruction!");
3364 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3365 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3366 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3369 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3370 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3371 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3374 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3375 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3376 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3379 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3380 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3381 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3385 return std::make_pair(Value, OverflowCmp);
3390 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3391 // Let legalize expand this if it isn't a legal type yet.
3392 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3395 SDValue Value, OverflowCmp;
3397 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3398 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3399 // We use 0 and 1 as false and true values.
3400 SDValue TVal = DAG.getConstant(1, MVT::i32);
3401 SDValue FVal = DAG.getConstant(0, MVT::i32);
3402 EVT VT = Op.getValueType();
3404 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3405 ARMcc, CCR, OverflowCmp);
3407 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3408 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3412 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3413 SDValue Cond = Op.getOperand(0);
3414 SDValue SelectTrue = Op.getOperand(1);
3415 SDValue SelectFalse = Op.getOperand(2);
3417 unsigned Opc = Cond.getOpcode();
3419 if (Cond.getResNo() == 1 &&
3420 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3421 Opc == ISD::USUBO)) {
3422 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3425 SDValue Value, OverflowCmp;
3427 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3428 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3429 EVT VT = Op.getValueType();
3431 return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3437 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3438 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3440 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3441 const ConstantSDNode *CMOVTrue =
3442 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3443 const ConstantSDNode *CMOVFalse =
3444 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3446 if (CMOVTrue && CMOVFalse) {
3447 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3448 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3452 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3454 False = SelectFalse;
3455 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3460 if (True.getNode() && False.getNode()) {
3461 EVT VT = Op.getValueType();
3462 SDValue ARMcc = Cond.getOperand(2);
3463 SDValue CCR = Cond.getOperand(3);
3464 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3465 assert(True.getValueType() == VT);
3466 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3471 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3472 // undefined bits before doing a full-word comparison with zero.
3473 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3474 DAG.getConstant(1, Cond.getValueType()));
3476 return DAG.getSelectCC(dl, Cond,
3477 DAG.getConstant(0, Cond.getValueType()),
3478 SelectTrue, SelectFalse, ISD::SETNE);
3481 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3482 if (CC == ISD::SETNE)
3484 return ISD::getSetCCInverse(CC, true);
3487 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3488 bool &swpCmpOps, bool &swpVselOps) {
3489 // Start by selecting the GE condition code for opcodes that return true for
3491 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3493 CondCode = ARMCC::GE;
3495 // and GT for opcodes that return false for 'equality'.
3496 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3498 CondCode = ARMCC::GT;
3500 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3501 // to swap the compare operands.
3502 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3506 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3507 // If we have an unordered opcode, we need to swap the operands to the VSEL
3508 // instruction (effectively negating the condition).
3510 // This also has the effect of swapping which one of 'less' or 'greater'
3511 // returns true, so we also swap the compare operands. It also switches
3512 // whether we return true for 'equality', so we compensate by picking the
3513 // opposite condition code to our original choice.
3514 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3515 CC == ISD::SETUGT) {
3516 swpCmpOps = !swpCmpOps;
3517 swpVselOps = !swpVselOps;
3518 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3521 // 'ordered' is 'anything but unordered', so use the VS condition code and
3522 // swap the VSEL operands.
3523 if (CC == ISD::SETO) {
3524 CondCode = ARMCC::VS;
3528 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3529 // code and swap the VSEL operands.
3530 if (CC == ISD::SETUNE) {
3531 CondCode = ARMCC::EQ;
3536 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3537 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3538 SDValue Cmp, SelectionDAG &DAG) const {
3539 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3540 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3541 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3542 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3543 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3545 SDValue TrueLow = TrueVal.getValue(0);
3546 SDValue TrueHigh = TrueVal.getValue(1);
3547 SDValue FalseLow = FalseVal.getValue(0);
3548 SDValue FalseHigh = FalseVal.getValue(1);
3550 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3552 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3553 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3555 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3557 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3562 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3563 EVT VT = Op.getValueType();
3564 SDValue LHS = Op.getOperand(0);
3565 SDValue RHS = Op.getOperand(1);
3566 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3567 SDValue TrueVal = Op.getOperand(2);
3568 SDValue FalseVal = Op.getOperand(3);
3571 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3572 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3575 // If softenSetCCOperands only returned one value, we should compare it to
3577 if (!RHS.getNode()) {
3578 RHS = DAG.getConstant(0, LHS.getValueType());
3583 if (LHS.getValueType() == MVT::i32) {
3584 // Try to generate VSEL on ARMv8.
3585 // The VSEL instruction can't use all the usual ARM condition
3586 // codes: it only has two bits to select the condition code, so it's
3587 // constrained to use only GE, GT, VS and EQ.
3589 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3590 // swap the operands of the previous compare instruction (effectively
3591 // inverting the compare condition, swapping 'less' and 'greater') and
3592 // sometimes need to swap the operands to the VSEL (which inverts the
3593 // condition in the sense of firing whenever the previous condition didn't)
3594 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3595 TrueVal.getValueType() == MVT::f64)) {
3596 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3597 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3598 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3599 CC = getInverseCCForVSEL(CC);
3600 std::swap(TrueVal, FalseVal);
3605 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3606 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3607 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3610 ARMCC::CondCodes CondCode, CondCode2;
3611 FPCCToARMCC(CC, CondCode, CondCode2);
3613 // Try to generate VSEL on ARMv8.
3614 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3615 TrueVal.getValueType() == MVT::f64)) {
3616 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3617 // same operands, as follows:
3618 // c = fcmp [ogt, olt, ugt, ult] a, b
3620 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3621 // handled differently than the original code sequence.
3622 if (getTargetMachine().Options.UnsafeFPMath) {
3623 if (LHS == TrueVal && RHS == FalseVal) {
3624 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3625 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3626 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3627 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3628 } else if (LHS == FalseVal && RHS == TrueVal) {
3629 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3630 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3631 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3632 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3636 bool swpCmpOps = false;
3637 bool swpVselOps = false;
3638 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3640 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3641 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3643 std::swap(LHS, RHS);
3645 std::swap(TrueVal, FalseVal);
3649 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3650 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3651 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3652 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3653 if (CondCode2 != ARMCC::AL) {
3654 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3655 // FIXME: Needs another CMP because flag can have but one use.
3656 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3657 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3662 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3663 /// to morph to an integer compare sequence.
3664 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3665 const ARMSubtarget *Subtarget) {
3666 SDNode *N = Op.getNode();
3667 if (!N->hasOneUse())
3668 // Otherwise it requires moving the value from fp to integer registers.
3670 if (!N->getNumValues())
3672 EVT VT = Op.getValueType();
3673 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3674 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3675 // vmrs are very slow, e.g. cortex-a8.
3678 if (isFloatingPointZero(Op)) {
3682 return ISD::isNormalLoad(N);
3685 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3686 if (isFloatingPointZero(Op))
3687 return DAG.getConstant(0, MVT::i32);
3689 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3690 return DAG.getLoad(MVT::i32, SDLoc(Op),
3691 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3692 Ld->isVolatile(), Ld->isNonTemporal(),
3693 Ld->isInvariant(), Ld->getAlignment());
3695 llvm_unreachable("Unknown VFP cmp argument!");
3698 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3699 SDValue &RetVal1, SDValue &RetVal2) {
3700 if (isFloatingPointZero(Op)) {
3701 RetVal1 = DAG.getConstant(0, MVT::i32);
3702 RetVal2 = DAG.getConstant(0, MVT::i32);
3706 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3707 SDValue Ptr = Ld->getBasePtr();
3708 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3709 Ld->getChain(), Ptr,
3710 Ld->getPointerInfo(),
3711 Ld->isVolatile(), Ld->isNonTemporal(),
3712 Ld->isInvariant(), Ld->getAlignment());
3714 EVT PtrType = Ptr.getValueType();
3715 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3716 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3717 PtrType, Ptr, DAG.getConstant(4, PtrType));
3718 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3719 Ld->getChain(), NewPtr,
3720 Ld->getPointerInfo().getWithOffset(4),
3721 Ld->isVolatile(), Ld->isNonTemporal(),
3722 Ld->isInvariant(), NewAlign);
3726 llvm_unreachable("Unknown VFP cmp argument!");
3729 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3730 /// f32 and even f64 comparisons to integer ones.
3732 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3733 SDValue Chain = Op.getOperand(0);
3734 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3735 SDValue LHS = Op.getOperand(2);
3736 SDValue RHS = Op.getOperand(3);
3737 SDValue Dest = Op.getOperand(4);
3740 bool LHSSeenZero = false;
3741 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3742 bool RHSSeenZero = false;
3743 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3744 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3745 // If unsafe fp math optimization is enabled and there are no other uses of
3746 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3747 // to an integer comparison.
3748 if (CC == ISD::SETOEQ)
3750 else if (CC == ISD::SETUNE)
3753 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3755 if (LHS.getValueType() == MVT::f32) {
3756 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3757 bitcastf32Toi32(LHS, DAG), Mask);
3758 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3759 bitcastf32Toi32(RHS, DAG), Mask);
3760 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3761 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3762 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3763 Chain, Dest, ARMcc, CCR, Cmp);
3768 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3769 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3770 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3771 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3772 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3773 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3774 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3775 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3776 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3782 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3783 SDValue Chain = Op.getOperand(0);
3784 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3785 SDValue LHS = Op.getOperand(2);
3786 SDValue RHS = Op.getOperand(3);
3787 SDValue Dest = Op.getOperand(4);
3790 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3791 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3794 // If softenSetCCOperands only returned one value, we should compare it to
3796 if (!RHS.getNode()) {
3797 RHS = DAG.getConstant(0, LHS.getValueType());
3802 if (LHS.getValueType() == MVT::i32) {
3804 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3805 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3806 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3807 Chain, Dest, ARMcc, CCR, Cmp);
3810 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3812 if (getTargetMachine().Options.UnsafeFPMath &&
3813 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3814 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3815 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3816 if (Result.getNode())
3820 ARMCC::CondCodes CondCode, CondCode2;
3821 FPCCToARMCC(CC, CondCode, CondCode2);
3823 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3824 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3825 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3826 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3827 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3828 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3829 if (CondCode2 != ARMCC::AL) {
3830 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3831 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3832 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3837 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3838 SDValue Chain = Op.getOperand(0);
3839 SDValue Table = Op.getOperand(1);
3840 SDValue Index = Op.getOperand(2);
3843 EVT PTy = getPointerTy();
3844 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3845 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3846 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3847 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3848 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3849 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3850 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3851 if (Subtarget->isThumb2()) {
3852 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3853 // which does another jump to the destination. This also makes it easier
3854 // to translate it to TBB / TBH later.
3855 // FIXME: This might not work if the function is extremely large.
3856 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3857 Addr, Op.getOperand(2), JTI, UId);
3859 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3860 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3861 MachinePointerInfo::getJumpTable(),
3862 false, false, false, 0);
3863 Chain = Addr.getValue(1);
3864 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3865 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3867 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3868 MachinePointerInfo::getJumpTable(),
3869 false, false, false, 0);
3870 Chain = Addr.getValue(1);
3871 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3875 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3876 EVT VT = Op.getValueType();
3879 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3880 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3882 return DAG.UnrollVectorOp(Op.getNode());
3885 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3886 "Invalid type for custom lowering!");
3887 if (VT != MVT::v4i16)
3888 return DAG.UnrollVectorOp(Op.getNode());
3890 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3891 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3894 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3895 EVT VT = Op.getValueType();
3897 return LowerVectorFP_TO_INT(Op, DAG);
3899 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3901 if (Op.getOpcode() == ISD::FP_TO_SINT)
3902 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3905 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3907 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3908 /*isSigned*/ false, SDLoc(Op)).first;
3914 switch (Op.getOpcode()) {
3915 default: llvm_unreachable("Invalid opcode!");
3916 case ISD::FP_TO_SINT:
3917 Opc = ARMISD::FTOSI;
3919 case ISD::FP_TO_UINT:
3920 Opc = ARMISD::FTOUI;
3923 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3924 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3927 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3928 EVT VT = Op.getValueType();
3931 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3932 if (VT.getVectorElementType() == MVT::f32)
3934 return DAG.UnrollVectorOp(Op.getNode());
3937 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3938 "Invalid type for custom lowering!");
3939 if (VT != MVT::v4f32)
3940 return DAG.UnrollVectorOp(Op.getNode());
3944 switch (Op.getOpcode()) {
3945 default: llvm_unreachable("Invalid opcode!");
3946 case ISD::SINT_TO_FP:
3947 CastOpc = ISD::SIGN_EXTEND;
3948 Opc = ISD::SINT_TO_FP;
3950 case ISD::UINT_TO_FP:
3951 CastOpc = ISD::ZERO_EXTEND;
3952 Opc = ISD::UINT_TO_FP;
3956 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3957 return DAG.getNode(Opc, dl, VT, Op);
3960 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3961 EVT VT = Op.getValueType();
3963 return LowerVectorINT_TO_FP(Op, DAG);
3965 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3967 if (Op.getOpcode() == ISD::SINT_TO_FP)
3968 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3971 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3973 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3974 /*isSigned*/ false, SDLoc(Op)).first;
3980 switch (Op.getOpcode()) {
3981 default: llvm_unreachable("Invalid opcode!");
3982 case ISD::SINT_TO_FP:
3983 Opc = ARMISD::SITOF;
3985 case ISD::UINT_TO_FP:
3986 Opc = ARMISD::UITOF;
3990 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3991 return DAG.getNode(Opc, dl, VT, Op);
3994 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3995 // Implement fcopysign with a fabs and a conditional fneg.
3996 SDValue Tmp0 = Op.getOperand(0);
3997 SDValue Tmp1 = Op.getOperand(1);
3999 EVT VT = Op.getValueType();
4000 EVT SrcVT = Tmp1.getValueType();
4001 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4002 Tmp0.getOpcode() == ARMISD::VMOVDRR;
4003 bool UseNEON = !InGPR && Subtarget->hasNEON();
4006 // Use VBSL to copy the sign bit.
4007 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4008 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4009 DAG.getTargetConstant(EncodedVal, MVT::i32));
4010 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4012 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4013 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4014 DAG.getConstant(32, MVT::i32));
4015 else /*if (VT == MVT::f32)*/
4016 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4017 if (SrcVT == MVT::f32) {
4018 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4020 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4021 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4022 DAG.getConstant(32, MVT::i32));
4023 } else if (VT == MVT::f32)
4024 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4025 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4026 DAG.getConstant(32, MVT::i32));
4027 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4028 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4030 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4032 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4033 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4034 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4036 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4037 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4038 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4039 if (VT == MVT::f32) {
4040 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4041 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4042 DAG.getConstant(0, MVT::i32));
4044 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4050 // Bitcast operand 1 to i32.
4051 if (SrcVT == MVT::f64)
4052 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4054 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4056 // Or in the signbit with integer operations.
4057 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
4058 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
4059 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4060 if (VT == MVT::f32) {
4061 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4062 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4063 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4064 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4067 // f64: Or the high part with signbit and then combine two parts.
4068 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4070 SDValue Lo = Tmp0.getValue(0);
4071 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4072 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4073 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4076 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4077 MachineFunction &MF = DAG.getMachineFunction();
4078 MachineFrameInfo *MFI = MF.getFrameInfo();
4079 MFI->setReturnAddressIsTaken(true);
4081 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4084 EVT VT = Op.getValueType();
4086 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4088 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4089 SDValue Offset = DAG.getConstant(4, MVT::i32);
4090 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4091 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4092 MachinePointerInfo(), false, false, false, 0);
4095 // Return LR, which contains the return address. Mark it an implicit live-in.
4096 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4097 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4100 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4101 const ARMBaseRegisterInfo &ARI =
4102 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4103 MachineFunction &MF = DAG.getMachineFunction();
4104 MachineFrameInfo *MFI = MF.getFrameInfo();
4105 MFI->setFrameAddressIsTaken(true);
4107 EVT VT = Op.getValueType();
4108 SDLoc dl(Op); // FIXME probably not meaningful
4109 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4110 unsigned FrameReg = ARI.getFrameRegister(MF);
4111 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4113 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4114 MachinePointerInfo(),
4115 false, false, false, 0);
4119 // FIXME? Maybe this could be a TableGen attribute on some registers and
4120 // this table could be generated automatically from RegInfo.
4121 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4123 unsigned Reg = StringSwitch<unsigned>(RegName)
4124 .Case("sp", ARM::SP)
4128 report_fatal_error("Invalid register name global variable");
4131 /// ExpandBITCAST - If the target supports VFP, this function is called to
4132 /// expand a bit convert where either the source or destination type is i64 to
4133 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4134 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4135 /// vectors), since the legalizer won't know what to do with that.
4136 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4137 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4139 SDValue Op = N->getOperand(0);
4141 // This function is only supposed to be called for i64 types, either as the
4142 // source or destination of the bit convert.
4143 EVT SrcVT = Op.getValueType();
4144 EVT DstVT = N->getValueType(0);
4145 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4146 "ExpandBITCAST called for non-i64 type");
4148 // Turn i64->f64 into VMOVDRR.
4149 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4150 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4151 DAG.getConstant(0, MVT::i32));
4152 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4153 DAG.getConstant(1, MVT::i32));
4154 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4155 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4158 // Turn f64->i64 into VMOVRRD.
4159 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4161 if (TLI.isBigEndian() && SrcVT.isVector() &&
4162 SrcVT.getVectorNumElements() > 1)
4163 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4164 DAG.getVTList(MVT::i32, MVT::i32),
4165 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4167 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4168 DAG.getVTList(MVT::i32, MVT::i32), Op);
4169 // Merge the pieces into a single i64 value.
4170 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4176 /// getZeroVector - Returns a vector of specified type with all zero elements.
4177 /// Zero vectors are used to represent vector negation and in those cases
4178 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4179 /// not support i64 elements, so sometimes the zero vectors will need to be
4180 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4182 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4183 assert(VT.isVector() && "Expected a vector type");
4184 // The canonical modified immediate encoding of a zero vector is....0!
4185 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4186 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4187 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4188 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4191 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4192 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4193 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4194 SelectionDAG &DAG) const {
4195 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4196 EVT VT = Op.getValueType();
4197 unsigned VTBits = VT.getSizeInBits();
4199 SDValue ShOpLo = Op.getOperand(0);
4200 SDValue ShOpHi = Op.getOperand(1);
4201 SDValue ShAmt = Op.getOperand(2);
4203 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4205 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4207 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4208 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4209 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4210 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4211 DAG.getConstant(VTBits, MVT::i32));
4212 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4213 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4214 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4216 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4217 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4219 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4220 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4223 SDValue Ops[2] = { Lo, Hi };
4224 return DAG.getMergeValues(Ops, dl);
4227 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4228 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4229 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4230 SelectionDAG &DAG) const {
4231 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4232 EVT VT = Op.getValueType();
4233 unsigned VTBits = VT.getSizeInBits();
4235 SDValue ShOpLo = Op.getOperand(0);
4236 SDValue ShOpHi = Op.getOperand(1);
4237 SDValue ShAmt = Op.getOperand(2);
4240 assert(Op.getOpcode() == ISD::SHL_PARTS);
4241 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4242 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4243 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4244 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4245 DAG.getConstant(VTBits, MVT::i32));
4246 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4247 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4249 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4250 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4251 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4253 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4254 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4257 SDValue Ops[2] = { Lo, Hi };
4258 return DAG.getMergeValues(Ops, dl);
4261 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4262 SelectionDAG &DAG) const {
4263 // The rounding mode is in bits 23:22 of the FPSCR.
4264 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4265 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4266 // so that the shift + and get folded into a bitfield extract.
4268 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4269 DAG.getConstant(Intrinsic::arm_get_fpscr,
4271 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4272 DAG.getConstant(1U << 22, MVT::i32));
4273 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4274 DAG.getConstant(22, MVT::i32));
4275 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4276 DAG.getConstant(3, MVT::i32));
4279 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4280 const ARMSubtarget *ST) {
4281 EVT VT = N->getValueType(0);
4284 if (!ST->hasV6T2Ops())
4287 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4288 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4291 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4292 /// for each 16-bit element from operand, repeated. The basic idea is to
4293 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4295 /// Trace for v4i16:
4296 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4297 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4298 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4299 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4300 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4301 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4302 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4303 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4304 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4305 EVT VT = N->getValueType(0);
4308 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4309 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4310 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4311 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4312 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4313 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4316 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4317 /// bit-count for each 16-bit element from the operand. We need slightly
4318 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4319 /// 64/128-bit registers.
4321 /// Trace for v4i16:
4322 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4323 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4324 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4325 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4326 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4327 EVT VT = N->getValueType(0);
4330 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4331 if (VT.is64BitVector()) {
4332 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4333 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4334 DAG.getIntPtrConstant(0));
4336 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4337 BitCounts, DAG.getIntPtrConstant(0));
4338 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4342 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4343 /// bit-count for each 32-bit element from the operand. The idea here is
4344 /// to split the vector into 16-bit elements, leverage the 16-bit count
4345 /// routine, and then combine the results.
4347 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4348 /// input = [v0 v1 ] (vi: 32-bit elements)
4349 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4350 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4351 /// vrev: N0 = [k1 k0 k3 k2 ]
4353 /// N1 =+[k1 k0 k3 k2 ]
4355 /// N2 =+[k1 k3 k0 k2 ]
4357 /// Extended =+[k1 k3 k0 k2 ]
4359 /// Extracted=+[k1 k3 ]
4361 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4362 EVT VT = N->getValueType(0);
4365 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4367 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4368 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4369 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4370 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4371 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4373 if (VT.is64BitVector()) {
4374 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4375 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4376 DAG.getIntPtrConstant(0));
4378 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4379 DAG.getIntPtrConstant(0));
4380 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4384 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4385 const ARMSubtarget *ST) {
4386 EVT VT = N->getValueType(0);
4388 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4389 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4390 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4391 "Unexpected type for custom ctpop lowering");
4393 if (VT.getVectorElementType() == MVT::i32)
4394 return lowerCTPOP32BitElements(N, DAG);
4396 return lowerCTPOP16BitElements(N, DAG);
4399 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4400 const ARMSubtarget *ST) {
4401 EVT VT = N->getValueType(0);
4407 // Lower vector shifts on NEON to use VSHL.
4408 assert(ST->hasNEON() && "unexpected vector shift");
4410 // Left shifts translate directly to the vshiftu intrinsic.
4411 if (N->getOpcode() == ISD::SHL)
4412 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4413 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4414 N->getOperand(0), N->getOperand(1));
4416 assert((N->getOpcode() == ISD::SRA ||
4417 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4419 // NEON uses the same intrinsics for both left and right shifts. For
4420 // right shifts, the shift amounts are negative, so negate the vector of
4422 EVT ShiftVT = N->getOperand(1).getValueType();
4423 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4424 getZeroVector(ShiftVT, DAG, dl),
4426 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4427 Intrinsic::arm_neon_vshifts :
4428 Intrinsic::arm_neon_vshiftu);
4429 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4430 DAG.getConstant(vshiftInt, MVT::i32),
4431 N->getOperand(0), NegatedCount);
4434 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4435 const ARMSubtarget *ST) {
4436 EVT VT = N->getValueType(0);
4439 // We can get here for a node like i32 = ISD::SHL i32, i64
4443 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4444 "Unknown shift to lower!");
4446 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4447 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4448 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4451 // If we are in thumb mode, we don't have RRX.
4452 if (ST->isThumb1Only()) return SDValue();
4454 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4455 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4456 DAG.getConstant(0, MVT::i32));
4457 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4458 DAG.getConstant(1, MVT::i32));
4460 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4461 // captures the result into a carry flag.
4462 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4463 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4465 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4466 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4468 // Merge the pieces into a single i64 value.
4469 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4472 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4473 SDValue TmpOp0, TmpOp1;
4474 bool Invert = false;
4478 SDValue Op0 = Op.getOperand(0);
4479 SDValue Op1 = Op.getOperand(1);
4480 SDValue CC = Op.getOperand(2);
4481 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4482 EVT VT = Op.getValueType();
4483 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4486 if (Op1.getValueType().isFloatingPoint()) {
4487 switch (SetCCOpcode) {
4488 default: llvm_unreachable("Illegal FP comparison");
4490 case ISD::SETNE: Invert = true; // Fallthrough
4492 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4494 case ISD::SETLT: Swap = true; // Fallthrough
4496 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4498 case ISD::SETLE: Swap = true; // Fallthrough
4500 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4501 case ISD::SETUGE: Swap = true; // Fallthrough
4502 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4503 case ISD::SETUGT: Swap = true; // Fallthrough
4504 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4505 case ISD::SETUEQ: Invert = true; // Fallthrough
4507 // Expand this to (OLT | OGT).
4511 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4512 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4514 case ISD::SETUO: Invert = true; // Fallthrough
4516 // Expand this to (OLT | OGE).
4520 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4521 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4525 // Integer comparisons.
4526 switch (SetCCOpcode) {
4527 default: llvm_unreachable("Illegal integer comparison");
4528 case ISD::SETNE: Invert = true;
4529 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4530 case ISD::SETLT: Swap = true;
4531 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4532 case ISD::SETLE: Swap = true;
4533 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4534 case ISD::SETULT: Swap = true;
4535 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4536 case ISD::SETULE: Swap = true;
4537 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4540 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4541 if (Opc == ARMISD::VCEQ) {
4544 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4546 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4549 // Ignore bitconvert.
4550 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4551 AndOp = AndOp.getOperand(0);
4553 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4555 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4556 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4563 std::swap(Op0, Op1);
4565 // If one of the operands is a constant vector zero, attempt to fold the
4566 // comparison to a specialized compare-against-zero form.
4568 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4570 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4571 if (Opc == ARMISD::VCGE)
4572 Opc = ARMISD::VCLEZ;
4573 else if (Opc == ARMISD::VCGT)
4574 Opc = ARMISD::VCLTZ;
4579 if (SingleOp.getNode()) {
4582 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4584 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4586 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4588 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4590 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4592 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4595 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4598 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4601 Result = DAG.getNOT(dl, Result, VT);
4606 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4607 /// valid vector constant for a NEON instruction with a "modified immediate"
4608 /// operand (e.g., VMOV). If so, return the encoded value.
4609 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4610 unsigned SplatBitSize, SelectionDAG &DAG,
4611 EVT &VT, bool is128Bits, NEONModImmType type) {
4612 unsigned OpCmode, Imm;
4614 // SplatBitSize is set to the smallest size that splats the vector, so a
4615 // zero vector will always have SplatBitSize == 8. However, NEON modified
4616 // immediate instructions others than VMOV do not support the 8-bit encoding
4617 // of a zero vector, and the default encoding of zero is supposed to be the
4622 switch (SplatBitSize) {
4624 if (type != VMOVModImm)
4626 // Any 1-byte value is OK. Op=0, Cmode=1110.
4627 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4630 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4634 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4635 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4636 if ((SplatBits & ~0xff) == 0) {
4637 // Value = 0x00nn: Op=x, Cmode=100x.
4642 if ((SplatBits & ~0xff00) == 0) {
4643 // Value = 0xnn00: Op=x, Cmode=101x.
4645 Imm = SplatBits >> 8;
4651 // NEON's 32-bit VMOV supports splat values where:
4652 // * only one byte is nonzero, or
4653 // * the least significant byte is 0xff and the second byte is nonzero, or
4654 // * the least significant 2 bytes are 0xff and the third is nonzero.
4655 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4656 if ((SplatBits & ~0xff) == 0) {
4657 // Value = 0x000000nn: Op=x, Cmode=000x.
4662 if ((SplatBits & ~0xff00) == 0) {
4663 // Value = 0x0000nn00: Op=x, Cmode=001x.
4665 Imm = SplatBits >> 8;
4668 if ((SplatBits & ~0xff0000) == 0) {
4669 // Value = 0x00nn0000: Op=x, Cmode=010x.
4671 Imm = SplatBits >> 16;
4674 if ((SplatBits & ~0xff000000) == 0) {
4675 // Value = 0xnn000000: Op=x, Cmode=011x.
4677 Imm = SplatBits >> 24;
4681 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4682 if (type == OtherModImm) return SDValue();
4684 if ((SplatBits & ~0xffff) == 0 &&
4685 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4686 // Value = 0x0000nnff: Op=x, Cmode=1100.
4688 Imm = SplatBits >> 8;
4692 if ((SplatBits & ~0xffffff) == 0 &&
4693 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4694 // Value = 0x00nnffff: Op=x, Cmode=1101.
4696 Imm = SplatBits >> 16;
4700 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4701 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4702 // VMOV.I32. A (very) minor optimization would be to replicate the value
4703 // and fall through here to test for a valid 64-bit splat. But, then the
4704 // caller would also need to check and handle the change in size.
4708 if (type != VMOVModImm)
4710 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4711 uint64_t BitMask = 0xff;
4713 unsigned ImmMask = 1;
4715 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4716 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4719 } else if ((SplatBits & BitMask) != 0) {
4726 if (DAG.getTargetLoweringInfo().isBigEndian())
4727 // swap higher and lower 32 bit word
4728 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4730 // Op=1, Cmode=1110.
4732 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4737 llvm_unreachable("unexpected size for isNEONModifiedImm");
4740 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4741 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4744 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4745 const ARMSubtarget *ST) const {
4749 bool IsDouble = Op.getValueType() == MVT::f64;
4750 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4752 // Use the default (constant pool) lowering for double constants when we have
4754 if (IsDouble && Subtarget->isFPOnlySP())
4757 // Try splatting with a VMOV.f32...
4758 APFloat FPVal = CFP->getValueAPF();
4759 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4762 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4763 // We have code in place to select a valid ConstantFP already, no need to
4768 // It's a float and we are trying to use NEON operations where
4769 // possible. Lower it to a splat followed by an extract.
4771 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4772 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4774 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4775 DAG.getConstant(0, MVT::i32));
4778 // The rest of our options are NEON only, make sure that's allowed before
4780 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4784 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4786 // It wouldn't really be worth bothering for doubles except for one very
4787 // important value, which does happen to match: 0.0. So make sure we don't do
4789 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4792 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4793 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4795 if (NewVal != SDValue()) {
4797 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4800 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4802 // It's a float: cast and extract a vector element.
4803 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4805 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4806 DAG.getConstant(0, MVT::i32));
4809 // Finally, try a VMVN.i32
4810 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4812 if (NewVal != SDValue()) {
4814 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4817 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4819 // It's a float: cast and extract a vector element.
4820 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4822 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4823 DAG.getConstant(0, MVT::i32));
4829 // check if an VEXT instruction can handle the shuffle mask when the
4830 // vector sources of the shuffle are the same.
4831 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4832 unsigned NumElts = VT.getVectorNumElements();
4834 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4840 // If this is a VEXT shuffle, the immediate value is the index of the first
4841 // element. The other shuffle indices must be the successive elements after
4843 unsigned ExpectedElt = Imm;
4844 for (unsigned i = 1; i < NumElts; ++i) {
4845 // Increment the expected index. If it wraps around, just follow it
4846 // back to index zero and keep going.
4848 if (ExpectedElt == NumElts)
4851 if (M[i] < 0) continue; // ignore UNDEF indices
4852 if (ExpectedElt != static_cast<unsigned>(M[i]))
4860 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4861 bool &ReverseVEXT, unsigned &Imm) {
4862 unsigned NumElts = VT.getVectorNumElements();
4863 ReverseVEXT = false;
4865 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4871 // If this is a VEXT shuffle, the immediate value is the index of the first
4872 // element. The other shuffle indices must be the successive elements after
4874 unsigned ExpectedElt = Imm;
4875 for (unsigned i = 1; i < NumElts; ++i) {
4876 // Increment the expected index. If it wraps around, it may still be
4877 // a VEXT but the source vectors must be swapped.
4879 if (ExpectedElt == NumElts * 2) {
4884 if (M[i] < 0) continue; // ignore UNDEF indices
4885 if (ExpectedElt != static_cast<unsigned>(M[i]))
4889 // Adjust the index value if the source operands will be swapped.
4896 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4897 /// instruction with the specified blocksize. (The order of the elements
4898 /// within each block of the vector is reversed.)
4899 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4900 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4901 "Only possible block sizes for VREV are: 16, 32, 64");
4903 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4907 unsigned NumElts = VT.getVectorNumElements();
4908 unsigned BlockElts = M[0] + 1;
4909 // If the first shuffle index is UNDEF, be optimistic.
4911 BlockElts = BlockSize / EltSz;
4913 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4916 for (unsigned i = 0; i < NumElts; ++i) {
4917 if (M[i] < 0) continue; // ignore UNDEF indices
4918 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4925 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4926 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4927 // range, then 0 is placed into the resulting vector. So pretty much any mask
4928 // of 8 elements can work here.
4929 return VT == MVT::v8i8 && M.size() == 8;
4932 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4933 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4937 unsigned NumElts = VT.getVectorNumElements();
4938 WhichResult = (M[0] == 0 ? 0 : 1);
4939 for (unsigned i = 0; i < NumElts; i += 2) {
4940 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4941 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4947 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4948 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4949 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4950 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4951 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4955 unsigned NumElts = VT.getVectorNumElements();
4956 WhichResult = (M[0] == 0 ? 0 : 1);
4957 for (unsigned i = 0; i < NumElts; i += 2) {
4958 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4959 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4965 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4966 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4970 unsigned NumElts = VT.getVectorNumElements();
4971 WhichResult = (M[0] == 0 ? 0 : 1);
4972 for (unsigned i = 0; i != NumElts; ++i) {
4973 if (M[i] < 0) continue; // ignore UNDEF indices
4974 if ((unsigned) M[i] != 2 * i + WhichResult)
4978 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4979 if (VT.is64BitVector() && EltSz == 32)
4985 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4986 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4987 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4988 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4989 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4993 unsigned Half = VT.getVectorNumElements() / 2;
4994 WhichResult = (M[0] == 0 ? 0 : 1);
4995 for (unsigned j = 0; j != 2; ++j) {
4996 unsigned Idx = WhichResult;
4997 for (unsigned i = 0; i != Half; ++i) {
4998 int MIdx = M[i + j * Half];
4999 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5005 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5006 if (VT.is64BitVector() && EltSz == 32)
5012 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5013 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5017 unsigned NumElts = VT.getVectorNumElements();
5018 WhichResult = (M[0] == 0 ? 0 : 1);
5019 unsigned Idx = WhichResult * NumElts / 2;
5020 for (unsigned i = 0; i != NumElts; i += 2) {
5021 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5022 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5027 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5028 if (VT.is64BitVector() && EltSz == 32)
5034 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5035 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5036 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5037 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5038 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5042 unsigned NumElts = VT.getVectorNumElements();
5043 WhichResult = (M[0] == 0 ? 0 : 1);
5044 unsigned Idx = WhichResult * NumElts / 2;
5045 for (unsigned i = 0; i != NumElts; i += 2) {
5046 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5047 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5052 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5053 if (VT.is64BitVector() && EltSz == 32)
5059 /// \return true if this is a reverse operation on an vector.
5060 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5061 unsigned NumElts = VT.getVectorNumElements();
5062 // Make sure the mask has the right size.
5063 if (NumElts != M.size())
5066 // Look for <15, ..., 3, -1, 1, 0>.
5067 for (unsigned i = 0; i != NumElts; ++i)
5068 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5074 // If N is an integer constant that can be moved into a register in one
5075 // instruction, return an SDValue of such a constant (will become a MOV
5076 // instruction). Otherwise return null.
5077 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5078 const ARMSubtarget *ST, SDLoc dl) {
5080 if (!isa<ConstantSDNode>(N))
5082 Val = cast<ConstantSDNode>(N)->getZExtValue();
5084 if (ST->isThumb1Only()) {
5085 if (Val <= 255 || ~Val <= 255)
5086 return DAG.getConstant(Val, MVT::i32);
5088 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5089 return DAG.getConstant(Val, MVT::i32);
5094 // If this is a case we can't handle, return null and let the default
5095 // expansion code take care of it.
5096 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5097 const ARMSubtarget *ST) const {
5098 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5100 EVT VT = Op.getValueType();
5102 APInt SplatBits, SplatUndef;
5103 unsigned SplatBitSize;
5105 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5106 if (SplatBitSize <= 64) {
5107 // Check if an immediate VMOV works.
5109 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5110 SplatUndef.getZExtValue(), SplatBitSize,
5111 DAG, VmovVT, VT.is128BitVector(),
5113 if (Val.getNode()) {
5114 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5115 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5118 // Try an immediate VMVN.
5119 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5120 Val = isNEONModifiedImm(NegatedImm,
5121 SplatUndef.getZExtValue(), SplatBitSize,
5122 DAG, VmovVT, VT.is128BitVector(),
5124 if (Val.getNode()) {
5125 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5126 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5129 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5130 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5131 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5133 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5134 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5140 // Scan through the operands to see if only one value is used.
5142 // As an optimisation, even if more than one value is used it may be more
5143 // profitable to splat with one value then change some lanes.
5145 // Heuristically we decide to do this if the vector has a "dominant" value,
5146 // defined as splatted to more than half of the lanes.
5147 unsigned NumElts = VT.getVectorNumElements();
5148 bool isOnlyLowElement = true;
5149 bool usesOnlyOneValue = true;
5150 bool hasDominantValue = false;
5151 bool isConstant = true;
5153 // Map of the number of times a particular SDValue appears in the
5155 DenseMap<SDValue, unsigned> ValueCounts;
5157 for (unsigned i = 0; i < NumElts; ++i) {
5158 SDValue V = Op.getOperand(i);
5159 if (V.getOpcode() == ISD::UNDEF)
5162 isOnlyLowElement = false;
5163 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5166 ValueCounts.insert(std::make_pair(V, 0));
5167 unsigned &Count = ValueCounts[V];
5169 // Is this value dominant? (takes up more than half of the lanes)
5170 if (++Count > (NumElts / 2)) {
5171 hasDominantValue = true;
5175 if (ValueCounts.size() != 1)
5176 usesOnlyOneValue = false;
5177 if (!Value.getNode() && ValueCounts.size() > 0)
5178 Value = ValueCounts.begin()->first;
5180 if (ValueCounts.size() == 0)
5181 return DAG.getUNDEF(VT);
5183 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5184 // Keep going if we are hitting this case.
5185 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5186 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5188 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5190 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5191 // i32 and try again.
5192 if (hasDominantValue && EltSize <= 32) {
5196 // If we are VDUPing a value that comes directly from a vector, that will
5197 // cause an unnecessary move to and from a GPR, where instead we could
5198 // just use VDUPLANE. We can only do this if the lane being extracted
5199 // is at a constant index, as the VDUP from lane instructions only have
5200 // constant-index forms.
5201 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5202 isa<ConstantSDNode>(Value->getOperand(1))) {
5203 // We need to create a new undef vector to use for the VDUPLANE if the
5204 // size of the vector from which we get the value is different than the
5205 // size of the vector that we need to create. We will insert the element
5206 // such that the register coalescer will remove unnecessary copies.
5207 if (VT != Value->getOperand(0).getValueType()) {
5208 ConstantSDNode *constIndex;
5209 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5210 assert(constIndex && "The index is not a constant!");
5211 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5212 VT.getVectorNumElements();
5213 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5214 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5215 Value, DAG.getConstant(index, MVT::i32)),
5216 DAG.getConstant(index, MVT::i32));
5218 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5219 Value->getOperand(0), Value->getOperand(1));
5221 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5223 if (!usesOnlyOneValue) {
5224 // The dominant value was splatted as 'N', but we now have to insert
5225 // all differing elements.
5226 for (unsigned I = 0; I < NumElts; ++I) {
5227 if (Op.getOperand(I) == Value)
5229 SmallVector<SDValue, 3> Ops;
5231 Ops.push_back(Op.getOperand(I));
5232 Ops.push_back(DAG.getConstant(I, MVT::i32));
5233 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5238 if (VT.getVectorElementType().isFloatingPoint()) {
5239 SmallVector<SDValue, 8> Ops;
5240 for (unsigned i = 0; i < NumElts; ++i)
5241 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5243 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5244 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5245 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5247 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5249 if (usesOnlyOneValue) {
5250 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5251 if (isConstant && Val.getNode())
5252 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5256 // If all elements are constants and the case above didn't get hit, fall back
5257 // to the default expansion, which will generate a load from the constant
5262 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5264 SDValue shuffle = ReconstructShuffle(Op, DAG);
5265 if (shuffle != SDValue())
5269 // Vectors with 32- or 64-bit elements can be built by directly assigning
5270 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5271 // will be legalized.
5272 if (EltSize >= 32) {
5273 // Do the expansion with floating-point types, since that is what the VFP
5274 // registers are defined to use, and since i64 is not legal.
5275 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5276 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5277 SmallVector<SDValue, 8> Ops;
5278 for (unsigned i = 0; i < NumElts; ++i)
5279 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5280 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5281 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5284 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5285 // know the default expansion would otherwise fall back on something even
5286 // worse. For a vector with one or two non-undef values, that's
5287 // scalar_to_vector for the elements followed by a shuffle (provided the
5288 // shuffle is valid for the target) and materialization element by element
5289 // on the stack followed by a load for everything else.
5290 if (!isConstant && !usesOnlyOneValue) {
5291 SDValue Vec = DAG.getUNDEF(VT);
5292 for (unsigned i = 0 ; i < NumElts; ++i) {
5293 SDValue V = Op.getOperand(i);
5294 if (V.getOpcode() == ISD::UNDEF)
5296 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5297 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5305 // Gather data to see if the operation can be modelled as a
5306 // shuffle in combination with VEXTs.
5307 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5308 SelectionDAG &DAG) const {
5310 EVT VT = Op.getValueType();
5311 unsigned NumElts = VT.getVectorNumElements();
5313 SmallVector<SDValue, 2> SourceVecs;
5314 SmallVector<unsigned, 2> MinElts;
5315 SmallVector<unsigned, 2> MaxElts;
5317 for (unsigned i = 0; i < NumElts; ++i) {
5318 SDValue V = Op.getOperand(i);
5319 if (V.getOpcode() == ISD::UNDEF)
5321 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5322 // A shuffle can only come from building a vector from various
5323 // elements of other vectors.
5325 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5326 VT.getVectorElementType()) {
5327 // This code doesn't know how to handle shuffles where the vector
5328 // element types do not match (this happens because type legalization
5329 // promotes the return type of EXTRACT_VECTOR_ELT).
5330 // FIXME: It might be appropriate to extend this code to handle
5331 // mismatched types.
5335 // Record this extraction against the appropriate vector if possible...
5336 SDValue SourceVec = V.getOperand(0);
5337 // If the element number isn't a constant, we can't effectively
5338 // analyze what's going on.
5339 if (!isa<ConstantSDNode>(V.getOperand(1)))
5341 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5342 bool FoundSource = false;
5343 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5344 if (SourceVecs[j] == SourceVec) {
5345 if (MinElts[j] > EltNo)
5347 if (MaxElts[j] < EltNo)
5354 // Or record a new source if not...
5356 SourceVecs.push_back(SourceVec);
5357 MinElts.push_back(EltNo);
5358 MaxElts.push_back(EltNo);
5362 // Currently only do something sane when at most two source vectors
5364 if (SourceVecs.size() > 2)
5367 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5368 int VEXTOffsets[2] = {0, 0};
5370 // This loop extracts the usage patterns of the source vectors
5371 // and prepares appropriate SDValues for a shuffle if possible.
5372 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5373 if (SourceVecs[i].getValueType() == VT) {
5374 // No VEXT necessary
5375 ShuffleSrcs[i] = SourceVecs[i];
5378 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5379 // It probably isn't worth padding out a smaller vector just to
5380 // break it down again in a shuffle.
5384 // Since only 64-bit and 128-bit vectors are legal on ARM and
5385 // we've eliminated the other cases...
5386 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5387 "unexpected vector sizes in ReconstructShuffle");
5389 if (MaxElts[i] - MinElts[i] >= NumElts) {
5390 // Span too large for a VEXT to cope
5394 if (MinElts[i] >= NumElts) {
5395 // The extraction can just take the second half
5396 VEXTOffsets[i] = NumElts;
5397 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5399 DAG.getIntPtrConstant(NumElts));
5400 } else if (MaxElts[i] < NumElts) {
5401 // The extraction can just take the first half
5403 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5405 DAG.getIntPtrConstant(0));
5407 // An actual VEXT is needed
5408 VEXTOffsets[i] = MinElts[i];
5409 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5411 DAG.getIntPtrConstant(0));
5412 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5414 DAG.getIntPtrConstant(NumElts));
5415 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5416 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5420 SmallVector<int, 8> Mask;
5422 for (unsigned i = 0; i < NumElts; ++i) {
5423 SDValue Entry = Op.getOperand(i);
5424 if (Entry.getOpcode() == ISD::UNDEF) {
5429 SDValue ExtractVec = Entry.getOperand(0);
5430 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5431 .getOperand(1))->getSExtValue();
5432 if (ExtractVec == SourceVecs[0]) {
5433 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5435 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5439 // Final check before we try to produce nonsense...
5440 if (isShuffleMaskLegal(Mask, VT))
5441 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5447 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5448 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5449 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5450 /// are assumed to be legal.
5452 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5454 if (VT.getVectorNumElements() == 4 &&
5455 (VT.is128BitVector() || VT.is64BitVector())) {
5456 unsigned PFIndexes[4];
5457 for (unsigned i = 0; i != 4; ++i) {
5461 PFIndexes[i] = M[i];
5464 // Compute the index in the perfect shuffle table.
5465 unsigned PFTableIndex =
5466 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5467 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5468 unsigned Cost = (PFEntry >> 30);
5475 unsigned Imm, WhichResult;
5477 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5478 return (EltSize >= 32 ||
5479 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5480 isVREVMask(M, VT, 64) ||
5481 isVREVMask(M, VT, 32) ||
5482 isVREVMask(M, VT, 16) ||
5483 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5484 isVTBLMask(M, VT) ||
5485 isVTRNMask(M, VT, WhichResult) ||
5486 isVUZPMask(M, VT, WhichResult) ||
5487 isVZIPMask(M, VT, WhichResult) ||
5488 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5489 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5490 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5491 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5494 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5495 /// the specified operations to build the shuffle.
5496 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5497 SDValue RHS, SelectionDAG &DAG,
5499 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5500 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5501 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5504 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5513 OP_VUZPL, // VUZP, left result
5514 OP_VUZPR, // VUZP, right result
5515 OP_VZIPL, // VZIP, left result
5516 OP_VZIPR, // VZIP, right result
5517 OP_VTRNL, // VTRN, left result
5518 OP_VTRNR // VTRN, right result
5521 if (OpNum == OP_COPY) {
5522 if (LHSID == (1*9+2)*9+3) return LHS;
5523 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5527 SDValue OpLHS, OpRHS;
5528 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5529 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5530 EVT VT = OpLHS.getValueType();
5533 default: llvm_unreachable("Unknown shuffle opcode!");
5535 // VREV divides the vector in half and swaps within the half.
5536 if (VT.getVectorElementType() == MVT::i32 ||
5537 VT.getVectorElementType() == MVT::f32)
5538 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5539 // vrev <4 x i16> -> VREV32
5540 if (VT.getVectorElementType() == MVT::i16)
5541 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5542 // vrev <4 x i8> -> VREV16
5543 assert(VT.getVectorElementType() == MVT::i8);
5544 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5549 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5550 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5554 return DAG.getNode(ARMISD::VEXT, dl, VT,
5556 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5559 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5560 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5563 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5564 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5567 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5568 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5572 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5573 ArrayRef<int> ShuffleMask,
5574 SelectionDAG &DAG) {
5575 // Check to see if we can use the VTBL instruction.
5576 SDValue V1 = Op.getOperand(0);
5577 SDValue V2 = Op.getOperand(1);
5580 SmallVector<SDValue, 8> VTBLMask;
5581 for (ArrayRef<int>::iterator
5582 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5583 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5585 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5586 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5587 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5589 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5590 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5593 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5594 SelectionDAG &DAG) {
5596 SDValue OpLHS = Op.getOperand(0);
5597 EVT VT = OpLHS.getValueType();
5599 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5600 "Expect an v8i16/v16i8 type");
5601 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5602 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5603 // extract the first 8 bytes into the top double word and the last 8 bytes
5604 // into the bottom double word. The v8i16 case is similar.
5605 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5606 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5607 DAG.getConstant(ExtractNum, MVT::i32));
5610 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5611 SDValue V1 = Op.getOperand(0);
5612 SDValue V2 = Op.getOperand(1);
5614 EVT VT = Op.getValueType();
5615 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5617 // Convert shuffles that are directly supported on NEON to target-specific
5618 // DAG nodes, instead of keeping them as shuffles and matching them again
5619 // during code selection. This is more efficient and avoids the possibility
5620 // of inconsistencies between legalization and selection.
5621 // FIXME: floating-point vectors should be canonicalized to integer vectors
5622 // of the same time so that they get CSEd properly.
5623 ArrayRef<int> ShuffleMask = SVN->getMask();
5625 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5626 if (EltSize <= 32) {
5627 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5628 int Lane = SVN->getSplatIndex();
5629 // If this is undef splat, generate it via "just" vdup, if possible.
5630 if (Lane == -1) Lane = 0;
5632 // Test if V1 is a SCALAR_TO_VECTOR.
5633 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5634 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5636 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5637 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5639 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5640 !isa<ConstantSDNode>(V1.getOperand(0))) {
5641 bool IsScalarToVector = true;
5642 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5643 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5644 IsScalarToVector = false;
5647 if (IsScalarToVector)
5648 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5650 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5651 DAG.getConstant(Lane, MVT::i32));
5656 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5659 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5660 DAG.getConstant(Imm, MVT::i32));
5663 if (isVREVMask(ShuffleMask, VT, 64))
5664 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5665 if (isVREVMask(ShuffleMask, VT, 32))
5666 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5667 if (isVREVMask(ShuffleMask, VT, 16))
5668 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5670 if (V2->getOpcode() == ISD::UNDEF &&
5671 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5672 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5673 DAG.getConstant(Imm, MVT::i32));
5676 // Check for Neon shuffles that modify both input vectors in place.
5677 // If both results are used, i.e., if there are two shuffles with the same
5678 // source operands and with masks corresponding to both results of one of
5679 // these operations, DAG memoization will ensure that a single node is
5680 // used for both shuffles.
5681 unsigned WhichResult;
5682 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5683 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5684 V1, V2).getValue(WhichResult);
5685 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5686 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5687 V1, V2).getValue(WhichResult);
5688 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5689 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5690 V1, V2).getValue(WhichResult);
5692 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5693 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5694 V1, V1).getValue(WhichResult);
5695 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5696 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5697 V1, V1).getValue(WhichResult);
5698 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5699 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5700 V1, V1).getValue(WhichResult);
5703 // If the shuffle is not directly supported and it has 4 elements, use
5704 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5705 unsigned NumElts = VT.getVectorNumElements();
5707 unsigned PFIndexes[4];
5708 for (unsigned i = 0; i != 4; ++i) {
5709 if (ShuffleMask[i] < 0)
5712 PFIndexes[i] = ShuffleMask[i];
5715 // Compute the index in the perfect shuffle table.
5716 unsigned PFTableIndex =
5717 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5718 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5719 unsigned Cost = (PFEntry >> 30);
5722 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5725 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5726 if (EltSize >= 32) {
5727 // Do the expansion with floating-point types, since that is what the VFP
5728 // registers are defined to use, and since i64 is not legal.
5729 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5730 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5731 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5732 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5733 SmallVector<SDValue, 8> Ops;
5734 for (unsigned i = 0; i < NumElts; ++i) {
5735 if (ShuffleMask[i] < 0)
5736 Ops.push_back(DAG.getUNDEF(EltVT));
5738 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5739 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5740 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5743 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5744 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5747 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5748 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5750 if (VT == MVT::v8i8) {
5751 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5752 if (NewOp.getNode())
5759 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5760 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5761 SDValue Lane = Op.getOperand(2);
5762 if (!isa<ConstantSDNode>(Lane))
5768 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5769 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5770 SDValue Lane = Op.getOperand(1);
5771 if (!isa<ConstantSDNode>(Lane))
5774 SDValue Vec = Op.getOperand(0);
5775 if (Op.getValueType() == MVT::i32 &&
5776 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5778 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5784 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5785 // The only time a CONCAT_VECTORS operation can have legal types is when
5786 // two 64-bit vectors are concatenated to a 128-bit vector.
5787 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5788 "unexpected CONCAT_VECTORS");
5790 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5791 SDValue Op0 = Op.getOperand(0);
5792 SDValue Op1 = Op.getOperand(1);
5793 if (Op0.getOpcode() != ISD::UNDEF)
5794 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5795 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5796 DAG.getIntPtrConstant(0));
5797 if (Op1.getOpcode() != ISD::UNDEF)
5798 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5799 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5800 DAG.getIntPtrConstant(1));
5801 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5804 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5805 /// element has been zero/sign-extended, depending on the isSigned parameter,
5806 /// from an integer type half its size.
5807 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5809 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5810 EVT VT = N->getValueType(0);
5811 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5812 SDNode *BVN = N->getOperand(0).getNode();
5813 if (BVN->getValueType(0) != MVT::v4i32 ||
5814 BVN->getOpcode() != ISD::BUILD_VECTOR)
5816 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5817 unsigned HiElt = 1 - LoElt;
5818 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5819 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5820 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5821 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5822 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5825 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5826 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5829 if (Hi0->isNullValue() && Hi1->isNullValue())
5835 if (N->getOpcode() != ISD::BUILD_VECTOR)
5838 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5839 SDNode *Elt = N->getOperand(i).getNode();
5840 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5841 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5842 unsigned HalfSize = EltSize / 2;
5844 if (!isIntN(HalfSize, C->getSExtValue()))
5847 if (!isUIntN(HalfSize, C->getZExtValue()))
5858 /// isSignExtended - Check if a node is a vector value that is sign-extended
5859 /// or a constant BUILD_VECTOR with sign-extended elements.
5860 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5861 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5863 if (isExtendedBUILD_VECTOR(N, DAG, true))
5868 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5869 /// or a constant BUILD_VECTOR with zero-extended elements.
5870 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5871 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5873 if (isExtendedBUILD_VECTOR(N, DAG, false))
5878 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5879 if (OrigVT.getSizeInBits() >= 64)
5882 assert(OrigVT.isSimple() && "Expecting a simple value type");
5884 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5885 switch (OrigSimpleTy) {
5886 default: llvm_unreachable("Unexpected Vector Type");
5895 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5896 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5897 /// We insert the required extension here to get the vector to fill a D register.
5898 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5901 unsigned ExtOpcode) {
5902 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5903 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5904 // 64-bits we need to insert a new extension so that it will be 64-bits.
5905 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5906 if (OrigTy.getSizeInBits() >= 64)
5909 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5910 EVT NewVT = getExtensionTo64Bits(OrigTy);
5912 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5915 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5916 /// does not do any sign/zero extension. If the original vector is less
5917 /// than 64 bits, an appropriate extension will be added after the load to
5918 /// reach a total size of 64 bits. We have to add the extension separately
5919 /// because ARM does not have a sign/zero extending load for vectors.
5920 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5921 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5923 // The load already has the right type.
5924 if (ExtendedTy == LD->getMemoryVT())
5925 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5926 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5927 LD->isNonTemporal(), LD->isInvariant(),
5928 LD->getAlignment());
5930 // We need to create a zextload/sextload. We cannot just create a load
5931 // followed by a zext/zext node because LowerMUL is also run during normal
5932 // operation legalization where we can't create illegal types.
5933 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5934 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5935 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5936 LD->isNonTemporal(), LD->getAlignment());
5939 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5940 /// extending load, or BUILD_VECTOR with extended elements, return the
5941 /// unextended value. The unextended vector should be 64 bits so that it can
5942 /// be used as an operand to a VMULL instruction. If the original vector size
5943 /// before extension is less than 64 bits we add a an extension to resize
5944 /// the vector to 64 bits.
5945 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5946 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5947 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5948 N->getOperand(0)->getValueType(0),
5952 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5953 return SkipLoadExtensionForVMULL(LD, DAG);
5955 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5956 // have been legalized as a BITCAST from v4i32.
5957 if (N->getOpcode() == ISD::BITCAST) {
5958 SDNode *BVN = N->getOperand(0).getNode();
5959 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5960 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5961 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5962 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5963 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5965 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5966 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5967 EVT VT = N->getValueType(0);
5968 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5969 unsigned NumElts = VT.getVectorNumElements();
5970 MVT TruncVT = MVT::getIntegerVT(EltSize);
5971 SmallVector<SDValue, 8> Ops;
5972 for (unsigned i = 0; i != NumElts; ++i) {
5973 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5974 const APInt &CInt = C->getAPIntValue();
5975 // Element types smaller than 32 bits are not legal, so use i32 elements.
5976 // The values are implicitly truncated so sext vs. zext doesn't matter.
5977 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5979 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5980 MVT::getVectorVT(TruncVT, NumElts), Ops);
5983 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5984 unsigned Opcode = N->getOpcode();
5985 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5986 SDNode *N0 = N->getOperand(0).getNode();
5987 SDNode *N1 = N->getOperand(1).getNode();
5988 return N0->hasOneUse() && N1->hasOneUse() &&
5989 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5994 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5995 unsigned Opcode = N->getOpcode();
5996 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5997 SDNode *N0 = N->getOperand(0).getNode();
5998 SDNode *N1 = N->getOperand(1).getNode();
5999 return N0->hasOneUse() && N1->hasOneUse() &&
6000 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6005 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6006 // Multiplications are only custom-lowered for 128-bit vectors so that
6007 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6008 EVT VT = Op.getValueType();
6009 assert(VT.is128BitVector() && VT.isInteger() &&
6010 "unexpected type for custom-lowering ISD::MUL");
6011 SDNode *N0 = Op.getOperand(0).getNode();
6012 SDNode *N1 = Op.getOperand(1).getNode();
6013 unsigned NewOpc = 0;
6015 bool isN0SExt = isSignExtended(N0, DAG);
6016 bool isN1SExt = isSignExtended(N1, DAG);
6017 if (isN0SExt && isN1SExt)
6018 NewOpc = ARMISD::VMULLs;
6020 bool isN0ZExt = isZeroExtended(N0, DAG);
6021 bool isN1ZExt = isZeroExtended(N1, DAG);
6022 if (isN0ZExt && isN1ZExt)
6023 NewOpc = ARMISD::VMULLu;
6024 else if (isN1SExt || isN1ZExt) {
6025 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6026 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6027 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6028 NewOpc = ARMISD::VMULLs;
6030 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6031 NewOpc = ARMISD::VMULLu;
6033 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6035 NewOpc = ARMISD::VMULLu;
6041 if (VT == MVT::v2i64)
6042 // Fall through to expand this. It is not legal.
6045 // Other vector multiplications are legal.
6050 // Legalize to a VMULL instruction.
6053 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6055 Op0 = SkipExtensionForVMULL(N0, DAG);
6056 assert(Op0.getValueType().is64BitVector() &&
6057 Op1.getValueType().is64BitVector() &&
6058 "unexpected types for extended operands to VMULL");
6059 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6062 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6063 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6070 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6071 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6072 EVT Op1VT = Op1.getValueType();
6073 return DAG.getNode(N0->getOpcode(), DL, VT,
6074 DAG.getNode(NewOpc, DL, VT,
6075 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6076 DAG.getNode(NewOpc, DL, VT,
6077 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6081 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6083 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6084 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6085 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6086 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6087 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6088 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6089 // Get reciprocal estimate.
6090 // float4 recip = vrecpeq_f32(yf);
6091 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6092 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
6093 // Because char has a smaller range than uchar, we can actually get away
6094 // without any newton steps. This requires that we use a weird bias
6095 // of 0xb000, however (again, this has been exhaustively tested).
6096 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6097 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6098 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6099 Y = DAG.getConstant(0xb000, MVT::i32);
6100 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6101 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6102 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6103 // Convert back to short.
6104 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6105 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6110 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6112 // Convert to float.
6113 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6114 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6115 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6116 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6117 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6118 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6120 // Use reciprocal estimate and one refinement step.
6121 // float4 recip = vrecpeq_f32(yf);
6122 // recip *= vrecpsq_f32(yf, recip);
6123 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6124 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6125 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6126 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6128 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6129 // Because short has a smaller range than ushort, we can actually get away
6130 // with only a single newton step. This requires that we use a weird bias
6131 // of 89, however (again, this has been exhaustively tested).
6132 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6133 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6134 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6135 N1 = DAG.getConstant(0x89, MVT::i32);
6136 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6137 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6138 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6139 // Convert back to integer and return.
6140 // return vmovn_s32(vcvt_s32_f32(result));
6141 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6142 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6146 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6147 EVT VT = Op.getValueType();
6148 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6149 "unexpected type for custom-lowering ISD::SDIV");
6152 SDValue N0 = Op.getOperand(0);
6153 SDValue N1 = Op.getOperand(1);
6156 if (VT == MVT::v8i8) {
6157 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6158 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6160 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6161 DAG.getIntPtrConstant(4));
6162 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6163 DAG.getIntPtrConstant(4));
6164 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6165 DAG.getIntPtrConstant(0));
6166 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6167 DAG.getIntPtrConstant(0));
6169 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6170 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6172 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6173 N0 = LowerCONCAT_VECTORS(N0, DAG);
6175 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6178 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6181 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6182 EVT VT = Op.getValueType();
6183 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6184 "unexpected type for custom-lowering ISD::UDIV");
6187 SDValue N0 = Op.getOperand(0);
6188 SDValue N1 = Op.getOperand(1);
6191 if (VT == MVT::v8i8) {
6192 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6193 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6195 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6196 DAG.getIntPtrConstant(4));
6197 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6198 DAG.getIntPtrConstant(4));
6199 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6200 DAG.getIntPtrConstant(0));
6201 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6202 DAG.getIntPtrConstant(0));
6204 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6205 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6207 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6208 N0 = LowerCONCAT_VECTORS(N0, DAG);
6210 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6211 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6216 // v4i16 sdiv ... Convert to float.
6217 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6218 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6219 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6220 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6221 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6222 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6224 // Use reciprocal estimate and two refinement steps.
6225 // float4 recip = vrecpeq_f32(yf);
6226 // recip *= vrecpsq_f32(yf, recip);
6227 // recip *= vrecpsq_f32(yf, recip);
6228 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6229 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6230 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6231 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6233 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6234 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6235 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6237 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6238 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6239 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6240 // and that it will never cause us to return an answer too large).
6241 // float4 result = as_float4(as_int4(xf*recip) + 2);
6242 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6243 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6244 N1 = DAG.getConstant(2, MVT::i32);
6245 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6246 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6247 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6248 // Convert back to integer and return.
6249 // return vmovn_u32(vcvt_s32_f32(result));
6250 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6251 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6255 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6256 EVT VT = Op.getNode()->getValueType(0);
6257 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6260 bool ExtraOp = false;
6261 switch (Op.getOpcode()) {
6262 default: llvm_unreachable("Invalid code");
6263 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6264 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6265 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6266 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6270 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6272 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6273 Op.getOperand(1), Op.getOperand(2));
6276 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6277 assert(Subtarget->isTargetDarwin());
6279 // For iOS, we want to call an alternative entry point: __sincos_stret,
6280 // return values are passed via sret.
6282 SDValue Arg = Op.getOperand(0);
6283 EVT ArgVT = Arg.getValueType();
6284 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6286 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6287 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6289 // Pair of floats / doubles used to pass the result.
6290 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6292 // Create stack object for sret.
6293 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6294 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6295 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6296 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6302 Entry.Ty = RetTy->getPointerTo();
6303 Entry.isSExt = false;
6304 Entry.isZExt = false;
6305 Entry.isSRet = true;
6306 Args.push_back(Entry);
6310 Entry.isSExt = false;
6311 Entry.isZExt = false;
6312 Args.push_back(Entry);
6314 const char *LibcallName = (ArgVT == MVT::f64)
6315 ? "__sincos_stret" : "__sincosf_stret";
6316 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6318 TargetLowering::CallLoweringInfo CLI(DAG);
6319 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6320 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6322 .setDiscardResult();
6324 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6326 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6327 MachinePointerInfo(), false, false, false, 0);
6329 // Address of cos field.
6330 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6331 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6332 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6333 MachinePointerInfo(), false, false, false, 0);
6335 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6336 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6337 LoadSin.getValue(0), LoadCos.getValue(0));
6340 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6341 // Monotonic load/store is legal for all targets
6342 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6345 // Acquire/Release load/store is not legal for targets without a
6346 // dmb or equivalent available.
6350 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6351 SmallVectorImpl<SDValue> &Results,
6353 const ARMSubtarget *Subtarget) {
6355 SDValue Cycles32, OutChain;
6357 if (Subtarget->hasPerfMon()) {
6358 // Under Power Management extensions, the cycle-count is:
6359 // mrc p15, #0, <Rt>, c9, c13, #0
6360 SDValue Ops[] = { N->getOperand(0), // Chain
6361 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6362 DAG.getConstant(15, MVT::i32),
6363 DAG.getConstant(0, MVT::i32),
6364 DAG.getConstant(9, MVT::i32),
6365 DAG.getConstant(13, MVT::i32),
6366 DAG.getConstant(0, MVT::i32)
6369 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6370 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6371 OutChain = Cycles32.getValue(1);
6373 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6374 // there are older ARM CPUs that have implementation-specific ways of
6375 // obtaining this information (FIXME!).
6376 Cycles32 = DAG.getConstant(0, MVT::i32);
6377 OutChain = DAG.getEntryNode();
6381 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6382 Cycles32, DAG.getConstant(0, MVT::i32));
6383 Results.push_back(Cycles64);
6384 Results.push_back(OutChain);
6387 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6388 switch (Op.getOpcode()) {
6389 default: llvm_unreachable("Don't know how to custom lower this!");
6390 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6391 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6392 case ISD::GlobalAddress:
6393 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6394 default: llvm_unreachable("unknown object format");
6396 return LowerGlobalAddressWindows(Op, DAG);
6398 return LowerGlobalAddressELF(Op, DAG);
6400 return LowerGlobalAddressDarwin(Op, DAG);
6402 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6403 case ISD::SELECT: return LowerSELECT(Op, DAG);
6404 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6405 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6406 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6407 case ISD::VASTART: return LowerVASTART(Op, DAG);
6408 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6409 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6410 case ISD::SINT_TO_FP:
6411 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6412 case ISD::FP_TO_SINT:
6413 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6414 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6415 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6416 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6417 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6418 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6419 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6420 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6422 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6425 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6426 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6427 case ISD::SRL_PARTS:
6428 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6429 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6430 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6431 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6432 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6433 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6434 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6435 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6436 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6437 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6438 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6439 case ISD::MUL: return LowerMUL(Op, DAG);
6440 case ISD::SDIV: return LowerSDIV(Op, DAG);
6441 case ISD::UDIV: return LowerUDIV(Op, DAG);
6445 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6450 return LowerXALUO(Op, DAG);
6451 case ISD::ATOMIC_LOAD:
6452 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6453 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6455 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6456 case ISD::DYNAMIC_STACKALLOC:
6457 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6458 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6459 llvm_unreachable("Don't know how to custom lower this!");
6460 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6461 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6465 /// ReplaceNodeResults - Replace the results of node with an illegal result
6466 /// type with new values built out of custom code.
6467 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6468 SmallVectorImpl<SDValue>&Results,
6469 SelectionDAG &DAG) const {
6471 switch (N->getOpcode()) {
6473 llvm_unreachable("Don't know how to custom expand this!");
6475 Res = ExpandBITCAST(N, DAG);
6479 Res = Expand64BitShift(N, DAG, Subtarget);
6481 case ISD::READCYCLECOUNTER:
6482 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6486 Results.push_back(Res);
6489 //===----------------------------------------------------------------------===//
6490 // ARM Scheduler Hooks
6491 //===----------------------------------------------------------------------===//
6493 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6494 /// registers the function context.
6495 void ARMTargetLowering::
6496 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6497 MachineBasicBlock *DispatchBB, int FI) const {
6498 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6499 DebugLoc dl = MI->getDebugLoc();
6500 MachineFunction *MF = MBB->getParent();
6501 MachineRegisterInfo *MRI = &MF->getRegInfo();
6502 MachineConstantPool *MCP = MF->getConstantPool();
6503 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6504 const Function *F = MF->getFunction();
6506 bool isThumb = Subtarget->isThumb();
6507 bool isThumb2 = Subtarget->isThumb2();
6509 unsigned PCLabelId = AFI->createPICLabelUId();
6510 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6511 ARMConstantPoolValue *CPV =
6512 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6513 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6515 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6516 : &ARM::GPRRegClass;
6518 // Grab constant pool and fixed stack memory operands.
6519 MachineMemOperand *CPMMO =
6520 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6521 MachineMemOperand::MOLoad, 4, 4);
6523 MachineMemOperand *FIMMOSt =
6524 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6525 MachineMemOperand::MOStore, 4, 4);
6527 // Load the address of the dispatch MBB into the jump buffer.
6529 // Incoming value: jbuf
6530 // ldr.n r5, LCPI1_1
6533 // str r5, [$jbuf, #+4] ; &jbuf[1]
6534 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6535 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6536 .addConstantPoolIndex(CPI)
6537 .addMemOperand(CPMMO));
6538 // Set the low bit because of thumb mode.
6539 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6541 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6542 .addReg(NewVReg1, RegState::Kill)
6544 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6545 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6546 .addReg(NewVReg2, RegState::Kill)
6548 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6549 .addReg(NewVReg3, RegState::Kill)
6551 .addImm(36) // &jbuf[1] :: pc
6552 .addMemOperand(FIMMOSt));
6553 } else if (isThumb) {
6554 // Incoming value: jbuf
6555 // ldr.n r1, LCPI1_4
6559 // add r2, $jbuf, #+4 ; &jbuf[1]
6561 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6562 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6563 .addConstantPoolIndex(CPI)
6564 .addMemOperand(CPMMO));
6565 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6566 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6567 .addReg(NewVReg1, RegState::Kill)
6569 // Set the low bit because of thumb mode.
6570 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6571 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6572 .addReg(ARM::CPSR, RegState::Define)
6574 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6575 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6576 .addReg(ARM::CPSR, RegState::Define)
6577 .addReg(NewVReg2, RegState::Kill)
6578 .addReg(NewVReg3, RegState::Kill));
6579 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6580 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6582 .addImm(36); // &jbuf[1] :: pc
6583 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6584 .addReg(NewVReg4, RegState::Kill)
6585 .addReg(NewVReg5, RegState::Kill)
6587 .addMemOperand(FIMMOSt));
6589 // Incoming value: jbuf
6592 // str r1, [$jbuf, #+4] ; &jbuf[1]
6593 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6594 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6595 .addConstantPoolIndex(CPI)
6597 .addMemOperand(CPMMO));
6598 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6599 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6600 .addReg(NewVReg1, RegState::Kill)
6601 .addImm(PCLabelId));
6602 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6603 .addReg(NewVReg2, RegState::Kill)
6605 .addImm(36) // &jbuf[1] :: pc
6606 .addMemOperand(FIMMOSt));
6610 MachineBasicBlock *ARMTargetLowering::
6611 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6612 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6613 DebugLoc dl = MI->getDebugLoc();
6614 MachineFunction *MF = MBB->getParent();
6615 MachineRegisterInfo *MRI = &MF->getRegInfo();
6616 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6617 MachineFrameInfo *MFI = MF->getFrameInfo();
6618 int FI = MFI->getFunctionContextIndex();
6620 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6621 : &ARM::GPRnopcRegClass;
6623 // Get a mapping of the call site numbers to all of the landing pads they're
6625 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6626 unsigned MaxCSNum = 0;
6627 MachineModuleInfo &MMI = MF->getMMI();
6628 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6630 if (!BB->isLandingPad()) continue;
6632 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6634 for (MachineBasicBlock::iterator
6635 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6636 if (!II->isEHLabel()) continue;
6638 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6639 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6641 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6642 for (SmallVectorImpl<unsigned>::iterator
6643 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6644 CSI != CSE; ++CSI) {
6645 CallSiteNumToLPad[*CSI].push_back(BB);
6646 MaxCSNum = std::max(MaxCSNum, *CSI);
6652 // Get an ordered list of the machine basic blocks for the jump table.
6653 std::vector<MachineBasicBlock*> LPadList;
6654 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6655 LPadList.reserve(CallSiteNumToLPad.size());
6656 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6657 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6658 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6659 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6660 LPadList.push_back(*II);
6661 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6665 assert(!LPadList.empty() &&
6666 "No landing pad destinations for the dispatch jump table!");
6668 // Create the jump table and associated information.
6669 MachineJumpTableInfo *JTI =
6670 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6671 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6672 unsigned UId = AFI->createJumpTableUId();
6673 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6675 // Create the MBBs for the dispatch code.
6677 // Shove the dispatch's address into the return slot in the function context.
6678 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6679 DispatchBB->setIsLandingPad();
6681 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6682 unsigned trap_opcode;
6683 if (Subtarget->isThumb())
6684 trap_opcode = ARM::tTRAP;
6686 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6688 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6689 DispatchBB->addSuccessor(TrapBB);
6691 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6692 DispatchBB->addSuccessor(DispContBB);
6695 MF->insert(MF->end(), DispatchBB);
6696 MF->insert(MF->end(), DispContBB);
6697 MF->insert(MF->end(), TrapBB);
6699 // Insert code into the entry block that creates and registers the function
6701 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6703 MachineMemOperand *FIMMOLd =
6704 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6705 MachineMemOperand::MOLoad |
6706 MachineMemOperand::MOVolatile, 4, 4);
6708 MachineInstrBuilder MIB;
6709 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6711 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6712 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6714 // Add a register mask with no preserved registers. This results in all
6715 // registers being marked as clobbered.
6716 MIB.addRegMask(RI.getNoPreservedMask());
6718 unsigned NumLPads = LPadList.size();
6719 if (Subtarget->isThumb2()) {
6720 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6721 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6724 .addMemOperand(FIMMOLd));
6726 if (NumLPads < 256) {
6727 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6729 .addImm(LPadList.size()));
6731 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6732 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6733 .addImm(NumLPads & 0xFFFF));
6735 unsigned VReg2 = VReg1;
6736 if ((NumLPads & 0xFFFF0000) != 0) {
6737 VReg2 = MRI->createVirtualRegister(TRC);
6738 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6740 .addImm(NumLPads >> 16));
6743 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6748 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6753 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6754 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6755 .addJumpTableIndex(MJTI)
6758 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6761 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6762 .addReg(NewVReg3, RegState::Kill)
6764 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6766 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6767 .addReg(NewVReg4, RegState::Kill)
6769 .addJumpTableIndex(MJTI)
6771 } else if (Subtarget->isThumb()) {
6772 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6773 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6776 .addMemOperand(FIMMOLd));
6778 if (NumLPads < 256) {
6779 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6783 MachineConstantPool *ConstantPool = MF->getConstantPool();
6784 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6785 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6787 // MachineConstantPool wants an explicit alignment.
6788 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6790 Align = getDataLayout()->getTypeAllocSize(C->getType());
6791 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6793 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6794 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6795 .addReg(VReg1, RegState::Define)
6796 .addConstantPoolIndex(Idx));
6797 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6802 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6807 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6808 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6809 .addReg(ARM::CPSR, RegState::Define)
6813 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6814 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6815 .addJumpTableIndex(MJTI)
6818 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6819 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6820 .addReg(ARM::CPSR, RegState::Define)
6821 .addReg(NewVReg2, RegState::Kill)
6824 MachineMemOperand *JTMMOLd =
6825 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6826 MachineMemOperand::MOLoad, 4, 4);
6828 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6829 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6830 .addReg(NewVReg4, RegState::Kill)
6832 .addMemOperand(JTMMOLd));
6834 unsigned NewVReg6 = NewVReg5;
6835 if (RelocM == Reloc::PIC_) {
6836 NewVReg6 = MRI->createVirtualRegister(TRC);
6837 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6838 .addReg(ARM::CPSR, RegState::Define)
6839 .addReg(NewVReg5, RegState::Kill)
6843 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6844 .addReg(NewVReg6, RegState::Kill)
6845 .addJumpTableIndex(MJTI)
6848 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6849 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6852 .addMemOperand(FIMMOLd));
6854 if (NumLPads < 256) {
6855 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6858 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6859 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6860 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6861 .addImm(NumLPads & 0xFFFF));
6863 unsigned VReg2 = VReg1;
6864 if ((NumLPads & 0xFFFF0000) != 0) {
6865 VReg2 = MRI->createVirtualRegister(TRC);
6866 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6868 .addImm(NumLPads >> 16));
6871 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6875 MachineConstantPool *ConstantPool = MF->getConstantPool();
6876 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6877 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6879 // MachineConstantPool wants an explicit alignment.
6880 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6882 Align = getDataLayout()->getTypeAllocSize(C->getType());
6883 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6885 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6886 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6887 .addReg(VReg1, RegState::Define)
6888 .addConstantPoolIndex(Idx)
6890 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6892 .addReg(VReg1, RegState::Kill));
6895 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6900 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6902 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6904 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6905 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6906 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6907 .addJumpTableIndex(MJTI)
6910 MachineMemOperand *JTMMOLd =
6911 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6912 MachineMemOperand::MOLoad, 4, 4);
6913 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6915 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6916 .addReg(NewVReg3, RegState::Kill)
6919 .addMemOperand(JTMMOLd));
6921 if (RelocM == Reloc::PIC_) {
6922 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6923 .addReg(NewVReg5, RegState::Kill)
6925 .addJumpTableIndex(MJTI)
6928 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6929 .addReg(NewVReg5, RegState::Kill)
6930 .addJumpTableIndex(MJTI)
6935 // Add the jump table entries as successors to the MBB.
6936 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6937 for (std::vector<MachineBasicBlock*>::iterator
6938 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6939 MachineBasicBlock *CurMBB = *I;
6940 if (SeenMBBs.insert(CurMBB).second)
6941 DispContBB->addSuccessor(CurMBB);
6944 // N.B. the order the invoke BBs are processed in doesn't matter here.
6945 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6946 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6947 for (MachineBasicBlock *BB : InvokeBBs) {
6949 // Remove the landing pad successor from the invoke block and replace it
6950 // with the new dispatch block.
6951 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6953 while (!Successors.empty()) {
6954 MachineBasicBlock *SMBB = Successors.pop_back_val();
6955 if (SMBB->isLandingPad()) {
6956 BB->removeSuccessor(SMBB);
6957 MBBLPads.push_back(SMBB);
6961 BB->addSuccessor(DispatchBB);
6963 // Find the invoke call and mark all of the callee-saved registers as
6964 // 'implicit defined' so that they're spilled. This prevents code from
6965 // moving instructions to before the EH block, where they will never be
6967 for (MachineBasicBlock::reverse_iterator
6968 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6969 if (!II->isCall()) continue;
6971 DenseMap<unsigned, bool> DefRegs;
6972 for (MachineInstr::mop_iterator
6973 OI = II->operands_begin(), OE = II->operands_end();
6975 if (!OI->isReg()) continue;
6976 DefRegs[OI->getReg()] = true;
6979 MachineInstrBuilder MIB(*MF, &*II);
6981 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6982 unsigned Reg = SavedRegs[i];
6983 if (Subtarget->isThumb2() &&
6984 !ARM::tGPRRegClass.contains(Reg) &&
6985 !ARM::hGPRRegClass.contains(Reg))
6987 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6989 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6992 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6999 // Mark all former landing pads as non-landing pads. The dispatch is the only
7001 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7002 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7003 (*I)->setIsLandingPad(false);
7005 // The instruction is gone now.
7006 MI->eraseFromParent();
7012 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7013 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7014 E = MBB->succ_end(); I != E; ++I)
7017 llvm_unreachable("Expecting a BB with two successors!");
7020 /// Return the load opcode for a given load size. If load size >= 8,
7021 /// neon opcode will be returned.
7022 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7024 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7025 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7027 return LdSize == 4 ? ARM::tLDRi
7028 : LdSize == 2 ? ARM::tLDRHi
7029 : LdSize == 1 ? ARM::tLDRBi : 0;
7031 return LdSize == 4 ? ARM::t2LDR_POST
7032 : LdSize == 2 ? ARM::t2LDRH_POST
7033 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7034 return LdSize == 4 ? ARM::LDR_POST_IMM
7035 : LdSize == 2 ? ARM::LDRH_POST
7036 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7039 /// Return the store opcode for a given store size. If store size >= 8,
7040 /// neon opcode will be returned.
7041 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7043 return StSize == 16 ? ARM::VST1q32wb_fixed
7044 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7046 return StSize == 4 ? ARM::tSTRi
7047 : StSize == 2 ? ARM::tSTRHi
7048 : StSize == 1 ? ARM::tSTRBi : 0;
7050 return StSize == 4 ? ARM::t2STR_POST
7051 : StSize == 2 ? ARM::t2STRH_POST
7052 : StSize == 1 ? ARM::t2STRB_POST : 0;
7053 return StSize == 4 ? ARM::STR_POST_IMM
7054 : StSize == 2 ? ARM::STRH_POST
7055 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7058 /// Emit a post-increment load operation with given size. The instructions
7059 /// will be added to BB at Pos.
7060 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7061 const TargetInstrInfo *TII, DebugLoc dl,
7062 unsigned LdSize, unsigned Data, unsigned AddrIn,
7063 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7064 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7065 assert(LdOpc != 0 && "Should have a load opcode");
7067 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7068 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7070 } else if (IsThumb1) {
7071 // load + update AddrIn
7072 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7073 .addReg(AddrIn).addImm(0));
7074 MachineInstrBuilder MIB =
7075 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7076 MIB = AddDefaultT1CC(MIB);
7077 MIB.addReg(AddrIn).addImm(LdSize);
7078 AddDefaultPred(MIB);
7079 } else if (IsThumb2) {
7080 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7081 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7084 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7085 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7086 .addReg(0).addImm(LdSize));
7090 /// Emit a post-increment store operation with given size. The instructions
7091 /// will be added to BB at Pos.
7092 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7093 const TargetInstrInfo *TII, DebugLoc dl,
7094 unsigned StSize, unsigned Data, unsigned AddrIn,
7095 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7096 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7097 assert(StOpc != 0 && "Should have a store opcode");
7099 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7100 .addReg(AddrIn).addImm(0).addReg(Data));
7101 } else if (IsThumb1) {
7102 // store + update AddrIn
7103 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7104 .addReg(AddrIn).addImm(0));
7105 MachineInstrBuilder MIB =
7106 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7107 MIB = AddDefaultT1CC(MIB);
7108 MIB.addReg(AddrIn).addImm(StSize);
7109 AddDefaultPred(MIB);
7110 } else if (IsThumb2) {
7111 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7112 .addReg(Data).addReg(AddrIn).addImm(StSize));
7114 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7115 .addReg(Data).addReg(AddrIn).addReg(0)
7121 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7122 MachineBasicBlock *BB) const {
7123 // This pseudo instruction has 3 operands: dst, src, size
7124 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7125 // Otherwise, we will generate unrolled scalar copies.
7126 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7127 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7128 MachineFunction::iterator It = BB;
7131 unsigned dest = MI->getOperand(0).getReg();
7132 unsigned src = MI->getOperand(1).getReg();
7133 unsigned SizeVal = MI->getOperand(2).getImm();
7134 unsigned Align = MI->getOperand(3).getImm();
7135 DebugLoc dl = MI->getDebugLoc();
7137 MachineFunction *MF = BB->getParent();
7138 MachineRegisterInfo &MRI = MF->getRegInfo();
7139 unsigned UnitSize = 0;
7140 const TargetRegisterClass *TRC = nullptr;
7141 const TargetRegisterClass *VecTRC = nullptr;
7143 bool IsThumb1 = Subtarget->isThumb1Only();
7144 bool IsThumb2 = Subtarget->isThumb2();
7148 } else if (Align & 2) {
7151 // Check whether we can use NEON instructions.
7152 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7153 Subtarget->hasNEON()) {
7154 if ((Align % 16 == 0) && SizeVal >= 16)
7156 else if ((Align % 8 == 0) && SizeVal >= 8)
7159 // Can't use NEON instructions.
7164 // Select the correct opcode and register class for unit size load/store
7165 bool IsNeon = UnitSize >= 8;
7166 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7168 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7169 : UnitSize == 8 ? &ARM::DPRRegClass
7172 unsigned BytesLeft = SizeVal % UnitSize;
7173 unsigned LoopSize = SizeVal - BytesLeft;
7175 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7176 // Use LDR and STR to copy.
7177 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7178 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7179 unsigned srcIn = src;
7180 unsigned destIn = dest;
7181 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7182 unsigned srcOut = MRI.createVirtualRegister(TRC);
7183 unsigned destOut = MRI.createVirtualRegister(TRC);
7184 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7185 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7186 IsThumb1, IsThumb2);
7187 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7188 IsThumb1, IsThumb2);
7193 // Handle the leftover bytes with LDRB and STRB.
7194 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7195 // [destOut] = STRB_POST(scratch, destIn, 1)
7196 for (unsigned i = 0; i < BytesLeft; i++) {
7197 unsigned srcOut = MRI.createVirtualRegister(TRC);
7198 unsigned destOut = MRI.createVirtualRegister(TRC);
7199 unsigned scratch = MRI.createVirtualRegister(TRC);
7200 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7201 IsThumb1, IsThumb2);
7202 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7203 IsThumb1, IsThumb2);
7207 MI->eraseFromParent(); // The instruction is gone now.
7211 // Expand the pseudo op to a loop.
7214 // movw varEnd, # --> with thumb2
7216 // ldrcp varEnd, idx --> without thumb2
7217 // fallthrough --> loopMBB
7219 // PHI varPhi, varEnd, varLoop
7220 // PHI srcPhi, src, srcLoop
7221 // PHI destPhi, dst, destLoop
7222 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7223 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7224 // subs varLoop, varPhi, #UnitSize
7226 // fallthrough --> exitMBB
7228 // epilogue to handle left-over bytes
7229 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7230 // [destOut] = STRB_POST(scratch, destLoop, 1)
7231 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7232 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7233 MF->insert(It, loopMBB);
7234 MF->insert(It, exitMBB);
7236 // Transfer the remainder of BB and its successor edges to exitMBB.
7237 exitMBB->splice(exitMBB->begin(), BB,
7238 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7239 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7241 // Load an immediate to varEnd.
7242 unsigned varEnd = MRI.createVirtualRegister(TRC);
7244 unsigned Vtmp = varEnd;
7245 if ((LoopSize & 0xFFFF0000) != 0)
7246 Vtmp = MRI.createVirtualRegister(TRC);
7247 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7248 .addImm(LoopSize & 0xFFFF));
7250 if ((LoopSize & 0xFFFF0000) != 0)
7251 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7252 .addReg(Vtmp).addImm(LoopSize >> 16));
7254 MachineConstantPool *ConstantPool = MF->getConstantPool();
7255 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7256 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7258 // MachineConstantPool wants an explicit alignment.
7259 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7261 Align = getDataLayout()->getTypeAllocSize(C->getType());
7262 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7265 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7266 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7268 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7269 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7271 BB->addSuccessor(loopMBB);
7273 // Generate the loop body:
7274 // varPhi = PHI(varLoop, varEnd)
7275 // srcPhi = PHI(srcLoop, src)
7276 // destPhi = PHI(destLoop, dst)
7277 MachineBasicBlock *entryBB = BB;
7279 unsigned varLoop = MRI.createVirtualRegister(TRC);
7280 unsigned varPhi = MRI.createVirtualRegister(TRC);
7281 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7282 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7283 unsigned destLoop = MRI.createVirtualRegister(TRC);
7284 unsigned destPhi = MRI.createVirtualRegister(TRC);
7286 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7287 .addReg(varLoop).addMBB(loopMBB)
7288 .addReg(varEnd).addMBB(entryBB);
7289 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7290 .addReg(srcLoop).addMBB(loopMBB)
7291 .addReg(src).addMBB(entryBB);
7292 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7293 .addReg(destLoop).addMBB(loopMBB)
7294 .addReg(dest).addMBB(entryBB);
7296 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7297 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7298 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7299 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7300 IsThumb1, IsThumb2);
7301 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7302 IsThumb1, IsThumb2);
7304 // Decrement loop variable by UnitSize.
7306 MachineInstrBuilder MIB =
7307 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7308 MIB = AddDefaultT1CC(MIB);
7309 MIB.addReg(varPhi).addImm(UnitSize);
7310 AddDefaultPred(MIB);
7312 MachineInstrBuilder MIB =
7313 BuildMI(*BB, BB->end(), dl,
7314 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7315 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7316 MIB->getOperand(5).setReg(ARM::CPSR);
7317 MIB->getOperand(5).setIsDef(true);
7319 BuildMI(*BB, BB->end(), dl,
7320 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7321 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7323 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7324 BB->addSuccessor(loopMBB);
7325 BB->addSuccessor(exitMBB);
7327 // Add epilogue to handle BytesLeft.
7329 MachineInstr *StartOfExit = exitMBB->begin();
7331 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7332 // [destOut] = STRB_POST(scratch, destLoop, 1)
7333 unsigned srcIn = srcLoop;
7334 unsigned destIn = destLoop;
7335 for (unsigned i = 0; i < BytesLeft; i++) {
7336 unsigned srcOut = MRI.createVirtualRegister(TRC);
7337 unsigned destOut = MRI.createVirtualRegister(TRC);
7338 unsigned scratch = MRI.createVirtualRegister(TRC);
7339 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7340 IsThumb1, IsThumb2);
7341 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7342 IsThumb1, IsThumb2);
7347 MI->eraseFromParent(); // The instruction is gone now.
7352 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7353 MachineBasicBlock *MBB) const {
7354 const TargetMachine &TM = getTargetMachine();
7355 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7356 DebugLoc DL = MI->getDebugLoc();
7358 assert(Subtarget->isTargetWindows() &&
7359 "__chkstk is only supported on Windows");
7360 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7362 // __chkstk takes the number of words to allocate on the stack in R4, and
7363 // returns the stack adjustment in number of bytes in R4. This will not
7364 // clober any other registers (other than the obvious lr).
7366 // Although, technically, IP should be considered a register which may be
7367 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7368 // thumb-2 environment, so there is no interworking required. As a result, we
7369 // do not expect a veneer to be emitted by the linker, clobbering IP.
7371 // Each module receives its own copy of __chkstk, so no import thunk is
7372 // required, again, ensuring that IP is not clobbered.
7374 // Finally, although some linkers may theoretically provide a trampoline for
7375 // out of range calls (which is quite common due to a 32M range limitation of
7376 // branches for Thumb), we can generate the long-call version via
7377 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7380 switch (TM.getCodeModel()) {
7381 case CodeModel::Small:
7382 case CodeModel::Medium:
7383 case CodeModel::Default:
7384 case CodeModel::Kernel:
7385 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7386 .addImm((unsigned)ARMCC::AL).addReg(0)
7387 .addExternalSymbol("__chkstk")
7388 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7389 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7390 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7392 case CodeModel::Large:
7393 case CodeModel::JITDefault: {
7394 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7395 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7397 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7398 .addExternalSymbol("__chkstk");
7399 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7400 .addImm((unsigned)ARMCC::AL).addReg(0)
7401 .addReg(Reg, RegState::Kill)
7402 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7403 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7404 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7409 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7411 .addReg(ARM::SP).addReg(ARM::R4)));
7413 MI->eraseFromParent();
7418 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7419 MachineBasicBlock *BB) const {
7420 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7421 DebugLoc dl = MI->getDebugLoc();
7422 bool isThumb2 = Subtarget->isThumb2();
7423 switch (MI->getOpcode()) {
7426 llvm_unreachable("Unexpected instr type to insert");
7428 // The Thumb2 pre-indexed stores have the same MI operands, they just
7429 // define them differently in the .td files from the isel patterns, so
7430 // they need pseudos.
7431 case ARM::t2STR_preidx:
7432 MI->setDesc(TII->get(ARM::t2STR_PRE));
7434 case ARM::t2STRB_preidx:
7435 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7437 case ARM::t2STRH_preidx:
7438 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7441 case ARM::STRi_preidx:
7442 case ARM::STRBi_preidx: {
7443 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7444 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7445 // Decode the offset.
7446 unsigned Offset = MI->getOperand(4).getImm();
7447 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7448 Offset = ARM_AM::getAM2Offset(Offset);
7452 MachineMemOperand *MMO = *MI->memoperands_begin();
7453 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7454 .addOperand(MI->getOperand(0)) // Rn_wb
7455 .addOperand(MI->getOperand(1)) // Rt
7456 .addOperand(MI->getOperand(2)) // Rn
7457 .addImm(Offset) // offset (skip GPR==zero_reg)
7458 .addOperand(MI->getOperand(5)) // pred
7459 .addOperand(MI->getOperand(6))
7460 .addMemOperand(MMO);
7461 MI->eraseFromParent();
7464 case ARM::STRr_preidx:
7465 case ARM::STRBr_preidx:
7466 case ARM::STRH_preidx: {
7468 switch (MI->getOpcode()) {
7469 default: llvm_unreachable("unexpected opcode!");
7470 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7471 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7472 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7474 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7475 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7476 MIB.addOperand(MI->getOperand(i));
7477 MI->eraseFromParent();
7481 case ARM::tMOVCCr_pseudo: {
7482 // To "insert" a SELECT_CC instruction, we actually have to insert the
7483 // diamond control-flow pattern. The incoming instruction knows the
7484 // destination vreg to set, the condition code register to branch on, the
7485 // true/false values to select between, and a branch opcode to use.
7486 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7487 MachineFunction::iterator It = BB;
7493 // cmpTY ccX, r1, r2
7495 // fallthrough --> copy0MBB
7496 MachineBasicBlock *thisMBB = BB;
7497 MachineFunction *F = BB->getParent();
7498 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7499 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7500 F->insert(It, copy0MBB);
7501 F->insert(It, sinkMBB);
7503 // Transfer the remainder of BB and its successor edges to sinkMBB.
7504 sinkMBB->splice(sinkMBB->begin(), BB,
7505 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7506 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7508 BB->addSuccessor(copy0MBB);
7509 BB->addSuccessor(sinkMBB);
7511 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7512 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7515 // %FalseValue = ...
7516 // # fallthrough to sinkMBB
7519 // Update machine-CFG edges
7520 BB->addSuccessor(sinkMBB);
7523 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7526 BuildMI(*BB, BB->begin(), dl,
7527 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7528 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7529 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7531 MI->eraseFromParent(); // The pseudo instruction is gone now.
7536 case ARM::BCCZi64: {
7537 // If there is an unconditional branch to the other successor, remove it.
7538 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7540 // Compare both parts that make up the double comparison separately for
7542 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7544 unsigned LHS1 = MI->getOperand(1).getReg();
7545 unsigned LHS2 = MI->getOperand(2).getReg();
7547 AddDefaultPred(BuildMI(BB, dl,
7548 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7549 .addReg(LHS1).addImm(0));
7550 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7551 .addReg(LHS2).addImm(0)
7552 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7554 unsigned RHS1 = MI->getOperand(3).getReg();
7555 unsigned RHS2 = MI->getOperand(4).getReg();
7556 AddDefaultPred(BuildMI(BB, dl,
7557 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7558 .addReg(LHS1).addReg(RHS1));
7559 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7560 .addReg(LHS2).addReg(RHS2)
7561 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7564 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7565 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7566 if (MI->getOperand(0).getImm() == ARMCC::NE)
7567 std::swap(destMBB, exitMBB);
7569 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7570 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7572 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7574 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7576 MI->eraseFromParent(); // The pseudo instruction is gone now.
7580 case ARM::Int_eh_sjlj_setjmp:
7581 case ARM::Int_eh_sjlj_setjmp_nofp:
7582 case ARM::tInt_eh_sjlj_setjmp:
7583 case ARM::t2Int_eh_sjlj_setjmp:
7584 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7585 EmitSjLjDispatchBlock(MI, BB);
7590 // To insert an ABS instruction, we have to insert the
7591 // diamond control-flow pattern. The incoming instruction knows the
7592 // source vreg to test against 0, the destination vreg to set,
7593 // the condition code register to branch on, the
7594 // true/false values to select between, and a branch opcode to use.
7599 // BCC (branch to SinkBB if V0 >= 0)
7600 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7601 // SinkBB: V1 = PHI(V2, V3)
7602 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7603 MachineFunction::iterator BBI = BB;
7605 MachineFunction *Fn = BB->getParent();
7606 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7607 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7608 Fn->insert(BBI, RSBBB);
7609 Fn->insert(BBI, SinkBB);
7611 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7612 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7613 bool isThumb2 = Subtarget->isThumb2();
7614 MachineRegisterInfo &MRI = Fn->getRegInfo();
7615 // In Thumb mode S must not be specified if source register is the SP or
7616 // PC and if destination register is the SP, so restrict register class
7617 unsigned NewRsbDstReg =
7618 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7620 // Transfer the remainder of BB and its successor edges to sinkMBB.
7621 SinkBB->splice(SinkBB->begin(), BB,
7622 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7623 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7625 BB->addSuccessor(RSBBB);
7626 BB->addSuccessor(SinkBB);
7628 // fall through to SinkMBB
7629 RSBBB->addSuccessor(SinkBB);
7631 // insert a cmp at the end of BB
7632 AddDefaultPred(BuildMI(BB, dl,
7633 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7634 .addReg(ABSSrcReg).addImm(0));
7636 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7638 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7639 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7641 // insert rsbri in RSBBB
7642 // Note: BCC and rsbri will be converted into predicated rsbmi
7643 // by if-conversion pass
7644 BuildMI(*RSBBB, RSBBB->begin(), dl,
7645 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7646 .addReg(ABSSrcReg, RegState::Kill)
7647 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7649 // insert PHI in SinkBB,
7650 // reuse ABSDstReg to not change uses of ABS instruction
7651 BuildMI(*SinkBB, SinkBB->begin(), dl,
7652 TII->get(ARM::PHI), ABSDstReg)
7653 .addReg(NewRsbDstReg).addMBB(RSBBB)
7654 .addReg(ABSSrcReg).addMBB(BB);
7656 // remove ABS instruction
7657 MI->eraseFromParent();
7659 // return last added BB
7662 case ARM::COPY_STRUCT_BYVAL_I32:
7664 return EmitStructByval(MI, BB);
7665 case ARM::WIN__CHKSTK:
7666 return EmitLowered__chkstk(MI, BB);
7670 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7671 SDNode *Node) const {
7672 const MCInstrDesc *MCID = &MI->getDesc();
7673 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7674 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7675 // operand is still set to noreg. If needed, set the optional operand's
7676 // register to CPSR, and remove the redundant implicit def.
7678 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7680 // Rename pseudo opcodes.
7681 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7683 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7684 MCID = &TII->get(NewOpc);
7686 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7687 "converted opcode should be the same except for cc_out");
7691 // Add the optional cc_out operand
7692 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7694 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7696 // Any ARM instruction that sets the 's' bit should specify an optional
7697 // "cc_out" operand in the last operand position.
7698 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7699 assert(!NewOpc && "Optional cc_out operand required");
7702 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7703 // since we already have an optional CPSR def.
7704 bool definesCPSR = false;
7705 bool deadCPSR = false;
7706 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7708 const MachineOperand &MO = MI->getOperand(i);
7709 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7713 MI->RemoveOperand(i);
7718 assert(!NewOpc && "Optional cc_out operand required");
7721 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7723 assert(!MI->getOperand(ccOutIdx).getReg() &&
7724 "expect uninitialized optional cc_out operand");
7728 // If this instruction was defined with an optional CPSR def and its dag node
7729 // had a live implicit CPSR def, then activate the optional CPSR def.
7730 MachineOperand &MO = MI->getOperand(ccOutIdx);
7731 MO.setReg(ARM::CPSR);
7735 //===----------------------------------------------------------------------===//
7736 // ARM Optimization Hooks
7737 //===----------------------------------------------------------------------===//
7739 // Helper function that checks if N is a null or all ones constant.
7740 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7741 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7744 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7747 // Return true if N is conditionally 0 or all ones.
7748 // Detects these expressions where cc is an i1 value:
7750 // (select cc 0, y) [AllOnes=0]
7751 // (select cc y, 0) [AllOnes=0]
7752 // (zext cc) [AllOnes=0]
7753 // (sext cc) [AllOnes=0/1]
7754 // (select cc -1, y) [AllOnes=1]
7755 // (select cc y, -1) [AllOnes=1]
7757 // Invert is set when N is the null/all ones constant when CC is false.
7758 // OtherOp is set to the alternative value of N.
7759 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7760 SDValue &CC, bool &Invert,
7762 SelectionDAG &DAG) {
7763 switch (N->getOpcode()) {
7764 default: return false;
7766 CC = N->getOperand(0);
7767 SDValue N1 = N->getOperand(1);
7768 SDValue N2 = N->getOperand(2);
7769 if (isZeroOrAllOnes(N1, AllOnes)) {
7774 if (isZeroOrAllOnes(N2, AllOnes)) {
7781 case ISD::ZERO_EXTEND:
7782 // (zext cc) can never be the all ones value.
7786 case ISD::SIGN_EXTEND: {
7787 EVT VT = N->getValueType(0);
7788 CC = N->getOperand(0);
7789 if (CC.getValueType() != MVT::i1)
7793 // When looking for an AllOnes constant, N is an sext, and the 'other'
7795 OtherOp = DAG.getConstant(0, VT);
7796 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7797 // When looking for a 0 constant, N can be zext or sext.
7798 OtherOp = DAG.getConstant(1, VT);
7800 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7806 // Combine a constant select operand into its use:
7808 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7809 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7810 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7811 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7812 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7814 // The transform is rejected if the select doesn't have a constant operand that
7815 // is null, or all ones when AllOnes is set.
7817 // Also recognize sext/zext from i1:
7819 // (add (zext cc), x) -> (select cc (add x, 1), x)
7820 // (add (sext cc), x) -> (select cc (add x, -1), x)
7822 // These transformations eventually create predicated instructions.
7824 // @param N The node to transform.
7825 // @param Slct The N operand that is a select.
7826 // @param OtherOp The other N operand (x above).
7827 // @param DCI Context.
7828 // @param AllOnes Require the select constant to be all ones instead of null.
7829 // @returns The new node, or SDValue() on failure.
7831 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7832 TargetLowering::DAGCombinerInfo &DCI,
7833 bool AllOnes = false) {
7834 SelectionDAG &DAG = DCI.DAG;
7835 EVT VT = N->getValueType(0);
7836 SDValue NonConstantVal;
7839 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7840 NonConstantVal, DAG))
7843 // Slct is now know to be the desired identity constant when CC is true.
7844 SDValue TrueVal = OtherOp;
7845 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7846 OtherOp, NonConstantVal);
7847 // Unless SwapSelectOps says CC should be false.
7849 std::swap(TrueVal, FalseVal);
7851 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7852 CCOp, TrueVal, FalseVal);
7855 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7857 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7858 TargetLowering::DAGCombinerInfo &DCI) {
7859 SDValue N0 = N->getOperand(0);
7860 SDValue N1 = N->getOperand(1);
7861 if (N0.getNode()->hasOneUse()) {
7862 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7863 if (Result.getNode())
7866 if (N1.getNode()->hasOneUse()) {
7867 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7868 if (Result.getNode())
7874 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7875 // (only after legalization).
7876 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7877 TargetLowering::DAGCombinerInfo &DCI,
7878 const ARMSubtarget *Subtarget) {
7880 // Only perform optimization if after legalize, and if NEON is available. We
7881 // also expected both operands to be BUILD_VECTORs.
7882 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7883 || N0.getOpcode() != ISD::BUILD_VECTOR
7884 || N1.getOpcode() != ISD::BUILD_VECTOR)
7887 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7888 EVT VT = N->getValueType(0);
7889 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7892 // Check that the vector operands are of the right form.
7893 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7894 // operands, where N is the size of the formed vector.
7895 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7896 // index such that we have a pair wise add pattern.
7898 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7899 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7901 SDValue Vec = N0->getOperand(0)->getOperand(0);
7902 SDNode *V = Vec.getNode();
7903 unsigned nextIndex = 0;
7905 // For each operands to the ADD which are BUILD_VECTORs,
7906 // check to see if each of their operands are an EXTRACT_VECTOR with
7907 // the same vector and appropriate index.
7908 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7909 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7910 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7912 SDValue ExtVec0 = N0->getOperand(i);
7913 SDValue ExtVec1 = N1->getOperand(i);
7915 // First operand is the vector, verify its the same.
7916 if (V != ExtVec0->getOperand(0).getNode() ||
7917 V != ExtVec1->getOperand(0).getNode())
7920 // Second is the constant, verify its correct.
7921 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7922 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7924 // For the constant, we want to see all the even or all the odd.
7925 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7926 || C1->getZExtValue() != nextIndex+1)
7935 // Create VPADDL node.
7936 SelectionDAG &DAG = DCI.DAG;
7937 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7939 // Build operand list.
7940 SmallVector<SDValue, 8> Ops;
7941 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7942 TLI.getPointerTy()));
7944 // Input is the vector.
7947 // Get widened type and narrowed type.
7949 unsigned numElem = VT.getVectorNumElements();
7951 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7952 switch (inputLaneType.getSimpleVT().SimpleTy) {
7953 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7954 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7955 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7957 llvm_unreachable("Invalid vector element type for padd optimization.");
7960 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7961 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7962 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7965 static SDValue findMUL_LOHI(SDValue V) {
7966 if (V->getOpcode() == ISD::UMUL_LOHI ||
7967 V->getOpcode() == ISD::SMUL_LOHI)
7972 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7973 TargetLowering::DAGCombinerInfo &DCI,
7974 const ARMSubtarget *Subtarget) {
7976 if (Subtarget->isThumb1Only()) return SDValue();
7978 // Only perform the checks after legalize when the pattern is available.
7979 if (DCI.isBeforeLegalize()) return SDValue();
7981 // Look for multiply add opportunities.
7982 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7983 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7984 // a glue link from the first add to the second add.
7985 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7986 // a S/UMLAL instruction.
7989 // \ / \ [no multiline comment]
7995 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7996 SDValue AddcOp0 = AddcNode->getOperand(0);
7997 SDValue AddcOp1 = AddcNode->getOperand(1);
7999 // Check if the two operands are from the same mul_lohi node.
8000 if (AddcOp0.getNode() == AddcOp1.getNode())
8003 assert(AddcNode->getNumValues() == 2 &&
8004 AddcNode->getValueType(0) == MVT::i32 &&
8005 "Expect ADDC with two result values. First: i32");
8007 // Check that we have a glued ADDC node.
8008 if (AddcNode->getValueType(1) != MVT::Glue)
8011 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8012 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8013 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8014 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8015 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8018 // Look for the glued ADDE.
8019 SDNode* AddeNode = AddcNode->getGluedUser();
8023 // Make sure it is really an ADDE.
8024 if (AddeNode->getOpcode() != ISD::ADDE)
8027 assert(AddeNode->getNumOperands() == 3 &&
8028 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8029 "ADDE node has the wrong inputs");
8031 // Check for the triangle shape.
8032 SDValue AddeOp0 = AddeNode->getOperand(0);
8033 SDValue AddeOp1 = AddeNode->getOperand(1);
8035 // Make sure that the ADDE operands are not coming from the same node.
8036 if (AddeOp0.getNode() == AddeOp1.getNode())
8039 // Find the MUL_LOHI node walking up ADDE's operands.
8040 bool IsLeftOperandMUL = false;
8041 SDValue MULOp = findMUL_LOHI(AddeOp0);
8042 if (MULOp == SDValue())
8043 MULOp = findMUL_LOHI(AddeOp1);
8045 IsLeftOperandMUL = true;
8046 if (MULOp == SDValue())
8049 // Figure out the right opcode.
8050 unsigned Opc = MULOp->getOpcode();
8051 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8053 // Figure out the high and low input values to the MLAL node.
8054 SDValue* HiAdd = nullptr;
8055 SDValue* LoMul = nullptr;
8056 SDValue* LowAdd = nullptr;
8058 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8059 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8062 if (IsLeftOperandMUL)
8068 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8069 // whose low result is fed to the ADDC we are checking.
8071 if (AddcOp0 == MULOp.getValue(0)) {
8075 if (AddcOp1 == MULOp.getValue(0)) {
8083 // Create the merged node.
8084 SelectionDAG &DAG = DCI.DAG;
8086 // Build operand list.
8087 SmallVector<SDValue, 8> Ops;
8088 Ops.push_back(LoMul->getOperand(0));
8089 Ops.push_back(LoMul->getOperand(1));
8090 Ops.push_back(*LowAdd);
8091 Ops.push_back(*HiAdd);
8093 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8094 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8096 // Replace the ADDs' nodes uses by the MLA node's values.
8097 SDValue HiMLALResult(MLALNode.getNode(), 1);
8098 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8100 SDValue LoMLALResult(MLALNode.getNode(), 0);
8101 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8103 // Return original node to notify the driver to stop replacing.
8104 SDValue resNode(AddcNode, 0);
8108 /// PerformADDCCombine - Target-specific dag combine transform from
8109 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8110 static SDValue PerformADDCCombine(SDNode *N,
8111 TargetLowering::DAGCombinerInfo &DCI,
8112 const ARMSubtarget *Subtarget) {
8114 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8118 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8119 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8120 /// called with the default operands, and if that fails, with commuted
8122 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8123 TargetLowering::DAGCombinerInfo &DCI,
8124 const ARMSubtarget *Subtarget){
8126 // Attempt to create vpaddl for this add.
8127 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8128 if (Result.getNode())
8131 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8132 if (N0.getNode()->hasOneUse()) {
8133 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8134 if (Result.getNode()) return Result;
8139 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8141 static SDValue PerformADDCombine(SDNode *N,
8142 TargetLowering::DAGCombinerInfo &DCI,
8143 const ARMSubtarget *Subtarget) {
8144 SDValue N0 = N->getOperand(0);
8145 SDValue N1 = N->getOperand(1);
8147 // First try with the default operand order.
8148 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8149 if (Result.getNode())
8152 // If that didn't work, try again with the operands commuted.
8153 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8156 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8158 static SDValue PerformSUBCombine(SDNode *N,
8159 TargetLowering::DAGCombinerInfo &DCI) {
8160 SDValue N0 = N->getOperand(0);
8161 SDValue N1 = N->getOperand(1);
8163 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8164 if (N1.getNode()->hasOneUse()) {
8165 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8166 if (Result.getNode()) return Result;
8172 /// PerformVMULCombine
8173 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8174 /// special multiplier accumulator forwarding.
8180 // However, for (A + B) * (A + B),
8187 static SDValue PerformVMULCombine(SDNode *N,
8188 TargetLowering::DAGCombinerInfo &DCI,
8189 const ARMSubtarget *Subtarget) {
8190 if (!Subtarget->hasVMLxForwarding())
8193 SelectionDAG &DAG = DCI.DAG;
8194 SDValue N0 = N->getOperand(0);
8195 SDValue N1 = N->getOperand(1);
8196 unsigned Opcode = N0.getOpcode();
8197 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8198 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8199 Opcode = N1.getOpcode();
8200 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8201 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8209 EVT VT = N->getValueType(0);
8211 SDValue N00 = N0->getOperand(0);
8212 SDValue N01 = N0->getOperand(1);
8213 return DAG.getNode(Opcode, DL, VT,
8214 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8215 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8218 static SDValue PerformMULCombine(SDNode *N,
8219 TargetLowering::DAGCombinerInfo &DCI,
8220 const ARMSubtarget *Subtarget) {
8221 SelectionDAG &DAG = DCI.DAG;
8223 if (Subtarget->isThumb1Only())
8226 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8229 EVT VT = N->getValueType(0);
8230 if (VT.is64BitVector() || VT.is128BitVector())
8231 return PerformVMULCombine(N, DCI, Subtarget);
8235 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8239 int64_t MulAmt = C->getSExtValue();
8240 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8242 ShiftAmt = ShiftAmt & (32 - 1);
8243 SDValue V = N->getOperand(0);
8247 MulAmt >>= ShiftAmt;
8250 if (isPowerOf2_32(MulAmt - 1)) {
8251 // (mul x, 2^N + 1) => (add (shl x, N), x)
8252 Res = DAG.getNode(ISD::ADD, DL, VT,
8254 DAG.getNode(ISD::SHL, DL, VT,
8256 DAG.getConstant(Log2_32(MulAmt - 1),
8258 } else if (isPowerOf2_32(MulAmt + 1)) {
8259 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8260 Res = DAG.getNode(ISD::SUB, DL, VT,
8261 DAG.getNode(ISD::SHL, DL, VT,
8263 DAG.getConstant(Log2_32(MulAmt + 1),
8269 uint64_t MulAmtAbs = -MulAmt;
8270 if (isPowerOf2_32(MulAmtAbs + 1)) {
8271 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8272 Res = DAG.getNode(ISD::SUB, DL, VT,
8274 DAG.getNode(ISD::SHL, DL, VT,
8276 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8278 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8279 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8280 Res = DAG.getNode(ISD::ADD, DL, VT,
8282 DAG.getNode(ISD::SHL, DL, VT,
8284 DAG.getConstant(Log2_32(MulAmtAbs-1),
8286 Res = DAG.getNode(ISD::SUB, DL, VT,
8287 DAG.getConstant(0, MVT::i32),Res);
8294 Res = DAG.getNode(ISD::SHL, DL, VT,
8295 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8297 // Do not add new nodes to DAG combiner worklist.
8298 DCI.CombineTo(N, Res, false);
8302 static SDValue PerformANDCombine(SDNode *N,
8303 TargetLowering::DAGCombinerInfo &DCI,
8304 const ARMSubtarget *Subtarget) {
8306 // Attempt to use immediate-form VBIC
8307 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8309 EVT VT = N->getValueType(0);
8310 SelectionDAG &DAG = DCI.DAG;
8312 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8315 APInt SplatBits, SplatUndef;
8316 unsigned SplatBitSize;
8319 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8320 if (SplatBitSize <= 64) {
8322 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8323 SplatUndef.getZExtValue(), SplatBitSize,
8324 DAG, VbicVT, VT.is128BitVector(),
8326 if (Val.getNode()) {
8328 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8329 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8330 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8335 if (!Subtarget->isThumb1Only()) {
8336 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8337 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8338 if (Result.getNode())
8345 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8346 static SDValue PerformORCombine(SDNode *N,
8347 TargetLowering::DAGCombinerInfo &DCI,
8348 const ARMSubtarget *Subtarget) {
8349 // Attempt to use immediate-form VORR
8350 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8352 EVT VT = N->getValueType(0);
8353 SelectionDAG &DAG = DCI.DAG;
8355 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8358 APInt SplatBits, SplatUndef;
8359 unsigned SplatBitSize;
8361 if (BVN && Subtarget->hasNEON() &&
8362 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8363 if (SplatBitSize <= 64) {
8365 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8366 SplatUndef.getZExtValue(), SplatBitSize,
8367 DAG, VorrVT, VT.is128BitVector(),
8369 if (Val.getNode()) {
8371 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8372 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8373 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8378 if (!Subtarget->isThumb1Only()) {
8379 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8380 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8381 if (Result.getNode())
8385 // The code below optimizes (or (and X, Y), Z).
8386 // The AND operand needs to have a single user to make these optimizations
8388 SDValue N0 = N->getOperand(0);
8389 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8391 SDValue N1 = N->getOperand(1);
8393 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8394 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8395 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8397 unsigned SplatBitSize;
8400 APInt SplatBits0, SplatBits1;
8401 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8402 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8403 // Ensure that the second operand of both ands are constants
8404 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8405 HasAnyUndefs) && !HasAnyUndefs) {
8406 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8407 HasAnyUndefs) && !HasAnyUndefs) {
8408 // Ensure that the bit width of the constants are the same and that
8409 // the splat arguments are logical inverses as per the pattern we
8410 // are trying to simplify.
8411 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8412 SplatBits0 == ~SplatBits1) {
8413 // Canonicalize the vector type to make instruction selection
8415 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8416 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8420 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8426 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8429 // BFI is only available on V6T2+
8430 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8434 // 1) or (and A, mask), val => ARMbfi A, val, mask
8435 // iff (val & mask) == val
8437 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8438 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8439 // && mask == ~mask2
8440 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8441 // && ~mask == mask2
8442 // (i.e., copy a bitfield value into another bitfield of the same width)
8447 SDValue N00 = N0.getOperand(0);
8449 // The value and the mask need to be constants so we can verify this is
8450 // actually a bitfield set. If the mask is 0xffff, we can do better
8451 // via a movt instruction, so don't use BFI in that case.
8452 SDValue MaskOp = N0.getOperand(1);
8453 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8456 unsigned Mask = MaskC->getZExtValue();
8460 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8461 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8463 unsigned Val = N1C->getZExtValue();
8464 if ((Val & ~Mask) != Val)
8467 if (ARM::isBitFieldInvertedMask(Mask)) {
8468 Val >>= countTrailingZeros(~Mask);
8470 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8471 DAG.getConstant(Val, MVT::i32),
8472 DAG.getConstant(Mask, MVT::i32));
8474 // Do not add new nodes to DAG combiner worklist.
8475 DCI.CombineTo(N, Res, false);
8478 } else if (N1.getOpcode() == ISD::AND) {
8479 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8480 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8483 unsigned Mask2 = N11C->getZExtValue();
8485 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8487 if (ARM::isBitFieldInvertedMask(Mask) &&
8489 // The pack halfword instruction works better for masks that fit it,
8490 // so use that when it's available.
8491 if (Subtarget->hasT2ExtractPack() &&
8492 (Mask == 0xffff || Mask == 0xffff0000))
8495 unsigned amt = countTrailingZeros(Mask2);
8496 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8497 DAG.getConstant(amt, MVT::i32));
8498 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8499 DAG.getConstant(Mask, MVT::i32));
8500 // Do not add new nodes to DAG combiner worklist.
8501 DCI.CombineTo(N, Res, false);
8503 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8505 // The pack halfword instruction works better for masks that fit it,
8506 // so use that when it's available.
8507 if (Subtarget->hasT2ExtractPack() &&
8508 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8511 unsigned lsb = countTrailingZeros(Mask);
8512 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8513 DAG.getConstant(lsb, MVT::i32));
8514 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8515 DAG.getConstant(Mask2, MVT::i32));
8516 // Do not add new nodes to DAG combiner worklist.
8517 DCI.CombineTo(N, Res, false);
8522 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8523 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8524 ARM::isBitFieldInvertedMask(~Mask)) {
8525 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8526 // where lsb(mask) == #shamt and masked bits of B are known zero.
8527 SDValue ShAmt = N00.getOperand(1);
8528 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8529 unsigned LSB = countTrailingZeros(Mask);
8533 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8534 DAG.getConstant(~Mask, MVT::i32));
8536 // Do not add new nodes to DAG combiner worklist.
8537 DCI.CombineTo(N, Res, false);
8543 static SDValue PerformXORCombine(SDNode *N,
8544 TargetLowering::DAGCombinerInfo &DCI,
8545 const ARMSubtarget *Subtarget) {
8546 EVT VT = N->getValueType(0);
8547 SelectionDAG &DAG = DCI.DAG;
8549 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8552 if (!Subtarget->isThumb1Only()) {
8553 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8554 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8555 if (Result.getNode())
8562 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8563 /// the bits being cleared by the AND are not demanded by the BFI.
8564 static SDValue PerformBFICombine(SDNode *N,
8565 TargetLowering::DAGCombinerInfo &DCI) {
8566 SDValue N1 = N->getOperand(1);
8567 if (N1.getOpcode() == ISD::AND) {
8568 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8571 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8572 unsigned LSB = countTrailingZeros(~InvMask);
8573 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8575 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8576 "undefined behavior");
8577 unsigned Mask = (1u << Width) - 1;
8578 unsigned Mask2 = N11C->getZExtValue();
8579 if ((Mask & (~Mask2)) == 0)
8580 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8581 N->getOperand(0), N1.getOperand(0),
8587 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8588 /// ARMISD::VMOVRRD.
8589 static SDValue PerformVMOVRRDCombine(SDNode *N,
8590 TargetLowering::DAGCombinerInfo &DCI,
8591 const ARMSubtarget *Subtarget) {
8592 // vmovrrd(vmovdrr x, y) -> x,y
8593 SDValue InDouble = N->getOperand(0);
8594 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8595 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8597 // vmovrrd(load f64) -> (load i32), (load i32)
8598 SDNode *InNode = InDouble.getNode();
8599 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8600 InNode->getValueType(0) == MVT::f64 &&
8601 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8602 !cast<LoadSDNode>(InNode)->isVolatile()) {
8603 // TODO: Should this be done for non-FrameIndex operands?
8604 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8606 SelectionDAG &DAG = DCI.DAG;
8608 SDValue BasePtr = LD->getBasePtr();
8609 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8610 LD->getPointerInfo(), LD->isVolatile(),
8611 LD->isNonTemporal(), LD->isInvariant(),
8612 LD->getAlignment());
8614 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8615 DAG.getConstant(4, MVT::i32));
8616 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8617 LD->getPointerInfo(), LD->isVolatile(),
8618 LD->isNonTemporal(), LD->isInvariant(),
8619 std::min(4U, LD->getAlignment() / 2));
8621 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8622 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8623 std::swap (NewLD1, NewLD2);
8624 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8631 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8632 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8633 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8634 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8635 SDValue Op0 = N->getOperand(0);
8636 SDValue Op1 = N->getOperand(1);
8637 if (Op0.getOpcode() == ISD::BITCAST)
8638 Op0 = Op0.getOperand(0);
8639 if (Op1.getOpcode() == ISD::BITCAST)
8640 Op1 = Op1.getOperand(0);
8641 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8642 Op0.getNode() == Op1.getNode() &&
8643 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8644 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8645 N->getValueType(0), Op0.getOperand(0));
8649 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8650 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8651 /// i64 vector to have f64 elements, since the value can then be loaded
8652 /// directly into a VFP register.
8653 static bool hasNormalLoadOperand(SDNode *N) {
8654 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8655 for (unsigned i = 0; i < NumElts; ++i) {
8656 SDNode *Elt = N->getOperand(i).getNode();
8657 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8663 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8664 /// ISD::BUILD_VECTOR.
8665 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8666 TargetLowering::DAGCombinerInfo &DCI,
8667 const ARMSubtarget *Subtarget) {
8668 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8669 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8670 // into a pair of GPRs, which is fine when the value is used as a scalar,
8671 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8672 SelectionDAG &DAG = DCI.DAG;
8673 if (N->getNumOperands() == 2) {
8674 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8679 // Load i64 elements as f64 values so that type legalization does not split
8680 // them up into i32 values.
8681 EVT VT = N->getValueType(0);
8682 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8685 SmallVector<SDValue, 8> Ops;
8686 unsigned NumElts = VT.getVectorNumElements();
8687 for (unsigned i = 0; i < NumElts; ++i) {
8688 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8690 // Make the DAGCombiner fold the bitcast.
8691 DCI.AddToWorklist(V.getNode());
8693 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8694 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8695 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8698 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8700 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8701 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8702 // At that time, we may have inserted bitcasts from integer to float.
8703 // If these bitcasts have survived DAGCombine, change the lowering of this
8704 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8705 // force to use floating point types.
8707 // Make sure we can change the type of the vector.
8708 // This is possible iff:
8709 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8710 // 1.1. Vector is used only once.
8711 // 1.2. Use is a bit convert to an integer type.
8712 // 2. The size of its operands are 32-bits (64-bits are not legal).
8713 EVT VT = N->getValueType(0);
8714 EVT EltVT = VT.getVectorElementType();
8716 // Check 1.1. and 2.
8717 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8720 // By construction, the input type must be float.
8721 assert(EltVT == MVT::f32 && "Unexpected type!");
8724 SDNode *Use = *N->use_begin();
8725 if (Use->getOpcode() != ISD::BITCAST ||
8726 Use->getValueType(0).isFloatingPoint())
8729 // Check profitability.
8730 // Model is, if more than half of the relevant operands are bitcast from
8731 // i32, turn the build_vector into a sequence of insert_vector_elt.
8732 // Relevant operands are everything that is not statically
8733 // (i.e., at compile time) bitcasted.
8734 unsigned NumOfBitCastedElts = 0;
8735 unsigned NumElts = VT.getVectorNumElements();
8736 unsigned NumOfRelevantElts = NumElts;
8737 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8738 SDValue Elt = N->getOperand(Idx);
8739 if (Elt->getOpcode() == ISD::BITCAST) {
8740 // Assume only bit cast to i32 will go away.
8741 if (Elt->getOperand(0).getValueType() == MVT::i32)
8742 ++NumOfBitCastedElts;
8743 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8744 // Constants are statically casted, thus do not count them as
8745 // relevant operands.
8746 --NumOfRelevantElts;
8749 // Check if more than half of the elements require a non-free bitcast.
8750 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8753 SelectionDAG &DAG = DCI.DAG;
8754 // Create the new vector type.
8755 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8756 // Check if the type is legal.
8757 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8758 if (!TLI.isTypeLegal(VecVT))
8762 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8763 // => BITCAST INSERT_VECTOR_ELT
8764 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8766 SDValue Vec = DAG.getUNDEF(VecVT);
8768 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8769 SDValue V = N->getOperand(Idx);
8770 if (V.getOpcode() == ISD::UNDEF)
8772 if (V.getOpcode() == ISD::BITCAST &&
8773 V->getOperand(0).getValueType() == MVT::i32)
8774 // Fold obvious case.
8775 V = V.getOperand(0);
8777 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8778 // Make the DAGCombiner fold the bitcasts.
8779 DCI.AddToWorklist(V.getNode());
8781 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8782 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8784 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8785 // Make the DAGCombiner fold the bitcasts.
8786 DCI.AddToWorklist(Vec.getNode());
8790 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8791 /// ISD::INSERT_VECTOR_ELT.
8792 static SDValue PerformInsertEltCombine(SDNode *N,
8793 TargetLowering::DAGCombinerInfo &DCI) {
8794 // Bitcast an i64 load inserted into a vector to f64.
8795 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8796 EVT VT = N->getValueType(0);
8797 SDNode *Elt = N->getOperand(1).getNode();
8798 if (VT.getVectorElementType() != MVT::i64 ||
8799 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8802 SelectionDAG &DAG = DCI.DAG;
8804 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8805 VT.getVectorNumElements());
8806 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8807 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8808 // Make the DAGCombiner fold the bitcasts.
8809 DCI.AddToWorklist(Vec.getNode());
8810 DCI.AddToWorklist(V.getNode());
8811 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8812 Vec, V, N->getOperand(2));
8813 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8816 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8817 /// ISD::VECTOR_SHUFFLE.
8818 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8819 // The LLVM shufflevector instruction does not require the shuffle mask
8820 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8821 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8822 // operands do not match the mask length, they are extended by concatenating
8823 // them with undef vectors. That is probably the right thing for other
8824 // targets, but for NEON it is better to concatenate two double-register
8825 // size vector operands into a single quad-register size vector. Do that
8826 // transformation here:
8827 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8828 // shuffle(concat(v1, v2), undef)
8829 SDValue Op0 = N->getOperand(0);
8830 SDValue Op1 = N->getOperand(1);
8831 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8832 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8833 Op0.getNumOperands() != 2 ||
8834 Op1.getNumOperands() != 2)
8836 SDValue Concat0Op1 = Op0.getOperand(1);
8837 SDValue Concat1Op1 = Op1.getOperand(1);
8838 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8839 Concat1Op1.getOpcode() != ISD::UNDEF)
8841 // Skip the transformation if any of the types are illegal.
8842 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8843 EVT VT = N->getValueType(0);
8844 if (!TLI.isTypeLegal(VT) ||
8845 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8846 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8849 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8850 Op0.getOperand(0), Op1.getOperand(0));
8851 // Translate the shuffle mask.
8852 SmallVector<int, 16> NewMask;
8853 unsigned NumElts = VT.getVectorNumElements();
8854 unsigned HalfElts = NumElts/2;
8855 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8856 for (unsigned n = 0; n < NumElts; ++n) {
8857 int MaskElt = SVN->getMaskElt(n);
8859 if (MaskElt < (int)HalfElts)
8861 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8862 NewElt = HalfElts + MaskElt - NumElts;
8863 NewMask.push_back(NewElt);
8865 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8866 DAG.getUNDEF(VT), NewMask.data());
8869 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8870 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8871 /// base address updates.
8872 /// For generic load/stores, the memory type is assumed to be a vector.
8873 /// The caller is assumed to have checked legality.
8874 static SDValue CombineBaseUpdate(SDNode *N,
8875 TargetLowering::DAGCombinerInfo &DCI) {
8876 SelectionDAG &DAG = DCI.DAG;
8877 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8878 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8879 const bool isStore = N->getOpcode() == ISD::STORE;
8880 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8881 SDValue Addr = N->getOperand(AddrOpIdx);
8882 MemSDNode *MemN = cast<MemSDNode>(N);
8884 // Search for a use of the address operand that is an increment.
8885 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8886 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8888 if (User->getOpcode() != ISD::ADD ||
8889 UI.getUse().getResNo() != Addr.getResNo())
8892 // Check that the add is independent of the load/store. Otherwise, folding
8893 // it would create a cycle.
8894 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8897 // Find the new opcode for the updating load/store.
8898 bool isLoadOp = true;
8899 bool isLaneOp = false;
8900 unsigned NewOpc = 0;
8901 unsigned NumVecs = 0;
8903 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8905 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8906 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8908 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8910 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8912 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8914 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8915 NumVecs = 2; isLaneOp = true; break;
8916 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8917 NumVecs = 3; isLaneOp = true; break;
8918 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8919 NumVecs = 4; isLaneOp = true; break;
8920 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8921 NumVecs = 1; isLoadOp = false; break;
8922 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8923 NumVecs = 2; isLoadOp = false; break;
8924 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8925 NumVecs = 3; isLoadOp = false; break;
8926 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8927 NumVecs = 4; isLoadOp = false; break;
8928 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8929 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8930 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8931 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8932 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8933 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8937 switch (N->getOpcode()) {
8938 default: llvm_unreachable("unexpected opcode for Neon base update");
8939 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8940 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8941 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8942 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
8943 NumVecs = 1; isLaneOp = false; break;
8944 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
8945 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
8949 // Find the size of memory referenced by the load/store.
8952 VecTy = N->getValueType(0);
8953 } else if (isIntrinsic) {
8954 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8956 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
8957 VecTy = N->getOperand(1).getValueType();
8960 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8962 NumBytes /= VecTy.getVectorNumElements();
8964 // If the increment is a constant, it must match the memory ref size.
8965 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8966 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8967 uint64_t IncVal = CInc->getZExtValue();
8968 if (IncVal != NumBytes)
8970 } else if (NumBytes >= 3 * 16) {
8971 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8972 // separate instructions that make it harder to use a non-constant update.
8976 // OK, we found an ADD we can fold into the base update.
8977 // Now, create a _UPD node, taking care of not breaking alignment.
8979 EVT AlignedVecTy = VecTy;
8980 unsigned Alignment = MemN->getAlignment();
8982 // If this is a less-than-standard-aligned load/store, change the type to
8983 // match the standard alignment.
8984 // The alignment is overlooked when selecting _UPD variants; and it's
8985 // easier to introduce bitcasts here than fix that.
8986 // There are 3 ways to get to this base-update combine:
8987 // - intrinsics: they are assumed to be properly aligned (to the standard
8988 // alignment of the memory type), so we don't need to do anything.
8989 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
8990 // intrinsics, so, likewise, there's nothing to do.
8991 // - generic load/store instructions: the alignment is specified as an
8992 // explicit operand, rather than implicitly as the standard alignment
8993 // of the memory type (like the intrisics). We need to change the
8994 // memory type to match the explicit alignment. That way, we don't
8995 // generate non-standard-aligned ARMISD::VLDx nodes.
8996 if (isa<LSBaseSDNode>(N)) {
8999 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9000 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9001 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9002 assert(!isLaneOp && "Unexpected generic load/store lane.");
9003 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9004 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9006 // Don't set an explicit alignment on regular load/stores that we want
9007 // to transform to VLD/VST 1_UPD nodes.
9008 // This matches the behavior of regular load/stores, which only get an
9009 // explicit alignment if the MMO alignment is larger than the standard
9010 // alignment of the memory type.
9011 // Intrinsics, however, always get an explicit alignment, set to the
9012 // alignment of the MMO.
9016 // Create the new updating load/store node.
9017 // First, create an SDVTList for the new updating node's results.
9019 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9021 for (n = 0; n < NumResultVecs; ++n)
9022 Tys[n] = AlignedVecTy;
9023 Tys[n++] = MVT::i32;
9024 Tys[n] = MVT::Other;
9025 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9027 // Then, gather the new node's operands.
9028 SmallVector<SDValue, 8> Ops;
9029 Ops.push_back(N->getOperand(0)); // incoming chain
9030 Ops.push_back(N->getOperand(AddrOpIdx));
9033 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9034 // Try to match the intrinsic's signature
9035 Ops.push_back(StN->getValue());
9037 // Loads (and of course intrinsics) match the intrinsics' signature,
9038 // so just add all but the alignment operand.
9039 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9040 Ops.push_back(N->getOperand(i));
9043 // For all node types, the alignment operand is always the last one.
9044 Ops.push_back(DAG.getConstant(Alignment, MVT::i32));
9046 // If this is a non-standard-aligned STORE, the penultimate operand is the
9047 // stored value. Bitcast it to the aligned type.
9048 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9049 SDValue &StVal = Ops[Ops.size()-2];
9050 StVal = DAG.getNode(ISD::BITCAST, SDLoc(N), AlignedVecTy, StVal);
9053 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9055 MemN->getMemOperand());
9058 SmallVector<SDValue, 5> NewResults;
9059 for (unsigned i = 0; i < NumResultVecs; ++i)
9060 NewResults.push_back(SDValue(UpdN.getNode(), i));
9062 // If this is an non-standard-aligned LOAD, the first result is the loaded
9063 // value. Bitcast it to the expected result type.
9064 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9065 SDValue &LdVal = NewResults[0];
9066 LdVal = DAG.getNode(ISD::BITCAST, SDLoc(N), VecTy, LdVal);
9069 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9070 DCI.CombineTo(N, NewResults);
9071 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9078 static SDValue PerformVLDCombine(SDNode *N,
9079 TargetLowering::DAGCombinerInfo &DCI) {
9080 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9083 return CombineBaseUpdate(N, DCI);
9086 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9087 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9088 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9090 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9091 SelectionDAG &DAG = DCI.DAG;
9092 EVT VT = N->getValueType(0);
9093 // vldN-dup instructions only support 64-bit vectors for N > 1.
9094 if (!VT.is64BitVector())
9097 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9098 SDNode *VLD = N->getOperand(0).getNode();
9099 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9101 unsigned NumVecs = 0;
9102 unsigned NewOpc = 0;
9103 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9104 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9106 NewOpc = ARMISD::VLD2DUP;
9107 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9109 NewOpc = ARMISD::VLD3DUP;
9110 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9112 NewOpc = ARMISD::VLD4DUP;
9117 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9118 // numbers match the load.
9119 unsigned VLDLaneNo =
9120 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9121 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9123 // Ignore uses of the chain result.
9124 if (UI.getUse().getResNo() == NumVecs)
9127 if (User->getOpcode() != ARMISD::VDUPLANE ||
9128 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9132 // Create the vldN-dup node.
9135 for (n = 0; n < NumVecs; ++n)
9137 Tys[n] = MVT::Other;
9138 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9139 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9140 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9141 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9142 Ops, VLDMemInt->getMemoryVT(),
9143 VLDMemInt->getMemOperand());
9146 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9148 unsigned ResNo = UI.getUse().getResNo();
9149 // Ignore uses of the chain result.
9150 if (ResNo == NumVecs)
9153 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9156 // Now the vldN-lane intrinsic is dead except for its chain result.
9157 // Update uses of the chain.
9158 std::vector<SDValue> VLDDupResults;
9159 for (unsigned n = 0; n < NumVecs; ++n)
9160 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9161 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9162 DCI.CombineTo(VLD, VLDDupResults);
9167 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9168 /// ARMISD::VDUPLANE.
9169 static SDValue PerformVDUPLANECombine(SDNode *N,
9170 TargetLowering::DAGCombinerInfo &DCI) {
9171 SDValue Op = N->getOperand(0);
9173 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9174 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9175 if (CombineVLDDUP(N, DCI))
9176 return SDValue(N, 0);
9178 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9179 // redundant. Ignore bit_converts for now; element sizes are checked below.
9180 while (Op.getOpcode() == ISD::BITCAST)
9181 Op = Op.getOperand(0);
9182 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9185 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9186 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9187 // The canonical VMOV for a zero vector uses a 32-bit element size.
9188 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9190 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9192 EVT VT = N->getValueType(0);
9193 if (EltSize > VT.getVectorElementType().getSizeInBits())
9196 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9199 static SDValue PerformLOADCombine(SDNode *N,
9200 TargetLowering::DAGCombinerInfo &DCI) {
9201 EVT VT = N->getValueType(0);
9203 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9204 if (ISD::isNormalLoad(N) && VT.isVector() &&
9205 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9206 return CombineBaseUpdate(N, DCI);
9211 /// PerformSTORECombine - Target-specific dag combine xforms for
9213 static SDValue PerformSTORECombine(SDNode *N,
9214 TargetLowering::DAGCombinerInfo &DCI) {
9215 StoreSDNode *St = cast<StoreSDNode>(N);
9216 if (St->isVolatile())
9219 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9220 // pack all of the elements in one place. Next, store to memory in fewer
9222 SDValue StVal = St->getValue();
9223 EVT VT = StVal.getValueType();
9224 if (St->isTruncatingStore() && VT.isVector()) {
9225 SelectionDAG &DAG = DCI.DAG;
9226 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9227 EVT StVT = St->getMemoryVT();
9228 unsigned NumElems = VT.getVectorNumElements();
9229 assert(StVT != VT && "Cannot truncate to the same type");
9230 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9231 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9233 // From, To sizes and ElemCount must be pow of two
9234 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9236 // We are going to use the original vector elt for storing.
9237 // Accumulated smaller vector elements must be a multiple of the store size.
9238 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9240 unsigned SizeRatio = FromEltSz / ToEltSz;
9241 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9243 // Create a type on which we perform the shuffle.
9244 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9245 NumElems*SizeRatio);
9246 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9249 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9250 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9251 for (unsigned i = 0; i < NumElems; ++i)
9252 ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9254 // Can't shuffle using an illegal type.
9255 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9257 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9258 DAG.getUNDEF(WideVec.getValueType()),
9260 // At this point all of the data is stored at the bottom of the
9261 // register. We now need to save it to mem.
9263 // Find the largest store unit
9264 MVT StoreType = MVT::i8;
9265 for (MVT Tp : MVT::integer_valuetypes()) {
9266 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9269 // Didn't find a legal store type.
9270 if (!TLI.isTypeLegal(StoreType))
9273 // Bitcast the original vector into a vector of store-size units
9274 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9275 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9276 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9277 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9278 SmallVector<SDValue, 8> Chains;
9279 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9280 TLI.getPointerTy());
9281 SDValue BasePtr = St->getBasePtr();
9283 // Perform one or more big stores into memory.
9284 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9285 for (unsigned I = 0; I < E; I++) {
9286 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9287 StoreType, ShuffWide,
9288 DAG.getIntPtrConstant(I));
9289 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9290 St->getPointerInfo(), St->isVolatile(),
9291 St->isNonTemporal(), St->getAlignment());
9292 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9294 Chains.push_back(Ch);
9296 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9299 if (!ISD::isNormalStore(St))
9302 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9303 // ARM stores of arguments in the same cache line.
9304 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9305 StVal.getNode()->hasOneUse()) {
9306 SelectionDAG &DAG = DCI.DAG;
9307 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9309 SDValue BasePtr = St->getBasePtr();
9310 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9311 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9312 BasePtr, St->getPointerInfo(), St->isVolatile(),
9313 St->isNonTemporal(), St->getAlignment());
9315 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9316 DAG.getConstant(4, MVT::i32));
9317 return DAG.getStore(NewST1.getValue(0), DL,
9318 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9319 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9320 St->isNonTemporal(),
9321 std::min(4U, St->getAlignment() / 2));
9324 if (StVal.getValueType() == MVT::i64 &&
9325 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9327 // Bitcast an i64 store extracted from a vector to f64.
9328 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9329 SelectionDAG &DAG = DCI.DAG;
9331 SDValue IntVec = StVal.getOperand(0);
9332 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9333 IntVec.getValueType().getVectorNumElements());
9334 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9335 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9336 Vec, StVal.getOperand(1));
9338 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9339 // Make the DAGCombiner fold the bitcasts.
9340 DCI.AddToWorklist(Vec.getNode());
9341 DCI.AddToWorklist(ExtElt.getNode());
9342 DCI.AddToWorklist(V.getNode());
9343 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9344 St->getPointerInfo(), St->isVolatile(),
9345 St->isNonTemporal(), St->getAlignment(),
9349 // If this is a legal vector store, try to combine it into a VST1_UPD.
9350 if (ISD::isNormalStore(N) && VT.isVector() &&
9351 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9352 return CombineBaseUpdate(N, DCI);
9357 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9358 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9359 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9363 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9365 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9370 APFloat APF = C->getValueAPF();
9371 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9372 != APFloat::opOK || !isExact)
9375 c0 = (I == 0) ? cN : c0;
9376 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9383 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9384 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9385 /// when the VMUL has a constant operand that is a power of 2.
9387 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9388 /// vmul.f32 d16, d17, d16
9389 /// vcvt.s32.f32 d16, d16
9391 /// vcvt.s32.f32 d16, d16, #3
9392 static SDValue PerformVCVTCombine(SDNode *N,
9393 TargetLowering::DAGCombinerInfo &DCI,
9394 const ARMSubtarget *Subtarget) {
9395 SelectionDAG &DAG = DCI.DAG;
9396 SDValue Op = N->getOperand(0);
9398 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9399 Op.getOpcode() != ISD::FMUL)
9403 SDValue N0 = Op->getOperand(0);
9404 SDValue ConstVec = Op->getOperand(1);
9405 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9407 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9408 !isConstVecPow2(ConstVec, isSigned, C))
9411 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9412 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9413 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9414 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9416 // These instructions only exist converting from f32 to i32. We can handle
9417 // smaller integers by generating an extra truncate, but larger ones would
9418 // be lossy. We also can't handle more then 4 lanes, since these intructions
9419 // only support v2i32/v4i32 types.
9423 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9424 Intrinsic::arm_neon_vcvtfp2fxu;
9425 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9426 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9427 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9428 DAG.getConstant(Log2_64(C), MVT::i32));
9430 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9431 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9436 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9437 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9438 /// when the VDIV has a constant operand that is a power of 2.
9440 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9441 /// vcvt.f32.s32 d16, d16
9442 /// vdiv.f32 d16, d17, d16
9444 /// vcvt.f32.s32 d16, d16, #3
9445 static SDValue PerformVDIVCombine(SDNode *N,
9446 TargetLowering::DAGCombinerInfo &DCI,
9447 const ARMSubtarget *Subtarget) {
9448 SelectionDAG &DAG = DCI.DAG;
9449 SDValue Op = N->getOperand(0);
9450 unsigned OpOpcode = Op.getNode()->getOpcode();
9452 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9453 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9457 SDValue ConstVec = N->getOperand(1);
9458 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9460 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9461 !isConstVecPow2(ConstVec, isSigned, C))
9464 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9465 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9466 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9467 // These instructions only exist converting from i32 to f32. We can handle
9468 // smaller integers by generating an extra extend, but larger ones would
9473 SDValue ConvInput = Op.getOperand(0);
9474 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9475 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9476 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9477 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9480 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9481 Intrinsic::arm_neon_vcvtfxu2fp;
9482 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9484 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9485 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9488 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9489 /// operand of a vector shift operation, where all the elements of the
9490 /// build_vector must have the same constant integer value.
9491 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9492 // Ignore bit_converts.
9493 while (Op.getOpcode() == ISD::BITCAST)
9494 Op = Op.getOperand(0);
9495 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9496 APInt SplatBits, SplatUndef;
9497 unsigned SplatBitSize;
9499 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9500 HasAnyUndefs, ElementBits) ||
9501 SplatBitSize > ElementBits)
9503 Cnt = SplatBits.getSExtValue();
9507 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9508 /// operand of a vector shift left operation. That value must be in the range:
9509 /// 0 <= Value < ElementBits for a left shift; or
9510 /// 0 <= Value <= ElementBits for a long left shift.
9511 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9512 assert(VT.isVector() && "vector shift count is not a vector type");
9513 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9514 if (! getVShiftImm(Op, ElementBits, Cnt))
9516 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9519 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9520 /// operand of a vector shift right operation. For a shift opcode, the value
9521 /// is positive, but for an intrinsic the value count must be negative. The
9522 /// absolute value must be in the range:
9523 /// 1 <= |Value| <= ElementBits for a right shift; or
9524 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9525 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9527 assert(VT.isVector() && "vector shift count is not a vector type");
9528 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9529 if (! getVShiftImm(Op, ElementBits, Cnt))
9533 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9536 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9537 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9538 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9541 // Don't do anything for most intrinsics.
9544 // Vector shifts: check for immediate versions and lower them.
9545 // Note: This is done during DAG combining instead of DAG legalizing because
9546 // the build_vectors for 64-bit vector element shift counts are generally
9547 // not legal, and it is hard to see their values after they get legalized to
9548 // loads from a constant pool.
9549 case Intrinsic::arm_neon_vshifts:
9550 case Intrinsic::arm_neon_vshiftu:
9551 case Intrinsic::arm_neon_vrshifts:
9552 case Intrinsic::arm_neon_vrshiftu:
9553 case Intrinsic::arm_neon_vrshiftn:
9554 case Intrinsic::arm_neon_vqshifts:
9555 case Intrinsic::arm_neon_vqshiftu:
9556 case Intrinsic::arm_neon_vqshiftsu:
9557 case Intrinsic::arm_neon_vqshiftns:
9558 case Intrinsic::arm_neon_vqshiftnu:
9559 case Intrinsic::arm_neon_vqshiftnsu:
9560 case Intrinsic::arm_neon_vqrshiftns:
9561 case Intrinsic::arm_neon_vqrshiftnu:
9562 case Intrinsic::arm_neon_vqrshiftnsu: {
9563 EVT VT = N->getOperand(1).getValueType();
9565 unsigned VShiftOpc = 0;
9568 case Intrinsic::arm_neon_vshifts:
9569 case Intrinsic::arm_neon_vshiftu:
9570 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9571 VShiftOpc = ARMISD::VSHL;
9574 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9575 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9576 ARMISD::VSHRs : ARMISD::VSHRu);
9581 case Intrinsic::arm_neon_vrshifts:
9582 case Intrinsic::arm_neon_vrshiftu:
9583 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9587 case Intrinsic::arm_neon_vqshifts:
9588 case Intrinsic::arm_neon_vqshiftu:
9589 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9593 case Intrinsic::arm_neon_vqshiftsu:
9594 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9596 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9598 case Intrinsic::arm_neon_vrshiftn:
9599 case Intrinsic::arm_neon_vqshiftns:
9600 case Intrinsic::arm_neon_vqshiftnu:
9601 case Intrinsic::arm_neon_vqshiftnsu:
9602 case Intrinsic::arm_neon_vqrshiftns:
9603 case Intrinsic::arm_neon_vqrshiftnu:
9604 case Intrinsic::arm_neon_vqrshiftnsu:
9605 // Narrowing shifts require an immediate right shift.
9606 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9608 llvm_unreachable("invalid shift count for narrowing vector shift "
9612 llvm_unreachable("unhandled vector shift");
9616 case Intrinsic::arm_neon_vshifts:
9617 case Intrinsic::arm_neon_vshiftu:
9618 // Opcode already set above.
9620 case Intrinsic::arm_neon_vrshifts:
9621 VShiftOpc = ARMISD::VRSHRs; break;
9622 case Intrinsic::arm_neon_vrshiftu:
9623 VShiftOpc = ARMISD::VRSHRu; break;
9624 case Intrinsic::arm_neon_vrshiftn:
9625 VShiftOpc = ARMISD::VRSHRN; break;
9626 case Intrinsic::arm_neon_vqshifts:
9627 VShiftOpc = ARMISD::VQSHLs; break;
9628 case Intrinsic::arm_neon_vqshiftu:
9629 VShiftOpc = ARMISD::VQSHLu; break;
9630 case Intrinsic::arm_neon_vqshiftsu:
9631 VShiftOpc = ARMISD::VQSHLsu; break;
9632 case Intrinsic::arm_neon_vqshiftns:
9633 VShiftOpc = ARMISD::VQSHRNs; break;
9634 case Intrinsic::arm_neon_vqshiftnu:
9635 VShiftOpc = ARMISD::VQSHRNu; break;
9636 case Intrinsic::arm_neon_vqshiftnsu:
9637 VShiftOpc = ARMISD::VQSHRNsu; break;
9638 case Intrinsic::arm_neon_vqrshiftns:
9639 VShiftOpc = ARMISD::VQRSHRNs; break;
9640 case Intrinsic::arm_neon_vqrshiftnu:
9641 VShiftOpc = ARMISD::VQRSHRNu; break;
9642 case Intrinsic::arm_neon_vqrshiftnsu:
9643 VShiftOpc = ARMISD::VQRSHRNsu; break;
9646 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9647 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9650 case Intrinsic::arm_neon_vshiftins: {
9651 EVT VT = N->getOperand(1).getValueType();
9653 unsigned VShiftOpc = 0;
9655 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9656 VShiftOpc = ARMISD::VSLI;
9657 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9658 VShiftOpc = ARMISD::VSRI;
9660 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9663 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9664 N->getOperand(1), N->getOperand(2),
9665 DAG.getConstant(Cnt, MVT::i32));
9668 case Intrinsic::arm_neon_vqrshifts:
9669 case Intrinsic::arm_neon_vqrshiftu:
9670 // No immediate versions of these to check for.
9677 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9678 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9679 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9680 /// vector element shift counts are generally not legal, and it is hard to see
9681 /// their values after they get legalized to loads from a constant pool.
9682 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9683 const ARMSubtarget *ST) {
9684 EVT VT = N->getValueType(0);
9685 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9686 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9687 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9688 SDValue N1 = N->getOperand(1);
9689 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9690 SDValue N0 = N->getOperand(0);
9691 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9692 DAG.MaskedValueIsZero(N0.getOperand(0),
9693 APInt::getHighBitsSet(32, 16)))
9694 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9698 // Nothing to be done for scalar shifts.
9699 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9700 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9703 assert(ST->hasNEON() && "unexpected vector shift");
9706 switch (N->getOpcode()) {
9707 default: llvm_unreachable("unexpected shift opcode");
9710 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9711 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9712 DAG.getConstant(Cnt, MVT::i32));
9717 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9718 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9719 ARMISD::VSHRs : ARMISD::VSHRu);
9720 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9721 DAG.getConstant(Cnt, MVT::i32));
9727 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9728 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9729 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9730 const ARMSubtarget *ST) {
9731 SDValue N0 = N->getOperand(0);
9733 // Check for sign- and zero-extensions of vector extract operations of 8-
9734 // and 16-bit vector elements. NEON supports these directly. They are
9735 // handled during DAG combining because type legalization will promote them
9736 // to 32-bit types and it is messy to recognize the operations after that.
9737 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9738 SDValue Vec = N0.getOperand(0);
9739 SDValue Lane = N0.getOperand(1);
9740 EVT VT = N->getValueType(0);
9741 EVT EltVT = N0.getValueType();
9742 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9744 if (VT == MVT::i32 &&
9745 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9746 TLI.isTypeLegal(Vec.getValueType()) &&
9747 isa<ConstantSDNode>(Lane)) {
9750 switch (N->getOpcode()) {
9751 default: llvm_unreachable("unexpected opcode");
9752 case ISD::SIGN_EXTEND:
9753 Opc = ARMISD::VGETLANEs;
9755 case ISD::ZERO_EXTEND:
9756 case ISD::ANY_EXTEND:
9757 Opc = ARMISD::VGETLANEu;
9760 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9767 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9768 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9769 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9770 const ARMSubtarget *ST) {
9771 // If the target supports NEON, try to use vmax/vmin instructions for f32
9772 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9773 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9774 // a NaN; only do the transformation when it matches that behavior.
9776 // For now only do this when using NEON for FP operations; if using VFP, it
9777 // is not obvious that the benefit outweighs the cost of switching to the
9779 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9780 N->getValueType(0) != MVT::f32)
9783 SDValue CondLHS = N->getOperand(0);
9784 SDValue CondRHS = N->getOperand(1);
9785 SDValue LHS = N->getOperand(2);
9786 SDValue RHS = N->getOperand(3);
9787 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9789 unsigned Opcode = 0;
9791 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9792 IsReversed = false; // x CC y ? x : y
9793 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9794 IsReversed = true ; // x CC y ? y : x
9808 // If LHS is NaN, an ordered comparison will be false and the result will
9809 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9810 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9811 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9812 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9814 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9815 // will return -0, so vmin can only be used for unsafe math or if one of
9816 // the operands is known to be nonzero.
9817 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9818 !DAG.getTarget().Options.UnsafeFPMath &&
9819 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9821 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9830 // If LHS is NaN, an ordered comparison will be false and the result will
9831 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9832 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9833 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9834 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9836 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9837 // will return +0, so vmax can only be used for unsafe math or if one of
9838 // the operands is known to be nonzero.
9839 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9840 !DAG.getTarget().Options.UnsafeFPMath &&
9841 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9843 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9849 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9852 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9854 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9855 SDValue Cmp = N->getOperand(4);
9856 if (Cmp.getOpcode() != ARMISD::CMPZ)
9857 // Only looking at EQ and NE cases.
9860 EVT VT = N->getValueType(0);
9862 SDValue LHS = Cmp.getOperand(0);
9863 SDValue RHS = Cmp.getOperand(1);
9864 SDValue FalseVal = N->getOperand(0);
9865 SDValue TrueVal = N->getOperand(1);
9866 SDValue ARMcc = N->getOperand(2);
9867 ARMCC::CondCodes CC =
9868 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9886 /// FIXME: Turn this into a target neutral optimization?
9888 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9889 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9890 N->getOperand(3), Cmp);
9891 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9893 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9894 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9895 N->getOperand(3), NewCmp);
9898 if (Res.getNode()) {
9899 APInt KnownZero, KnownOne;
9900 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9901 // Capture demanded bits information that would be otherwise lost.
9902 if (KnownZero == 0xfffffffe)
9903 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9904 DAG.getValueType(MVT::i1));
9905 else if (KnownZero == 0xffffff00)
9906 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9907 DAG.getValueType(MVT::i8));
9908 else if (KnownZero == 0xffff0000)
9909 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9910 DAG.getValueType(MVT::i16));
9916 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9917 DAGCombinerInfo &DCI) const {
9918 switch (N->getOpcode()) {
9920 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9921 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9922 case ISD::SUB: return PerformSUBCombine(N, DCI);
9923 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9924 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9925 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9926 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9927 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9928 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9929 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9930 case ISD::STORE: return PerformSTORECombine(N, DCI);
9931 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9932 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9933 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9934 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9935 case ISD::FP_TO_SINT:
9936 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9937 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9938 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9941 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9942 case ISD::SIGN_EXTEND:
9943 case ISD::ZERO_EXTEND:
9944 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9945 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9946 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9947 case ISD::LOAD: return PerformLOADCombine(N, DCI);
9948 case ARMISD::VLD2DUP:
9949 case ARMISD::VLD3DUP:
9950 case ARMISD::VLD4DUP:
9951 return PerformVLDCombine(N, DCI);
9952 case ARMISD::BUILD_VECTOR:
9953 return PerformARMBUILD_VECTORCombine(N, DCI);
9954 case ISD::INTRINSIC_VOID:
9955 case ISD::INTRINSIC_W_CHAIN:
9956 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9957 case Intrinsic::arm_neon_vld1:
9958 case Intrinsic::arm_neon_vld2:
9959 case Intrinsic::arm_neon_vld3:
9960 case Intrinsic::arm_neon_vld4:
9961 case Intrinsic::arm_neon_vld2lane:
9962 case Intrinsic::arm_neon_vld3lane:
9963 case Intrinsic::arm_neon_vld4lane:
9964 case Intrinsic::arm_neon_vst1:
9965 case Intrinsic::arm_neon_vst2:
9966 case Intrinsic::arm_neon_vst3:
9967 case Intrinsic::arm_neon_vst4:
9968 case Intrinsic::arm_neon_vst2lane:
9969 case Intrinsic::arm_neon_vst3lane:
9970 case Intrinsic::arm_neon_vst4lane:
9971 return PerformVLDCombine(N, DCI);
9979 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9981 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9984 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9988 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9989 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9991 switch (VT.getSimpleVT().SimpleTy) {
9997 // Unaligned access can use (for example) LRDB, LRDH, LDR
9998 if (AllowsUnaligned) {
10000 *Fast = Subtarget->hasV7Ops();
10007 // For any little-endian targets with neon, we can support unaligned ld/st
10008 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10009 // A big-endian target may also explicitly support unaligned accesses
10010 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10020 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10021 unsigned AlignCheck) {
10022 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10023 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10026 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10027 unsigned DstAlign, unsigned SrcAlign,
10028 bool IsMemset, bool ZeroMemset,
10030 MachineFunction &MF) const {
10031 const Function *F = MF.getFunction();
10033 // See if we can use NEON instructions for this...
10034 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10035 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10038 (memOpAlign(SrcAlign, DstAlign, 16) ||
10039 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10041 } else if (Size >= 8 &&
10042 (memOpAlign(SrcAlign, DstAlign, 8) ||
10043 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10049 // Lowering to i32/i16 if the size permits.
10052 else if (Size >= 2)
10055 // Let the target-independent logic figure it out.
10059 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10060 if (Val.getOpcode() != ISD::LOAD)
10063 EVT VT1 = Val.getValueType();
10064 if (!VT1.isSimple() || !VT1.isInteger() ||
10065 !VT2.isSimple() || !VT2.isInteger())
10068 switch (VT1.getSimpleVT().SimpleTy) {
10073 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10080 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10081 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10084 if (!isTypeLegal(EVT::getEVT(Ty1)))
10087 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10089 // Assuming the caller doesn't have a zeroext or signext return parameter,
10090 // truncation all the way down to i1 is valid.
10095 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10099 unsigned Scale = 1;
10100 switch (VT.getSimpleVT().SimpleTy) {
10101 default: return false;
10116 if ((V & (Scale - 1)) != 0)
10119 return V == (V & ((1LL << 5) - 1));
10122 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10123 const ARMSubtarget *Subtarget) {
10124 bool isNeg = false;
10130 switch (VT.getSimpleVT().SimpleTy) {
10131 default: return false;
10136 // + imm12 or - imm8
10138 return V == (V & ((1LL << 8) - 1));
10139 return V == (V & ((1LL << 12) - 1));
10142 // Same as ARM mode. FIXME: NEON?
10143 if (!Subtarget->hasVFP2())
10148 return V == (V & ((1LL << 8) - 1));
10152 /// isLegalAddressImmediate - Return true if the integer value can be used
10153 /// as the offset of the target addressing mode for load / store of the
10155 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10156 const ARMSubtarget *Subtarget) {
10160 if (!VT.isSimple())
10163 if (Subtarget->isThumb1Only())
10164 return isLegalT1AddressImmediate(V, VT);
10165 else if (Subtarget->isThumb2())
10166 return isLegalT2AddressImmediate(V, VT, Subtarget);
10171 switch (VT.getSimpleVT().SimpleTy) {
10172 default: return false;
10177 return V == (V & ((1LL << 12) - 1));
10180 return V == (V & ((1LL << 8) - 1));
10183 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10188 return V == (V & ((1LL << 8) - 1));
10192 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10194 int Scale = AM.Scale;
10198 switch (VT.getSimpleVT().SimpleTy) {
10199 default: return false;
10207 Scale = Scale & ~1;
10208 return Scale == 2 || Scale == 4 || Scale == 8;
10211 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10215 // Note, we allow "void" uses (basically, uses that aren't loads or
10216 // stores), because arm allows folding a scale into many arithmetic
10217 // operations. This should be made more precise and revisited later.
10219 // Allow r << imm, but the imm has to be a multiple of two.
10220 if (Scale & 1) return false;
10221 return isPowerOf2_32(Scale);
10225 /// isLegalAddressingMode - Return true if the addressing mode represented
10226 /// by AM is legal for this target, for a load/store of the specified type.
10227 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10229 EVT VT = getValueType(Ty, true);
10230 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10233 // Can never fold addr of global into load/store.
10237 switch (AM.Scale) {
10238 case 0: // no scale reg, must be "r+i" or "r", or "i".
10241 if (Subtarget->isThumb1Only())
10245 // ARM doesn't support any R+R*scale+imm addr modes.
10249 if (!VT.isSimple())
10252 if (Subtarget->isThumb2())
10253 return isLegalT2ScaledAddressingMode(AM, VT);
10255 int Scale = AM.Scale;
10256 switch (VT.getSimpleVT().SimpleTy) {
10257 default: return false;
10261 if (Scale < 0) Scale = -Scale;
10265 return isPowerOf2_32(Scale & ~1);
10269 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10274 // Note, we allow "void" uses (basically, uses that aren't loads or
10275 // stores), because arm allows folding a scale into many arithmetic
10276 // operations. This should be made more precise and revisited later.
10278 // Allow r << imm, but the imm has to be a multiple of two.
10279 if (Scale & 1) return false;
10280 return isPowerOf2_32(Scale);
10286 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10287 /// icmp immediate, that is the target has icmp instructions which can compare
10288 /// a register against the immediate without having to materialize the
10289 /// immediate into a register.
10290 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10291 // Thumb2 and ARM modes can use cmn for negative immediates.
10292 if (!Subtarget->isThumb())
10293 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10294 if (Subtarget->isThumb2())
10295 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10296 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10297 return Imm >= 0 && Imm <= 255;
10300 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10301 /// *or sub* immediate, that is the target has add or sub instructions which can
10302 /// add a register with the immediate without having to materialize the
10303 /// immediate into a register.
10304 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10305 // Same encoding for add/sub, just flip the sign.
10306 int64_t AbsImm = llvm::abs64(Imm);
10307 if (!Subtarget->isThumb())
10308 return ARM_AM::getSOImmVal(AbsImm) != -1;
10309 if (Subtarget->isThumb2())
10310 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10311 // Thumb1 only has 8-bit unsigned immediate.
10312 return AbsImm >= 0 && AbsImm <= 255;
10315 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10316 bool isSEXTLoad, SDValue &Base,
10317 SDValue &Offset, bool &isInc,
10318 SelectionDAG &DAG) {
10319 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10322 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10323 // AddressingMode 3
10324 Base = Ptr->getOperand(0);
10325 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10326 int RHSC = (int)RHS->getZExtValue();
10327 if (RHSC < 0 && RHSC > -256) {
10328 assert(Ptr->getOpcode() == ISD::ADD);
10330 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10334 isInc = (Ptr->getOpcode() == ISD::ADD);
10335 Offset = Ptr->getOperand(1);
10337 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10338 // AddressingMode 2
10339 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10340 int RHSC = (int)RHS->getZExtValue();
10341 if (RHSC < 0 && RHSC > -0x1000) {
10342 assert(Ptr->getOpcode() == ISD::ADD);
10344 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10345 Base = Ptr->getOperand(0);
10350 if (Ptr->getOpcode() == ISD::ADD) {
10352 ARM_AM::ShiftOpc ShOpcVal=
10353 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10354 if (ShOpcVal != ARM_AM::no_shift) {
10355 Base = Ptr->getOperand(1);
10356 Offset = Ptr->getOperand(0);
10358 Base = Ptr->getOperand(0);
10359 Offset = Ptr->getOperand(1);
10364 isInc = (Ptr->getOpcode() == ISD::ADD);
10365 Base = Ptr->getOperand(0);
10366 Offset = Ptr->getOperand(1);
10370 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10374 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10375 bool isSEXTLoad, SDValue &Base,
10376 SDValue &Offset, bool &isInc,
10377 SelectionDAG &DAG) {
10378 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10381 Base = Ptr->getOperand(0);
10382 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10383 int RHSC = (int)RHS->getZExtValue();
10384 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10385 assert(Ptr->getOpcode() == ISD::ADD);
10387 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10389 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10390 isInc = Ptr->getOpcode() == ISD::ADD;
10391 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10399 /// getPreIndexedAddressParts - returns true by value, base pointer and
10400 /// offset pointer and addressing mode by reference if the node's address
10401 /// can be legally represented as pre-indexed load / store address.
10403 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10405 ISD::MemIndexedMode &AM,
10406 SelectionDAG &DAG) const {
10407 if (Subtarget->isThumb1Only())
10412 bool isSEXTLoad = false;
10413 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10414 Ptr = LD->getBasePtr();
10415 VT = LD->getMemoryVT();
10416 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10417 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10418 Ptr = ST->getBasePtr();
10419 VT = ST->getMemoryVT();
10424 bool isLegal = false;
10425 if (Subtarget->isThumb2())
10426 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10427 Offset, isInc, DAG);
10429 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10430 Offset, isInc, DAG);
10434 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10438 /// getPostIndexedAddressParts - returns true by value, base pointer and
10439 /// offset pointer and addressing mode by reference if this node can be
10440 /// combined with a load / store to form a post-indexed load / store.
10441 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10444 ISD::MemIndexedMode &AM,
10445 SelectionDAG &DAG) const {
10446 if (Subtarget->isThumb1Only())
10451 bool isSEXTLoad = false;
10452 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10453 VT = LD->getMemoryVT();
10454 Ptr = LD->getBasePtr();
10455 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10456 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10457 VT = ST->getMemoryVT();
10458 Ptr = ST->getBasePtr();
10463 bool isLegal = false;
10464 if (Subtarget->isThumb2())
10465 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10468 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10474 // Swap base ptr and offset to catch more post-index load / store when
10475 // it's legal. In Thumb2 mode, offset must be an immediate.
10476 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10477 !Subtarget->isThumb2())
10478 std::swap(Base, Offset);
10480 // Post-indexed load / store update the base pointer.
10485 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10489 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10492 const SelectionDAG &DAG,
10493 unsigned Depth) const {
10494 unsigned BitWidth = KnownOne.getBitWidth();
10495 KnownZero = KnownOne = APInt(BitWidth, 0);
10496 switch (Op.getOpcode()) {
10502 // These nodes' second result is a boolean
10503 if (Op.getResNo() == 0)
10505 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10507 case ARMISD::CMOV: {
10508 // Bits are known zero/one if known on the LHS and RHS.
10509 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10510 if (KnownZero == 0 && KnownOne == 0) return;
10512 APInt KnownZeroRHS, KnownOneRHS;
10513 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10514 KnownZero &= KnownZeroRHS;
10515 KnownOne &= KnownOneRHS;
10518 case ISD::INTRINSIC_W_CHAIN: {
10519 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10520 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10523 case Intrinsic::arm_ldaex:
10524 case Intrinsic::arm_ldrex: {
10525 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10526 unsigned MemBits = VT.getScalarType().getSizeInBits();
10527 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10535 //===----------------------------------------------------------------------===//
10536 // ARM Inline Assembly Support
10537 //===----------------------------------------------------------------------===//
10539 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10540 // Looking for "rev" which is V6+.
10541 if (!Subtarget->hasV6Ops())
10544 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10545 std::string AsmStr = IA->getAsmString();
10546 SmallVector<StringRef, 4> AsmPieces;
10547 SplitString(AsmStr, AsmPieces, ";\n");
10549 switch (AsmPieces.size()) {
10550 default: return false;
10552 AsmStr = AsmPieces[0];
10554 SplitString(AsmStr, AsmPieces, " \t,");
10557 if (AsmPieces.size() == 3 &&
10558 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10559 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10560 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10561 if (Ty && Ty->getBitWidth() == 32)
10562 return IntrinsicLowering::LowerToByteSwap(CI);
10570 /// getConstraintType - Given a constraint letter, return the type of
10571 /// constraint it is for this target.
10572 ARMTargetLowering::ConstraintType
10573 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10574 if (Constraint.size() == 1) {
10575 switch (Constraint[0]) {
10577 case 'l': return C_RegisterClass;
10578 case 'w': return C_RegisterClass;
10579 case 'h': return C_RegisterClass;
10580 case 'x': return C_RegisterClass;
10581 case 't': return C_RegisterClass;
10582 case 'j': return C_Other; // Constant for movw.
10583 // An address with a single base register. Due to the way we
10584 // currently handle addresses it is the same as an 'r' memory constraint.
10585 case 'Q': return C_Memory;
10587 } else if (Constraint.size() == 2) {
10588 switch (Constraint[0]) {
10590 // All 'U+' constraints are addresses.
10591 case 'U': return C_Memory;
10594 return TargetLowering::getConstraintType(Constraint);
10597 /// Examine constraint type and operand type and determine a weight value.
10598 /// This object must already have been set up with the operand type
10599 /// and the current alternative constraint selected.
10600 TargetLowering::ConstraintWeight
10601 ARMTargetLowering::getSingleConstraintMatchWeight(
10602 AsmOperandInfo &info, const char *constraint) const {
10603 ConstraintWeight weight = CW_Invalid;
10604 Value *CallOperandVal = info.CallOperandVal;
10605 // If we don't have a value, we can't do a match,
10606 // but allow it at the lowest weight.
10607 if (!CallOperandVal)
10609 Type *type = CallOperandVal->getType();
10610 // Look at the constraint type.
10611 switch (*constraint) {
10613 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10616 if (type->isIntegerTy()) {
10617 if (Subtarget->isThumb())
10618 weight = CW_SpecificReg;
10620 weight = CW_Register;
10624 if (type->isFloatingPointTy())
10625 weight = CW_Register;
10631 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10633 ARMTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10634 const std::string &Constraint,
10636 if (Constraint.size() == 1) {
10637 // GCC ARM Constraint Letters
10638 switch (Constraint[0]) {
10639 case 'l': // Low regs or general regs.
10640 if (Subtarget->isThumb())
10641 return RCPair(0U, &ARM::tGPRRegClass);
10642 return RCPair(0U, &ARM::GPRRegClass);
10643 case 'h': // High regs or no regs.
10644 if (Subtarget->isThumb())
10645 return RCPair(0U, &ARM::hGPRRegClass);
10648 if (Subtarget->isThumb1Only())
10649 return RCPair(0U, &ARM::tGPRRegClass);
10650 return RCPair(0U, &ARM::GPRRegClass);
10652 if (VT == MVT::Other)
10654 if (VT == MVT::f32)
10655 return RCPair(0U, &ARM::SPRRegClass);
10656 if (VT.getSizeInBits() == 64)
10657 return RCPair(0U, &ARM::DPRRegClass);
10658 if (VT.getSizeInBits() == 128)
10659 return RCPair(0U, &ARM::QPRRegClass);
10662 if (VT == MVT::Other)
10664 if (VT == MVT::f32)
10665 return RCPair(0U, &ARM::SPR_8RegClass);
10666 if (VT.getSizeInBits() == 64)
10667 return RCPair(0U, &ARM::DPR_8RegClass);
10668 if (VT.getSizeInBits() == 128)
10669 return RCPair(0U, &ARM::QPR_8RegClass);
10672 if (VT == MVT::f32)
10673 return RCPair(0U, &ARM::SPRRegClass);
10677 if (StringRef("{cc}").equals_lower(Constraint))
10678 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10680 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10683 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10684 /// vector. If it is invalid, don't add anything to Ops.
10685 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10686 std::string &Constraint,
10687 std::vector<SDValue>&Ops,
10688 SelectionDAG &DAG) const {
10691 // Currently only support length 1 constraints.
10692 if (Constraint.length() != 1) return;
10694 char ConstraintLetter = Constraint[0];
10695 switch (ConstraintLetter) {
10698 case 'I': case 'J': case 'K': case 'L':
10699 case 'M': case 'N': case 'O':
10700 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10704 int64_t CVal64 = C->getSExtValue();
10705 int CVal = (int) CVal64;
10706 // None of these constraints allow values larger than 32 bits. Check
10707 // that the value fits in an int.
10708 if (CVal != CVal64)
10711 switch (ConstraintLetter) {
10713 // Constant suitable for movw, must be between 0 and
10715 if (Subtarget->hasV6T2Ops())
10716 if (CVal >= 0 && CVal <= 65535)
10720 if (Subtarget->isThumb1Only()) {
10721 // This must be a constant between 0 and 255, for ADD
10723 if (CVal >= 0 && CVal <= 255)
10725 } else if (Subtarget->isThumb2()) {
10726 // A constant that can be used as an immediate value in a
10727 // data-processing instruction.
10728 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10731 // A constant that can be used as an immediate value in a
10732 // data-processing instruction.
10733 if (ARM_AM::getSOImmVal(CVal) != -1)
10739 if (Subtarget->isThumb()) { // FIXME thumb2
10740 // This must be a constant between -255 and -1, for negated ADD
10741 // immediates. This can be used in GCC with an "n" modifier that
10742 // prints the negated value, for use with SUB instructions. It is
10743 // not useful otherwise but is implemented for compatibility.
10744 if (CVal >= -255 && CVal <= -1)
10747 // This must be a constant between -4095 and 4095. It is not clear
10748 // what this constraint is intended for. Implemented for
10749 // compatibility with GCC.
10750 if (CVal >= -4095 && CVal <= 4095)
10756 if (Subtarget->isThumb1Only()) {
10757 // A 32-bit value where only one byte has a nonzero value. Exclude
10758 // zero to match GCC. This constraint is used by GCC internally for
10759 // constants that can be loaded with a move/shift combination.
10760 // It is not useful otherwise but is implemented for compatibility.
10761 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10763 } else if (Subtarget->isThumb2()) {
10764 // A constant whose bitwise inverse can be used as an immediate
10765 // value in a data-processing instruction. This can be used in GCC
10766 // with a "B" modifier that prints the inverted value, for use with
10767 // BIC and MVN instructions. It is not useful otherwise but is
10768 // implemented for compatibility.
10769 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10772 // A constant whose bitwise inverse can be used as an immediate
10773 // value in a data-processing instruction. This can be used in GCC
10774 // with a "B" modifier that prints the inverted value, for use with
10775 // BIC and MVN instructions. It is not useful otherwise but is
10776 // implemented for compatibility.
10777 if (ARM_AM::getSOImmVal(~CVal) != -1)
10783 if (Subtarget->isThumb1Only()) {
10784 // This must be a constant between -7 and 7,
10785 // for 3-operand ADD/SUB immediate instructions.
10786 if (CVal >= -7 && CVal < 7)
10788 } else if (Subtarget->isThumb2()) {
10789 // A constant whose negation can be used as an immediate value in a
10790 // data-processing instruction. This can be used in GCC with an "n"
10791 // modifier that prints the negated value, for use with SUB
10792 // instructions. It is not useful otherwise but is implemented for
10794 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10797 // A constant whose negation can be used as an immediate value in a
10798 // data-processing instruction. This can be used in GCC with an "n"
10799 // modifier that prints the negated value, for use with SUB
10800 // instructions. It is not useful otherwise but is implemented for
10802 if (ARM_AM::getSOImmVal(-CVal) != -1)
10808 if (Subtarget->isThumb()) { // FIXME thumb2
10809 // This must be a multiple of 4 between 0 and 1020, for
10810 // ADD sp + immediate.
10811 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10814 // A power of two or a constant between 0 and 32. This is used in
10815 // GCC for the shift amount on shifted register operands, but it is
10816 // useful in general for any shift amounts.
10817 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10823 if (Subtarget->isThumb()) { // FIXME thumb2
10824 // This must be a constant between 0 and 31, for shift amounts.
10825 if (CVal >= 0 && CVal <= 31)
10831 if (Subtarget->isThumb()) { // FIXME thumb2
10832 // This must be a multiple of 4 between -508 and 508, for
10833 // ADD/SUB sp = sp + immediate.
10834 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10839 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10843 if (Result.getNode()) {
10844 Ops.push_back(Result);
10847 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10850 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10851 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10852 unsigned Opcode = Op->getOpcode();
10853 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10854 "Invalid opcode for Div/Rem lowering");
10855 bool isSigned = (Opcode == ISD::SDIVREM);
10856 EVT VT = Op->getValueType(0);
10857 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10860 switch (VT.getSimpleVT().SimpleTy) {
10861 default: llvm_unreachable("Unexpected request for libcall!");
10862 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10863 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10864 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10865 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10868 SDValue InChain = DAG.getEntryNode();
10870 TargetLowering::ArgListTy Args;
10871 TargetLowering::ArgListEntry Entry;
10872 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10873 EVT ArgVT = Op->getOperand(i).getValueType();
10874 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10875 Entry.Node = Op->getOperand(i);
10877 Entry.isSExt = isSigned;
10878 Entry.isZExt = !isSigned;
10879 Args.push_back(Entry);
10882 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10885 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10888 TargetLowering::CallLoweringInfo CLI(DAG);
10889 CLI.setDebugLoc(dl).setChain(InChain)
10890 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10891 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10893 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10894 return CallInfo.first;
10898 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10899 assert(Subtarget->isTargetWindows() && "unsupported target platform");
10903 SDValue Chain = Op.getOperand(0);
10904 SDValue Size = Op.getOperand(1);
10906 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10907 DAG.getConstant(2, MVT::i32));
10910 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10911 Flag = Chain.getValue(1);
10913 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10914 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10916 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10917 Chain = NewSP.getValue(1);
10919 SDValue Ops[2] = { NewSP, Chain };
10920 return DAG.getMergeValues(Ops, DL);
10923 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10924 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10925 "Unexpected type for custom-lowering FP_EXTEND");
10928 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10930 SDValue SrcVal = Op.getOperand(0);
10931 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10932 /*isSigned*/ false, SDLoc(Op)).first;
10935 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10936 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10937 Subtarget->isFPOnlySP() &&
10938 "Unexpected type for custom-lowering FP_ROUND");
10941 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10943 SDValue SrcVal = Op.getOperand(0);
10944 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10945 /*isSigned*/ false, SDLoc(Op)).first;
10949 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10950 // The ARM target isn't yet aware of offsets.
10954 bool ARM::isBitFieldInvertedMask(unsigned v) {
10955 if (v == 0xffffffff)
10958 // there can be 1's on either or both "outsides", all the "inside"
10959 // bits must be 0's
10960 return isShiftedMask_32(~v);
10963 /// isFPImmLegal - Returns true if the target can instruction select the
10964 /// specified FP immediate natively. If false, the legalizer will
10965 /// materialize the FP immediate as a load from a constant pool.
10966 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10967 if (!Subtarget->hasVFP3())
10969 if (VT == MVT::f32)
10970 return ARM_AM::getFP32Imm(Imm) != -1;
10971 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10972 return ARM_AM::getFP64Imm(Imm) != -1;
10976 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10977 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10978 /// specified in the intrinsic calls.
10979 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10981 unsigned Intrinsic) const {
10982 switch (Intrinsic) {
10983 case Intrinsic::arm_neon_vld1:
10984 case Intrinsic::arm_neon_vld2:
10985 case Intrinsic::arm_neon_vld3:
10986 case Intrinsic::arm_neon_vld4:
10987 case Intrinsic::arm_neon_vld2lane:
10988 case Intrinsic::arm_neon_vld3lane:
10989 case Intrinsic::arm_neon_vld4lane: {
10990 Info.opc = ISD::INTRINSIC_W_CHAIN;
10991 // Conservatively set memVT to the entire set of vectors loaded.
10992 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10993 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10994 Info.ptrVal = I.getArgOperand(0);
10996 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10997 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10998 Info.vol = false; // volatile loads with NEON intrinsics not supported
10999 Info.readMem = true;
11000 Info.writeMem = false;
11003 case Intrinsic::arm_neon_vst1:
11004 case Intrinsic::arm_neon_vst2:
11005 case Intrinsic::arm_neon_vst3:
11006 case Intrinsic::arm_neon_vst4:
11007 case Intrinsic::arm_neon_vst2lane:
11008 case Intrinsic::arm_neon_vst3lane:
11009 case Intrinsic::arm_neon_vst4lane: {
11010 Info.opc = ISD::INTRINSIC_VOID;
11011 // Conservatively set memVT to the entire set of vectors stored.
11012 unsigned NumElts = 0;
11013 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11014 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11015 if (!ArgTy->isVectorTy())
11017 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11019 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11020 Info.ptrVal = I.getArgOperand(0);
11022 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11023 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11024 Info.vol = false; // volatile stores with NEON intrinsics not supported
11025 Info.readMem = false;
11026 Info.writeMem = true;
11029 case Intrinsic::arm_ldaex:
11030 case Intrinsic::arm_ldrex: {
11031 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11032 Info.opc = ISD::INTRINSIC_W_CHAIN;
11033 Info.memVT = MVT::getVT(PtrTy->getElementType());
11034 Info.ptrVal = I.getArgOperand(0);
11036 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11038 Info.readMem = true;
11039 Info.writeMem = false;
11042 case Intrinsic::arm_stlex:
11043 case Intrinsic::arm_strex: {
11044 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11045 Info.opc = ISD::INTRINSIC_W_CHAIN;
11046 Info.memVT = MVT::getVT(PtrTy->getElementType());
11047 Info.ptrVal = I.getArgOperand(1);
11049 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11051 Info.readMem = false;
11052 Info.writeMem = true;
11055 case Intrinsic::arm_stlexd:
11056 case Intrinsic::arm_strexd: {
11057 Info.opc = ISD::INTRINSIC_W_CHAIN;
11058 Info.memVT = MVT::i64;
11059 Info.ptrVal = I.getArgOperand(2);
11063 Info.readMem = false;
11064 Info.writeMem = true;
11067 case Intrinsic::arm_ldaexd:
11068 case Intrinsic::arm_ldrexd: {
11069 Info.opc = ISD::INTRINSIC_W_CHAIN;
11070 Info.memVT = MVT::i64;
11071 Info.ptrVal = I.getArgOperand(0);
11075 Info.readMem = true;
11076 Info.writeMem = false;
11086 /// \brief Returns true if it is beneficial to convert a load of a constant
11087 /// to just the constant itself.
11088 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11090 assert(Ty->isIntegerTy());
11092 unsigned Bits = Ty->getPrimitiveSizeInBits();
11093 if (Bits == 0 || Bits > 32)
11098 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11100 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11101 ARM_MB::MemBOpt Domain) const {
11102 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11104 // First, if the target has no DMB, see what fallback we can use.
11105 if (!Subtarget->hasDataBarrier()) {
11106 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11107 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11109 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11110 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11111 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11112 Builder.getInt32(0), Builder.getInt32(7),
11113 Builder.getInt32(10), Builder.getInt32(5)};
11114 return Builder.CreateCall(MCR, args);
11116 // Instead of using barriers, atomic accesses on these subtargets use
11118 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11121 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11122 // Only a full system barrier exists in the M-class architectures.
11123 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11124 Constant *CDomain = Builder.getInt32(Domain);
11125 return Builder.CreateCall(DMB, CDomain);
11129 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11130 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11131 AtomicOrdering Ord, bool IsStore,
11132 bool IsLoad) const {
11133 if (!getInsertFencesForAtomic())
11139 llvm_unreachable("Invalid fence: unordered/non-atomic");
11142 return nullptr; // Nothing to do
11143 case SequentiallyConsistent:
11145 return nullptr; // Nothing to do
11148 case AcquireRelease:
11149 if (Subtarget->isSwift())
11150 return makeDMB(Builder, ARM_MB::ISHST);
11151 // FIXME: add a comment with a link to documentation justifying this.
11153 return makeDMB(Builder, ARM_MB::ISH);
11155 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11158 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11159 AtomicOrdering Ord, bool IsStore,
11160 bool IsLoad) const {
11161 if (!getInsertFencesForAtomic())
11167 llvm_unreachable("Invalid fence: unordered/not-atomic");
11170 return nullptr; // Nothing to do
11172 case AcquireRelease:
11173 case SequentiallyConsistent:
11174 return makeDMB(Builder, ARM_MB::ISH);
11176 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11179 // Loads and stores less than 64-bits are already atomic; ones above that
11180 // are doomed anyway, so defer to the default libcall and blame the OS when
11181 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11182 // anything for those.
11183 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11184 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11185 return (Size == 64) && !Subtarget->isMClass();
11188 // Loads and stores less than 64-bits are already atomic; ones above that
11189 // are doomed anyway, so defer to the default libcall and blame the OS when
11190 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11191 // anything for those.
11192 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11193 // guarantee, see DDI0406C ARM architecture reference manual,
11194 // sections A8.8.72-74 LDRD)
11195 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11196 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11197 return (Size == 64) && !Subtarget->isMClass();
11200 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11201 // and up to 64 bits on the non-M profiles
11202 TargetLoweringBase::AtomicRMWExpansionKind
11203 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11204 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11205 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11206 ? AtomicRMWExpansionKind::LLSC
11207 : AtomicRMWExpansionKind::None;
11210 // This has so far only been implemented for MachO.
11211 bool ARMTargetLowering::useLoadStackGuardNode() const {
11212 return Subtarget->isTargetMachO();
11215 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11216 unsigned &Cost) const {
11217 // If we do not have NEON, vector types are not natively supported.
11218 if (!Subtarget->hasNEON())
11221 // Floating point values and vector values map to the same register file.
11222 // Therefore, althought we could do a store extract of a vector type, this is
11223 // better to leave at float as we have more freedom in the addressing mode for
11225 if (VectorTy->isFPOrFPVectorTy())
11228 // If the index is unknown at compile time, this is very expensive to lower
11229 // and it is not possible to combine the store with the extract.
11230 if (!isa<ConstantInt>(Idx))
11233 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11234 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11235 // We can do a store + vector extract on any vector that fits perfectly in a D
11237 if (BitWidth == 64 || BitWidth == 128) {
11244 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11245 AtomicOrdering Ord) const {
11246 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11247 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11248 bool IsAcquire = isAtLeastAcquire(Ord);
11250 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11251 // intrinsic must return {i32, i32} and we have to recombine them into a
11252 // single i64 here.
11253 if (ValTy->getPrimitiveSizeInBits() == 64) {
11254 Intrinsic::ID Int =
11255 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11256 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11258 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11259 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11261 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11262 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11263 if (!Subtarget->isLittle())
11264 std::swap (Lo, Hi);
11265 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11266 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11267 return Builder.CreateOr(
11268 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11271 Type *Tys[] = { Addr->getType() };
11272 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11273 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11275 return Builder.CreateTruncOrBitCast(
11276 Builder.CreateCall(Ldrex, Addr),
11277 cast<PointerType>(Addr->getType())->getElementType());
11280 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11282 AtomicOrdering Ord) const {
11283 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11284 bool IsRelease = isAtLeastRelease(Ord);
11286 // Since the intrinsics must have legal type, the i64 intrinsics take two
11287 // parameters: "i32, i32". We must marshal Val into the appropriate form
11288 // before the call.
11289 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11290 Intrinsic::ID Int =
11291 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11292 Function *Strex = Intrinsic::getDeclaration(M, Int);
11293 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11295 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11296 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11297 if (!Subtarget->isLittle())
11298 std::swap (Lo, Hi);
11299 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11300 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11303 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11304 Type *Tys[] = { Addr->getType() };
11305 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11307 return Builder.CreateCall2(
11308 Strex, Builder.CreateZExtOrBitCast(
11309 Val, Strex->getFunctionType()->getParamType(0)),
11321 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11322 uint64_t &Members) {
11323 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11324 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11325 uint64_t SubMembers = 0;
11326 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11328 Members += SubMembers;
11330 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11331 uint64_t SubMembers = 0;
11332 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11334 Members += SubMembers * AT->getNumElements();
11335 } else if (Ty->isFloatTy()) {
11336 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11340 } else if (Ty->isDoubleTy()) {
11341 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11345 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11352 return VT->getBitWidth() == 64;
11354 return VT->getBitWidth() == 128;
11356 switch (VT->getBitWidth()) {
11369 return (Members > 0 && Members <= 4);
11372 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11373 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11374 /// passing according to AAPCS rules.
11375 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11376 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11377 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11378 CallingConv::ARM_AAPCS_VFP)
11381 HABaseType Base = HA_UNKNOWN;
11382 uint64_t Members = 0;
11383 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11384 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11386 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11387 return IsHA || IsIntArray;