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 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
574 for (MVT VT : MVT::integer_vector_valuetypes()) {
575 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
576 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
577 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
582 // ARM and Thumb2 support UMLAL/SMLAL.
583 if (!Subtarget->isThumb1Only())
584 setTargetDAGCombine(ISD::ADDC);
586 if (Subtarget->isFPOnlySP()) {
587 // When targetting a floating-point unit with only single-precision
588 // operations, f64 is legal for the few double-precision instructions which
589 // are present However, no double-precision operations other than moves,
590 // loads and stores are provided by the hardware.
591 setOperationAction(ISD::FADD, MVT::f64, Expand);
592 setOperationAction(ISD::FSUB, MVT::f64, Expand);
593 setOperationAction(ISD::FMUL, MVT::f64, Expand);
594 setOperationAction(ISD::FMA, MVT::f64, Expand);
595 setOperationAction(ISD::FDIV, MVT::f64, Expand);
596 setOperationAction(ISD::FREM, MVT::f64, Expand);
597 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
598 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
599 setOperationAction(ISD::FNEG, MVT::f64, Expand);
600 setOperationAction(ISD::FABS, MVT::f64, Expand);
601 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
602 setOperationAction(ISD::FSIN, MVT::f64, Expand);
603 setOperationAction(ISD::FCOS, MVT::f64, Expand);
604 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
605 setOperationAction(ISD::FPOW, MVT::f64, Expand);
606 setOperationAction(ISD::FLOG, MVT::f64, Expand);
607 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
608 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
609 setOperationAction(ISD::FEXP, MVT::f64, Expand);
610 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
611 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
612 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
613 setOperationAction(ISD::FRINT, MVT::f64, Expand);
614 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
615 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
616 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
617 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
620 computeRegisterProperties(Subtarget->getRegisterInfo());
622 // ARM does not have floating-point extending loads.
623 for (MVT VT : MVT::fp_valuetypes()) {
624 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
625 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
628 // ... or truncating stores
629 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
630 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
631 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
633 // ARM does not have i1 sign extending load.
634 for (MVT VT : MVT::integer_valuetypes())
635 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
637 // ARM supports all 4 flavors of integer indexed load / store.
638 if (!Subtarget->isThumb1Only()) {
639 for (unsigned im = (unsigned)ISD::PRE_INC;
640 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
641 setIndexedLoadAction(im, MVT::i1, Legal);
642 setIndexedLoadAction(im, MVT::i8, Legal);
643 setIndexedLoadAction(im, MVT::i16, Legal);
644 setIndexedLoadAction(im, MVT::i32, Legal);
645 setIndexedStoreAction(im, MVT::i1, Legal);
646 setIndexedStoreAction(im, MVT::i8, Legal);
647 setIndexedStoreAction(im, MVT::i16, Legal);
648 setIndexedStoreAction(im, MVT::i32, Legal);
652 setOperationAction(ISD::SADDO, MVT::i32, Custom);
653 setOperationAction(ISD::UADDO, MVT::i32, Custom);
654 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
655 setOperationAction(ISD::USUBO, MVT::i32, Custom);
657 // i64 operation support.
658 setOperationAction(ISD::MUL, MVT::i64, Expand);
659 setOperationAction(ISD::MULHU, MVT::i32, Expand);
660 if (Subtarget->isThumb1Only()) {
661 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
662 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
664 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
665 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
666 setOperationAction(ISD::MULHS, MVT::i32, Expand);
668 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
669 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
670 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
671 setOperationAction(ISD::SRL, MVT::i64, Custom);
672 setOperationAction(ISD::SRA, MVT::i64, Custom);
674 if (!Subtarget->isThumb1Only()) {
675 // FIXME: We should do this for Thumb1 as well.
676 setOperationAction(ISD::ADDC, MVT::i32, Custom);
677 setOperationAction(ISD::ADDE, MVT::i32, Custom);
678 setOperationAction(ISD::SUBC, MVT::i32, Custom);
679 setOperationAction(ISD::SUBE, MVT::i32, Custom);
682 // ARM does not have ROTL.
683 setOperationAction(ISD::ROTL, MVT::i32, Expand);
684 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
685 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
686 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
687 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
689 // These just redirect to CTTZ and CTLZ on ARM.
690 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
691 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
693 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
695 // Only ARMv6 has BSWAP.
696 if (!Subtarget->hasV6Ops())
697 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
699 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
700 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
701 // These are expanded into libcalls if the cpu doesn't have HW divider.
702 setOperationAction(ISD::SDIV, MVT::i32, Expand);
703 setOperationAction(ISD::UDIV, MVT::i32, Expand);
706 // FIXME: Also set divmod for SREM on EABI
707 setOperationAction(ISD::SREM, MVT::i32, Expand);
708 setOperationAction(ISD::UREM, MVT::i32, Expand);
709 // Register based DivRem for AEABI (RTABI 4.2)
710 if (Subtarget->isTargetAEABI()) {
711 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
712 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
713 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
714 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
715 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
716 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
717 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
718 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
720 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
721 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
722 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
723 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
724 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
725 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
726 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
727 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
729 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
730 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
732 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
733 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
736 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
737 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
738 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
739 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
740 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
742 setOperationAction(ISD::TRAP, MVT::Other, Legal);
744 // Use the default implementation.
745 setOperationAction(ISD::VASTART, MVT::Other, Custom);
746 setOperationAction(ISD::VAARG, MVT::Other, Expand);
747 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
748 setOperationAction(ISD::VAEND, MVT::Other, Expand);
749 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
750 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
752 if (!Subtarget->isTargetMachO()) {
753 // Non-MachO platforms may return values in these registers via the
754 // personality function.
755 setExceptionPointerRegister(ARM::R0);
756 setExceptionSelectorRegister(ARM::R1);
759 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
760 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
762 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
764 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
765 // the default expansion. If we are targeting a single threaded system,
766 // then set them all for expand so we can lower them later into their
768 if (TM.Options.ThreadModel == ThreadModel::Single)
769 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
770 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
771 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
772 // to ldrex/strex loops already.
773 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
775 // On v8, we have particularly efficient implementations of atomic fences
776 // if they can be combined with nearby atomic loads and stores.
777 if (!Subtarget->hasV8Ops()) {
778 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
779 setInsertFencesForAtomic(true);
782 // If there's anything we can use as a barrier, go through custom lowering
784 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
785 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
787 // Set them all for expansion, which will force libcalls.
788 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
789 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
790 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
791 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
792 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
793 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
794 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
795 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
796 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
797 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
798 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
799 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
800 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
801 // Unordered/Monotonic case.
802 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
803 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
806 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
808 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
809 if (!Subtarget->hasV6Ops()) {
810 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
811 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
813 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
815 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
816 !Subtarget->isThumb1Only()) {
817 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
818 // iff target supports vfp2.
819 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
820 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
823 // We want to custom lower some of our intrinsics.
824 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
825 if (Subtarget->isTargetDarwin()) {
826 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
827 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
828 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
831 setOperationAction(ISD::SETCC, MVT::i32, Expand);
832 setOperationAction(ISD::SETCC, MVT::f32, Expand);
833 setOperationAction(ISD::SETCC, MVT::f64, Expand);
834 setOperationAction(ISD::SELECT, MVT::i32, Custom);
835 setOperationAction(ISD::SELECT, MVT::f32, Custom);
836 setOperationAction(ISD::SELECT, MVT::f64, Custom);
837 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
838 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
839 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
841 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
842 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
843 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
844 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
845 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
847 // We don't support sin/cos/fmod/copysign/pow
848 setOperationAction(ISD::FSIN, MVT::f64, Expand);
849 setOperationAction(ISD::FSIN, MVT::f32, Expand);
850 setOperationAction(ISD::FCOS, MVT::f32, Expand);
851 setOperationAction(ISD::FCOS, MVT::f64, Expand);
852 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
853 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
854 setOperationAction(ISD::FREM, MVT::f64, Expand);
855 setOperationAction(ISD::FREM, MVT::f32, Expand);
856 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
857 !Subtarget->isThumb1Only()) {
858 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
859 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
861 setOperationAction(ISD::FPOW, MVT::f64, Expand);
862 setOperationAction(ISD::FPOW, MVT::f32, Expand);
864 if (!Subtarget->hasVFP4()) {
865 setOperationAction(ISD::FMA, MVT::f64, Expand);
866 setOperationAction(ISD::FMA, MVT::f32, Expand);
869 // Various VFP goodness
870 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
871 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
872 if (Subtarget->hasVFP2()) {
873 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
874 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
875 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
876 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
879 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
880 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
881 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
882 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
885 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
886 if (!Subtarget->hasFP16()) {
887 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
888 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
892 // Combine sin / cos into one node or libcall if possible.
893 if (Subtarget->hasSinCos()) {
894 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
895 setLibcallName(RTLIB::SINCOS_F64, "sincos");
896 if (Subtarget->getTargetTriple().isiOS()) {
897 // For iOS, we don't want to the normal expansion of a libcall to
898 // sincos. We want to issue a libcall to __sincos_stret.
899 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
900 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
904 // FP-ARMv8 implements a lot of rounding-like FP operations.
905 if (Subtarget->hasFPARMv8()) {
906 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
907 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
908 setOperationAction(ISD::FROUND, MVT::f32, Legal);
909 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
910 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
911 setOperationAction(ISD::FRINT, MVT::f32, Legal);
912 if (!Subtarget->isFPOnlySP()) {
913 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
914 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
915 setOperationAction(ISD::FROUND, MVT::f64, Legal);
916 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
917 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
918 setOperationAction(ISD::FRINT, MVT::f64, Legal);
921 // We have target-specific dag combine patterns for the following nodes:
922 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
923 setTargetDAGCombine(ISD::ADD);
924 setTargetDAGCombine(ISD::SUB);
925 setTargetDAGCombine(ISD::MUL);
926 setTargetDAGCombine(ISD::AND);
927 setTargetDAGCombine(ISD::OR);
928 setTargetDAGCombine(ISD::XOR);
930 if (Subtarget->hasV6Ops())
931 setTargetDAGCombine(ISD::SRL);
933 setStackPointerRegisterToSaveRestore(ARM::SP);
935 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
936 !Subtarget->hasVFP2())
937 setSchedulingPreference(Sched::RegPressure);
939 setSchedulingPreference(Sched::Hybrid);
941 //// temporary - rewrite interface to use type
942 MaxStoresPerMemset = 8;
943 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
944 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
945 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
946 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
947 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
949 // On ARM arguments smaller than 4 bytes are extended, so all arguments
950 // are at least 4 bytes aligned.
951 setMinStackArgumentAlignment(4);
953 // Prefer likely predicted branches to selects on out-of-order cores.
954 PredictableSelectIsExpensive = Subtarget->isLikeA9();
956 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
959 // FIXME: It might make sense to define the representative register class as the
960 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
961 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
962 // SPR's representative would be DPR_VFP2. This should work well if register
963 // pressure tracking were modified such that a register use would increment the
964 // pressure of the register class's representative and all of it's super
965 // classes' representatives transitively. We have not implemented this because
966 // of the difficulty prior to coalescing of modeling operand register classes
967 // due to the common occurrence of cross class copies and subregister insertions
969 std::pair<const TargetRegisterClass *, uint8_t>
970 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
972 const TargetRegisterClass *RRC = nullptr;
974 switch (VT.SimpleTy) {
976 return TargetLowering::findRepresentativeClass(TRI, VT);
977 // Use DPR as representative register class for all floating point
978 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
979 // the cost is 1 for both f32 and f64.
980 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
981 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
982 RRC = &ARM::DPRRegClass;
983 // When NEON is used for SP, only half of the register file is available
984 // because operations that define both SP and DP results will be constrained
985 // to the VFP2 class (D0-D15). We currently model this constraint prior to
986 // coalescing by double-counting the SP regs. See the FIXME above.
987 if (Subtarget->useNEONForSinglePrecisionFP())
990 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
991 case MVT::v4f32: case MVT::v2f64:
992 RRC = &ARM::DPRRegClass;
996 RRC = &ARM::DPRRegClass;
1000 RRC = &ARM::DPRRegClass;
1004 return std::make_pair(RRC, Cost);
1007 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1009 default: return nullptr;
1010 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1011 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1012 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1013 case ARMISD::CALL: return "ARMISD::CALL";
1014 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1015 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1016 case ARMISD::tCALL: return "ARMISD::tCALL";
1017 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1018 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1019 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1020 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1021 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1022 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1023 case ARMISD::CMP: return "ARMISD::CMP";
1024 case ARMISD::CMN: return "ARMISD::CMN";
1025 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1026 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1027 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1028 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1029 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1031 case ARMISD::CMOV: return "ARMISD::CMOV";
1033 case ARMISD::RBIT: return "ARMISD::RBIT";
1035 case ARMISD::FTOSI: return "ARMISD::FTOSI";
1036 case ARMISD::FTOUI: return "ARMISD::FTOUI";
1037 case ARMISD::SITOF: return "ARMISD::SITOF";
1038 case ARMISD::UITOF: return "ARMISD::UITOF";
1040 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1041 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1042 case ARMISD::RRX: return "ARMISD::RRX";
1044 case ARMISD::ADDC: return "ARMISD::ADDC";
1045 case ARMISD::ADDE: return "ARMISD::ADDE";
1046 case ARMISD::SUBC: return "ARMISD::SUBC";
1047 case ARMISD::SUBE: return "ARMISD::SUBE";
1049 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1050 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1052 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1053 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1055 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1057 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1059 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1061 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1063 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1065 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1067 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1068 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1069 case ARMISD::VCGE: return "ARMISD::VCGE";
1070 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1071 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1072 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1073 case ARMISD::VCGT: return "ARMISD::VCGT";
1074 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1075 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1076 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1077 case ARMISD::VTST: return "ARMISD::VTST";
1079 case ARMISD::VSHL: return "ARMISD::VSHL";
1080 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1081 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1082 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1083 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1084 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1085 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1086 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1087 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1088 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1089 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1090 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1091 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1092 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1093 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1094 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1095 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1096 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1097 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1098 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1099 case ARMISD::VDUP: return "ARMISD::VDUP";
1100 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1101 case ARMISD::VEXT: return "ARMISD::VEXT";
1102 case ARMISD::VREV64: return "ARMISD::VREV64";
1103 case ARMISD::VREV32: return "ARMISD::VREV32";
1104 case ARMISD::VREV16: return "ARMISD::VREV16";
1105 case ARMISD::VZIP: return "ARMISD::VZIP";
1106 case ARMISD::VUZP: return "ARMISD::VUZP";
1107 case ARMISD::VTRN: return "ARMISD::VTRN";
1108 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1109 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1110 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1111 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1112 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1113 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1114 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1115 case ARMISD::FMAX: return "ARMISD::FMAX";
1116 case ARMISD::FMIN: return "ARMISD::FMIN";
1117 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1118 case ARMISD::VMINNM: return "ARMISD::VMIN";
1119 case ARMISD::BFI: return "ARMISD::BFI";
1120 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1121 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1122 case ARMISD::VBSL: return "ARMISD::VBSL";
1123 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1124 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1125 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1126 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1127 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1128 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1129 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1130 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1131 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1132 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1133 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1134 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1135 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1136 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1137 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1138 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1139 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1140 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1141 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1142 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1146 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1147 if (!VT.isVector()) return getPointerTy();
1148 return VT.changeVectorElementTypeToInteger();
1151 /// getRegClassFor - Return the register class that should be used for the
1152 /// specified value type.
1153 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1154 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1155 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1156 // load / store 4 to 8 consecutive D registers.
1157 if (Subtarget->hasNEON()) {
1158 if (VT == MVT::v4i64)
1159 return &ARM::QQPRRegClass;
1160 if (VT == MVT::v8i64)
1161 return &ARM::QQQQPRRegClass;
1163 return TargetLowering::getRegClassFor(VT);
1166 // Create a fast isel object.
1168 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1169 const TargetLibraryInfo *libInfo) const {
1170 return ARM::createFastISel(funcInfo, libInfo);
1173 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1174 unsigned NumVals = N->getNumValues();
1176 return Sched::RegPressure;
1178 for (unsigned i = 0; i != NumVals; ++i) {
1179 EVT VT = N->getValueType(i);
1180 if (VT == MVT::Glue || VT == MVT::Other)
1182 if (VT.isFloatingPoint() || VT.isVector())
1186 if (!N->isMachineOpcode())
1187 return Sched::RegPressure;
1189 // Load are scheduled for latency even if there instruction itinerary
1190 // is not available.
1191 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1192 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1194 if (MCID.getNumDefs() == 0)
1195 return Sched::RegPressure;
1196 if (!Itins->isEmpty() &&
1197 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1200 return Sched::RegPressure;
1203 //===----------------------------------------------------------------------===//
1205 //===----------------------------------------------------------------------===//
1207 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1208 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1210 default: llvm_unreachable("Unknown condition code!");
1211 case ISD::SETNE: return ARMCC::NE;
1212 case ISD::SETEQ: return ARMCC::EQ;
1213 case ISD::SETGT: return ARMCC::GT;
1214 case ISD::SETGE: return ARMCC::GE;
1215 case ISD::SETLT: return ARMCC::LT;
1216 case ISD::SETLE: return ARMCC::LE;
1217 case ISD::SETUGT: return ARMCC::HI;
1218 case ISD::SETUGE: return ARMCC::HS;
1219 case ISD::SETULT: return ARMCC::LO;
1220 case ISD::SETULE: return ARMCC::LS;
1224 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1225 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1226 ARMCC::CondCodes &CondCode2) {
1227 CondCode2 = ARMCC::AL;
1229 default: llvm_unreachable("Unknown FP condition!");
1231 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1233 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1235 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1236 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1237 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1238 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1239 case ISD::SETO: CondCode = ARMCC::VC; break;
1240 case ISD::SETUO: CondCode = ARMCC::VS; break;
1241 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1242 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1243 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1245 case ISD::SETULT: CondCode = ARMCC::LT; break;
1247 case ISD::SETULE: CondCode = ARMCC::LE; break;
1249 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1253 //===----------------------------------------------------------------------===//
1254 // Calling Convention Implementation
1255 //===----------------------------------------------------------------------===//
1257 #include "ARMGenCallingConv.inc"
1259 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1260 /// account presence of floating point hardware and calling convention
1261 /// limitations, such as support for variadic functions.
1263 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1264 bool isVarArg) const {
1267 llvm_unreachable("Unsupported calling convention");
1268 case CallingConv::ARM_AAPCS:
1269 case CallingConv::ARM_APCS:
1270 case CallingConv::GHC:
1272 case CallingConv::ARM_AAPCS_VFP:
1273 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1274 case CallingConv::C:
1275 if (!Subtarget->isAAPCS_ABI())
1276 return CallingConv::ARM_APCS;
1277 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1278 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1280 return CallingConv::ARM_AAPCS_VFP;
1282 return CallingConv::ARM_AAPCS;
1283 case CallingConv::Fast:
1284 if (!Subtarget->isAAPCS_ABI()) {
1285 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1286 return CallingConv::Fast;
1287 return CallingConv::ARM_APCS;
1288 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1289 return CallingConv::ARM_AAPCS_VFP;
1291 return CallingConv::ARM_AAPCS;
1295 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1296 /// CallingConvention.
1297 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1299 bool isVarArg) const {
1300 switch (getEffectiveCallingConv(CC, isVarArg)) {
1302 llvm_unreachable("Unsupported calling convention");
1303 case CallingConv::ARM_APCS:
1304 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1305 case CallingConv::ARM_AAPCS:
1306 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1307 case CallingConv::ARM_AAPCS_VFP:
1308 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1309 case CallingConv::Fast:
1310 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1311 case CallingConv::GHC:
1312 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1316 /// LowerCallResult - Lower the result values of a call into the
1317 /// appropriate copies out of appropriate physical registers.
1319 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1320 CallingConv::ID CallConv, bool isVarArg,
1321 const SmallVectorImpl<ISD::InputArg> &Ins,
1322 SDLoc dl, SelectionDAG &DAG,
1323 SmallVectorImpl<SDValue> &InVals,
1324 bool isThisReturn, SDValue ThisVal) const {
1326 // Assign locations to each value returned by this call.
1327 SmallVector<CCValAssign, 16> RVLocs;
1328 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1329 *DAG.getContext(), Call);
1330 CCInfo.AnalyzeCallResult(Ins,
1331 CCAssignFnForNode(CallConv, /* Return*/ true,
1334 // Copy all of the result registers out of their specified physreg.
1335 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1336 CCValAssign VA = RVLocs[i];
1338 // Pass 'this' value directly from the argument to return value, to avoid
1339 // reg unit interference
1340 if (i == 0 && isThisReturn) {
1341 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1342 "unexpected return calling convention register assignment");
1343 InVals.push_back(ThisVal);
1348 if (VA.needsCustom()) {
1349 // Handle f64 or half of a v2f64.
1350 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1352 Chain = Lo.getValue(1);
1353 InFlag = Lo.getValue(2);
1354 VA = RVLocs[++i]; // skip ahead to next loc
1355 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1357 Chain = Hi.getValue(1);
1358 InFlag = Hi.getValue(2);
1359 if (!Subtarget->isLittle())
1361 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1363 if (VA.getLocVT() == MVT::v2f64) {
1364 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1365 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1366 DAG.getConstant(0, MVT::i32));
1368 VA = RVLocs[++i]; // skip ahead to next loc
1369 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1370 Chain = Lo.getValue(1);
1371 InFlag = Lo.getValue(2);
1372 VA = RVLocs[++i]; // skip ahead to next loc
1373 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1374 Chain = Hi.getValue(1);
1375 InFlag = Hi.getValue(2);
1376 if (!Subtarget->isLittle())
1378 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1379 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1380 DAG.getConstant(1, MVT::i32));
1383 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1385 Chain = Val.getValue(1);
1386 InFlag = Val.getValue(2);
1389 switch (VA.getLocInfo()) {
1390 default: llvm_unreachable("Unknown loc info!");
1391 case CCValAssign::Full: break;
1392 case CCValAssign::BCvt:
1393 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1397 InVals.push_back(Val);
1403 /// LowerMemOpCallTo - Store the argument to the stack.
1405 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1406 SDValue StackPtr, SDValue Arg,
1407 SDLoc dl, SelectionDAG &DAG,
1408 const CCValAssign &VA,
1409 ISD::ArgFlagsTy Flags) const {
1410 unsigned LocMemOffset = VA.getLocMemOffset();
1411 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1412 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1413 return DAG.getStore(Chain, dl, Arg, PtrOff,
1414 MachinePointerInfo::getStack(LocMemOffset),
1418 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1419 SDValue Chain, SDValue &Arg,
1420 RegsToPassVector &RegsToPass,
1421 CCValAssign &VA, CCValAssign &NextVA,
1423 SmallVectorImpl<SDValue> &MemOpChains,
1424 ISD::ArgFlagsTy Flags) const {
1426 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1427 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1428 unsigned id = Subtarget->isLittle() ? 0 : 1;
1429 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1431 if (NextVA.isRegLoc())
1432 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1434 assert(NextVA.isMemLoc());
1435 if (!StackPtr.getNode())
1436 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1438 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1444 /// LowerCall - Lowering a call into a callseq_start <-
1445 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1448 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1449 SmallVectorImpl<SDValue> &InVals) const {
1450 SelectionDAG &DAG = CLI.DAG;
1452 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1453 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1454 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1455 SDValue Chain = CLI.Chain;
1456 SDValue Callee = CLI.Callee;
1457 bool &isTailCall = CLI.IsTailCall;
1458 CallingConv::ID CallConv = CLI.CallConv;
1459 bool doesNotRet = CLI.DoesNotReturn;
1460 bool isVarArg = CLI.IsVarArg;
1462 MachineFunction &MF = DAG.getMachineFunction();
1463 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1464 bool isThisReturn = false;
1465 bool isSibCall = false;
1467 // Disable tail calls if they're not supported.
1468 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1472 // Check if it's really possible to do a tail call.
1473 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1474 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1475 Outs, OutVals, Ins, DAG);
1476 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1477 report_fatal_error("failed to perform tail call elimination on a call "
1478 "site marked musttail");
1479 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1480 // detected sibcalls.
1487 // Analyze operands of the call, assigning locations to each operand.
1488 SmallVector<CCValAssign, 16> ArgLocs;
1489 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1490 *DAG.getContext(), Call);
1491 CCInfo.AnalyzeCallOperands(Outs,
1492 CCAssignFnForNode(CallConv, /* Return*/ false,
1495 // Get a count of how many bytes are to be pushed on the stack.
1496 unsigned NumBytes = CCInfo.getNextStackOffset();
1498 // For tail calls, memory operands are available in our caller's stack.
1502 // Adjust the stack pointer for the new arguments...
1503 // These operations are automatically eliminated by the prolog/epilog pass
1505 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1508 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1510 RegsToPassVector RegsToPass;
1511 SmallVector<SDValue, 8> MemOpChains;
1513 // Walk the register/memloc assignments, inserting copies/loads. In the case
1514 // of tail call optimization, arguments are handled later.
1515 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1517 ++i, ++realArgIdx) {
1518 CCValAssign &VA = ArgLocs[i];
1519 SDValue Arg = OutVals[realArgIdx];
1520 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1521 bool isByVal = Flags.isByVal();
1523 // Promote the value if needed.
1524 switch (VA.getLocInfo()) {
1525 default: llvm_unreachable("Unknown loc info!");
1526 case CCValAssign::Full: break;
1527 case CCValAssign::SExt:
1528 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1530 case CCValAssign::ZExt:
1531 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1533 case CCValAssign::AExt:
1534 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1536 case CCValAssign::BCvt:
1537 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1541 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1542 if (VA.needsCustom()) {
1543 if (VA.getLocVT() == MVT::v2f64) {
1544 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1545 DAG.getConstant(0, MVT::i32));
1546 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1547 DAG.getConstant(1, MVT::i32));
1549 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1550 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1552 VA = ArgLocs[++i]; // skip ahead to next loc
1553 if (VA.isRegLoc()) {
1554 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1555 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1557 assert(VA.isMemLoc());
1559 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1560 dl, DAG, VA, Flags));
1563 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1564 StackPtr, MemOpChains, Flags);
1566 } else if (VA.isRegLoc()) {
1567 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1568 assert(VA.getLocVT() == MVT::i32 &&
1569 "unexpected calling convention register assignment");
1570 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1571 "unexpected use of 'returned'");
1572 isThisReturn = true;
1574 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1575 } else if (isByVal) {
1576 assert(VA.isMemLoc());
1577 unsigned offset = 0;
1579 // True if this byval aggregate will be split between registers
1581 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1582 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1584 if (CurByValIdx < ByValArgsCount) {
1586 unsigned RegBegin, RegEnd;
1587 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1589 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1591 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1592 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1593 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1594 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1595 MachinePointerInfo(),
1596 false, false, false,
1597 DAG.InferPtrAlignment(AddArg));
1598 MemOpChains.push_back(Load.getValue(1));
1599 RegsToPass.push_back(std::make_pair(j, Load));
1602 // If parameter size outsides register area, "offset" value
1603 // helps us to calculate stack slot for remained part properly.
1604 offset = RegEnd - RegBegin;
1606 CCInfo.nextInRegsParam();
1609 if (Flags.getByValSize() > 4*offset) {
1610 unsigned LocMemOffset = VA.getLocMemOffset();
1611 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1612 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1614 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1615 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1616 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1618 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1620 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1621 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1622 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1625 } else if (!isSibCall) {
1626 assert(VA.isMemLoc());
1628 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1629 dl, DAG, VA, Flags));
1633 if (!MemOpChains.empty())
1634 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1636 // Build a sequence of copy-to-reg nodes chained together with token chain
1637 // and flag operands which copy the outgoing args into the appropriate regs.
1639 // Tail call byval lowering might overwrite argument registers so in case of
1640 // tail call optimization the copies to registers are lowered later.
1642 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1643 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1644 RegsToPass[i].second, InFlag);
1645 InFlag = Chain.getValue(1);
1648 // For tail calls lower the arguments to the 'real' stack slot.
1650 // Force all the incoming stack arguments to be loaded from the stack
1651 // before any new outgoing arguments are stored to the stack, because the
1652 // outgoing stack slots may alias the incoming argument stack slots, and
1653 // the alias isn't otherwise explicit. This is slightly more conservative
1654 // than necessary, because it means that each store effectively depends
1655 // on every argument instead of just those arguments it would clobber.
1657 // Do not flag preceding copytoreg stuff together with the following stuff.
1659 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1660 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1661 RegsToPass[i].second, InFlag);
1662 InFlag = Chain.getValue(1);
1667 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1668 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1669 // node so that legalize doesn't hack it.
1670 bool isDirect = false;
1671 bool isARMFunc = false;
1672 bool isLocalARMFunc = false;
1673 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1675 if (EnableARMLongCalls) {
1676 assert((Subtarget->isTargetWindows() ||
1677 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1678 "long-calls with non-static relocation model!");
1679 // Handle a global address or an external symbol. If it's not one of
1680 // those, the target's already in a register, so we don't need to do
1682 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1683 const GlobalValue *GV = G->getGlobal();
1684 // Create a constant pool entry for the callee address
1685 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1686 ARMConstantPoolValue *CPV =
1687 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1689 // Get the address of the callee into a register
1690 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1691 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1692 Callee = DAG.getLoad(getPointerTy(), dl,
1693 DAG.getEntryNode(), CPAddr,
1694 MachinePointerInfo::getConstantPool(),
1695 false, false, false, 0);
1696 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1697 const char *Sym = S->getSymbol();
1699 // Create a constant pool entry for the callee address
1700 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1701 ARMConstantPoolValue *CPV =
1702 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1703 ARMPCLabelIndex, 0);
1704 // Get the address of the callee into a register
1705 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1706 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1707 Callee = DAG.getLoad(getPointerTy(), dl,
1708 DAG.getEntryNode(), CPAddr,
1709 MachinePointerInfo::getConstantPool(),
1710 false, false, false, 0);
1712 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1713 const GlobalValue *GV = G->getGlobal();
1715 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1716 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1717 getTargetMachine().getRelocationModel() != Reloc::Static;
1718 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1719 // ARM call to a local ARM function is predicable.
1720 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1721 // tBX takes a register source operand.
1722 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1723 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1724 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1725 DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1726 0, ARMII::MO_NONLAZY));
1727 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1728 MachinePointerInfo::getGOT(), false, false, true, 0);
1729 } else if (Subtarget->isTargetCOFF()) {
1730 assert(Subtarget->isTargetWindows() &&
1731 "Windows is the only supported COFF target");
1732 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1733 ? ARMII::MO_DLLIMPORT
1734 : ARMII::MO_NO_FLAG;
1735 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1737 if (GV->hasDLLImportStorageClass())
1738 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1739 DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1740 Callee), MachinePointerInfo::getGOT(),
1741 false, false, false, 0);
1743 // On ELF targets for PIC code, direct calls should go through the PLT
1744 unsigned OpFlags = 0;
1745 if (Subtarget->isTargetELF() &&
1746 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1747 OpFlags = ARMII::MO_PLT;
1748 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1750 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1752 bool isStub = Subtarget->isTargetMachO() &&
1753 getTargetMachine().getRelocationModel() != Reloc::Static;
1754 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1755 // tBX takes a register source operand.
1756 const char *Sym = S->getSymbol();
1757 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1758 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1759 ARMConstantPoolValue *CPV =
1760 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1761 ARMPCLabelIndex, 4);
1762 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1763 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1764 Callee = DAG.getLoad(getPointerTy(), dl,
1765 DAG.getEntryNode(), CPAddr,
1766 MachinePointerInfo::getConstantPool(),
1767 false, false, false, 0);
1768 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1769 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1770 getPointerTy(), Callee, PICLabel);
1772 unsigned OpFlags = 0;
1773 // On ELF targets for PIC code, direct calls should go through the PLT
1774 if (Subtarget->isTargetELF() &&
1775 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1776 OpFlags = ARMII::MO_PLT;
1777 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1781 // FIXME: handle tail calls differently.
1783 bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1784 if (Subtarget->isThumb()) {
1785 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1786 CallOpc = ARMISD::CALL_NOLINK;
1788 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1790 if (!isDirect && !Subtarget->hasV5TOps())
1791 CallOpc = ARMISD::CALL_NOLINK;
1792 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1793 // Emit regular call when code size is the priority
1795 // "mov lr, pc; b _foo" to avoid confusing the RSP
1796 CallOpc = ARMISD::CALL_NOLINK;
1798 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1801 std::vector<SDValue> Ops;
1802 Ops.push_back(Chain);
1803 Ops.push_back(Callee);
1805 // Add argument registers to the end of the list so that they are known live
1807 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1808 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1809 RegsToPass[i].second.getValueType()));
1811 // Add a register mask operand representing the call-preserved registers.
1813 const uint32_t *Mask;
1814 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1816 // For 'this' returns, use the R0-preserving mask if applicable
1817 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1819 // Set isThisReturn to false if the calling convention is not one that
1820 // allows 'returned' to be modeled in this way, so LowerCallResult does
1821 // not try to pass 'this' straight through
1822 isThisReturn = false;
1823 Mask = ARI->getCallPreservedMask(MF, CallConv);
1826 Mask = ARI->getCallPreservedMask(MF, CallConv);
1828 assert(Mask && "Missing call preserved mask for calling convention");
1829 Ops.push_back(DAG.getRegisterMask(Mask));
1832 if (InFlag.getNode())
1833 Ops.push_back(InFlag);
1835 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1837 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1839 // Returns a chain and a flag for retval copy to use.
1840 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1841 InFlag = Chain.getValue(1);
1843 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1844 DAG.getIntPtrConstant(0, true), InFlag, dl);
1846 InFlag = Chain.getValue(1);
1848 // Handle result values, copying them out of physregs into vregs that we
1850 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1851 InVals, isThisReturn,
1852 isThisReturn ? OutVals[0] : SDValue());
1855 /// HandleByVal - Every parameter *after* a byval parameter is passed
1856 /// on the stack. Remember the next parameter register to allocate,
1857 /// and then confiscate the rest of the parameter registers to insure
1859 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1860 unsigned Align) const {
1861 assert((State->getCallOrPrologue() == Prologue ||
1862 State->getCallOrPrologue() == Call) &&
1863 "unhandled ParmContext");
1865 // Byval (as with any stack) slots are always at least 4 byte aligned.
1866 Align = std::max(Align, 4U);
1868 unsigned Reg = State->AllocateReg(GPRArgRegs);
1872 unsigned AlignInRegs = Align / 4;
1873 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1874 for (unsigned i = 0; i < Waste; ++i)
1875 Reg = State->AllocateReg(GPRArgRegs);
1880 unsigned Excess = 4 * (ARM::R4 - Reg);
1882 // Special case when NSAA != SP and parameter size greater than size of
1883 // all remained GPR regs. In that case we can't split parameter, we must
1884 // send it to stack. We also must set NCRN to R4, so waste all
1885 // remained registers.
1886 const unsigned NSAAOffset = State->getNextStackOffset();
1887 if (NSAAOffset != 0 && Size > Excess) {
1888 while (State->AllocateReg(GPRArgRegs))
1893 // First register for byval parameter is the first register that wasn't
1894 // allocated before this method call, so it would be "reg".
1895 // If parameter is small enough to be saved in range [reg, r4), then
1896 // the end (first after last) register would be reg + param-size-in-regs,
1897 // else parameter would be splitted between registers and stack,
1898 // end register would be r4 in this case.
1899 unsigned ByValRegBegin = Reg;
1900 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1901 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1902 // Note, first register is allocated in the beginning of function already,
1903 // allocate remained amount of registers we need.
1904 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1905 State->AllocateReg(GPRArgRegs);
1906 // A byval parameter that is split between registers and memory needs its
1907 // size truncated here.
1908 // In the case where the entire structure fits in registers, we set the
1909 // size in memory to zero.
1910 Size = std::max<int>(Size - Excess, 0);
1914 /// MatchingStackOffset - Return true if the given stack call argument is
1915 /// already available in the same position (relatively) of the caller's
1916 /// incoming argument stack.
1918 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1919 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1920 const TargetInstrInfo *TII) {
1921 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1923 if (Arg.getOpcode() == ISD::CopyFromReg) {
1924 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1925 if (!TargetRegisterInfo::isVirtualRegister(VR))
1927 MachineInstr *Def = MRI->getVRegDef(VR);
1930 if (!Flags.isByVal()) {
1931 if (!TII->isLoadFromStackSlot(Def, FI))
1936 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1937 if (Flags.isByVal())
1938 // ByVal argument is passed in as a pointer but it's now being
1939 // dereferenced. e.g.
1940 // define @foo(%struct.X* %A) {
1941 // tail call @bar(%struct.X* byval %A)
1944 SDValue Ptr = Ld->getBasePtr();
1945 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1948 FI = FINode->getIndex();
1952 assert(FI != INT_MAX);
1953 if (!MFI->isFixedObjectIndex(FI))
1955 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1958 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1959 /// for tail call optimization. Targets which want to do tail call
1960 /// optimization should implement this function.
1962 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1963 CallingConv::ID CalleeCC,
1965 bool isCalleeStructRet,
1966 bool isCallerStructRet,
1967 const SmallVectorImpl<ISD::OutputArg> &Outs,
1968 const SmallVectorImpl<SDValue> &OutVals,
1969 const SmallVectorImpl<ISD::InputArg> &Ins,
1970 SelectionDAG& DAG) const {
1971 const Function *CallerF = DAG.getMachineFunction().getFunction();
1972 CallingConv::ID CallerCC = CallerF->getCallingConv();
1973 bool CCMatch = CallerCC == CalleeCC;
1975 // Look for obvious safe cases to perform tail call optimization that do not
1976 // require ABI changes. This is what gcc calls sibcall.
1978 // Do not sibcall optimize vararg calls unless the call site is not passing
1980 if (isVarArg && !Outs.empty())
1983 // Exception-handling functions need a special set of instructions to indicate
1984 // a return to the hardware. Tail-calling another function would probably
1986 if (CallerF->hasFnAttribute("interrupt"))
1989 // Also avoid sibcall optimization if either caller or callee uses struct
1990 // return semantics.
1991 if (isCalleeStructRet || isCallerStructRet)
1994 // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
1995 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1996 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1997 // support in the assembler and linker to be used. This would need to be
1998 // fixed to fully support tail calls in Thumb1.
2000 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2001 // LR. This means if we need to reload LR, it takes an extra instructions,
2002 // which outweighs the value of the tail call; but here we don't know yet
2003 // whether LR is going to be used. Probably the right approach is to
2004 // generate the tail call here and turn it back into CALL/RET in
2005 // emitEpilogue if LR is used.
2007 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2008 // but we need to make sure there are enough registers; the only valid
2009 // registers are the 4 used for parameters. We don't currently do this
2011 if (Subtarget->isThumb1Only())
2014 // Externally-defined functions with weak linkage should not be
2015 // tail-called on ARM when the OS does not support dynamic
2016 // pre-emption of symbols, as the AAELF spec requires normal calls
2017 // to undefined weak functions to be replaced with a NOP or jump to the
2018 // next instruction. The behaviour of branch instructions in this
2019 // situation (as used for tail calls) is implementation-defined, so we
2020 // cannot rely on the linker replacing the tail call with a return.
2021 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2022 const GlobalValue *GV = G->getGlobal();
2023 const Triple TT(getTargetMachine().getTargetTriple());
2024 if (GV->hasExternalWeakLinkage() &&
2025 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2029 // If the calling conventions do not match, then we'd better make sure the
2030 // results are returned in the same way as what the caller expects.
2032 SmallVector<CCValAssign, 16> RVLocs1;
2033 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2034 *DAG.getContext(), Call);
2035 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2037 SmallVector<CCValAssign, 16> RVLocs2;
2038 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2039 *DAG.getContext(), Call);
2040 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2042 if (RVLocs1.size() != RVLocs2.size())
2044 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2045 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2047 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2049 if (RVLocs1[i].isRegLoc()) {
2050 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2053 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2059 // If Caller's vararg or byval argument has been split between registers and
2060 // stack, do not perform tail call, since part of the argument is in caller's
2062 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2063 getInfo<ARMFunctionInfo>();
2064 if (AFI_Caller->getArgRegsSaveSize())
2067 // If the callee takes no arguments then go on to check the results of the
2069 if (!Outs.empty()) {
2070 // Check if stack adjustment is needed. For now, do not do this if any
2071 // argument is passed on the stack.
2072 SmallVector<CCValAssign, 16> ArgLocs;
2073 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2074 *DAG.getContext(), Call);
2075 CCInfo.AnalyzeCallOperands(Outs,
2076 CCAssignFnForNode(CalleeCC, false, isVarArg));
2077 if (CCInfo.getNextStackOffset()) {
2078 MachineFunction &MF = DAG.getMachineFunction();
2080 // Check if the arguments are already laid out in the right way as
2081 // the caller's fixed stack objects.
2082 MachineFrameInfo *MFI = MF.getFrameInfo();
2083 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2084 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2085 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2087 ++i, ++realArgIdx) {
2088 CCValAssign &VA = ArgLocs[i];
2089 EVT RegVT = VA.getLocVT();
2090 SDValue Arg = OutVals[realArgIdx];
2091 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2092 if (VA.getLocInfo() == CCValAssign::Indirect)
2094 if (VA.needsCustom()) {
2095 // f64 and vector types are split into multiple registers or
2096 // register/stack-slot combinations. The types will not match
2097 // the registers; give up on memory f64 refs until we figure
2098 // out what to do about this.
2101 if (!ArgLocs[++i].isRegLoc())
2103 if (RegVT == MVT::v2f64) {
2104 if (!ArgLocs[++i].isRegLoc())
2106 if (!ArgLocs[++i].isRegLoc())
2109 } else if (!VA.isRegLoc()) {
2110 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2122 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2123 MachineFunction &MF, bool isVarArg,
2124 const SmallVectorImpl<ISD::OutputArg> &Outs,
2125 LLVMContext &Context) const {
2126 SmallVector<CCValAssign, 16> RVLocs;
2127 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2128 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2132 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2133 SDLoc DL, SelectionDAG &DAG) {
2134 const MachineFunction &MF = DAG.getMachineFunction();
2135 const Function *F = MF.getFunction();
2137 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2139 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2140 // version of the "preferred return address". These offsets affect the return
2141 // instruction if this is a return from PL1 without hypervisor extensions.
2142 // IRQ/FIQ: +4 "subs pc, lr, #4"
2143 // SWI: 0 "subs pc, lr, #0"
2144 // ABORT: +4 "subs pc, lr, #4"
2145 // UNDEF: +4/+2 "subs pc, lr, #0"
2146 // UNDEF varies depending on where the exception came from ARM or Thumb
2147 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2150 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2153 else if (IntKind == "SWI" || IntKind == "UNDEF")
2156 report_fatal_error("Unsupported interrupt attribute. If present, value "
2157 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2159 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2161 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2165 ARMTargetLowering::LowerReturn(SDValue Chain,
2166 CallingConv::ID CallConv, bool isVarArg,
2167 const SmallVectorImpl<ISD::OutputArg> &Outs,
2168 const SmallVectorImpl<SDValue> &OutVals,
2169 SDLoc dl, SelectionDAG &DAG) const {
2171 // CCValAssign - represent the assignment of the return value to a location.
2172 SmallVector<CCValAssign, 16> RVLocs;
2174 // CCState - Info about the registers and stack slots.
2175 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2176 *DAG.getContext(), Call);
2178 // Analyze outgoing return values.
2179 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2183 SmallVector<SDValue, 4> RetOps;
2184 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2185 bool isLittleEndian = Subtarget->isLittle();
2187 MachineFunction &MF = DAG.getMachineFunction();
2188 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2189 AFI->setReturnRegsCount(RVLocs.size());
2191 // Copy the result values into the output registers.
2192 for (unsigned i = 0, realRVLocIdx = 0;
2194 ++i, ++realRVLocIdx) {
2195 CCValAssign &VA = RVLocs[i];
2196 assert(VA.isRegLoc() && "Can only return in registers!");
2198 SDValue Arg = OutVals[realRVLocIdx];
2200 switch (VA.getLocInfo()) {
2201 default: llvm_unreachable("Unknown loc info!");
2202 case CCValAssign::Full: break;
2203 case CCValAssign::BCvt:
2204 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2208 if (VA.needsCustom()) {
2209 if (VA.getLocVT() == MVT::v2f64) {
2210 // Extract the first half and return it in two registers.
2211 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2212 DAG.getConstant(0, MVT::i32));
2213 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2214 DAG.getVTList(MVT::i32, MVT::i32), Half);
2216 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2217 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2219 Flag = Chain.getValue(1);
2220 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2221 VA = RVLocs[++i]; // skip ahead to next loc
2222 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2223 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2225 Flag = Chain.getValue(1);
2226 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2227 VA = RVLocs[++i]; // skip ahead to next loc
2229 // Extract the 2nd half and fall through to handle it as an f64 value.
2230 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2231 DAG.getConstant(1, MVT::i32));
2233 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2235 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2236 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2237 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2238 fmrrd.getValue(isLittleEndian ? 0 : 1),
2240 Flag = Chain.getValue(1);
2241 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2242 VA = RVLocs[++i]; // skip ahead to next loc
2243 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2244 fmrrd.getValue(isLittleEndian ? 1 : 0),
2247 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2249 // Guarantee that all emitted copies are
2250 // stuck together, avoiding something bad.
2251 Flag = Chain.getValue(1);
2252 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2255 // Update chain and glue.
2258 RetOps.push_back(Flag);
2260 // CPUs which aren't M-class use a special sequence to return from
2261 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2262 // though we use "subs pc, lr, #N").
2264 // M-class CPUs actually use a normal return sequence with a special
2265 // (hardware-provided) value in LR, so the normal code path works.
2266 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2267 !Subtarget->isMClass()) {
2268 if (Subtarget->isThumb1Only())
2269 report_fatal_error("interrupt attribute is not supported in Thumb1");
2270 return LowerInterruptReturn(RetOps, dl, DAG);
2273 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2276 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2277 if (N->getNumValues() != 1)
2279 if (!N->hasNUsesOfValue(1, 0))
2282 SDValue TCChain = Chain;
2283 SDNode *Copy = *N->use_begin();
2284 if (Copy->getOpcode() == ISD::CopyToReg) {
2285 // If the copy has a glue operand, we conservatively assume it isn't safe to
2286 // perform a tail call.
2287 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2289 TCChain = Copy->getOperand(0);
2290 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2291 SDNode *VMov = Copy;
2292 // f64 returned in a pair of GPRs.
2293 SmallPtrSet<SDNode*, 2> Copies;
2294 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2296 if (UI->getOpcode() != ISD::CopyToReg)
2300 if (Copies.size() > 2)
2303 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2305 SDValue UseChain = UI->getOperand(0);
2306 if (Copies.count(UseChain.getNode()))
2310 // We are at the top of this chain.
2311 // If the copy has a glue operand, we conservatively assume it
2312 // isn't safe to perform a tail call.
2313 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2319 } else if (Copy->getOpcode() == ISD::BITCAST) {
2320 // f32 returned in a single GPR.
2321 if (!Copy->hasOneUse())
2323 Copy = *Copy->use_begin();
2324 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2326 // If the copy has a glue operand, we conservatively assume it isn't safe to
2327 // perform a tail call.
2328 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2330 TCChain = Copy->getOperand(0);
2335 bool HasRet = false;
2336 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2338 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2339 UI->getOpcode() != ARMISD::INTRET_FLAG)
2351 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2352 if (!Subtarget->supportsTailCall())
2355 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2358 return !Subtarget->isThumb1Only();
2361 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2362 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2363 // one of the above mentioned nodes. It has to be wrapped because otherwise
2364 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2365 // be used to form addressing mode. These wrapped nodes will be selected
2367 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2368 EVT PtrVT = Op.getValueType();
2369 // FIXME there is no actual debug info here
2371 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2373 if (CP->isMachineConstantPoolEntry())
2374 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2375 CP->getAlignment());
2377 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2378 CP->getAlignment());
2379 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2382 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2383 return MachineJumpTableInfo::EK_Inline;
2386 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2387 SelectionDAG &DAG) const {
2388 MachineFunction &MF = DAG.getMachineFunction();
2389 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2390 unsigned ARMPCLabelIndex = 0;
2392 EVT PtrVT = getPointerTy();
2393 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2394 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2396 if (RelocM == Reloc::Static) {
2397 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2399 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2400 ARMPCLabelIndex = AFI->createPICLabelUId();
2401 ARMConstantPoolValue *CPV =
2402 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2403 ARMCP::CPBlockAddress, PCAdj);
2404 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2406 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2407 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2408 MachinePointerInfo::getConstantPool(),
2409 false, false, false, 0);
2410 if (RelocM == Reloc::Static)
2412 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2413 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2416 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2418 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2419 SelectionDAG &DAG) const {
2421 EVT PtrVT = getPointerTy();
2422 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2423 MachineFunction &MF = DAG.getMachineFunction();
2424 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2425 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2426 ARMConstantPoolValue *CPV =
2427 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2428 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2429 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2430 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2431 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2432 MachinePointerInfo::getConstantPool(),
2433 false, false, false, 0);
2434 SDValue Chain = Argument.getValue(1);
2436 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2437 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2439 // call __tls_get_addr.
2442 Entry.Node = Argument;
2443 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2444 Args.push_back(Entry);
2446 // FIXME: is there useful debug info available here?
2447 TargetLowering::CallLoweringInfo CLI(DAG);
2448 CLI.setDebugLoc(dl).setChain(Chain)
2449 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2450 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2453 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2454 return CallResult.first;
2457 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2458 // "local exec" model.
2460 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2462 TLSModel::Model model) const {
2463 const GlobalValue *GV = GA->getGlobal();
2466 SDValue Chain = DAG.getEntryNode();
2467 EVT PtrVT = getPointerTy();
2468 // Get the Thread Pointer
2469 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2471 if (model == TLSModel::InitialExec) {
2472 MachineFunction &MF = DAG.getMachineFunction();
2473 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2474 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2475 // Initial exec model.
2476 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2477 ARMConstantPoolValue *CPV =
2478 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2479 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2481 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2482 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2483 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2484 MachinePointerInfo::getConstantPool(),
2485 false, false, false, 0);
2486 Chain = Offset.getValue(1);
2488 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2489 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2491 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2492 MachinePointerInfo::getConstantPool(),
2493 false, false, false, 0);
2496 assert(model == TLSModel::LocalExec);
2497 ARMConstantPoolValue *CPV =
2498 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2499 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2500 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2501 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2502 MachinePointerInfo::getConstantPool(),
2503 false, false, false, 0);
2506 // The address of the thread local variable is the add of the thread
2507 // pointer with the offset of the variable.
2508 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2512 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2513 // TODO: implement the "local dynamic" model
2514 assert(Subtarget->isTargetELF() &&
2515 "TLS not implemented for non-ELF targets");
2516 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2518 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2521 case TLSModel::GeneralDynamic:
2522 case TLSModel::LocalDynamic:
2523 return LowerToTLSGeneralDynamicModel(GA, DAG);
2524 case TLSModel::InitialExec:
2525 case TLSModel::LocalExec:
2526 return LowerToTLSExecModels(GA, DAG, model);
2528 llvm_unreachable("bogus TLS model");
2531 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2532 SelectionDAG &DAG) const {
2533 EVT PtrVT = getPointerTy();
2535 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2536 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2537 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2538 ARMConstantPoolValue *CPV =
2539 ARMConstantPoolConstant::Create(GV,
2540 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2541 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2542 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2543 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2545 MachinePointerInfo::getConstantPool(),
2546 false, false, false, 0);
2547 SDValue Chain = Result.getValue(1);
2548 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2549 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2551 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2552 MachinePointerInfo::getGOT(),
2553 false, false, false, 0);
2557 // If we have T2 ops, we can materialize the address directly via movt/movw
2558 // pair. This is always cheaper.
2559 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2561 // FIXME: Once remat is capable of dealing with instructions with register
2562 // operands, expand this into two nodes.
2563 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2564 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2566 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2567 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2568 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2569 MachinePointerInfo::getConstantPool(),
2570 false, false, false, 0);
2574 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2575 SelectionDAG &DAG) const {
2576 EVT PtrVT = getPointerTy();
2578 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2579 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2581 if (Subtarget->useMovt(DAG.getMachineFunction()))
2584 // FIXME: Once remat is capable of dealing with instructions with register
2585 // operands, expand this into multiple nodes
2587 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2589 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2590 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2592 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2593 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2594 MachinePointerInfo::getGOT(), false, false, false, 0);
2598 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2599 SelectionDAG &DAG) const {
2600 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2601 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2602 "Windows on ARM expects to use movw/movt");
2604 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2605 const ARMII::TOF TargetFlags =
2606 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2607 EVT PtrVT = getPointerTy();
2613 // FIXME: Once remat is capable of dealing with instructions with register
2614 // operands, expand this into two nodes.
2615 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2616 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2618 if (GV->hasDLLImportStorageClass())
2619 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2620 MachinePointerInfo::getGOT(), false, false, false, 0);
2624 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2625 SelectionDAG &DAG) const {
2626 assert(Subtarget->isTargetELF() &&
2627 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2628 MachineFunction &MF = DAG.getMachineFunction();
2629 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2630 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2631 EVT PtrVT = getPointerTy();
2633 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2634 ARMConstantPoolValue *CPV =
2635 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2636 ARMPCLabelIndex, PCAdj);
2637 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2638 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2639 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2640 MachinePointerInfo::getConstantPool(),
2641 false, false, false, 0);
2642 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2643 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2647 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2649 SDValue Val = DAG.getConstant(0, MVT::i32);
2650 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2651 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2652 Op.getOperand(1), Val);
2656 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2658 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2659 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2663 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2664 const ARMSubtarget *Subtarget) const {
2665 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2668 default: return SDValue(); // Don't custom lower most intrinsics.
2669 case Intrinsic::arm_rbit: {
2670 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2671 "RBIT intrinsic must have i32 type!");
2672 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2674 case Intrinsic::arm_thread_pointer: {
2675 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2676 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2678 case Intrinsic::eh_sjlj_lsda: {
2679 MachineFunction &MF = DAG.getMachineFunction();
2680 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2681 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2682 EVT PtrVT = getPointerTy();
2683 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2685 unsigned PCAdj = (RelocM != Reloc::PIC_)
2686 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2687 ARMConstantPoolValue *CPV =
2688 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2689 ARMCP::CPLSDA, PCAdj);
2690 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2691 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2693 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2694 MachinePointerInfo::getConstantPool(),
2695 false, false, false, 0);
2697 if (RelocM == Reloc::PIC_) {
2698 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2699 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2703 case Intrinsic::arm_neon_vmulls:
2704 case Intrinsic::arm_neon_vmullu: {
2705 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2706 ? ARMISD::VMULLs : ARMISD::VMULLu;
2707 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2708 Op.getOperand(1), Op.getOperand(2));
2713 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2714 const ARMSubtarget *Subtarget) {
2715 // FIXME: handle "fence singlethread" more efficiently.
2717 if (!Subtarget->hasDataBarrier()) {
2718 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2719 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2721 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2722 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2723 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2724 DAG.getConstant(0, MVT::i32));
2727 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2728 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2729 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2730 if (Subtarget->isMClass()) {
2731 // Only a full system barrier exists in the M-class architectures.
2732 Domain = ARM_MB::SY;
2733 } else if (Subtarget->isSwift() && Ord == Release) {
2734 // Swift happens to implement ISHST barriers in a way that's compatible with
2735 // Release semantics but weaker than ISH so we'd be fools not to use
2736 // it. Beware: other processors probably don't!
2737 Domain = ARM_MB::ISHST;
2740 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2741 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2742 DAG.getConstant(Domain, MVT::i32));
2745 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2746 const ARMSubtarget *Subtarget) {
2747 // ARM pre v5TE and Thumb1 does not have preload instructions.
2748 if (!(Subtarget->isThumb2() ||
2749 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2750 // Just preserve the chain.
2751 return Op.getOperand(0);
2754 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2756 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2757 // ARMv7 with MP extension has PLDW.
2758 return Op.getOperand(0);
2760 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2761 if (Subtarget->isThumb()) {
2763 isRead = ~isRead & 1;
2764 isData = ~isData & 1;
2767 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2768 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2769 DAG.getConstant(isData, MVT::i32));
2772 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2773 MachineFunction &MF = DAG.getMachineFunction();
2774 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2776 // vastart just stores the address of the VarArgsFrameIndex slot into the
2777 // memory location argument.
2779 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2780 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2781 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2782 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2783 MachinePointerInfo(SV), false, false, 0);
2787 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2788 SDValue &Root, SelectionDAG &DAG,
2790 MachineFunction &MF = DAG.getMachineFunction();
2791 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2793 const TargetRegisterClass *RC;
2794 if (AFI->isThumb1OnlyFunction())
2795 RC = &ARM::tGPRRegClass;
2797 RC = &ARM::GPRRegClass;
2799 // Transform the arguments stored in physical registers into virtual ones.
2800 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2801 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2804 if (NextVA.isMemLoc()) {
2805 MachineFrameInfo *MFI = MF.getFrameInfo();
2806 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2808 // Create load node to retrieve arguments from the stack.
2809 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2810 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2811 MachinePointerInfo::getFixedStack(FI),
2812 false, false, false, 0);
2814 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2815 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2817 if (!Subtarget->isLittle())
2818 std::swap (ArgValue, ArgValue2);
2819 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2822 // The remaining GPRs hold either the beginning of variable-argument
2823 // data, or the beginning of an aggregate passed by value (usually
2824 // byval). Either way, we allocate stack slots adjacent to the data
2825 // provided by our caller, and store the unallocated registers there.
2826 // If this is a variadic function, the va_list pointer will begin with
2827 // these values; otherwise, this reassembles a (byval) structure that
2828 // was split between registers and memory.
2829 // Return: The frame index registers were stored into.
2831 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2832 SDLoc dl, SDValue &Chain,
2833 const Value *OrigArg,
2834 unsigned InRegsParamRecordIdx,
2836 unsigned ArgSize) const {
2837 // Currently, two use-cases possible:
2838 // Case #1. Non-var-args function, and we meet first byval parameter.
2839 // Setup first unallocated register as first byval register;
2840 // eat all remained registers
2841 // (these two actions are performed by HandleByVal method).
2842 // Then, here, we initialize stack frame with
2843 // "store-reg" instructions.
2844 // Case #2. Var-args function, that doesn't contain byval parameters.
2845 // The same: eat all remained unallocated registers,
2846 // initialize stack frame.
2848 MachineFunction &MF = DAG.getMachineFunction();
2849 MachineFrameInfo *MFI = MF.getFrameInfo();
2850 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2851 unsigned RBegin, REnd;
2852 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2853 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2855 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2856 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2861 ArgOffset = -4 * (ARM::R4 - RBegin);
2863 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2864 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2866 SmallVector<SDValue, 4> MemOps;
2867 const TargetRegisterClass *RC =
2868 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2870 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2871 unsigned VReg = MF.addLiveIn(Reg, RC);
2872 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2874 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2875 MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2876 MemOps.push_back(Store);
2877 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2878 DAG.getConstant(4, getPointerTy()));
2881 if (!MemOps.empty())
2882 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2886 // Setup stack frame, the va_list pointer will start from.
2888 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2889 SDLoc dl, SDValue &Chain,
2891 unsigned TotalArgRegsSaveSize,
2892 bool ForceMutable) const {
2893 MachineFunction &MF = DAG.getMachineFunction();
2894 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2896 // Try to store any remaining integer argument regs
2897 // to their spots on the stack so that they may be loaded by deferencing
2898 // the result of va_next.
2899 // If there is no regs to be stored, just point address after last
2900 // argument passed via stack.
2901 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2902 CCInfo.getInRegsParamsCount(),
2903 CCInfo.getNextStackOffset(), 4);
2904 AFI->setVarArgsFrameIndex(FrameIndex);
2908 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2909 CallingConv::ID CallConv, bool isVarArg,
2910 const SmallVectorImpl<ISD::InputArg>
2912 SDLoc dl, SelectionDAG &DAG,
2913 SmallVectorImpl<SDValue> &InVals)
2915 MachineFunction &MF = DAG.getMachineFunction();
2916 MachineFrameInfo *MFI = MF.getFrameInfo();
2918 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2920 // Assign locations to all of the incoming arguments.
2921 SmallVector<CCValAssign, 16> ArgLocs;
2922 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2923 *DAG.getContext(), Prologue);
2924 CCInfo.AnalyzeFormalArguments(Ins,
2925 CCAssignFnForNode(CallConv, /* Return*/ false,
2928 SmallVector<SDValue, 16> ArgValues;
2930 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2931 unsigned CurArgIdx = 0;
2933 // Initially ArgRegsSaveSize is zero.
2934 // Then we increase this value each time we meet byval parameter.
2935 // We also increase this value in case of varargs function.
2936 AFI->setArgRegsSaveSize(0);
2938 // Calculate the amount of stack space that we need to allocate to store
2939 // byval and variadic arguments that are passed in registers.
2940 // We need to know this before we allocate the first byval or variadic
2941 // argument, as they will be allocated a stack slot below the CFA (Canonical
2942 // Frame Address, the stack pointer at entry to the function).
2943 unsigned ArgRegBegin = ARM::R4;
2944 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2945 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
2948 CCValAssign &VA = ArgLocs[i];
2949 unsigned Index = VA.getValNo();
2950 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
2951 if (!Flags.isByVal())
2954 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
2955 unsigned RBegin, REnd;
2956 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
2957 ArgRegBegin = std::min(ArgRegBegin, RBegin);
2959 CCInfo.nextInRegsParam();
2961 CCInfo.rewindByValRegsInfo();
2963 int lastInsIndex = -1;
2964 if (isVarArg && MFI->hasVAStart()) {
2965 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2966 if (RegIdx != array_lengthof(GPRArgRegs))
2967 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
2970 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
2971 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
2973 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2974 CCValAssign &VA = ArgLocs[i];
2975 if (Ins[VA.getValNo()].isOrigArg()) {
2976 std::advance(CurOrigArg,
2977 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
2978 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
2980 // Arguments stored in registers.
2981 if (VA.isRegLoc()) {
2982 EVT RegVT = VA.getLocVT();
2984 if (VA.needsCustom()) {
2985 // f64 and vector types are split up into multiple registers or
2986 // combinations of registers and stack slots.
2987 if (VA.getLocVT() == MVT::v2f64) {
2988 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2990 VA = ArgLocs[++i]; // skip ahead to next loc
2992 if (VA.isMemLoc()) {
2993 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2994 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2995 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2996 MachinePointerInfo::getFixedStack(FI),
2997 false, false, false, 0);
2999 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3002 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3003 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3004 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3005 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3006 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3008 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3011 const TargetRegisterClass *RC;
3013 if (RegVT == MVT::f32)
3014 RC = &ARM::SPRRegClass;
3015 else if (RegVT == MVT::f64)
3016 RC = &ARM::DPRRegClass;
3017 else if (RegVT == MVT::v2f64)
3018 RC = &ARM::QPRRegClass;
3019 else if (RegVT == MVT::i32)
3020 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3021 : &ARM::GPRRegClass;
3023 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3025 // Transform the arguments in physical registers into virtual ones.
3026 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3027 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3030 // If this is an 8 or 16-bit value, it is really passed promoted
3031 // to 32 bits. Insert an assert[sz]ext to capture this, then
3032 // truncate to the right size.
3033 switch (VA.getLocInfo()) {
3034 default: llvm_unreachable("Unknown loc info!");
3035 case CCValAssign::Full: break;
3036 case CCValAssign::BCvt:
3037 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3039 case CCValAssign::SExt:
3040 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3041 DAG.getValueType(VA.getValVT()));
3042 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3044 case CCValAssign::ZExt:
3045 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3046 DAG.getValueType(VA.getValVT()));
3047 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3051 InVals.push_back(ArgValue);
3053 } else { // VA.isRegLoc()
3056 assert(VA.isMemLoc());
3057 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3059 int index = VA.getValNo();
3061 // Some Ins[] entries become multiple ArgLoc[] entries.
3062 // Process them only once.
3063 if (index != lastInsIndex)
3065 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3066 // FIXME: For now, all byval parameter objects are marked mutable.
3067 // This can be changed with more analysis.
3068 // In case of tail call optimization mark all arguments mutable.
3069 // Since they could be overwritten by lowering of arguments in case of
3071 if (Flags.isByVal()) {
3072 assert(Ins[index].isOrigArg() &&
3073 "Byval arguments cannot be implicit");
3074 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3076 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3077 CurByValIndex, VA.getLocMemOffset(),
3078 Flags.getByValSize());
3079 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3080 CCInfo.nextInRegsParam();
3082 unsigned FIOffset = VA.getLocMemOffset();
3083 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3086 // Create load nodes to retrieve arguments from the stack.
3087 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3088 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3089 MachinePointerInfo::getFixedStack(FI),
3090 false, false, false, 0));
3092 lastInsIndex = index;
3098 if (isVarArg && MFI->hasVAStart())
3099 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3100 CCInfo.getNextStackOffset(),
3101 TotalArgRegsSaveSize);
3103 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3108 /// isFloatingPointZero - Return true if this is +0.0.
3109 static bool isFloatingPointZero(SDValue Op) {
3110 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3111 return CFP->getValueAPF().isPosZero();
3112 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3113 // Maybe this has already been legalized into the constant pool?
3114 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3115 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3116 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3117 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3118 return CFP->getValueAPF().isPosZero();
3120 } else if (Op->getOpcode() == ISD::BITCAST &&
3121 Op->getValueType(0) == MVT::f64) {
3122 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3123 // created by LowerConstantFP().
3124 SDValue BitcastOp = Op->getOperand(0);
3125 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3126 SDValue MoveOp = BitcastOp->getOperand(0);
3127 if (MoveOp->getOpcode() == ISD::TargetConstant &&
3128 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3136 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3137 /// the given operands.
3139 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3140 SDValue &ARMcc, SelectionDAG &DAG,
3142 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3143 unsigned C = RHSC->getZExtValue();
3144 if (!isLegalICmpImmediate(C)) {
3145 // Constant does not fit, try adjusting it by one?
3150 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3151 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3152 RHS = DAG.getConstant(C-1, MVT::i32);
3157 if (C != 0 && isLegalICmpImmediate(C-1)) {
3158 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3159 RHS = DAG.getConstant(C-1, MVT::i32);
3164 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3165 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3166 RHS = DAG.getConstant(C+1, MVT::i32);
3171 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3172 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3173 RHS = DAG.getConstant(C+1, MVT::i32);
3180 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3181 ARMISD::NodeType CompareType;
3184 CompareType = ARMISD::CMP;
3189 CompareType = ARMISD::CMPZ;
3192 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3193 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3196 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3198 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3200 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3202 if (!isFloatingPointZero(RHS))
3203 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3205 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3206 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3209 /// duplicateCmp - Glue values can have only one use, so this function
3210 /// duplicates a comparison node.
3212 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3213 unsigned Opc = Cmp.getOpcode();
3215 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3216 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3218 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3219 Cmp = Cmp.getOperand(0);
3220 Opc = Cmp.getOpcode();
3221 if (Opc == ARMISD::CMPFP)
3222 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3224 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3225 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3227 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3230 std::pair<SDValue, SDValue>
3231 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3232 SDValue &ARMcc) const {
3233 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3235 SDValue Value, OverflowCmp;
3236 SDValue LHS = Op.getOperand(0);
3237 SDValue RHS = Op.getOperand(1);
3240 // FIXME: We are currently always generating CMPs because we don't support
3241 // generating CMN through the backend. This is not as good as the natural
3242 // CMP case because it causes a register dependency and cannot be folded
3245 switch (Op.getOpcode()) {
3247 llvm_unreachable("Unknown overflow instruction!");
3249 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3250 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3251 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3254 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3255 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3256 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3259 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3260 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3261 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3264 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3265 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3266 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3270 return std::make_pair(Value, OverflowCmp);
3275 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3276 // Let legalize expand this if it isn't a legal type yet.
3277 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3280 SDValue Value, OverflowCmp;
3282 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3283 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3284 // We use 0 and 1 as false and true values.
3285 SDValue TVal = DAG.getConstant(1, MVT::i32);
3286 SDValue FVal = DAG.getConstant(0, MVT::i32);
3287 EVT VT = Op.getValueType();
3289 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3290 ARMcc, CCR, OverflowCmp);
3292 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3293 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3297 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3298 SDValue Cond = Op.getOperand(0);
3299 SDValue SelectTrue = Op.getOperand(1);
3300 SDValue SelectFalse = Op.getOperand(2);
3302 unsigned Opc = Cond.getOpcode();
3304 if (Cond.getResNo() == 1 &&
3305 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3306 Opc == ISD::USUBO)) {
3307 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3310 SDValue Value, OverflowCmp;
3312 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3313 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3314 EVT VT = Op.getValueType();
3316 return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3322 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3323 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3325 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3326 const ConstantSDNode *CMOVTrue =
3327 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3328 const ConstantSDNode *CMOVFalse =
3329 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3331 if (CMOVTrue && CMOVFalse) {
3332 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3333 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3337 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3339 False = SelectFalse;
3340 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3345 if (True.getNode() && False.getNode()) {
3346 EVT VT = Op.getValueType();
3347 SDValue ARMcc = Cond.getOperand(2);
3348 SDValue CCR = Cond.getOperand(3);
3349 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3350 assert(True.getValueType() == VT);
3351 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3356 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3357 // undefined bits before doing a full-word comparison with zero.
3358 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3359 DAG.getConstant(1, Cond.getValueType()));
3361 return DAG.getSelectCC(dl, Cond,
3362 DAG.getConstant(0, Cond.getValueType()),
3363 SelectTrue, SelectFalse, ISD::SETNE);
3366 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3367 if (CC == ISD::SETNE)
3369 return ISD::getSetCCInverse(CC, true);
3372 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3373 bool &swpCmpOps, bool &swpVselOps) {
3374 // Start by selecting the GE condition code for opcodes that return true for
3376 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3378 CondCode = ARMCC::GE;
3380 // and GT for opcodes that return false for 'equality'.
3381 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3383 CondCode = ARMCC::GT;
3385 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3386 // to swap the compare operands.
3387 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3391 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3392 // If we have an unordered opcode, we need to swap the operands to the VSEL
3393 // instruction (effectively negating the condition).
3395 // This also has the effect of swapping which one of 'less' or 'greater'
3396 // returns true, so we also swap the compare operands. It also switches
3397 // whether we return true for 'equality', so we compensate by picking the
3398 // opposite condition code to our original choice.
3399 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3400 CC == ISD::SETUGT) {
3401 swpCmpOps = !swpCmpOps;
3402 swpVselOps = !swpVselOps;
3403 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3406 // 'ordered' is 'anything but unordered', so use the VS condition code and
3407 // swap the VSEL operands.
3408 if (CC == ISD::SETO) {
3409 CondCode = ARMCC::VS;
3413 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3414 // code and swap the VSEL operands.
3415 if (CC == ISD::SETUNE) {
3416 CondCode = ARMCC::EQ;
3421 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3422 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3423 SDValue Cmp, SelectionDAG &DAG) const {
3424 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3425 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3426 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3427 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3428 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3430 SDValue TrueLow = TrueVal.getValue(0);
3431 SDValue TrueHigh = TrueVal.getValue(1);
3432 SDValue FalseLow = FalseVal.getValue(0);
3433 SDValue FalseHigh = FalseVal.getValue(1);
3435 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3437 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3438 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3440 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3442 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3447 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3448 EVT VT = Op.getValueType();
3449 SDValue LHS = Op.getOperand(0);
3450 SDValue RHS = Op.getOperand(1);
3451 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3452 SDValue TrueVal = Op.getOperand(2);
3453 SDValue FalseVal = Op.getOperand(3);
3456 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3457 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3460 // If softenSetCCOperands only returned one value, we should compare it to
3462 if (!RHS.getNode()) {
3463 RHS = DAG.getConstant(0, LHS.getValueType());
3468 if (LHS.getValueType() == MVT::i32) {
3469 // Try to generate VSEL on ARMv8.
3470 // The VSEL instruction can't use all the usual ARM condition
3471 // codes: it only has two bits to select the condition code, so it's
3472 // constrained to use only GE, GT, VS and EQ.
3474 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3475 // swap the operands of the previous compare instruction (effectively
3476 // inverting the compare condition, swapping 'less' and 'greater') and
3477 // sometimes need to swap the operands to the VSEL (which inverts the
3478 // condition in the sense of firing whenever the previous condition didn't)
3479 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3480 TrueVal.getValueType() == MVT::f64)) {
3481 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3482 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3483 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3484 CC = getInverseCCForVSEL(CC);
3485 std::swap(TrueVal, FalseVal);
3490 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3491 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3492 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3495 ARMCC::CondCodes CondCode, CondCode2;
3496 FPCCToARMCC(CC, CondCode, CondCode2);
3498 // Try to generate VSEL on ARMv8.
3499 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3500 TrueVal.getValueType() == MVT::f64)) {
3501 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3502 // same operands, as follows:
3503 // c = fcmp [ogt, olt, ugt, ult] a, b
3505 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3506 // handled differently than the original code sequence.
3507 if (getTargetMachine().Options.UnsafeFPMath) {
3508 if (LHS == TrueVal && RHS == FalseVal) {
3509 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3510 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3511 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3512 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3513 } else if (LHS == FalseVal && RHS == TrueVal) {
3514 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3515 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3516 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3517 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3521 bool swpCmpOps = false;
3522 bool swpVselOps = false;
3523 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3525 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3526 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3528 std::swap(LHS, RHS);
3530 std::swap(TrueVal, FalseVal);
3534 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3535 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3536 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3537 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3538 if (CondCode2 != ARMCC::AL) {
3539 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3540 // FIXME: Needs another CMP because flag can have but one use.
3541 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3542 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3547 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3548 /// to morph to an integer compare sequence.
3549 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3550 const ARMSubtarget *Subtarget) {
3551 SDNode *N = Op.getNode();
3552 if (!N->hasOneUse())
3553 // Otherwise it requires moving the value from fp to integer registers.
3555 if (!N->getNumValues())
3557 EVT VT = Op.getValueType();
3558 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3559 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3560 // vmrs are very slow, e.g. cortex-a8.
3563 if (isFloatingPointZero(Op)) {
3567 return ISD::isNormalLoad(N);
3570 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3571 if (isFloatingPointZero(Op))
3572 return DAG.getConstant(0, MVT::i32);
3574 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3575 return DAG.getLoad(MVT::i32, SDLoc(Op),
3576 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3577 Ld->isVolatile(), Ld->isNonTemporal(),
3578 Ld->isInvariant(), Ld->getAlignment());
3580 llvm_unreachable("Unknown VFP cmp argument!");
3583 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3584 SDValue &RetVal1, SDValue &RetVal2) {
3585 if (isFloatingPointZero(Op)) {
3586 RetVal1 = DAG.getConstant(0, MVT::i32);
3587 RetVal2 = DAG.getConstant(0, MVT::i32);
3591 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3592 SDValue Ptr = Ld->getBasePtr();
3593 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3594 Ld->getChain(), Ptr,
3595 Ld->getPointerInfo(),
3596 Ld->isVolatile(), Ld->isNonTemporal(),
3597 Ld->isInvariant(), Ld->getAlignment());
3599 EVT PtrType = Ptr.getValueType();
3600 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3601 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3602 PtrType, Ptr, DAG.getConstant(4, PtrType));
3603 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3604 Ld->getChain(), NewPtr,
3605 Ld->getPointerInfo().getWithOffset(4),
3606 Ld->isVolatile(), Ld->isNonTemporal(),
3607 Ld->isInvariant(), NewAlign);
3611 llvm_unreachable("Unknown VFP cmp argument!");
3614 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3615 /// f32 and even f64 comparisons to integer ones.
3617 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3618 SDValue Chain = Op.getOperand(0);
3619 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3620 SDValue LHS = Op.getOperand(2);
3621 SDValue RHS = Op.getOperand(3);
3622 SDValue Dest = Op.getOperand(4);
3625 bool LHSSeenZero = false;
3626 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3627 bool RHSSeenZero = false;
3628 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3629 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3630 // If unsafe fp math optimization is enabled and there are no other uses of
3631 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3632 // to an integer comparison.
3633 if (CC == ISD::SETOEQ)
3635 else if (CC == ISD::SETUNE)
3638 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3640 if (LHS.getValueType() == MVT::f32) {
3641 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3642 bitcastf32Toi32(LHS, DAG), Mask);
3643 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3644 bitcastf32Toi32(RHS, DAG), Mask);
3645 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3646 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3647 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3648 Chain, Dest, ARMcc, CCR, Cmp);
3653 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3654 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3655 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3656 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3657 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3658 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3659 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3660 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3661 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3667 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3668 SDValue Chain = Op.getOperand(0);
3669 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3670 SDValue LHS = Op.getOperand(2);
3671 SDValue RHS = Op.getOperand(3);
3672 SDValue Dest = Op.getOperand(4);
3675 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3676 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3679 // If softenSetCCOperands only returned one value, we should compare it to
3681 if (!RHS.getNode()) {
3682 RHS = DAG.getConstant(0, LHS.getValueType());
3687 if (LHS.getValueType() == MVT::i32) {
3689 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3690 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3691 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3692 Chain, Dest, ARMcc, CCR, Cmp);
3695 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3697 if (getTargetMachine().Options.UnsafeFPMath &&
3698 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3699 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3700 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3701 if (Result.getNode())
3705 ARMCC::CondCodes CondCode, CondCode2;
3706 FPCCToARMCC(CC, CondCode, CondCode2);
3708 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3709 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3710 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3711 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3712 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3713 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3714 if (CondCode2 != ARMCC::AL) {
3715 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3716 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3717 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3722 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3723 SDValue Chain = Op.getOperand(0);
3724 SDValue Table = Op.getOperand(1);
3725 SDValue Index = Op.getOperand(2);
3728 EVT PTy = getPointerTy();
3729 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3730 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3731 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3732 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3733 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3734 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3735 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3736 if (Subtarget->isThumb2()) {
3737 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3738 // which does another jump to the destination. This also makes it easier
3739 // to translate it to TBB / TBH later.
3740 // FIXME: This might not work if the function is extremely large.
3741 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3742 Addr, Op.getOperand(2), JTI, UId);
3744 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3745 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3746 MachinePointerInfo::getJumpTable(),
3747 false, false, false, 0);
3748 Chain = Addr.getValue(1);
3749 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3750 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3752 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3753 MachinePointerInfo::getJumpTable(),
3754 false, false, false, 0);
3755 Chain = Addr.getValue(1);
3756 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3760 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3761 EVT VT = Op.getValueType();
3764 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3765 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3767 return DAG.UnrollVectorOp(Op.getNode());
3770 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3771 "Invalid type for custom lowering!");
3772 if (VT != MVT::v4i16)
3773 return DAG.UnrollVectorOp(Op.getNode());
3775 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3776 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3779 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3780 EVT VT = Op.getValueType();
3782 return LowerVectorFP_TO_INT(Op, DAG);
3784 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3786 if (Op.getOpcode() == ISD::FP_TO_SINT)
3787 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3790 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3792 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3793 /*isSigned*/ false, SDLoc(Op)).first;
3799 switch (Op.getOpcode()) {
3800 default: llvm_unreachable("Invalid opcode!");
3801 case ISD::FP_TO_SINT:
3802 Opc = ARMISD::FTOSI;
3804 case ISD::FP_TO_UINT:
3805 Opc = ARMISD::FTOUI;
3808 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3809 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3812 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3813 EVT VT = Op.getValueType();
3816 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3817 if (VT.getVectorElementType() == MVT::f32)
3819 return DAG.UnrollVectorOp(Op.getNode());
3822 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3823 "Invalid type for custom lowering!");
3824 if (VT != MVT::v4f32)
3825 return DAG.UnrollVectorOp(Op.getNode());
3829 switch (Op.getOpcode()) {
3830 default: llvm_unreachable("Invalid opcode!");
3831 case ISD::SINT_TO_FP:
3832 CastOpc = ISD::SIGN_EXTEND;
3833 Opc = ISD::SINT_TO_FP;
3835 case ISD::UINT_TO_FP:
3836 CastOpc = ISD::ZERO_EXTEND;
3837 Opc = ISD::UINT_TO_FP;
3841 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3842 return DAG.getNode(Opc, dl, VT, Op);
3845 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3846 EVT VT = Op.getValueType();
3848 return LowerVectorINT_TO_FP(Op, DAG);
3850 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3852 if (Op.getOpcode() == ISD::SINT_TO_FP)
3853 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3856 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3858 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3859 /*isSigned*/ false, SDLoc(Op)).first;
3865 switch (Op.getOpcode()) {
3866 default: llvm_unreachable("Invalid opcode!");
3867 case ISD::SINT_TO_FP:
3868 Opc = ARMISD::SITOF;
3870 case ISD::UINT_TO_FP:
3871 Opc = ARMISD::UITOF;
3875 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3876 return DAG.getNode(Opc, dl, VT, Op);
3879 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3880 // Implement fcopysign with a fabs and a conditional fneg.
3881 SDValue Tmp0 = Op.getOperand(0);
3882 SDValue Tmp1 = Op.getOperand(1);
3884 EVT VT = Op.getValueType();
3885 EVT SrcVT = Tmp1.getValueType();
3886 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3887 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3888 bool UseNEON = !InGPR && Subtarget->hasNEON();
3891 // Use VBSL to copy the sign bit.
3892 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3893 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3894 DAG.getTargetConstant(EncodedVal, MVT::i32));
3895 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3897 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3898 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3899 DAG.getConstant(32, MVT::i32));
3900 else /*if (VT == MVT::f32)*/
3901 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3902 if (SrcVT == MVT::f32) {
3903 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3905 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3906 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3907 DAG.getConstant(32, MVT::i32));
3908 } else if (VT == MVT::f32)
3909 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3910 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3911 DAG.getConstant(32, MVT::i32));
3912 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3913 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3915 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3917 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3918 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3919 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3921 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3922 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3923 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3924 if (VT == MVT::f32) {
3925 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3926 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3927 DAG.getConstant(0, MVT::i32));
3929 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3935 // Bitcast operand 1 to i32.
3936 if (SrcVT == MVT::f64)
3937 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3939 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3941 // Or in the signbit with integer operations.
3942 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3943 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3944 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3945 if (VT == MVT::f32) {
3946 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3947 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3948 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3949 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3952 // f64: Or the high part with signbit and then combine two parts.
3953 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3955 SDValue Lo = Tmp0.getValue(0);
3956 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3957 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3958 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3961 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3962 MachineFunction &MF = DAG.getMachineFunction();
3963 MachineFrameInfo *MFI = MF.getFrameInfo();
3964 MFI->setReturnAddressIsTaken(true);
3966 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3969 EVT VT = Op.getValueType();
3971 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3973 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3974 SDValue Offset = DAG.getConstant(4, MVT::i32);
3975 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3976 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3977 MachinePointerInfo(), false, false, false, 0);
3980 // Return LR, which contains the return address. Mark it an implicit live-in.
3981 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3982 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3985 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3986 const ARMBaseRegisterInfo &ARI =
3987 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3988 MachineFunction &MF = DAG.getMachineFunction();
3989 MachineFrameInfo *MFI = MF.getFrameInfo();
3990 MFI->setFrameAddressIsTaken(true);
3992 EVT VT = Op.getValueType();
3993 SDLoc dl(Op); // FIXME probably not meaningful
3994 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3995 unsigned FrameReg = ARI.getFrameRegister(MF);
3996 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3998 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3999 MachinePointerInfo(),
4000 false, false, false, 0);
4004 // FIXME? Maybe this could be a TableGen attribute on some registers and
4005 // this table could be generated automatically from RegInfo.
4006 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4008 unsigned Reg = StringSwitch<unsigned>(RegName)
4009 .Case("sp", ARM::SP)
4013 report_fatal_error("Invalid register name global variable");
4016 /// ExpandBITCAST - If the target supports VFP, this function is called to
4017 /// expand a bit convert where either the source or destination type is i64 to
4018 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4019 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4020 /// vectors), since the legalizer won't know what to do with that.
4021 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4022 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4024 SDValue Op = N->getOperand(0);
4026 // This function is only supposed to be called for i64 types, either as the
4027 // source or destination of the bit convert.
4028 EVT SrcVT = Op.getValueType();
4029 EVT DstVT = N->getValueType(0);
4030 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4031 "ExpandBITCAST called for non-i64 type");
4033 // Turn i64->f64 into VMOVDRR.
4034 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4035 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4036 DAG.getConstant(0, MVT::i32));
4037 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4038 DAG.getConstant(1, MVT::i32));
4039 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4040 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4043 // Turn f64->i64 into VMOVRRD.
4044 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4046 if (TLI.isBigEndian() && SrcVT.isVector() &&
4047 SrcVT.getVectorNumElements() > 1)
4048 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4049 DAG.getVTList(MVT::i32, MVT::i32),
4050 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4052 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4053 DAG.getVTList(MVT::i32, MVT::i32), Op);
4054 // Merge the pieces into a single i64 value.
4055 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4061 /// getZeroVector - Returns a vector of specified type with all zero elements.
4062 /// Zero vectors are used to represent vector negation and in those cases
4063 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4064 /// not support i64 elements, so sometimes the zero vectors will need to be
4065 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4067 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4068 assert(VT.isVector() && "Expected a vector type");
4069 // The canonical modified immediate encoding of a zero vector is....0!
4070 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4071 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4072 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4073 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4076 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4077 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4078 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4079 SelectionDAG &DAG) const {
4080 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4081 EVT VT = Op.getValueType();
4082 unsigned VTBits = VT.getSizeInBits();
4084 SDValue ShOpLo = Op.getOperand(0);
4085 SDValue ShOpHi = Op.getOperand(1);
4086 SDValue ShAmt = Op.getOperand(2);
4088 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4090 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4092 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4093 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4094 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4095 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4096 DAG.getConstant(VTBits, MVT::i32));
4097 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4098 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4099 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4101 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4102 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4104 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4105 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4108 SDValue Ops[2] = { Lo, Hi };
4109 return DAG.getMergeValues(Ops, dl);
4112 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4113 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4114 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4115 SelectionDAG &DAG) const {
4116 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4117 EVT VT = Op.getValueType();
4118 unsigned VTBits = VT.getSizeInBits();
4120 SDValue ShOpLo = Op.getOperand(0);
4121 SDValue ShOpHi = Op.getOperand(1);
4122 SDValue ShAmt = Op.getOperand(2);
4125 assert(Op.getOpcode() == ISD::SHL_PARTS);
4126 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4127 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4128 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4129 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4130 DAG.getConstant(VTBits, MVT::i32));
4131 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4132 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4134 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4135 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4136 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4138 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4139 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4142 SDValue Ops[2] = { Lo, Hi };
4143 return DAG.getMergeValues(Ops, dl);
4146 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4147 SelectionDAG &DAG) const {
4148 // The rounding mode is in bits 23:22 of the FPSCR.
4149 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4150 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4151 // so that the shift + and get folded into a bitfield extract.
4153 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4154 DAG.getConstant(Intrinsic::arm_get_fpscr,
4156 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4157 DAG.getConstant(1U << 22, MVT::i32));
4158 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4159 DAG.getConstant(22, MVT::i32));
4160 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4161 DAG.getConstant(3, MVT::i32));
4164 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4165 const ARMSubtarget *ST) {
4166 EVT VT = N->getValueType(0);
4169 if (!ST->hasV6T2Ops())
4172 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4173 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4176 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4177 /// for each 16-bit element from operand, repeated. The basic idea is to
4178 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4180 /// Trace for v4i16:
4181 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4182 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4183 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4184 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4185 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4186 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4187 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4188 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4189 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4190 EVT VT = N->getValueType(0);
4193 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4194 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4195 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4196 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4197 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4198 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4201 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4202 /// bit-count for each 16-bit element from the operand. We need slightly
4203 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4204 /// 64/128-bit registers.
4206 /// Trace for v4i16:
4207 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4208 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4209 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4210 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4211 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4212 EVT VT = N->getValueType(0);
4215 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4216 if (VT.is64BitVector()) {
4217 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4218 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4219 DAG.getIntPtrConstant(0));
4221 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4222 BitCounts, DAG.getIntPtrConstant(0));
4223 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4227 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4228 /// bit-count for each 32-bit element from the operand. The idea here is
4229 /// to split the vector into 16-bit elements, leverage the 16-bit count
4230 /// routine, and then combine the results.
4232 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4233 /// input = [v0 v1 ] (vi: 32-bit elements)
4234 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4235 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4236 /// vrev: N0 = [k1 k0 k3 k2 ]
4238 /// N1 =+[k1 k0 k3 k2 ]
4240 /// N2 =+[k1 k3 k0 k2 ]
4242 /// Extended =+[k1 k3 k0 k2 ]
4244 /// Extracted=+[k1 k3 ]
4246 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4247 EVT VT = N->getValueType(0);
4250 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4252 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4253 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4254 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4255 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4256 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4258 if (VT.is64BitVector()) {
4259 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4260 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4261 DAG.getIntPtrConstant(0));
4263 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4264 DAG.getIntPtrConstant(0));
4265 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4269 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4270 const ARMSubtarget *ST) {
4271 EVT VT = N->getValueType(0);
4273 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4274 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4275 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4276 "Unexpected type for custom ctpop lowering");
4278 if (VT.getVectorElementType() == MVT::i32)
4279 return lowerCTPOP32BitElements(N, DAG);
4281 return lowerCTPOP16BitElements(N, DAG);
4284 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4285 const ARMSubtarget *ST) {
4286 EVT VT = N->getValueType(0);
4292 // Lower vector shifts on NEON to use VSHL.
4293 assert(ST->hasNEON() && "unexpected vector shift");
4295 // Left shifts translate directly to the vshiftu intrinsic.
4296 if (N->getOpcode() == ISD::SHL)
4297 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4298 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4299 N->getOperand(0), N->getOperand(1));
4301 assert((N->getOpcode() == ISD::SRA ||
4302 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4304 // NEON uses the same intrinsics for both left and right shifts. For
4305 // right shifts, the shift amounts are negative, so negate the vector of
4307 EVT ShiftVT = N->getOperand(1).getValueType();
4308 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4309 getZeroVector(ShiftVT, DAG, dl),
4311 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4312 Intrinsic::arm_neon_vshifts :
4313 Intrinsic::arm_neon_vshiftu);
4314 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4315 DAG.getConstant(vshiftInt, MVT::i32),
4316 N->getOperand(0), NegatedCount);
4319 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4320 const ARMSubtarget *ST) {
4321 EVT VT = N->getValueType(0);
4324 // We can get here for a node like i32 = ISD::SHL i32, i64
4328 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4329 "Unknown shift to lower!");
4331 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4332 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4333 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4336 // If we are in thumb mode, we don't have RRX.
4337 if (ST->isThumb1Only()) return SDValue();
4339 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4340 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4341 DAG.getConstant(0, MVT::i32));
4342 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4343 DAG.getConstant(1, MVT::i32));
4345 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4346 // captures the result into a carry flag.
4347 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4348 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4350 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4351 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4353 // Merge the pieces into a single i64 value.
4354 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4357 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4358 SDValue TmpOp0, TmpOp1;
4359 bool Invert = false;
4363 SDValue Op0 = Op.getOperand(0);
4364 SDValue Op1 = Op.getOperand(1);
4365 SDValue CC = Op.getOperand(2);
4366 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4367 EVT VT = Op.getValueType();
4368 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4371 if (Op1.getValueType().isFloatingPoint()) {
4372 switch (SetCCOpcode) {
4373 default: llvm_unreachable("Illegal FP comparison");
4375 case ISD::SETNE: Invert = true; // Fallthrough
4377 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4379 case ISD::SETLT: Swap = true; // Fallthrough
4381 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4383 case ISD::SETLE: Swap = true; // Fallthrough
4385 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4386 case ISD::SETUGE: Swap = true; // Fallthrough
4387 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4388 case ISD::SETUGT: Swap = true; // Fallthrough
4389 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4390 case ISD::SETUEQ: Invert = true; // Fallthrough
4392 // Expand this to (OLT | OGT).
4396 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4397 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4399 case ISD::SETUO: Invert = true; // Fallthrough
4401 // Expand this to (OLT | OGE).
4405 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4406 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4410 // Integer comparisons.
4411 switch (SetCCOpcode) {
4412 default: llvm_unreachable("Illegal integer comparison");
4413 case ISD::SETNE: Invert = true;
4414 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4415 case ISD::SETLT: Swap = true;
4416 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4417 case ISD::SETLE: Swap = true;
4418 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4419 case ISD::SETULT: Swap = true;
4420 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4421 case ISD::SETULE: Swap = true;
4422 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4425 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4426 if (Opc == ARMISD::VCEQ) {
4429 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4431 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4434 // Ignore bitconvert.
4435 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4436 AndOp = AndOp.getOperand(0);
4438 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4440 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4441 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4448 std::swap(Op0, Op1);
4450 // If one of the operands is a constant vector zero, attempt to fold the
4451 // comparison to a specialized compare-against-zero form.
4453 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4455 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4456 if (Opc == ARMISD::VCGE)
4457 Opc = ARMISD::VCLEZ;
4458 else if (Opc == ARMISD::VCGT)
4459 Opc = ARMISD::VCLTZ;
4464 if (SingleOp.getNode()) {
4467 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4469 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4471 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4473 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4475 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4477 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4480 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4483 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4486 Result = DAG.getNOT(dl, Result, VT);
4491 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4492 /// valid vector constant for a NEON instruction with a "modified immediate"
4493 /// operand (e.g., VMOV). If so, return the encoded value.
4494 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4495 unsigned SplatBitSize, SelectionDAG &DAG,
4496 EVT &VT, bool is128Bits, NEONModImmType type) {
4497 unsigned OpCmode, Imm;
4499 // SplatBitSize is set to the smallest size that splats the vector, so a
4500 // zero vector will always have SplatBitSize == 8. However, NEON modified
4501 // immediate instructions others than VMOV do not support the 8-bit encoding
4502 // of a zero vector, and the default encoding of zero is supposed to be the
4507 switch (SplatBitSize) {
4509 if (type != VMOVModImm)
4511 // Any 1-byte value is OK. Op=0, Cmode=1110.
4512 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4515 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4519 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4520 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4521 if ((SplatBits & ~0xff) == 0) {
4522 // Value = 0x00nn: Op=x, Cmode=100x.
4527 if ((SplatBits & ~0xff00) == 0) {
4528 // Value = 0xnn00: Op=x, Cmode=101x.
4530 Imm = SplatBits >> 8;
4536 // NEON's 32-bit VMOV supports splat values where:
4537 // * only one byte is nonzero, or
4538 // * the least significant byte is 0xff and the second byte is nonzero, or
4539 // * the least significant 2 bytes are 0xff and the third is nonzero.
4540 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4541 if ((SplatBits & ~0xff) == 0) {
4542 // Value = 0x000000nn: Op=x, Cmode=000x.
4547 if ((SplatBits & ~0xff00) == 0) {
4548 // Value = 0x0000nn00: Op=x, Cmode=001x.
4550 Imm = SplatBits >> 8;
4553 if ((SplatBits & ~0xff0000) == 0) {
4554 // Value = 0x00nn0000: Op=x, Cmode=010x.
4556 Imm = SplatBits >> 16;
4559 if ((SplatBits & ~0xff000000) == 0) {
4560 // Value = 0xnn000000: Op=x, Cmode=011x.
4562 Imm = SplatBits >> 24;
4566 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4567 if (type == OtherModImm) return SDValue();
4569 if ((SplatBits & ~0xffff) == 0 &&
4570 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4571 // Value = 0x0000nnff: Op=x, Cmode=1100.
4573 Imm = SplatBits >> 8;
4577 if ((SplatBits & ~0xffffff) == 0 &&
4578 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4579 // Value = 0x00nnffff: Op=x, Cmode=1101.
4581 Imm = SplatBits >> 16;
4585 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4586 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4587 // VMOV.I32. A (very) minor optimization would be to replicate the value
4588 // and fall through here to test for a valid 64-bit splat. But, then the
4589 // caller would also need to check and handle the change in size.
4593 if (type != VMOVModImm)
4595 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4596 uint64_t BitMask = 0xff;
4598 unsigned ImmMask = 1;
4600 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4601 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4604 } else if ((SplatBits & BitMask) != 0) {
4611 if (DAG.getTargetLoweringInfo().isBigEndian())
4612 // swap higher and lower 32 bit word
4613 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4615 // Op=1, Cmode=1110.
4617 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4622 llvm_unreachable("unexpected size for isNEONModifiedImm");
4625 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4626 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4629 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4630 const ARMSubtarget *ST) const {
4634 bool IsDouble = Op.getValueType() == MVT::f64;
4635 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4637 // Use the default (constant pool) lowering for double constants when we have
4639 if (IsDouble && Subtarget->isFPOnlySP())
4642 // Try splatting with a VMOV.f32...
4643 APFloat FPVal = CFP->getValueAPF();
4644 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4647 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4648 // We have code in place to select a valid ConstantFP already, no need to
4653 // It's a float and we are trying to use NEON operations where
4654 // possible. Lower it to a splat followed by an extract.
4656 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4657 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4659 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4660 DAG.getConstant(0, MVT::i32));
4663 // The rest of our options are NEON only, make sure that's allowed before
4665 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4669 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4671 // It wouldn't really be worth bothering for doubles except for one very
4672 // important value, which does happen to match: 0.0. So make sure we don't do
4674 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4677 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4678 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4680 if (NewVal != SDValue()) {
4682 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4685 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4687 // It's a float: cast and extract a vector element.
4688 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4690 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4691 DAG.getConstant(0, MVT::i32));
4694 // Finally, try a VMVN.i32
4695 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4697 if (NewVal != SDValue()) {
4699 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4702 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4704 // It's a float: cast and extract a vector element.
4705 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4707 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4708 DAG.getConstant(0, MVT::i32));
4714 // check if an VEXT instruction can handle the shuffle mask when the
4715 // vector sources of the shuffle are the same.
4716 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4717 unsigned NumElts = VT.getVectorNumElements();
4719 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4725 // If this is a VEXT shuffle, the immediate value is the index of the first
4726 // element. The other shuffle indices must be the successive elements after
4728 unsigned ExpectedElt = Imm;
4729 for (unsigned i = 1; i < NumElts; ++i) {
4730 // Increment the expected index. If it wraps around, just follow it
4731 // back to index zero and keep going.
4733 if (ExpectedElt == NumElts)
4736 if (M[i] < 0) continue; // ignore UNDEF indices
4737 if (ExpectedElt != static_cast<unsigned>(M[i]))
4745 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4746 bool &ReverseVEXT, unsigned &Imm) {
4747 unsigned NumElts = VT.getVectorNumElements();
4748 ReverseVEXT = false;
4750 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4756 // If this is a VEXT shuffle, the immediate value is the index of the first
4757 // element. The other shuffle indices must be the successive elements after
4759 unsigned ExpectedElt = Imm;
4760 for (unsigned i = 1; i < NumElts; ++i) {
4761 // Increment the expected index. If it wraps around, it may still be
4762 // a VEXT but the source vectors must be swapped.
4764 if (ExpectedElt == NumElts * 2) {
4769 if (M[i] < 0) continue; // ignore UNDEF indices
4770 if (ExpectedElt != static_cast<unsigned>(M[i]))
4774 // Adjust the index value if the source operands will be swapped.
4781 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4782 /// instruction with the specified blocksize. (The order of the elements
4783 /// within each block of the vector is reversed.)
4784 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4785 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4786 "Only possible block sizes for VREV are: 16, 32, 64");
4788 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4792 unsigned NumElts = VT.getVectorNumElements();
4793 unsigned BlockElts = M[0] + 1;
4794 // If the first shuffle index is UNDEF, be optimistic.
4796 BlockElts = BlockSize / EltSz;
4798 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4801 for (unsigned i = 0; i < NumElts; ++i) {
4802 if (M[i] < 0) continue; // ignore UNDEF indices
4803 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4810 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4811 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4812 // range, then 0 is placed into the resulting vector. So pretty much any mask
4813 // of 8 elements can work here.
4814 return VT == MVT::v8i8 && M.size() == 8;
4817 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4818 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4822 unsigned NumElts = VT.getVectorNumElements();
4823 WhichResult = (M[0] == 0 ? 0 : 1);
4824 for (unsigned i = 0; i < NumElts; i += 2) {
4825 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4826 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4832 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4833 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4834 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4835 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4836 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4840 unsigned NumElts = VT.getVectorNumElements();
4841 WhichResult = (M[0] == 0 ? 0 : 1);
4842 for (unsigned i = 0; i < NumElts; i += 2) {
4843 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4844 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4850 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4851 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4855 unsigned NumElts = VT.getVectorNumElements();
4856 WhichResult = (M[0] == 0 ? 0 : 1);
4857 for (unsigned i = 0; i != NumElts; ++i) {
4858 if (M[i] < 0) continue; // ignore UNDEF indices
4859 if ((unsigned) M[i] != 2 * i + WhichResult)
4863 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4864 if (VT.is64BitVector() && EltSz == 32)
4870 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4871 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4872 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4873 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4874 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4878 unsigned Half = VT.getVectorNumElements() / 2;
4879 WhichResult = (M[0] == 0 ? 0 : 1);
4880 for (unsigned j = 0; j != 2; ++j) {
4881 unsigned Idx = WhichResult;
4882 for (unsigned i = 0; i != Half; ++i) {
4883 int MIdx = M[i + j * Half];
4884 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4890 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4891 if (VT.is64BitVector() && EltSz == 32)
4897 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4898 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4902 unsigned NumElts = VT.getVectorNumElements();
4903 WhichResult = (M[0] == 0 ? 0 : 1);
4904 unsigned Idx = WhichResult * NumElts / 2;
4905 for (unsigned i = 0; i != NumElts; i += 2) {
4906 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4907 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4912 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4913 if (VT.is64BitVector() && EltSz == 32)
4919 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4920 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4921 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4922 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4923 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4927 unsigned NumElts = VT.getVectorNumElements();
4928 WhichResult = (M[0] == 0 ? 0 : 1);
4929 unsigned Idx = WhichResult * NumElts / 2;
4930 for (unsigned i = 0; i != NumElts; i += 2) {
4931 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4932 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4937 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4938 if (VT.is64BitVector() && EltSz == 32)
4944 /// \return true if this is a reverse operation on an vector.
4945 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4946 unsigned NumElts = VT.getVectorNumElements();
4947 // Make sure the mask has the right size.
4948 if (NumElts != M.size())
4951 // Look for <15, ..., 3, -1, 1, 0>.
4952 for (unsigned i = 0; i != NumElts; ++i)
4953 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4959 // If N is an integer constant that can be moved into a register in one
4960 // instruction, return an SDValue of such a constant (will become a MOV
4961 // instruction). Otherwise return null.
4962 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4963 const ARMSubtarget *ST, SDLoc dl) {
4965 if (!isa<ConstantSDNode>(N))
4967 Val = cast<ConstantSDNode>(N)->getZExtValue();
4969 if (ST->isThumb1Only()) {
4970 if (Val <= 255 || ~Val <= 255)
4971 return DAG.getConstant(Val, MVT::i32);
4973 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4974 return DAG.getConstant(Val, MVT::i32);
4979 // If this is a case we can't handle, return null and let the default
4980 // expansion code take care of it.
4981 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4982 const ARMSubtarget *ST) const {
4983 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4985 EVT VT = Op.getValueType();
4987 APInt SplatBits, SplatUndef;
4988 unsigned SplatBitSize;
4990 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4991 if (SplatBitSize <= 64) {
4992 // Check if an immediate VMOV works.
4994 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4995 SplatUndef.getZExtValue(), SplatBitSize,
4996 DAG, VmovVT, VT.is128BitVector(),
4998 if (Val.getNode()) {
4999 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5000 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5003 // Try an immediate VMVN.
5004 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5005 Val = isNEONModifiedImm(NegatedImm,
5006 SplatUndef.getZExtValue(), SplatBitSize,
5007 DAG, VmovVT, VT.is128BitVector(),
5009 if (Val.getNode()) {
5010 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5011 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5014 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5015 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5016 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5018 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5019 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5025 // Scan through the operands to see if only one value is used.
5027 // As an optimisation, even if more than one value is used it may be more
5028 // profitable to splat with one value then change some lanes.
5030 // Heuristically we decide to do this if the vector has a "dominant" value,
5031 // defined as splatted to more than half of the lanes.
5032 unsigned NumElts = VT.getVectorNumElements();
5033 bool isOnlyLowElement = true;
5034 bool usesOnlyOneValue = true;
5035 bool hasDominantValue = false;
5036 bool isConstant = true;
5038 // Map of the number of times a particular SDValue appears in the
5040 DenseMap<SDValue, unsigned> ValueCounts;
5042 for (unsigned i = 0; i < NumElts; ++i) {
5043 SDValue V = Op.getOperand(i);
5044 if (V.getOpcode() == ISD::UNDEF)
5047 isOnlyLowElement = false;
5048 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5051 ValueCounts.insert(std::make_pair(V, 0));
5052 unsigned &Count = ValueCounts[V];
5054 // Is this value dominant? (takes up more than half of the lanes)
5055 if (++Count > (NumElts / 2)) {
5056 hasDominantValue = true;
5060 if (ValueCounts.size() != 1)
5061 usesOnlyOneValue = false;
5062 if (!Value.getNode() && ValueCounts.size() > 0)
5063 Value = ValueCounts.begin()->first;
5065 if (ValueCounts.size() == 0)
5066 return DAG.getUNDEF(VT);
5068 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5069 // Keep going if we are hitting this case.
5070 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5071 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5073 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5075 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5076 // i32 and try again.
5077 if (hasDominantValue && EltSize <= 32) {
5081 // If we are VDUPing a value that comes directly from a vector, that will
5082 // cause an unnecessary move to and from a GPR, where instead we could
5083 // just use VDUPLANE. We can only do this if the lane being extracted
5084 // is at a constant index, as the VDUP from lane instructions only have
5085 // constant-index forms.
5086 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5087 isa<ConstantSDNode>(Value->getOperand(1))) {
5088 // We need to create a new undef vector to use for the VDUPLANE if the
5089 // size of the vector from which we get the value is different than the
5090 // size of the vector that we need to create. We will insert the element
5091 // such that the register coalescer will remove unnecessary copies.
5092 if (VT != Value->getOperand(0).getValueType()) {
5093 ConstantSDNode *constIndex;
5094 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5095 assert(constIndex && "The index is not a constant!");
5096 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5097 VT.getVectorNumElements();
5098 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5099 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5100 Value, DAG.getConstant(index, MVT::i32)),
5101 DAG.getConstant(index, MVT::i32));
5103 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5104 Value->getOperand(0), Value->getOperand(1));
5106 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5108 if (!usesOnlyOneValue) {
5109 // The dominant value was splatted as 'N', but we now have to insert
5110 // all differing elements.
5111 for (unsigned I = 0; I < NumElts; ++I) {
5112 if (Op.getOperand(I) == Value)
5114 SmallVector<SDValue, 3> Ops;
5116 Ops.push_back(Op.getOperand(I));
5117 Ops.push_back(DAG.getConstant(I, MVT::i32));
5118 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5123 if (VT.getVectorElementType().isFloatingPoint()) {
5124 SmallVector<SDValue, 8> Ops;
5125 for (unsigned i = 0; i < NumElts; ++i)
5126 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5128 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5129 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5130 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5132 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5134 if (usesOnlyOneValue) {
5135 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5136 if (isConstant && Val.getNode())
5137 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5141 // If all elements are constants and the case above didn't get hit, fall back
5142 // to the default expansion, which will generate a load from the constant
5147 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5149 SDValue shuffle = ReconstructShuffle(Op, DAG);
5150 if (shuffle != SDValue())
5154 // Vectors with 32- or 64-bit elements can be built by directly assigning
5155 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5156 // will be legalized.
5157 if (EltSize >= 32) {
5158 // Do the expansion with floating-point types, since that is what the VFP
5159 // registers are defined to use, and since i64 is not legal.
5160 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5161 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5162 SmallVector<SDValue, 8> Ops;
5163 for (unsigned i = 0; i < NumElts; ++i)
5164 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5165 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5166 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5169 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5170 // know the default expansion would otherwise fall back on something even
5171 // worse. For a vector with one or two non-undef values, that's
5172 // scalar_to_vector for the elements followed by a shuffle (provided the
5173 // shuffle is valid for the target) and materialization element by element
5174 // on the stack followed by a load for everything else.
5175 if (!isConstant && !usesOnlyOneValue) {
5176 SDValue Vec = DAG.getUNDEF(VT);
5177 for (unsigned i = 0 ; i < NumElts; ++i) {
5178 SDValue V = Op.getOperand(i);
5179 if (V.getOpcode() == ISD::UNDEF)
5181 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5182 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5190 // Gather data to see if the operation can be modelled as a
5191 // shuffle in combination with VEXTs.
5192 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5193 SelectionDAG &DAG) const {
5195 EVT VT = Op.getValueType();
5196 unsigned NumElts = VT.getVectorNumElements();
5198 SmallVector<SDValue, 2> SourceVecs;
5199 SmallVector<unsigned, 2> MinElts;
5200 SmallVector<unsigned, 2> MaxElts;
5202 for (unsigned i = 0; i < NumElts; ++i) {
5203 SDValue V = Op.getOperand(i);
5204 if (V.getOpcode() == ISD::UNDEF)
5206 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5207 // A shuffle can only come from building a vector from various
5208 // elements of other vectors.
5210 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5211 VT.getVectorElementType()) {
5212 // This code doesn't know how to handle shuffles where the vector
5213 // element types do not match (this happens because type legalization
5214 // promotes the return type of EXTRACT_VECTOR_ELT).
5215 // FIXME: It might be appropriate to extend this code to handle
5216 // mismatched types.
5220 // Record this extraction against the appropriate vector if possible...
5221 SDValue SourceVec = V.getOperand(0);
5222 // If the element number isn't a constant, we can't effectively
5223 // analyze what's going on.
5224 if (!isa<ConstantSDNode>(V.getOperand(1)))
5226 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5227 bool FoundSource = false;
5228 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5229 if (SourceVecs[j] == SourceVec) {
5230 if (MinElts[j] > EltNo)
5232 if (MaxElts[j] < EltNo)
5239 // Or record a new source if not...
5241 SourceVecs.push_back(SourceVec);
5242 MinElts.push_back(EltNo);
5243 MaxElts.push_back(EltNo);
5247 // Currently only do something sane when at most two source vectors
5249 if (SourceVecs.size() > 2)
5252 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5253 int VEXTOffsets[2] = {0, 0};
5255 // This loop extracts the usage patterns of the source vectors
5256 // and prepares appropriate SDValues for a shuffle if possible.
5257 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5258 if (SourceVecs[i].getValueType() == VT) {
5259 // No VEXT necessary
5260 ShuffleSrcs[i] = SourceVecs[i];
5263 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5264 // It probably isn't worth padding out a smaller vector just to
5265 // break it down again in a shuffle.
5269 // Since only 64-bit and 128-bit vectors are legal on ARM and
5270 // we've eliminated the other cases...
5271 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5272 "unexpected vector sizes in ReconstructShuffle");
5274 if (MaxElts[i] - MinElts[i] >= NumElts) {
5275 // Span too large for a VEXT to cope
5279 if (MinElts[i] >= NumElts) {
5280 // The extraction can just take the second half
5281 VEXTOffsets[i] = NumElts;
5282 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5284 DAG.getIntPtrConstant(NumElts));
5285 } else if (MaxElts[i] < NumElts) {
5286 // The extraction can just take the first half
5288 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5290 DAG.getIntPtrConstant(0));
5292 // An actual VEXT is needed
5293 VEXTOffsets[i] = MinElts[i];
5294 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5296 DAG.getIntPtrConstant(0));
5297 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5299 DAG.getIntPtrConstant(NumElts));
5300 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5301 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5305 SmallVector<int, 8> Mask;
5307 for (unsigned i = 0; i < NumElts; ++i) {
5308 SDValue Entry = Op.getOperand(i);
5309 if (Entry.getOpcode() == ISD::UNDEF) {
5314 SDValue ExtractVec = Entry.getOperand(0);
5315 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5316 .getOperand(1))->getSExtValue();
5317 if (ExtractVec == SourceVecs[0]) {
5318 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5320 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5324 // Final check before we try to produce nonsense...
5325 if (isShuffleMaskLegal(Mask, VT))
5326 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5332 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5333 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5334 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5335 /// are assumed to be legal.
5337 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5339 if (VT.getVectorNumElements() == 4 &&
5340 (VT.is128BitVector() || VT.is64BitVector())) {
5341 unsigned PFIndexes[4];
5342 for (unsigned i = 0; i != 4; ++i) {
5346 PFIndexes[i] = M[i];
5349 // Compute the index in the perfect shuffle table.
5350 unsigned PFTableIndex =
5351 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5352 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5353 unsigned Cost = (PFEntry >> 30);
5360 unsigned Imm, WhichResult;
5362 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5363 return (EltSize >= 32 ||
5364 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5365 isVREVMask(M, VT, 64) ||
5366 isVREVMask(M, VT, 32) ||
5367 isVREVMask(M, VT, 16) ||
5368 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5369 isVTBLMask(M, VT) ||
5370 isVTRNMask(M, VT, WhichResult) ||
5371 isVUZPMask(M, VT, WhichResult) ||
5372 isVZIPMask(M, VT, WhichResult) ||
5373 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5374 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5375 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5376 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5379 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5380 /// the specified operations to build the shuffle.
5381 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5382 SDValue RHS, SelectionDAG &DAG,
5384 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5385 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5386 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5389 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5398 OP_VUZPL, // VUZP, left result
5399 OP_VUZPR, // VUZP, right result
5400 OP_VZIPL, // VZIP, left result
5401 OP_VZIPR, // VZIP, right result
5402 OP_VTRNL, // VTRN, left result
5403 OP_VTRNR // VTRN, right result
5406 if (OpNum == OP_COPY) {
5407 if (LHSID == (1*9+2)*9+3) return LHS;
5408 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5412 SDValue OpLHS, OpRHS;
5413 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5414 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5415 EVT VT = OpLHS.getValueType();
5418 default: llvm_unreachable("Unknown shuffle opcode!");
5420 // VREV divides the vector in half and swaps within the half.
5421 if (VT.getVectorElementType() == MVT::i32 ||
5422 VT.getVectorElementType() == MVT::f32)
5423 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5424 // vrev <4 x i16> -> VREV32
5425 if (VT.getVectorElementType() == MVT::i16)
5426 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5427 // vrev <4 x i8> -> VREV16
5428 assert(VT.getVectorElementType() == MVT::i8);
5429 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5434 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5435 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5439 return DAG.getNode(ARMISD::VEXT, dl, VT,
5441 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5444 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5445 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5448 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5449 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5452 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5453 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5457 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5458 ArrayRef<int> ShuffleMask,
5459 SelectionDAG &DAG) {
5460 // Check to see if we can use the VTBL instruction.
5461 SDValue V1 = Op.getOperand(0);
5462 SDValue V2 = Op.getOperand(1);
5465 SmallVector<SDValue, 8> VTBLMask;
5466 for (ArrayRef<int>::iterator
5467 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5468 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5470 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5471 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5472 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5474 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5475 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5478 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5479 SelectionDAG &DAG) {
5481 SDValue OpLHS = Op.getOperand(0);
5482 EVT VT = OpLHS.getValueType();
5484 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5485 "Expect an v8i16/v16i8 type");
5486 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5487 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5488 // extract the first 8 bytes into the top double word and the last 8 bytes
5489 // into the bottom double word. The v8i16 case is similar.
5490 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5491 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5492 DAG.getConstant(ExtractNum, MVT::i32));
5495 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5496 SDValue V1 = Op.getOperand(0);
5497 SDValue V2 = Op.getOperand(1);
5499 EVT VT = Op.getValueType();
5500 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5502 // Convert shuffles that are directly supported on NEON to target-specific
5503 // DAG nodes, instead of keeping them as shuffles and matching them again
5504 // during code selection. This is more efficient and avoids the possibility
5505 // of inconsistencies between legalization and selection.
5506 // FIXME: floating-point vectors should be canonicalized to integer vectors
5507 // of the same time so that they get CSEd properly.
5508 ArrayRef<int> ShuffleMask = SVN->getMask();
5510 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5511 if (EltSize <= 32) {
5512 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5513 int Lane = SVN->getSplatIndex();
5514 // If this is undef splat, generate it via "just" vdup, if possible.
5515 if (Lane == -1) Lane = 0;
5517 // Test if V1 is a SCALAR_TO_VECTOR.
5518 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5519 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5521 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5522 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5524 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5525 !isa<ConstantSDNode>(V1.getOperand(0))) {
5526 bool IsScalarToVector = true;
5527 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5528 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5529 IsScalarToVector = false;
5532 if (IsScalarToVector)
5533 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5535 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5536 DAG.getConstant(Lane, MVT::i32));
5541 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5544 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5545 DAG.getConstant(Imm, MVT::i32));
5548 if (isVREVMask(ShuffleMask, VT, 64))
5549 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5550 if (isVREVMask(ShuffleMask, VT, 32))
5551 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5552 if (isVREVMask(ShuffleMask, VT, 16))
5553 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5555 if (V2->getOpcode() == ISD::UNDEF &&
5556 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5557 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5558 DAG.getConstant(Imm, MVT::i32));
5561 // Check for Neon shuffles that modify both input vectors in place.
5562 // If both results are used, i.e., if there are two shuffles with the same
5563 // source operands and with masks corresponding to both results of one of
5564 // these operations, DAG memoization will ensure that a single node is
5565 // used for both shuffles.
5566 unsigned WhichResult;
5567 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5568 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5569 V1, V2).getValue(WhichResult);
5570 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5571 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5572 V1, V2).getValue(WhichResult);
5573 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5574 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5575 V1, V2).getValue(WhichResult);
5577 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5578 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5579 V1, V1).getValue(WhichResult);
5580 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5581 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5582 V1, V1).getValue(WhichResult);
5583 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5584 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5585 V1, V1).getValue(WhichResult);
5588 // If the shuffle is not directly supported and it has 4 elements, use
5589 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5590 unsigned NumElts = VT.getVectorNumElements();
5592 unsigned PFIndexes[4];
5593 for (unsigned i = 0; i != 4; ++i) {
5594 if (ShuffleMask[i] < 0)
5597 PFIndexes[i] = ShuffleMask[i];
5600 // Compute the index in the perfect shuffle table.
5601 unsigned PFTableIndex =
5602 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5603 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5604 unsigned Cost = (PFEntry >> 30);
5607 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5610 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5611 if (EltSize >= 32) {
5612 // Do the expansion with floating-point types, since that is what the VFP
5613 // registers are defined to use, and since i64 is not legal.
5614 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5615 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5616 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5617 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5618 SmallVector<SDValue, 8> Ops;
5619 for (unsigned i = 0; i < NumElts; ++i) {
5620 if (ShuffleMask[i] < 0)
5621 Ops.push_back(DAG.getUNDEF(EltVT));
5623 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5624 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5625 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5628 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5629 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5632 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5633 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5635 if (VT == MVT::v8i8) {
5636 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5637 if (NewOp.getNode())
5644 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5645 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5646 SDValue Lane = Op.getOperand(2);
5647 if (!isa<ConstantSDNode>(Lane))
5653 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5654 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5655 SDValue Lane = Op.getOperand(1);
5656 if (!isa<ConstantSDNode>(Lane))
5659 SDValue Vec = Op.getOperand(0);
5660 if (Op.getValueType() == MVT::i32 &&
5661 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5663 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5669 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5670 // The only time a CONCAT_VECTORS operation can have legal types is when
5671 // two 64-bit vectors are concatenated to a 128-bit vector.
5672 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5673 "unexpected CONCAT_VECTORS");
5675 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5676 SDValue Op0 = Op.getOperand(0);
5677 SDValue Op1 = Op.getOperand(1);
5678 if (Op0.getOpcode() != ISD::UNDEF)
5679 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5680 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5681 DAG.getIntPtrConstant(0));
5682 if (Op1.getOpcode() != ISD::UNDEF)
5683 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5684 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5685 DAG.getIntPtrConstant(1));
5686 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5689 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5690 /// element has been zero/sign-extended, depending on the isSigned parameter,
5691 /// from an integer type half its size.
5692 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5694 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5695 EVT VT = N->getValueType(0);
5696 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5697 SDNode *BVN = N->getOperand(0).getNode();
5698 if (BVN->getValueType(0) != MVT::v4i32 ||
5699 BVN->getOpcode() != ISD::BUILD_VECTOR)
5701 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5702 unsigned HiElt = 1 - LoElt;
5703 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5704 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5705 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5706 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5707 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5710 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5711 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5714 if (Hi0->isNullValue() && Hi1->isNullValue())
5720 if (N->getOpcode() != ISD::BUILD_VECTOR)
5723 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5724 SDNode *Elt = N->getOperand(i).getNode();
5725 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5726 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5727 unsigned HalfSize = EltSize / 2;
5729 if (!isIntN(HalfSize, C->getSExtValue()))
5732 if (!isUIntN(HalfSize, C->getZExtValue()))
5743 /// isSignExtended - Check if a node is a vector value that is sign-extended
5744 /// or a constant BUILD_VECTOR with sign-extended elements.
5745 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5746 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5748 if (isExtendedBUILD_VECTOR(N, DAG, true))
5753 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5754 /// or a constant BUILD_VECTOR with zero-extended elements.
5755 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5756 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5758 if (isExtendedBUILD_VECTOR(N, DAG, false))
5763 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5764 if (OrigVT.getSizeInBits() >= 64)
5767 assert(OrigVT.isSimple() && "Expecting a simple value type");
5769 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5770 switch (OrigSimpleTy) {
5771 default: llvm_unreachable("Unexpected Vector Type");
5780 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5781 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5782 /// We insert the required extension here to get the vector to fill a D register.
5783 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5786 unsigned ExtOpcode) {
5787 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5788 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5789 // 64-bits we need to insert a new extension so that it will be 64-bits.
5790 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5791 if (OrigTy.getSizeInBits() >= 64)
5794 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5795 EVT NewVT = getExtensionTo64Bits(OrigTy);
5797 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5800 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5801 /// does not do any sign/zero extension. If the original vector is less
5802 /// than 64 bits, an appropriate extension will be added after the load to
5803 /// reach a total size of 64 bits. We have to add the extension separately
5804 /// because ARM does not have a sign/zero extending load for vectors.
5805 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5806 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5808 // The load already has the right type.
5809 if (ExtendedTy == LD->getMemoryVT())
5810 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5811 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5812 LD->isNonTemporal(), LD->isInvariant(),
5813 LD->getAlignment());
5815 // We need to create a zextload/sextload. We cannot just create a load
5816 // followed by a zext/zext node because LowerMUL is also run during normal
5817 // operation legalization where we can't create illegal types.
5818 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5819 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5820 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5821 LD->isNonTemporal(), LD->getAlignment());
5824 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5825 /// extending load, or BUILD_VECTOR with extended elements, return the
5826 /// unextended value. The unextended vector should be 64 bits so that it can
5827 /// be used as an operand to a VMULL instruction. If the original vector size
5828 /// before extension is less than 64 bits we add a an extension to resize
5829 /// the vector to 64 bits.
5830 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5831 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5832 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5833 N->getOperand(0)->getValueType(0),
5837 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5838 return SkipLoadExtensionForVMULL(LD, DAG);
5840 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5841 // have been legalized as a BITCAST from v4i32.
5842 if (N->getOpcode() == ISD::BITCAST) {
5843 SDNode *BVN = N->getOperand(0).getNode();
5844 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5845 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5846 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5847 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5848 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5850 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5851 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5852 EVT VT = N->getValueType(0);
5853 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5854 unsigned NumElts = VT.getVectorNumElements();
5855 MVT TruncVT = MVT::getIntegerVT(EltSize);
5856 SmallVector<SDValue, 8> Ops;
5857 for (unsigned i = 0; i != NumElts; ++i) {
5858 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5859 const APInt &CInt = C->getAPIntValue();
5860 // Element types smaller than 32 bits are not legal, so use i32 elements.
5861 // The values are implicitly truncated so sext vs. zext doesn't matter.
5862 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5864 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5865 MVT::getVectorVT(TruncVT, NumElts), Ops);
5868 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5869 unsigned Opcode = N->getOpcode();
5870 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5871 SDNode *N0 = N->getOperand(0).getNode();
5872 SDNode *N1 = N->getOperand(1).getNode();
5873 return N0->hasOneUse() && N1->hasOneUse() &&
5874 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5879 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5880 unsigned Opcode = N->getOpcode();
5881 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5882 SDNode *N0 = N->getOperand(0).getNode();
5883 SDNode *N1 = N->getOperand(1).getNode();
5884 return N0->hasOneUse() && N1->hasOneUse() &&
5885 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5890 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5891 // Multiplications are only custom-lowered for 128-bit vectors so that
5892 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5893 EVT VT = Op.getValueType();
5894 assert(VT.is128BitVector() && VT.isInteger() &&
5895 "unexpected type for custom-lowering ISD::MUL");
5896 SDNode *N0 = Op.getOperand(0).getNode();
5897 SDNode *N1 = Op.getOperand(1).getNode();
5898 unsigned NewOpc = 0;
5900 bool isN0SExt = isSignExtended(N0, DAG);
5901 bool isN1SExt = isSignExtended(N1, DAG);
5902 if (isN0SExt && isN1SExt)
5903 NewOpc = ARMISD::VMULLs;
5905 bool isN0ZExt = isZeroExtended(N0, DAG);
5906 bool isN1ZExt = isZeroExtended(N1, DAG);
5907 if (isN0ZExt && isN1ZExt)
5908 NewOpc = ARMISD::VMULLu;
5909 else if (isN1SExt || isN1ZExt) {
5910 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5911 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5912 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5913 NewOpc = ARMISD::VMULLs;
5915 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5916 NewOpc = ARMISD::VMULLu;
5918 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5920 NewOpc = ARMISD::VMULLu;
5926 if (VT == MVT::v2i64)
5927 // Fall through to expand this. It is not legal.
5930 // Other vector multiplications are legal.
5935 // Legalize to a VMULL instruction.
5938 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5940 Op0 = SkipExtensionForVMULL(N0, DAG);
5941 assert(Op0.getValueType().is64BitVector() &&
5942 Op1.getValueType().is64BitVector() &&
5943 "unexpected types for extended operands to VMULL");
5944 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5947 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5948 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5955 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5956 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5957 EVT Op1VT = Op1.getValueType();
5958 return DAG.getNode(N0->getOpcode(), DL, VT,
5959 DAG.getNode(NewOpc, DL, VT,
5960 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5961 DAG.getNode(NewOpc, DL, VT,
5962 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5966 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5968 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5969 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5970 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5971 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5972 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5973 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5974 // Get reciprocal estimate.
5975 // float4 recip = vrecpeq_f32(yf);
5976 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5977 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5978 // Because char has a smaller range than uchar, we can actually get away
5979 // without any newton steps. This requires that we use a weird bias
5980 // of 0xb000, however (again, this has been exhaustively tested).
5981 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5982 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5983 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5984 Y = DAG.getConstant(0xb000, MVT::i32);
5985 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5986 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5987 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5988 // Convert back to short.
5989 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5990 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5995 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5997 // Convert to float.
5998 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5999 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6000 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6001 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6002 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6003 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6005 // Use reciprocal estimate and one refinement step.
6006 // float4 recip = vrecpeq_f32(yf);
6007 // recip *= vrecpsq_f32(yf, recip);
6008 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6009 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6010 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6011 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6013 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6014 // Because short has a smaller range than ushort, we can actually get away
6015 // with only a single newton step. This requires that we use a weird bias
6016 // of 89, however (again, this has been exhaustively tested).
6017 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6018 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6019 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6020 N1 = DAG.getConstant(0x89, MVT::i32);
6021 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6022 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6023 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6024 // Convert back to integer and return.
6025 // return vmovn_s32(vcvt_s32_f32(result));
6026 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6027 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6031 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6032 EVT VT = Op.getValueType();
6033 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6034 "unexpected type for custom-lowering ISD::SDIV");
6037 SDValue N0 = Op.getOperand(0);
6038 SDValue N1 = Op.getOperand(1);
6041 if (VT == MVT::v8i8) {
6042 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6043 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6045 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6046 DAG.getIntPtrConstant(4));
6047 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6048 DAG.getIntPtrConstant(4));
6049 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6050 DAG.getIntPtrConstant(0));
6051 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6052 DAG.getIntPtrConstant(0));
6054 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6055 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6057 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6058 N0 = LowerCONCAT_VECTORS(N0, DAG);
6060 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6063 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6066 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6067 EVT VT = Op.getValueType();
6068 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6069 "unexpected type for custom-lowering ISD::UDIV");
6072 SDValue N0 = Op.getOperand(0);
6073 SDValue N1 = Op.getOperand(1);
6076 if (VT == MVT::v8i8) {
6077 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6078 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6080 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6081 DAG.getIntPtrConstant(4));
6082 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6083 DAG.getIntPtrConstant(4));
6084 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6085 DAG.getIntPtrConstant(0));
6086 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6087 DAG.getIntPtrConstant(0));
6089 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6090 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6092 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6093 N0 = LowerCONCAT_VECTORS(N0, DAG);
6095 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6096 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6101 // v4i16 sdiv ... Convert to float.
6102 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6103 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6104 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6105 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6106 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6107 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6109 // Use reciprocal estimate and two refinement steps.
6110 // float4 recip = vrecpeq_f32(yf);
6111 // recip *= vrecpsq_f32(yf, recip);
6112 // recip *= vrecpsq_f32(yf, recip);
6113 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6114 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6115 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6116 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6118 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6119 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6120 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6122 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6123 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6124 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6125 // and that it will never cause us to return an answer too large).
6126 // float4 result = as_float4(as_int4(xf*recip) + 2);
6127 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6128 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6129 N1 = DAG.getConstant(2, MVT::i32);
6130 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6131 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6132 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6133 // Convert back to integer and return.
6134 // return vmovn_u32(vcvt_s32_f32(result));
6135 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6136 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6140 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6141 EVT VT = Op.getNode()->getValueType(0);
6142 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6145 bool ExtraOp = false;
6146 switch (Op.getOpcode()) {
6147 default: llvm_unreachable("Invalid code");
6148 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6149 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6150 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6151 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6155 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6157 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6158 Op.getOperand(1), Op.getOperand(2));
6161 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6162 assert(Subtarget->isTargetDarwin());
6164 // For iOS, we want to call an alternative entry point: __sincos_stret,
6165 // return values are passed via sret.
6167 SDValue Arg = Op.getOperand(0);
6168 EVT ArgVT = Arg.getValueType();
6169 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6171 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6172 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6174 // Pair of floats / doubles used to pass the result.
6175 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6177 // Create stack object for sret.
6178 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6179 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6180 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6181 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6187 Entry.Ty = RetTy->getPointerTo();
6188 Entry.isSExt = false;
6189 Entry.isZExt = false;
6190 Entry.isSRet = true;
6191 Args.push_back(Entry);
6195 Entry.isSExt = false;
6196 Entry.isZExt = false;
6197 Args.push_back(Entry);
6199 const char *LibcallName = (ArgVT == MVT::f64)
6200 ? "__sincos_stret" : "__sincosf_stret";
6201 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6203 TargetLowering::CallLoweringInfo CLI(DAG);
6204 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6205 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6207 .setDiscardResult();
6209 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6211 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6212 MachinePointerInfo(), false, false, false, 0);
6214 // Address of cos field.
6215 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6216 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6217 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6218 MachinePointerInfo(), false, false, false, 0);
6220 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6221 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6222 LoadSin.getValue(0), LoadCos.getValue(0));
6225 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6226 // Monotonic load/store is legal for all targets
6227 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6230 // Acquire/Release load/store is not legal for targets without a
6231 // dmb or equivalent available.
6235 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6236 SmallVectorImpl<SDValue> &Results,
6238 const ARMSubtarget *Subtarget) {
6240 SDValue Cycles32, OutChain;
6242 if (Subtarget->hasPerfMon()) {
6243 // Under Power Management extensions, the cycle-count is:
6244 // mrc p15, #0, <Rt>, c9, c13, #0
6245 SDValue Ops[] = { N->getOperand(0), // Chain
6246 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6247 DAG.getConstant(15, MVT::i32),
6248 DAG.getConstant(0, MVT::i32),
6249 DAG.getConstant(9, MVT::i32),
6250 DAG.getConstant(13, MVT::i32),
6251 DAG.getConstant(0, MVT::i32)
6254 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6255 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6256 OutChain = Cycles32.getValue(1);
6258 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6259 // there are older ARM CPUs that have implementation-specific ways of
6260 // obtaining this information (FIXME!).
6261 Cycles32 = DAG.getConstant(0, MVT::i32);
6262 OutChain = DAG.getEntryNode();
6266 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6267 Cycles32, DAG.getConstant(0, MVT::i32));
6268 Results.push_back(Cycles64);
6269 Results.push_back(OutChain);
6272 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6273 switch (Op.getOpcode()) {
6274 default: llvm_unreachable("Don't know how to custom lower this!");
6275 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6276 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6277 case ISD::GlobalAddress:
6278 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6279 default: llvm_unreachable("unknown object format");
6281 return LowerGlobalAddressWindows(Op, DAG);
6283 return LowerGlobalAddressELF(Op, DAG);
6285 return LowerGlobalAddressDarwin(Op, DAG);
6287 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6288 case ISD::SELECT: return LowerSELECT(Op, DAG);
6289 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6290 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6291 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6292 case ISD::VASTART: return LowerVASTART(Op, DAG);
6293 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6294 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6295 case ISD::SINT_TO_FP:
6296 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6297 case ISD::FP_TO_SINT:
6298 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6299 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6300 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6301 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6302 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6303 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6304 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6305 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6307 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6310 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6311 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6312 case ISD::SRL_PARTS:
6313 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6314 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6315 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6316 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6317 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6318 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6319 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6320 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6321 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6322 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6323 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6324 case ISD::MUL: return LowerMUL(Op, DAG);
6325 case ISD::SDIV: return LowerSDIV(Op, DAG);
6326 case ISD::UDIV: return LowerUDIV(Op, DAG);
6330 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6335 return LowerXALUO(Op, DAG);
6336 case ISD::ATOMIC_LOAD:
6337 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6338 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6340 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6341 case ISD::DYNAMIC_STACKALLOC:
6342 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6343 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6344 llvm_unreachable("Don't know how to custom lower this!");
6345 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6346 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6350 /// ReplaceNodeResults - Replace the results of node with an illegal result
6351 /// type with new values built out of custom code.
6352 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6353 SmallVectorImpl<SDValue>&Results,
6354 SelectionDAG &DAG) const {
6356 switch (N->getOpcode()) {
6358 llvm_unreachable("Don't know how to custom expand this!");
6360 Res = ExpandBITCAST(N, DAG);
6364 Res = Expand64BitShift(N, DAG, Subtarget);
6366 case ISD::READCYCLECOUNTER:
6367 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6371 Results.push_back(Res);
6374 //===----------------------------------------------------------------------===//
6375 // ARM Scheduler Hooks
6376 //===----------------------------------------------------------------------===//
6378 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6379 /// registers the function context.
6380 void ARMTargetLowering::
6381 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6382 MachineBasicBlock *DispatchBB, int FI) const {
6383 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6384 DebugLoc dl = MI->getDebugLoc();
6385 MachineFunction *MF = MBB->getParent();
6386 MachineRegisterInfo *MRI = &MF->getRegInfo();
6387 MachineConstantPool *MCP = MF->getConstantPool();
6388 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6389 const Function *F = MF->getFunction();
6391 bool isThumb = Subtarget->isThumb();
6392 bool isThumb2 = Subtarget->isThumb2();
6394 unsigned PCLabelId = AFI->createPICLabelUId();
6395 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6396 ARMConstantPoolValue *CPV =
6397 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6398 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6400 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6401 : &ARM::GPRRegClass;
6403 // Grab constant pool and fixed stack memory operands.
6404 MachineMemOperand *CPMMO =
6405 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6406 MachineMemOperand::MOLoad, 4, 4);
6408 MachineMemOperand *FIMMOSt =
6409 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6410 MachineMemOperand::MOStore, 4, 4);
6412 // Load the address of the dispatch MBB into the jump buffer.
6414 // Incoming value: jbuf
6415 // ldr.n r5, LCPI1_1
6418 // str r5, [$jbuf, #+4] ; &jbuf[1]
6419 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6420 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6421 .addConstantPoolIndex(CPI)
6422 .addMemOperand(CPMMO));
6423 // Set the low bit because of thumb mode.
6424 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6426 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6427 .addReg(NewVReg1, RegState::Kill)
6429 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6430 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6431 .addReg(NewVReg2, RegState::Kill)
6433 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6434 .addReg(NewVReg3, RegState::Kill)
6436 .addImm(36) // &jbuf[1] :: pc
6437 .addMemOperand(FIMMOSt));
6438 } else if (isThumb) {
6439 // Incoming value: jbuf
6440 // ldr.n r1, LCPI1_4
6444 // add r2, $jbuf, #+4 ; &jbuf[1]
6446 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6447 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6448 .addConstantPoolIndex(CPI)
6449 .addMemOperand(CPMMO));
6450 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6451 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6452 .addReg(NewVReg1, RegState::Kill)
6454 // Set the low bit because of thumb mode.
6455 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6456 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6457 .addReg(ARM::CPSR, RegState::Define)
6459 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6460 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6461 .addReg(ARM::CPSR, RegState::Define)
6462 .addReg(NewVReg2, RegState::Kill)
6463 .addReg(NewVReg3, RegState::Kill));
6464 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6465 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6467 .addImm(36); // &jbuf[1] :: pc
6468 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6469 .addReg(NewVReg4, RegState::Kill)
6470 .addReg(NewVReg5, RegState::Kill)
6472 .addMemOperand(FIMMOSt));
6474 // Incoming value: jbuf
6477 // str r1, [$jbuf, #+4] ; &jbuf[1]
6478 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6479 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6480 .addConstantPoolIndex(CPI)
6482 .addMemOperand(CPMMO));
6483 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6484 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6485 .addReg(NewVReg1, RegState::Kill)
6486 .addImm(PCLabelId));
6487 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6488 .addReg(NewVReg2, RegState::Kill)
6490 .addImm(36) // &jbuf[1] :: pc
6491 .addMemOperand(FIMMOSt));
6495 MachineBasicBlock *ARMTargetLowering::
6496 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6497 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6498 DebugLoc dl = MI->getDebugLoc();
6499 MachineFunction *MF = MBB->getParent();
6500 MachineRegisterInfo *MRI = &MF->getRegInfo();
6501 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6502 MachineFrameInfo *MFI = MF->getFrameInfo();
6503 int FI = MFI->getFunctionContextIndex();
6505 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6506 : &ARM::GPRnopcRegClass;
6508 // Get a mapping of the call site numbers to all of the landing pads they're
6510 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6511 unsigned MaxCSNum = 0;
6512 MachineModuleInfo &MMI = MF->getMMI();
6513 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6515 if (!BB->isLandingPad()) continue;
6517 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6519 for (MachineBasicBlock::iterator
6520 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6521 if (!II->isEHLabel()) continue;
6523 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6524 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6526 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6527 for (SmallVectorImpl<unsigned>::iterator
6528 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6529 CSI != CSE; ++CSI) {
6530 CallSiteNumToLPad[*CSI].push_back(BB);
6531 MaxCSNum = std::max(MaxCSNum, *CSI);
6537 // Get an ordered list of the machine basic blocks for the jump table.
6538 std::vector<MachineBasicBlock*> LPadList;
6539 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6540 LPadList.reserve(CallSiteNumToLPad.size());
6541 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6542 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6543 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6544 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6545 LPadList.push_back(*II);
6546 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6550 assert(!LPadList.empty() &&
6551 "No landing pad destinations for the dispatch jump table!");
6553 // Create the jump table and associated information.
6554 MachineJumpTableInfo *JTI =
6555 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6556 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6557 unsigned UId = AFI->createJumpTableUId();
6558 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6560 // Create the MBBs for the dispatch code.
6562 // Shove the dispatch's address into the return slot in the function context.
6563 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6564 DispatchBB->setIsLandingPad();
6566 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6567 unsigned trap_opcode;
6568 if (Subtarget->isThumb())
6569 trap_opcode = ARM::tTRAP;
6571 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6573 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6574 DispatchBB->addSuccessor(TrapBB);
6576 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6577 DispatchBB->addSuccessor(DispContBB);
6580 MF->insert(MF->end(), DispatchBB);
6581 MF->insert(MF->end(), DispContBB);
6582 MF->insert(MF->end(), TrapBB);
6584 // Insert code into the entry block that creates and registers the function
6586 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6588 MachineMemOperand *FIMMOLd =
6589 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6590 MachineMemOperand::MOLoad |
6591 MachineMemOperand::MOVolatile, 4, 4);
6593 MachineInstrBuilder MIB;
6594 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6596 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6597 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6599 // Add a register mask with no preserved registers. This results in all
6600 // registers being marked as clobbered.
6601 MIB.addRegMask(RI.getNoPreservedMask());
6603 unsigned NumLPads = LPadList.size();
6604 if (Subtarget->isThumb2()) {
6605 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6606 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6609 .addMemOperand(FIMMOLd));
6611 if (NumLPads < 256) {
6612 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6614 .addImm(LPadList.size()));
6616 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6617 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6618 .addImm(NumLPads & 0xFFFF));
6620 unsigned VReg2 = VReg1;
6621 if ((NumLPads & 0xFFFF0000) != 0) {
6622 VReg2 = MRI->createVirtualRegister(TRC);
6623 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6625 .addImm(NumLPads >> 16));
6628 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6633 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6638 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6639 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6640 .addJumpTableIndex(MJTI)
6643 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6646 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6647 .addReg(NewVReg3, RegState::Kill)
6649 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6651 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6652 .addReg(NewVReg4, RegState::Kill)
6654 .addJumpTableIndex(MJTI)
6656 } else if (Subtarget->isThumb()) {
6657 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6658 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6661 .addMemOperand(FIMMOLd));
6663 if (NumLPads < 256) {
6664 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6668 MachineConstantPool *ConstantPool = MF->getConstantPool();
6669 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6670 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6672 // MachineConstantPool wants an explicit alignment.
6673 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6675 Align = getDataLayout()->getTypeAllocSize(C->getType());
6676 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6678 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6679 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6680 .addReg(VReg1, RegState::Define)
6681 .addConstantPoolIndex(Idx));
6682 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6687 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6692 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6693 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6694 .addReg(ARM::CPSR, RegState::Define)
6698 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6699 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6700 .addJumpTableIndex(MJTI)
6703 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6704 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6705 .addReg(ARM::CPSR, RegState::Define)
6706 .addReg(NewVReg2, RegState::Kill)
6709 MachineMemOperand *JTMMOLd =
6710 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6711 MachineMemOperand::MOLoad, 4, 4);
6713 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6714 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6715 .addReg(NewVReg4, RegState::Kill)
6717 .addMemOperand(JTMMOLd));
6719 unsigned NewVReg6 = NewVReg5;
6720 if (RelocM == Reloc::PIC_) {
6721 NewVReg6 = MRI->createVirtualRegister(TRC);
6722 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6723 .addReg(ARM::CPSR, RegState::Define)
6724 .addReg(NewVReg5, RegState::Kill)
6728 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6729 .addReg(NewVReg6, RegState::Kill)
6730 .addJumpTableIndex(MJTI)
6733 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6734 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6737 .addMemOperand(FIMMOLd));
6739 if (NumLPads < 256) {
6740 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6743 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6744 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6745 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6746 .addImm(NumLPads & 0xFFFF));
6748 unsigned VReg2 = VReg1;
6749 if ((NumLPads & 0xFFFF0000) != 0) {
6750 VReg2 = MRI->createVirtualRegister(TRC);
6751 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6753 .addImm(NumLPads >> 16));
6756 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6760 MachineConstantPool *ConstantPool = MF->getConstantPool();
6761 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6762 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6764 // MachineConstantPool wants an explicit alignment.
6765 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6767 Align = getDataLayout()->getTypeAllocSize(C->getType());
6768 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6770 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6771 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6772 .addReg(VReg1, RegState::Define)
6773 .addConstantPoolIndex(Idx)
6775 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6777 .addReg(VReg1, RegState::Kill));
6780 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6785 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6787 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6789 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6790 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6791 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6792 .addJumpTableIndex(MJTI)
6795 MachineMemOperand *JTMMOLd =
6796 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6797 MachineMemOperand::MOLoad, 4, 4);
6798 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6800 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6801 .addReg(NewVReg3, RegState::Kill)
6804 .addMemOperand(JTMMOLd));
6806 if (RelocM == Reloc::PIC_) {
6807 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6808 .addReg(NewVReg5, RegState::Kill)
6810 .addJumpTableIndex(MJTI)
6813 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6814 .addReg(NewVReg5, RegState::Kill)
6815 .addJumpTableIndex(MJTI)
6820 // Add the jump table entries as successors to the MBB.
6821 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6822 for (std::vector<MachineBasicBlock*>::iterator
6823 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6824 MachineBasicBlock *CurMBB = *I;
6825 if (SeenMBBs.insert(CurMBB).second)
6826 DispContBB->addSuccessor(CurMBB);
6829 // N.B. the order the invoke BBs are processed in doesn't matter here.
6830 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6831 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6832 for (MachineBasicBlock *BB : InvokeBBs) {
6834 // Remove the landing pad successor from the invoke block and replace it
6835 // with the new dispatch block.
6836 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6838 while (!Successors.empty()) {
6839 MachineBasicBlock *SMBB = Successors.pop_back_val();
6840 if (SMBB->isLandingPad()) {
6841 BB->removeSuccessor(SMBB);
6842 MBBLPads.push_back(SMBB);
6846 BB->addSuccessor(DispatchBB);
6848 // Find the invoke call and mark all of the callee-saved registers as
6849 // 'implicit defined' so that they're spilled. This prevents code from
6850 // moving instructions to before the EH block, where they will never be
6852 for (MachineBasicBlock::reverse_iterator
6853 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6854 if (!II->isCall()) continue;
6856 DenseMap<unsigned, bool> DefRegs;
6857 for (MachineInstr::mop_iterator
6858 OI = II->operands_begin(), OE = II->operands_end();
6860 if (!OI->isReg()) continue;
6861 DefRegs[OI->getReg()] = true;
6864 MachineInstrBuilder MIB(*MF, &*II);
6866 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6867 unsigned Reg = SavedRegs[i];
6868 if (Subtarget->isThumb2() &&
6869 !ARM::tGPRRegClass.contains(Reg) &&
6870 !ARM::hGPRRegClass.contains(Reg))
6872 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6874 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6877 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6884 // Mark all former landing pads as non-landing pads. The dispatch is the only
6886 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6887 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6888 (*I)->setIsLandingPad(false);
6890 // The instruction is gone now.
6891 MI->eraseFromParent();
6897 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6898 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6899 E = MBB->succ_end(); I != E; ++I)
6902 llvm_unreachable("Expecting a BB with two successors!");
6905 /// Return the load opcode for a given load size. If load size >= 8,
6906 /// neon opcode will be returned.
6907 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6909 return LdSize == 16 ? ARM::VLD1q32wb_fixed
6910 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6912 return LdSize == 4 ? ARM::tLDRi
6913 : LdSize == 2 ? ARM::tLDRHi
6914 : LdSize == 1 ? ARM::tLDRBi : 0;
6916 return LdSize == 4 ? ARM::t2LDR_POST
6917 : LdSize == 2 ? ARM::t2LDRH_POST
6918 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6919 return LdSize == 4 ? ARM::LDR_POST_IMM
6920 : LdSize == 2 ? ARM::LDRH_POST
6921 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6924 /// Return the store opcode for a given store size. If store size >= 8,
6925 /// neon opcode will be returned.
6926 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6928 return StSize == 16 ? ARM::VST1q32wb_fixed
6929 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6931 return StSize == 4 ? ARM::tSTRi
6932 : StSize == 2 ? ARM::tSTRHi
6933 : StSize == 1 ? ARM::tSTRBi : 0;
6935 return StSize == 4 ? ARM::t2STR_POST
6936 : StSize == 2 ? ARM::t2STRH_POST
6937 : StSize == 1 ? ARM::t2STRB_POST : 0;
6938 return StSize == 4 ? ARM::STR_POST_IMM
6939 : StSize == 2 ? ARM::STRH_POST
6940 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6943 /// Emit a post-increment load operation with given size. The instructions
6944 /// will be added to BB at Pos.
6945 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6946 const TargetInstrInfo *TII, DebugLoc dl,
6947 unsigned LdSize, unsigned Data, unsigned AddrIn,
6948 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6949 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6950 assert(LdOpc != 0 && "Should have a load opcode");
6952 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6953 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6955 } else if (IsThumb1) {
6956 // load + update AddrIn
6957 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6958 .addReg(AddrIn).addImm(0));
6959 MachineInstrBuilder MIB =
6960 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6961 MIB = AddDefaultT1CC(MIB);
6962 MIB.addReg(AddrIn).addImm(LdSize);
6963 AddDefaultPred(MIB);
6964 } else if (IsThumb2) {
6965 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6966 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6969 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6970 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6971 .addReg(0).addImm(LdSize));
6975 /// Emit a post-increment store operation with given size. The instructions
6976 /// will be added to BB at Pos.
6977 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6978 const TargetInstrInfo *TII, DebugLoc dl,
6979 unsigned StSize, unsigned Data, unsigned AddrIn,
6980 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6981 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6982 assert(StOpc != 0 && "Should have a store opcode");
6984 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6985 .addReg(AddrIn).addImm(0).addReg(Data));
6986 } else if (IsThumb1) {
6987 // store + update AddrIn
6988 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6989 .addReg(AddrIn).addImm(0));
6990 MachineInstrBuilder MIB =
6991 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6992 MIB = AddDefaultT1CC(MIB);
6993 MIB.addReg(AddrIn).addImm(StSize);
6994 AddDefaultPred(MIB);
6995 } else if (IsThumb2) {
6996 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6997 .addReg(Data).addReg(AddrIn).addImm(StSize));
6999 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7000 .addReg(Data).addReg(AddrIn).addReg(0)
7006 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7007 MachineBasicBlock *BB) const {
7008 // This pseudo instruction has 3 operands: dst, src, size
7009 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7010 // Otherwise, we will generate unrolled scalar copies.
7011 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7012 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7013 MachineFunction::iterator It = BB;
7016 unsigned dest = MI->getOperand(0).getReg();
7017 unsigned src = MI->getOperand(1).getReg();
7018 unsigned SizeVal = MI->getOperand(2).getImm();
7019 unsigned Align = MI->getOperand(3).getImm();
7020 DebugLoc dl = MI->getDebugLoc();
7022 MachineFunction *MF = BB->getParent();
7023 MachineRegisterInfo &MRI = MF->getRegInfo();
7024 unsigned UnitSize = 0;
7025 const TargetRegisterClass *TRC = nullptr;
7026 const TargetRegisterClass *VecTRC = nullptr;
7028 bool IsThumb1 = Subtarget->isThumb1Only();
7029 bool IsThumb2 = Subtarget->isThumb2();
7033 } else if (Align & 2) {
7036 // Check whether we can use NEON instructions.
7037 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7038 Subtarget->hasNEON()) {
7039 if ((Align % 16 == 0) && SizeVal >= 16)
7041 else if ((Align % 8 == 0) && SizeVal >= 8)
7044 // Can't use NEON instructions.
7049 // Select the correct opcode and register class for unit size load/store
7050 bool IsNeon = UnitSize >= 8;
7051 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7053 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7054 : UnitSize == 8 ? &ARM::DPRRegClass
7057 unsigned BytesLeft = SizeVal % UnitSize;
7058 unsigned LoopSize = SizeVal - BytesLeft;
7060 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7061 // Use LDR and STR to copy.
7062 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7063 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7064 unsigned srcIn = src;
7065 unsigned destIn = dest;
7066 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7067 unsigned srcOut = MRI.createVirtualRegister(TRC);
7068 unsigned destOut = MRI.createVirtualRegister(TRC);
7069 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7070 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7071 IsThumb1, IsThumb2);
7072 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7073 IsThumb1, IsThumb2);
7078 // Handle the leftover bytes with LDRB and STRB.
7079 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7080 // [destOut] = STRB_POST(scratch, destIn, 1)
7081 for (unsigned i = 0; i < BytesLeft; i++) {
7082 unsigned srcOut = MRI.createVirtualRegister(TRC);
7083 unsigned destOut = MRI.createVirtualRegister(TRC);
7084 unsigned scratch = MRI.createVirtualRegister(TRC);
7085 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7086 IsThumb1, IsThumb2);
7087 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7088 IsThumb1, IsThumb2);
7092 MI->eraseFromParent(); // The instruction is gone now.
7096 // Expand the pseudo op to a loop.
7099 // movw varEnd, # --> with thumb2
7101 // ldrcp varEnd, idx --> without thumb2
7102 // fallthrough --> loopMBB
7104 // PHI varPhi, varEnd, varLoop
7105 // PHI srcPhi, src, srcLoop
7106 // PHI destPhi, dst, destLoop
7107 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7108 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7109 // subs varLoop, varPhi, #UnitSize
7111 // fallthrough --> exitMBB
7113 // epilogue to handle left-over bytes
7114 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7115 // [destOut] = STRB_POST(scratch, destLoop, 1)
7116 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7117 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7118 MF->insert(It, loopMBB);
7119 MF->insert(It, exitMBB);
7121 // Transfer the remainder of BB and its successor edges to exitMBB.
7122 exitMBB->splice(exitMBB->begin(), BB,
7123 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7124 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7126 // Load an immediate to varEnd.
7127 unsigned varEnd = MRI.createVirtualRegister(TRC);
7129 unsigned Vtmp = varEnd;
7130 if ((LoopSize & 0xFFFF0000) != 0)
7131 Vtmp = MRI.createVirtualRegister(TRC);
7132 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7133 .addImm(LoopSize & 0xFFFF));
7135 if ((LoopSize & 0xFFFF0000) != 0)
7136 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7137 .addReg(Vtmp).addImm(LoopSize >> 16));
7139 MachineConstantPool *ConstantPool = MF->getConstantPool();
7140 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7141 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7143 // MachineConstantPool wants an explicit alignment.
7144 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7146 Align = getDataLayout()->getTypeAllocSize(C->getType());
7147 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7150 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7151 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7153 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7154 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7156 BB->addSuccessor(loopMBB);
7158 // Generate the loop body:
7159 // varPhi = PHI(varLoop, varEnd)
7160 // srcPhi = PHI(srcLoop, src)
7161 // destPhi = PHI(destLoop, dst)
7162 MachineBasicBlock *entryBB = BB;
7164 unsigned varLoop = MRI.createVirtualRegister(TRC);
7165 unsigned varPhi = MRI.createVirtualRegister(TRC);
7166 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7167 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7168 unsigned destLoop = MRI.createVirtualRegister(TRC);
7169 unsigned destPhi = MRI.createVirtualRegister(TRC);
7171 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7172 .addReg(varLoop).addMBB(loopMBB)
7173 .addReg(varEnd).addMBB(entryBB);
7174 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7175 .addReg(srcLoop).addMBB(loopMBB)
7176 .addReg(src).addMBB(entryBB);
7177 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7178 .addReg(destLoop).addMBB(loopMBB)
7179 .addReg(dest).addMBB(entryBB);
7181 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7182 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7183 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7184 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7185 IsThumb1, IsThumb2);
7186 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7187 IsThumb1, IsThumb2);
7189 // Decrement loop variable by UnitSize.
7191 MachineInstrBuilder MIB =
7192 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7193 MIB = AddDefaultT1CC(MIB);
7194 MIB.addReg(varPhi).addImm(UnitSize);
7195 AddDefaultPred(MIB);
7197 MachineInstrBuilder MIB =
7198 BuildMI(*BB, BB->end(), dl,
7199 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7200 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7201 MIB->getOperand(5).setReg(ARM::CPSR);
7202 MIB->getOperand(5).setIsDef(true);
7204 BuildMI(*BB, BB->end(), dl,
7205 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7206 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7208 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7209 BB->addSuccessor(loopMBB);
7210 BB->addSuccessor(exitMBB);
7212 // Add epilogue to handle BytesLeft.
7214 MachineInstr *StartOfExit = exitMBB->begin();
7216 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7217 // [destOut] = STRB_POST(scratch, destLoop, 1)
7218 unsigned srcIn = srcLoop;
7219 unsigned destIn = destLoop;
7220 for (unsigned i = 0; i < BytesLeft; i++) {
7221 unsigned srcOut = MRI.createVirtualRegister(TRC);
7222 unsigned destOut = MRI.createVirtualRegister(TRC);
7223 unsigned scratch = MRI.createVirtualRegister(TRC);
7224 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7225 IsThumb1, IsThumb2);
7226 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7227 IsThumb1, IsThumb2);
7232 MI->eraseFromParent(); // The instruction is gone now.
7237 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7238 MachineBasicBlock *MBB) const {
7239 const TargetMachine &TM = getTargetMachine();
7240 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7241 DebugLoc DL = MI->getDebugLoc();
7243 assert(Subtarget->isTargetWindows() &&
7244 "__chkstk is only supported on Windows");
7245 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7247 // __chkstk takes the number of words to allocate on the stack in R4, and
7248 // returns the stack adjustment in number of bytes in R4. This will not
7249 // clober any other registers (other than the obvious lr).
7251 // Although, technically, IP should be considered a register which may be
7252 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7253 // thumb-2 environment, so there is no interworking required. As a result, we
7254 // do not expect a veneer to be emitted by the linker, clobbering IP.
7256 // Each module receives its own copy of __chkstk, so no import thunk is
7257 // required, again, ensuring that IP is not clobbered.
7259 // Finally, although some linkers may theoretically provide a trampoline for
7260 // out of range calls (which is quite common due to a 32M range limitation of
7261 // branches for Thumb), we can generate the long-call version via
7262 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7265 switch (TM.getCodeModel()) {
7266 case CodeModel::Small:
7267 case CodeModel::Medium:
7268 case CodeModel::Default:
7269 case CodeModel::Kernel:
7270 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7271 .addImm((unsigned)ARMCC::AL).addReg(0)
7272 .addExternalSymbol("__chkstk")
7273 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7274 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7275 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7277 case CodeModel::Large:
7278 case CodeModel::JITDefault: {
7279 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7280 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7282 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7283 .addExternalSymbol("__chkstk");
7284 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7285 .addImm((unsigned)ARMCC::AL).addReg(0)
7286 .addReg(Reg, RegState::Kill)
7287 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7288 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7289 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7294 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7296 .addReg(ARM::SP).addReg(ARM::R4)));
7298 MI->eraseFromParent();
7303 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7304 MachineBasicBlock *BB) const {
7305 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7306 DebugLoc dl = MI->getDebugLoc();
7307 bool isThumb2 = Subtarget->isThumb2();
7308 switch (MI->getOpcode()) {
7311 llvm_unreachable("Unexpected instr type to insert");
7313 // The Thumb2 pre-indexed stores have the same MI operands, they just
7314 // define them differently in the .td files from the isel patterns, so
7315 // they need pseudos.
7316 case ARM::t2STR_preidx:
7317 MI->setDesc(TII->get(ARM::t2STR_PRE));
7319 case ARM::t2STRB_preidx:
7320 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7322 case ARM::t2STRH_preidx:
7323 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7326 case ARM::STRi_preidx:
7327 case ARM::STRBi_preidx: {
7328 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7329 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7330 // Decode the offset.
7331 unsigned Offset = MI->getOperand(4).getImm();
7332 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7333 Offset = ARM_AM::getAM2Offset(Offset);
7337 MachineMemOperand *MMO = *MI->memoperands_begin();
7338 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7339 .addOperand(MI->getOperand(0)) // Rn_wb
7340 .addOperand(MI->getOperand(1)) // Rt
7341 .addOperand(MI->getOperand(2)) // Rn
7342 .addImm(Offset) // offset (skip GPR==zero_reg)
7343 .addOperand(MI->getOperand(5)) // pred
7344 .addOperand(MI->getOperand(6))
7345 .addMemOperand(MMO);
7346 MI->eraseFromParent();
7349 case ARM::STRr_preidx:
7350 case ARM::STRBr_preidx:
7351 case ARM::STRH_preidx: {
7353 switch (MI->getOpcode()) {
7354 default: llvm_unreachable("unexpected opcode!");
7355 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7356 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7357 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7359 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7360 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7361 MIB.addOperand(MI->getOperand(i));
7362 MI->eraseFromParent();
7366 case ARM::tMOVCCr_pseudo: {
7367 // To "insert" a SELECT_CC instruction, we actually have to insert the
7368 // diamond control-flow pattern. The incoming instruction knows the
7369 // destination vreg to set, the condition code register to branch on, the
7370 // true/false values to select between, and a branch opcode to use.
7371 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7372 MachineFunction::iterator It = BB;
7378 // cmpTY ccX, r1, r2
7380 // fallthrough --> copy0MBB
7381 MachineBasicBlock *thisMBB = BB;
7382 MachineFunction *F = BB->getParent();
7383 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7384 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7385 F->insert(It, copy0MBB);
7386 F->insert(It, sinkMBB);
7388 // Transfer the remainder of BB and its successor edges to sinkMBB.
7389 sinkMBB->splice(sinkMBB->begin(), BB,
7390 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7391 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7393 BB->addSuccessor(copy0MBB);
7394 BB->addSuccessor(sinkMBB);
7396 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7397 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7400 // %FalseValue = ...
7401 // # fallthrough to sinkMBB
7404 // Update machine-CFG edges
7405 BB->addSuccessor(sinkMBB);
7408 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7411 BuildMI(*BB, BB->begin(), dl,
7412 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7413 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7414 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7416 MI->eraseFromParent(); // The pseudo instruction is gone now.
7421 case ARM::BCCZi64: {
7422 // If there is an unconditional branch to the other successor, remove it.
7423 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7425 // Compare both parts that make up the double comparison separately for
7427 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7429 unsigned LHS1 = MI->getOperand(1).getReg();
7430 unsigned LHS2 = MI->getOperand(2).getReg();
7432 AddDefaultPred(BuildMI(BB, dl,
7433 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7434 .addReg(LHS1).addImm(0));
7435 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7436 .addReg(LHS2).addImm(0)
7437 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7439 unsigned RHS1 = MI->getOperand(3).getReg();
7440 unsigned RHS2 = MI->getOperand(4).getReg();
7441 AddDefaultPred(BuildMI(BB, dl,
7442 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7443 .addReg(LHS1).addReg(RHS1));
7444 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7445 .addReg(LHS2).addReg(RHS2)
7446 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7449 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7450 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7451 if (MI->getOperand(0).getImm() == ARMCC::NE)
7452 std::swap(destMBB, exitMBB);
7454 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7455 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7457 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7459 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7461 MI->eraseFromParent(); // The pseudo instruction is gone now.
7465 case ARM::Int_eh_sjlj_setjmp:
7466 case ARM::Int_eh_sjlj_setjmp_nofp:
7467 case ARM::tInt_eh_sjlj_setjmp:
7468 case ARM::t2Int_eh_sjlj_setjmp:
7469 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7470 EmitSjLjDispatchBlock(MI, BB);
7475 // To insert an ABS instruction, we have to insert the
7476 // diamond control-flow pattern. The incoming instruction knows the
7477 // source vreg to test against 0, the destination vreg to set,
7478 // the condition code register to branch on, the
7479 // true/false values to select between, and a branch opcode to use.
7484 // BCC (branch to SinkBB if V0 >= 0)
7485 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7486 // SinkBB: V1 = PHI(V2, V3)
7487 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7488 MachineFunction::iterator BBI = BB;
7490 MachineFunction *Fn = BB->getParent();
7491 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7492 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7493 Fn->insert(BBI, RSBBB);
7494 Fn->insert(BBI, SinkBB);
7496 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7497 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7498 bool isThumb2 = Subtarget->isThumb2();
7499 MachineRegisterInfo &MRI = Fn->getRegInfo();
7500 // In Thumb mode S must not be specified if source register is the SP or
7501 // PC and if destination register is the SP, so restrict register class
7502 unsigned NewRsbDstReg =
7503 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7505 // Transfer the remainder of BB and its successor edges to sinkMBB.
7506 SinkBB->splice(SinkBB->begin(), BB,
7507 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7508 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7510 BB->addSuccessor(RSBBB);
7511 BB->addSuccessor(SinkBB);
7513 // fall through to SinkMBB
7514 RSBBB->addSuccessor(SinkBB);
7516 // insert a cmp at the end of BB
7517 AddDefaultPred(BuildMI(BB, dl,
7518 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7519 .addReg(ABSSrcReg).addImm(0));
7521 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7523 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7524 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7526 // insert rsbri in RSBBB
7527 // Note: BCC and rsbri will be converted into predicated rsbmi
7528 // by if-conversion pass
7529 BuildMI(*RSBBB, RSBBB->begin(), dl,
7530 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7531 .addReg(ABSSrcReg, RegState::Kill)
7532 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7534 // insert PHI in SinkBB,
7535 // reuse ABSDstReg to not change uses of ABS instruction
7536 BuildMI(*SinkBB, SinkBB->begin(), dl,
7537 TII->get(ARM::PHI), ABSDstReg)
7538 .addReg(NewRsbDstReg).addMBB(RSBBB)
7539 .addReg(ABSSrcReg).addMBB(BB);
7541 // remove ABS instruction
7542 MI->eraseFromParent();
7544 // return last added BB
7547 case ARM::COPY_STRUCT_BYVAL_I32:
7549 return EmitStructByval(MI, BB);
7550 case ARM::WIN__CHKSTK:
7551 return EmitLowered__chkstk(MI, BB);
7555 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7556 SDNode *Node) const {
7557 const MCInstrDesc *MCID = &MI->getDesc();
7558 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7559 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7560 // operand is still set to noreg. If needed, set the optional operand's
7561 // register to CPSR, and remove the redundant implicit def.
7563 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7565 // Rename pseudo opcodes.
7566 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7568 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7569 MCID = &TII->get(NewOpc);
7571 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7572 "converted opcode should be the same except for cc_out");
7576 // Add the optional cc_out operand
7577 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7579 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7581 // Any ARM instruction that sets the 's' bit should specify an optional
7582 // "cc_out" operand in the last operand position.
7583 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7584 assert(!NewOpc && "Optional cc_out operand required");
7587 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7588 // since we already have an optional CPSR def.
7589 bool definesCPSR = false;
7590 bool deadCPSR = false;
7591 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7593 const MachineOperand &MO = MI->getOperand(i);
7594 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7598 MI->RemoveOperand(i);
7603 assert(!NewOpc && "Optional cc_out operand required");
7606 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7608 assert(!MI->getOperand(ccOutIdx).getReg() &&
7609 "expect uninitialized optional cc_out operand");
7613 // If this instruction was defined with an optional CPSR def and its dag node
7614 // had a live implicit CPSR def, then activate the optional CPSR def.
7615 MachineOperand &MO = MI->getOperand(ccOutIdx);
7616 MO.setReg(ARM::CPSR);
7620 //===----------------------------------------------------------------------===//
7621 // ARM Optimization Hooks
7622 //===----------------------------------------------------------------------===//
7624 // Helper function that checks if N is a null or all ones constant.
7625 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7626 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7629 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7632 // Return true if N is conditionally 0 or all ones.
7633 // Detects these expressions where cc is an i1 value:
7635 // (select cc 0, y) [AllOnes=0]
7636 // (select cc y, 0) [AllOnes=0]
7637 // (zext cc) [AllOnes=0]
7638 // (sext cc) [AllOnes=0/1]
7639 // (select cc -1, y) [AllOnes=1]
7640 // (select cc y, -1) [AllOnes=1]
7642 // Invert is set when N is the null/all ones constant when CC is false.
7643 // OtherOp is set to the alternative value of N.
7644 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7645 SDValue &CC, bool &Invert,
7647 SelectionDAG &DAG) {
7648 switch (N->getOpcode()) {
7649 default: return false;
7651 CC = N->getOperand(0);
7652 SDValue N1 = N->getOperand(1);
7653 SDValue N2 = N->getOperand(2);
7654 if (isZeroOrAllOnes(N1, AllOnes)) {
7659 if (isZeroOrAllOnes(N2, AllOnes)) {
7666 case ISD::ZERO_EXTEND:
7667 // (zext cc) can never be the all ones value.
7671 case ISD::SIGN_EXTEND: {
7672 EVT VT = N->getValueType(0);
7673 CC = N->getOperand(0);
7674 if (CC.getValueType() != MVT::i1)
7678 // When looking for an AllOnes constant, N is an sext, and the 'other'
7680 OtherOp = DAG.getConstant(0, VT);
7681 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7682 // When looking for a 0 constant, N can be zext or sext.
7683 OtherOp = DAG.getConstant(1, VT);
7685 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7691 // Combine a constant select operand into its use:
7693 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7694 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7695 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7696 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7697 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7699 // The transform is rejected if the select doesn't have a constant operand that
7700 // is null, or all ones when AllOnes is set.
7702 // Also recognize sext/zext from i1:
7704 // (add (zext cc), x) -> (select cc (add x, 1), x)
7705 // (add (sext cc), x) -> (select cc (add x, -1), x)
7707 // These transformations eventually create predicated instructions.
7709 // @param N The node to transform.
7710 // @param Slct The N operand that is a select.
7711 // @param OtherOp The other N operand (x above).
7712 // @param DCI Context.
7713 // @param AllOnes Require the select constant to be all ones instead of null.
7714 // @returns The new node, or SDValue() on failure.
7716 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7717 TargetLowering::DAGCombinerInfo &DCI,
7718 bool AllOnes = false) {
7719 SelectionDAG &DAG = DCI.DAG;
7720 EVT VT = N->getValueType(0);
7721 SDValue NonConstantVal;
7724 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7725 NonConstantVal, DAG))
7728 // Slct is now know to be the desired identity constant when CC is true.
7729 SDValue TrueVal = OtherOp;
7730 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7731 OtherOp, NonConstantVal);
7732 // Unless SwapSelectOps says CC should be false.
7734 std::swap(TrueVal, FalseVal);
7736 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7737 CCOp, TrueVal, FalseVal);
7740 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7742 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7743 TargetLowering::DAGCombinerInfo &DCI) {
7744 SDValue N0 = N->getOperand(0);
7745 SDValue N1 = N->getOperand(1);
7746 if (N0.getNode()->hasOneUse()) {
7747 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7748 if (Result.getNode())
7751 if (N1.getNode()->hasOneUse()) {
7752 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7753 if (Result.getNode())
7759 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7760 // (only after legalization).
7761 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7762 TargetLowering::DAGCombinerInfo &DCI,
7763 const ARMSubtarget *Subtarget) {
7765 // Only perform optimization if after legalize, and if NEON is available. We
7766 // also expected both operands to be BUILD_VECTORs.
7767 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7768 || N0.getOpcode() != ISD::BUILD_VECTOR
7769 || N1.getOpcode() != ISD::BUILD_VECTOR)
7772 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7773 EVT VT = N->getValueType(0);
7774 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7777 // Check that the vector operands are of the right form.
7778 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7779 // operands, where N is the size of the formed vector.
7780 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7781 // index such that we have a pair wise add pattern.
7783 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7784 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7786 SDValue Vec = N0->getOperand(0)->getOperand(0);
7787 SDNode *V = Vec.getNode();
7788 unsigned nextIndex = 0;
7790 // For each operands to the ADD which are BUILD_VECTORs,
7791 // check to see if each of their operands are an EXTRACT_VECTOR with
7792 // the same vector and appropriate index.
7793 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7794 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7795 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7797 SDValue ExtVec0 = N0->getOperand(i);
7798 SDValue ExtVec1 = N1->getOperand(i);
7800 // First operand is the vector, verify its the same.
7801 if (V != ExtVec0->getOperand(0).getNode() ||
7802 V != ExtVec1->getOperand(0).getNode())
7805 // Second is the constant, verify its correct.
7806 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7807 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7809 // For the constant, we want to see all the even or all the odd.
7810 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7811 || C1->getZExtValue() != nextIndex+1)
7820 // Create VPADDL node.
7821 SelectionDAG &DAG = DCI.DAG;
7822 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7824 // Build operand list.
7825 SmallVector<SDValue, 8> Ops;
7826 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7827 TLI.getPointerTy()));
7829 // Input is the vector.
7832 // Get widened type and narrowed type.
7834 unsigned numElem = VT.getVectorNumElements();
7836 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7837 switch (inputLaneType.getSimpleVT().SimpleTy) {
7838 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7839 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7840 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7842 llvm_unreachable("Invalid vector element type for padd optimization.");
7845 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7846 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7847 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7850 static SDValue findMUL_LOHI(SDValue V) {
7851 if (V->getOpcode() == ISD::UMUL_LOHI ||
7852 V->getOpcode() == ISD::SMUL_LOHI)
7857 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7858 TargetLowering::DAGCombinerInfo &DCI,
7859 const ARMSubtarget *Subtarget) {
7861 if (Subtarget->isThumb1Only()) return SDValue();
7863 // Only perform the checks after legalize when the pattern is available.
7864 if (DCI.isBeforeLegalize()) return SDValue();
7866 // Look for multiply add opportunities.
7867 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7868 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7869 // a glue link from the first add to the second add.
7870 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7871 // a S/UMLAL instruction.
7874 // \ / \ [no multiline comment]
7880 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7881 SDValue AddcOp0 = AddcNode->getOperand(0);
7882 SDValue AddcOp1 = AddcNode->getOperand(1);
7884 // Check if the two operands are from the same mul_lohi node.
7885 if (AddcOp0.getNode() == AddcOp1.getNode())
7888 assert(AddcNode->getNumValues() == 2 &&
7889 AddcNode->getValueType(0) == MVT::i32 &&
7890 "Expect ADDC with two result values. First: i32");
7892 // Check that we have a glued ADDC node.
7893 if (AddcNode->getValueType(1) != MVT::Glue)
7896 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7897 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7898 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7899 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7900 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7903 // Look for the glued ADDE.
7904 SDNode* AddeNode = AddcNode->getGluedUser();
7908 // Make sure it is really an ADDE.
7909 if (AddeNode->getOpcode() != ISD::ADDE)
7912 assert(AddeNode->getNumOperands() == 3 &&
7913 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7914 "ADDE node has the wrong inputs");
7916 // Check for the triangle shape.
7917 SDValue AddeOp0 = AddeNode->getOperand(0);
7918 SDValue AddeOp1 = AddeNode->getOperand(1);
7920 // Make sure that the ADDE operands are not coming from the same node.
7921 if (AddeOp0.getNode() == AddeOp1.getNode())
7924 // Find the MUL_LOHI node walking up ADDE's operands.
7925 bool IsLeftOperandMUL = false;
7926 SDValue MULOp = findMUL_LOHI(AddeOp0);
7927 if (MULOp == SDValue())
7928 MULOp = findMUL_LOHI(AddeOp1);
7930 IsLeftOperandMUL = true;
7931 if (MULOp == SDValue())
7934 // Figure out the right opcode.
7935 unsigned Opc = MULOp->getOpcode();
7936 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7938 // Figure out the high and low input values to the MLAL node.
7939 SDValue* HiAdd = nullptr;
7940 SDValue* LoMul = nullptr;
7941 SDValue* LowAdd = nullptr;
7943 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
7944 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
7947 if (IsLeftOperandMUL)
7953 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
7954 // whose low result is fed to the ADDC we are checking.
7956 if (AddcOp0 == MULOp.getValue(0)) {
7960 if (AddcOp1 == MULOp.getValue(0)) {
7968 // Create the merged node.
7969 SelectionDAG &DAG = DCI.DAG;
7971 // Build operand list.
7972 SmallVector<SDValue, 8> Ops;
7973 Ops.push_back(LoMul->getOperand(0));
7974 Ops.push_back(LoMul->getOperand(1));
7975 Ops.push_back(*LowAdd);
7976 Ops.push_back(*HiAdd);
7978 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
7979 DAG.getVTList(MVT::i32, MVT::i32), Ops);
7981 // Replace the ADDs' nodes uses by the MLA node's values.
7982 SDValue HiMLALResult(MLALNode.getNode(), 1);
7983 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7985 SDValue LoMLALResult(MLALNode.getNode(), 0);
7986 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7988 // Return original node to notify the driver to stop replacing.
7989 SDValue resNode(AddcNode, 0);
7993 /// PerformADDCCombine - Target-specific dag combine transform from
7994 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7995 static SDValue PerformADDCCombine(SDNode *N,
7996 TargetLowering::DAGCombinerInfo &DCI,
7997 const ARMSubtarget *Subtarget) {
7999 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8003 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8004 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8005 /// called with the default operands, and if that fails, with commuted
8007 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8008 TargetLowering::DAGCombinerInfo &DCI,
8009 const ARMSubtarget *Subtarget){
8011 // Attempt to create vpaddl for this add.
8012 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8013 if (Result.getNode())
8016 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8017 if (N0.getNode()->hasOneUse()) {
8018 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8019 if (Result.getNode()) return Result;
8024 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8026 static SDValue PerformADDCombine(SDNode *N,
8027 TargetLowering::DAGCombinerInfo &DCI,
8028 const ARMSubtarget *Subtarget) {
8029 SDValue N0 = N->getOperand(0);
8030 SDValue N1 = N->getOperand(1);
8032 // First try with the default operand order.
8033 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8034 if (Result.getNode())
8037 // If that didn't work, try again with the operands commuted.
8038 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8041 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8043 static SDValue PerformSUBCombine(SDNode *N,
8044 TargetLowering::DAGCombinerInfo &DCI) {
8045 SDValue N0 = N->getOperand(0);
8046 SDValue N1 = N->getOperand(1);
8048 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8049 if (N1.getNode()->hasOneUse()) {
8050 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8051 if (Result.getNode()) return Result;
8057 /// PerformVMULCombine
8058 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8059 /// special multiplier accumulator forwarding.
8065 // However, for (A + B) * (A + B),
8072 static SDValue PerformVMULCombine(SDNode *N,
8073 TargetLowering::DAGCombinerInfo &DCI,
8074 const ARMSubtarget *Subtarget) {
8075 if (!Subtarget->hasVMLxForwarding())
8078 SelectionDAG &DAG = DCI.DAG;
8079 SDValue N0 = N->getOperand(0);
8080 SDValue N1 = N->getOperand(1);
8081 unsigned Opcode = N0.getOpcode();
8082 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8083 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8084 Opcode = N1.getOpcode();
8085 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8086 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8094 EVT VT = N->getValueType(0);
8096 SDValue N00 = N0->getOperand(0);
8097 SDValue N01 = N0->getOperand(1);
8098 return DAG.getNode(Opcode, DL, VT,
8099 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8100 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8103 static SDValue PerformMULCombine(SDNode *N,
8104 TargetLowering::DAGCombinerInfo &DCI,
8105 const ARMSubtarget *Subtarget) {
8106 SelectionDAG &DAG = DCI.DAG;
8108 if (Subtarget->isThumb1Only())
8111 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8114 EVT VT = N->getValueType(0);
8115 if (VT.is64BitVector() || VT.is128BitVector())
8116 return PerformVMULCombine(N, DCI, Subtarget);
8120 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8124 int64_t MulAmt = C->getSExtValue();
8125 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8127 ShiftAmt = ShiftAmt & (32 - 1);
8128 SDValue V = N->getOperand(0);
8132 MulAmt >>= ShiftAmt;
8135 if (isPowerOf2_32(MulAmt - 1)) {
8136 // (mul x, 2^N + 1) => (add (shl x, N), x)
8137 Res = DAG.getNode(ISD::ADD, DL, VT,
8139 DAG.getNode(ISD::SHL, DL, VT,
8141 DAG.getConstant(Log2_32(MulAmt - 1),
8143 } else if (isPowerOf2_32(MulAmt + 1)) {
8144 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8145 Res = DAG.getNode(ISD::SUB, DL, VT,
8146 DAG.getNode(ISD::SHL, DL, VT,
8148 DAG.getConstant(Log2_32(MulAmt + 1),
8154 uint64_t MulAmtAbs = -MulAmt;
8155 if (isPowerOf2_32(MulAmtAbs + 1)) {
8156 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8157 Res = DAG.getNode(ISD::SUB, DL, VT,
8159 DAG.getNode(ISD::SHL, DL, VT,
8161 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8163 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8164 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8165 Res = DAG.getNode(ISD::ADD, DL, VT,
8167 DAG.getNode(ISD::SHL, DL, VT,
8169 DAG.getConstant(Log2_32(MulAmtAbs-1),
8171 Res = DAG.getNode(ISD::SUB, DL, VT,
8172 DAG.getConstant(0, MVT::i32),Res);
8179 Res = DAG.getNode(ISD::SHL, DL, VT,
8180 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8182 // Do not add new nodes to DAG combiner worklist.
8183 DCI.CombineTo(N, Res, false);
8187 static SDValue PerformANDCombine(SDNode *N,
8188 TargetLowering::DAGCombinerInfo &DCI,
8189 const ARMSubtarget *Subtarget) {
8191 // Attempt to use immediate-form VBIC
8192 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8194 EVT VT = N->getValueType(0);
8195 SelectionDAG &DAG = DCI.DAG;
8197 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8200 APInt SplatBits, SplatUndef;
8201 unsigned SplatBitSize;
8204 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8205 if (SplatBitSize <= 64) {
8207 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8208 SplatUndef.getZExtValue(), SplatBitSize,
8209 DAG, VbicVT, VT.is128BitVector(),
8211 if (Val.getNode()) {
8213 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8214 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8215 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8220 if (!Subtarget->isThumb1Only()) {
8221 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8222 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8223 if (Result.getNode())
8230 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8231 static SDValue PerformORCombine(SDNode *N,
8232 TargetLowering::DAGCombinerInfo &DCI,
8233 const ARMSubtarget *Subtarget) {
8234 // Attempt to use immediate-form VORR
8235 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8237 EVT VT = N->getValueType(0);
8238 SelectionDAG &DAG = DCI.DAG;
8240 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8243 APInt SplatBits, SplatUndef;
8244 unsigned SplatBitSize;
8246 if (BVN && Subtarget->hasNEON() &&
8247 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8248 if (SplatBitSize <= 64) {
8250 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8251 SplatUndef.getZExtValue(), SplatBitSize,
8252 DAG, VorrVT, VT.is128BitVector(),
8254 if (Val.getNode()) {
8256 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8257 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8258 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8263 if (!Subtarget->isThumb1Only()) {
8264 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8265 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8266 if (Result.getNode())
8270 // The code below optimizes (or (and X, Y), Z).
8271 // The AND operand needs to have a single user to make these optimizations
8273 SDValue N0 = N->getOperand(0);
8274 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8276 SDValue N1 = N->getOperand(1);
8278 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8279 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8280 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8282 unsigned SplatBitSize;
8285 APInt SplatBits0, SplatBits1;
8286 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8287 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8288 // Ensure that the second operand of both ands are constants
8289 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8290 HasAnyUndefs) && !HasAnyUndefs) {
8291 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8292 HasAnyUndefs) && !HasAnyUndefs) {
8293 // Ensure that the bit width of the constants are the same and that
8294 // the splat arguments are logical inverses as per the pattern we
8295 // are trying to simplify.
8296 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8297 SplatBits0 == ~SplatBits1) {
8298 // Canonicalize the vector type to make instruction selection
8300 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8301 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8305 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8311 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8314 // BFI is only available on V6T2+
8315 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8319 // 1) or (and A, mask), val => ARMbfi A, val, mask
8320 // iff (val & mask) == val
8322 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8323 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8324 // && mask == ~mask2
8325 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8326 // && ~mask == mask2
8327 // (i.e., copy a bitfield value into another bitfield of the same width)
8332 SDValue N00 = N0.getOperand(0);
8334 // The value and the mask need to be constants so we can verify this is
8335 // actually a bitfield set. If the mask is 0xffff, we can do better
8336 // via a movt instruction, so don't use BFI in that case.
8337 SDValue MaskOp = N0.getOperand(1);
8338 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8341 unsigned Mask = MaskC->getZExtValue();
8345 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8346 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8348 unsigned Val = N1C->getZExtValue();
8349 if ((Val & ~Mask) != Val)
8352 if (ARM::isBitFieldInvertedMask(Mask)) {
8353 Val >>= countTrailingZeros(~Mask);
8355 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8356 DAG.getConstant(Val, MVT::i32),
8357 DAG.getConstant(Mask, MVT::i32));
8359 // Do not add new nodes to DAG combiner worklist.
8360 DCI.CombineTo(N, Res, false);
8363 } else if (N1.getOpcode() == ISD::AND) {
8364 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8365 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8368 unsigned Mask2 = N11C->getZExtValue();
8370 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8372 if (ARM::isBitFieldInvertedMask(Mask) &&
8374 // The pack halfword instruction works better for masks that fit it,
8375 // so use that when it's available.
8376 if (Subtarget->hasT2ExtractPack() &&
8377 (Mask == 0xffff || Mask == 0xffff0000))
8380 unsigned amt = countTrailingZeros(Mask2);
8381 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8382 DAG.getConstant(amt, MVT::i32));
8383 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8384 DAG.getConstant(Mask, MVT::i32));
8385 // Do not add new nodes to DAG combiner worklist.
8386 DCI.CombineTo(N, Res, false);
8388 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8390 // The pack halfword instruction works better for masks that fit it,
8391 // so use that when it's available.
8392 if (Subtarget->hasT2ExtractPack() &&
8393 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8396 unsigned lsb = countTrailingZeros(Mask);
8397 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8398 DAG.getConstant(lsb, MVT::i32));
8399 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8400 DAG.getConstant(Mask2, MVT::i32));
8401 // Do not add new nodes to DAG combiner worklist.
8402 DCI.CombineTo(N, Res, false);
8407 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8408 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8409 ARM::isBitFieldInvertedMask(~Mask)) {
8410 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8411 // where lsb(mask) == #shamt and masked bits of B are known zero.
8412 SDValue ShAmt = N00.getOperand(1);
8413 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8414 unsigned LSB = countTrailingZeros(Mask);
8418 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8419 DAG.getConstant(~Mask, MVT::i32));
8421 // Do not add new nodes to DAG combiner worklist.
8422 DCI.CombineTo(N, Res, false);
8428 static SDValue PerformXORCombine(SDNode *N,
8429 TargetLowering::DAGCombinerInfo &DCI,
8430 const ARMSubtarget *Subtarget) {
8431 EVT VT = N->getValueType(0);
8432 SelectionDAG &DAG = DCI.DAG;
8434 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8437 if (!Subtarget->isThumb1Only()) {
8438 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8439 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8440 if (Result.getNode())
8447 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8448 /// the bits being cleared by the AND are not demanded by the BFI.
8449 static SDValue PerformBFICombine(SDNode *N,
8450 TargetLowering::DAGCombinerInfo &DCI) {
8451 SDValue N1 = N->getOperand(1);
8452 if (N1.getOpcode() == ISD::AND) {
8453 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8456 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8457 unsigned LSB = countTrailingZeros(~InvMask);
8458 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8460 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8461 "undefined behavior");
8462 unsigned Mask = (1u << Width) - 1;
8463 unsigned Mask2 = N11C->getZExtValue();
8464 if ((Mask & (~Mask2)) == 0)
8465 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8466 N->getOperand(0), N1.getOperand(0),
8472 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8473 /// ARMISD::VMOVRRD.
8474 static SDValue PerformVMOVRRDCombine(SDNode *N,
8475 TargetLowering::DAGCombinerInfo &DCI,
8476 const ARMSubtarget *Subtarget) {
8477 // vmovrrd(vmovdrr x, y) -> x,y
8478 SDValue InDouble = N->getOperand(0);
8479 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8480 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8482 // vmovrrd(load f64) -> (load i32), (load i32)
8483 SDNode *InNode = InDouble.getNode();
8484 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8485 InNode->getValueType(0) == MVT::f64 &&
8486 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8487 !cast<LoadSDNode>(InNode)->isVolatile()) {
8488 // TODO: Should this be done for non-FrameIndex operands?
8489 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8491 SelectionDAG &DAG = DCI.DAG;
8493 SDValue BasePtr = LD->getBasePtr();
8494 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8495 LD->getPointerInfo(), LD->isVolatile(),
8496 LD->isNonTemporal(), LD->isInvariant(),
8497 LD->getAlignment());
8499 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8500 DAG.getConstant(4, MVT::i32));
8501 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8502 LD->getPointerInfo(), LD->isVolatile(),
8503 LD->isNonTemporal(), LD->isInvariant(),
8504 std::min(4U, LD->getAlignment() / 2));
8506 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8507 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8508 std::swap (NewLD1, NewLD2);
8509 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8516 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8517 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8518 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8519 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8520 SDValue Op0 = N->getOperand(0);
8521 SDValue Op1 = N->getOperand(1);
8522 if (Op0.getOpcode() == ISD::BITCAST)
8523 Op0 = Op0.getOperand(0);
8524 if (Op1.getOpcode() == ISD::BITCAST)
8525 Op1 = Op1.getOperand(0);
8526 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8527 Op0.getNode() == Op1.getNode() &&
8528 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8529 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8530 N->getValueType(0), Op0.getOperand(0));
8534 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8535 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8536 /// i64 vector to have f64 elements, since the value can then be loaded
8537 /// directly into a VFP register.
8538 static bool hasNormalLoadOperand(SDNode *N) {
8539 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8540 for (unsigned i = 0; i < NumElts; ++i) {
8541 SDNode *Elt = N->getOperand(i).getNode();
8542 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8548 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8549 /// ISD::BUILD_VECTOR.
8550 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8551 TargetLowering::DAGCombinerInfo &DCI,
8552 const ARMSubtarget *Subtarget) {
8553 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8554 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8555 // into a pair of GPRs, which is fine when the value is used as a scalar,
8556 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8557 SelectionDAG &DAG = DCI.DAG;
8558 if (N->getNumOperands() == 2) {
8559 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8564 // Load i64 elements as f64 values so that type legalization does not split
8565 // them up into i32 values.
8566 EVT VT = N->getValueType(0);
8567 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8570 SmallVector<SDValue, 8> Ops;
8571 unsigned NumElts = VT.getVectorNumElements();
8572 for (unsigned i = 0; i < NumElts; ++i) {
8573 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8575 // Make the DAGCombiner fold the bitcast.
8576 DCI.AddToWorklist(V.getNode());
8578 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8579 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8580 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8583 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8585 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8586 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8587 // At that time, we may have inserted bitcasts from integer to float.
8588 // If these bitcasts have survived DAGCombine, change the lowering of this
8589 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8590 // force to use floating point types.
8592 // Make sure we can change the type of the vector.
8593 // This is possible iff:
8594 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8595 // 1.1. Vector is used only once.
8596 // 1.2. Use is a bit convert to an integer type.
8597 // 2. The size of its operands are 32-bits (64-bits are not legal).
8598 EVT VT = N->getValueType(0);
8599 EVT EltVT = VT.getVectorElementType();
8601 // Check 1.1. and 2.
8602 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8605 // By construction, the input type must be float.
8606 assert(EltVT == MVT::f32 && "Unexpected type!");
8609 SDNode *Use = *N->use_begin();
8610 if (Use->getOpcode() != ISD::BITCAST ||
8611 Use->getValueType(0).isFloatingPoint())
8614 // Check profitability.
8615 // Model is, if more than half of the relevant operands are bitcast from
8616 // i32, turn the build_vector into a sequence of insert_vector_elt.
8617 // Relevant operands are everything that is not statically
8618 // (i.e., at compile time) bitcasted.
8619 unsigned NumOfBitCastedElts = 0;
8620 unsigned NumElts = VT.getVectorNumElements();
8621 unsigned NumOfRelevantElts = NumElts;
8622 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8623 SDValue Elt = N->getOperand(Idx);
8624 if (Elt->getOpcode() == ISD::BITCAST) {
8625 // Assume only bit cast to i32 will go away.
8626 if (Elt->getOperand(0).getValueType() == MVT::i32)
8627 ++NumOfBitCastedElts;
8628 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8629 // Constants are statically casted, thus do not count them as
8630 // relevant operands.
8631 --NumOfRelevantElts;
8634 // Check if more than half of the elements require a non-free bitcast.
8635 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8638 SelectionDAG &DAG = DCI.DAG;
8639 // Create the new vector type.
8640 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8641 // Check if the type is legal.
8642 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8643 if (!TLI.isTypeLegal(VecVT))
8647 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8648 // => BITCAST INSERT_VECTOR_ELT
8649 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8651 SDValue Vec = DAG.getUNDEF(VecVT);
8653 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8654 SDValue V = N->getOperand(Idx);
8655 if (V.getOpcode() == ISD::UNDEF)
8657 if (V.getOpcode() == ISD::BITCAST &&
8658 V->getOperand(0).getValueType() == MVT::i32)
8659 // Fold obvious case.
8660 V = V.getOperand(0);
8662 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8663 // Make the DAGCombiner fold the bitcasts.
8664 DCI.AddToWorklist(V.getNode());
8666 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8667 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8669 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8670 // Make the DAGCombiner fold the bitcasts.
8671 DCI.AddToWorklist(Vec.getNode());
8675 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8676 /// ISD::INSERT_VECTOR_ELT.
8677 static SDValue PerformInsertEltCombine(SDNode *N,
8678 TargetLowering::DAGCombinerInfo &DCI) {
8679 // Bitcast an i64 load inserted into a vector to f64.
8680 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8681 EVT VT = N->getValueType(0);
8682 SDNode *Elt = N->getOperand(1).getNode();
8683 if (VT.getVectorElementType() != MVT::i64 ||
8684 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8687 SelectionDAG &DAG = DCI.DAG;
8689 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8690 VT.getVectorNumElements());
8691 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8692 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8693 // Make the DAGCombiner fold the bitcasts.
8694 DCI.AddToWorklist(Vec.getNode());
8695 DCI.AddToWorklist(V.getNode());
8696 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8697 Vec, V, N->getOperand(2));
8698 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8701 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8702 /// ISD::VECTOR_SHUFFLE.
8703 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8704 // The LLVM shufflevector instruction does not require the shuffle mask
8705 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8706 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8707 // operands do not match the mask length, they are extended by concatenating
8708 // them with undef vectors. That is probably the right thing for other
8709 // targets, but for NEON it is better to concatenate two double-register
8710 // size vector operands into a single quad-register size vector. Do that
8711 // transformation here:
8712 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8713 // shuffle(concat(v1, v2), undef)
8714 SDValue Op0 = N->getOperand(0);
8715 SDValue Op1 = N->getOperand(1);
8716 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8717 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8718 Op0.getNumOperands() != 2 ||
8719 Op1.getNumOperands() != 2)
8721 SDValue Concat0Op1 = Op0.getOperand(1);
8722 SDValue Concat1Op1 = Op1.getOperand(1);
8723 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8724 Concat1Op1.getOpcode() != ISD::UNDEF)
8726 // Skip the transformation if any of the types are illegal.
8727 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8728 EVT VT = N->getValueType(0);
8729 if (!TLI.isTypeLegal(VT) ||
8730 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8731 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8734 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8735 Op0.getOperand(0), Op1.getOperand(0));
8736 // Translate the shuffle mask.
8737 SmallVector<int, 16> NewMask;
8738 unsigned NumElts = VT.getVectorNumElements();
8739 unsigned HalfElts = NumElts/2;
8740 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8741 for (unsigned n = 0; n < NumElts; ++n) {
8742 int MaskElt = SVN->getMaskElt(n);
8744 if (MaskElt < (int)HalfElts)
8746 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8747 NewElt = HalfElts + MaskElt - NumElts;
8748 NewMask.push_back(NewElt);
8750 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8751 DAG.getUNDEF(VT), NewMask.data());
8754 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8755 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8756 /// base address updates.
8757 /// For generic load/stores, the memory type is assumed to be a vector.
8758 /// The caller is assumed to have checked legality.
8759 static SDValue CombineBaseUpdate(SDNode *N,
8760 TargetLowering::DAGCombinerInfo &DCI) {
8761 SelectionDAG &DAG = DCI.DAG;
8762 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8763 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8764 const bool isStore = N->getOpcode() == ISD::STORE;
8765 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8766 SDValue Addr = N->getOperand(AddrOpIdx);
8767 MemSDNode *MemN = cast<MemSDNode>(N);
8769 // Search for a use of the address operand that is an increment.
8770 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8771 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8773 if (User->getOpcode() != ISD::ADD ||
8774 UI.getUse().getResNo() != Addr.getResNo())
8777 // Check that the add is independent of the load/store. Otherwise, folding
8778 // it would create a cycle.
8779 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8782 // Find the new opcode for the updating load/store.
8783 bool isLoadOp = true;
8784 bool isLaneOp = false;
8785 unsigned NewOpc = 0;
8786 unsigned NumVecs = 0;
8788 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8790 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8791 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8793 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8795 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8797 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8799 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8800 NumVecs = 2; isLaneOp = true; break;
8801 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8802 NumVecs = 3; isLaneOp = true; break;
8803 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8804 NumVecs = 4; isLaneOp = true; break;
8805 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8806 NumVecs = 1; isLoadOp = false; break;
8807 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8808 NumVecs = 2; isLoadOp = false; break;
8809 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8810 NumVecs = 3; isLoadOp = false; break;
8811 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8812 NumVecs = 4; isLoadOp = false; break;
8813 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8814 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8815 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8816 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8817 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8818 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8822 switch (N->getOpcode()) {
8823 default: llvm_unreachable("unexpected opcode for Neon base update");
8824 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8825 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8826 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8827 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
8828 NumVecs = 1; isLaneOp = false; break;
8829 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
8830 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
8834 // Find the size of memory referenced by the load/store.
8837 VecTy = N->getValueType(0);
8838 } else if (isIntrinsic) {
8839 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8841 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
8842 VecTy = N->getOperand(1).getValueType();
8845 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8847 NumBytes /= VecTy.getVectorNumElements();
8849 // If the increment is a constant, it must match the memory ref size.
8850 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8851 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8852 uint64_t IncVal = CInc->getZExtValue();
8853 if (IncVal != NumBytes)
8855 } else if (NumBytes >= 3 * 16) {
8856 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8857 // separate instructions that make it harder to use a non-constant update.
8861 // OK, we found an ADD we can fold into the base update.
8862 // Now, create a _UPD node, taking care of not breaking alignment.
8864 EVT AlignedVecTy = VecTy;
8865 unsigned Alignment = MemN->getAlignment();
8867 // If this is a less-than-standard-aligned load/store, change the type to
8868 // match the standard alignment.
8869 // The alignment is overlooked when selecting _UPD variants; and it's
8870 // easier to introduce bitcasts here than fix that.
8871 // There are 3 ways to get to this base-update combine:
8872 // - intrinsics: they are assumed to be properly aligned (to the standard
8873 // alignment of the memory type), so we don't need to do anything.
8874 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
8875 // intrinsics, so, likewise, there's nothing to do.
8876 // - generic load/store instructions: the alignment is specified as an
8877 // explicit operand, rather than implicitly as the standard alignment
8878 // of the memory type (like the intrisics). We need to change the
8879 // memory type to match the explicit alignment. That way, we don't
8880 // generate non-standard-aligned ARMISD::VLDx nodes.
8881 if (isa<LSBaseSDNode>(N)) {
8884 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
8885 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
8886 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
8887 assert(!isLaneOp && "Unexpected generic load/store lane.");
8888 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
8889 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
8891 // Don't set an explicit alignment on regular load/stores that we want
8892 // to transform to VLD/VST 1_UPD nodes.
8893 // This matches the behavior of regular load/stores, which only get an
8894 // explicit alignment if the MMO alignment is larger than the standard
8895 // alignment of the memory type.
8896 // Intrinsics, however, always get an explicit alignment, set to the
8897 // alignment of the MMO.
8901 // Create the new updating load/store node.
8902 // First, create an SDVTList for the new updating node's results.
8904 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
8906 for (n = 0; n < NumResultVecs; ++n)
8907 Tys[n] = AlignedVecTy;
8908 Tys[n++] = MVT::i32;
8909 Tys[n] = MVT::Other;
8910 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
8912 // Then, gather the new node's operands.
8913 SmallVector<SDValue, 8> Ops;
8914 Ops.push_back(N->getOperand(0)); // incoming chain
8915 Ops.push_back(N->getOperand(AddrOpIdx));
8918 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
8919 // Try to match the intrinsic's signature
8920 Ops.push_back(StN->getValue());
8922 // Loads (and of course intrinsics) match the intrinsics' signature,
8923 // so just add all but the alignment operand.
8924 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
8925 Ops.push_back(N->getOperand(i));
8928 // For all node types, the alignment operand is always the last one.
8929 Ops.push_back(DAG.getConstant(Alignment, MVT::i32));
8931 // If this is a non-standard-aligned STORE, the penultimate operand is the
8932 // stored value. Bitcast it to the aligned type.
8933 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
8934 SDValue &StVal = Ops[Ops.size()-2];
8935 StVal = DAG.getNode(ISD::BITCAST, SDLoc(N), AlignedVecTy, StVal);
8938 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8940 MemN->getMemOperand());
8943 SmallVector<SDValue, 5> NewResults;
8944 for (unsigned i = 0; i < NumResultVecs; ++i)
8945 NewResults.push_back(SDValue(UpdN.getNode(), i));
8947 // If this is an non-standard-aligned LOAD, the first result is the loaded
8948 // value. Bitcast it to the expected result type.
8949 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
8950 SDValue &LdVal = NewResults[0];
8951 LdVal = DAG.getNode(ISD::BITCAST, SDLoc(N), VecTy, LdVal);
8954 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8955 DCI.CombineTo(N, NewResults);
8956 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8963 static SDValue PerformVLDCombine(SDNode *N,
8964 TargetLowering::DAGCombinerInfo &DCI) {
8965 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8968 return CombineBaseUpdate(N, DCI);
8971 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8972 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8973 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8975 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8976 SelectionDAG &DAG = DCI.DAG;
8977 EVT VT = N->getValueType(0);
8978 // vldN-dup instructions only support 64-bit vectors for N > 1.
8979 if (!VT.is64BitVector())
8982 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8983 SDNode *VLD = N->getOperand(0).getNode();
8984 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8986 unsigned NumVecs = 0;
8987 unsigned NewOpc = 0;
8988 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8989 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8991 NewOpc = ARMISD::VLD2DUP;
8992 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8994 NewOpc = ARMISD::VLD3DUP;
8995 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8997 NewOpc = ARMISD::VLD4DUP;
9002 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9003 // numbers match the load.
9004 unsigned VLDLaneNo =
9005 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9006 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9008 // Ignore uses of the chain result.
9009 if (UI.getUse().getResNo() == NumVecs)
9012 if (User->getOpcode() != ARMISD::VDUPLANE ||
9013 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9017 // Create the vldN-dup node.
9020 for (n = 0; n < NumVecs; ++n)
9022 Tys[n] = MVT::Other;
9023 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9024 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9025 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9026 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9027 Ops, VLDMemInt->getMemoryVT(),
9028 VLDMemInt->getMemOperand());
9031 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9033 unsigned ResNo = UI.getUse().getResNo();
9034 // Ignore uses of the chain result.
9035 if (ResNo == NumVecs)
9038 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9041 // Now the vldN-lane intrinsic is dead except for its chain result.
9042 // Update uses of the chain.
9043 std::vector<SDValue> VLDDupResults;
9044 for (unsigned n = 0; n < NumVecs; ++n)
9045 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9046 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9047 DCI.CombineTo(VLD, VLDDupResults);
9052 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9053 /// ARMISD::VDUPLANE.
9054 static SDValue PerformVDUPLANECombine(SDNode *N,
9055 TargetLowering::DAGCombinerInfo &DCI) {
9056 SDValue Op = N->getOperand(0);
9058 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9059 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9060 if (CombineVLDDUP(N, DCI))
9061 return SDValue(N, 0);
9063 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9064 // redundant. Ignore bit_converts for now; element sizes are checked below.
9065 while (Op.getOpcode() == ISD::BITCAST)
9066 Op = Op.getOperand(0);
9067 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9070 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9071 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9072 // The canonical VMOV for a zero vector uses a 32-bit element size.
9073 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9075 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9077 EVT VT = N->getValueType(0);
9078 if (EltSize > VT.getVectorElementType().getSizeInBits())
9081 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9084 static SDValue PerformLOADCombine(SDNode *N,
9085 TargetLowering::DAGCombinerInfo &DCI) {
9086 EVT VT = N->getValueType(0);
9088 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9089 if (ISD::isNormalLoad(N) && VT.isVector() &&
9090 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9091 return CombineBaseUpdate(N, DCI);
9096 /// PerformSTORECombine - Target-specific dag combine xforms for
9098 static SDValue PerformSTORECombine(SDNode *N,
9099 TargetLowering::DAGCombinerInfo &DCI) {
9100 StoreSDNode *St = cast<StoreSDNode>(N);
9101 if (St->isVolatile())
9104 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9105 // pack all of the elements in one place. Next, store to memory in fewer
9107 SDValue StVal = St->getValue();
9108 EVT VT = StVal.getValueType();
9109 if (St->isTruncatingStore() && VT.isVector()) {
9110 SelectionDAG &DAG = DCI.DAG;
9111 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9112 EVT StVT = St->getMemoryVT();
9113 unsigned NumElems = VT.getVectorNumElements();
9114 assert(StVT != VT && "Cannot truncate to the same type");
9115 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9116 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9118 // From, To sizes and ElemCount must be pow of two
9119 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9121 // We are going to use the original vector elt for storing.
9122 // Accumulated smaller vector elements must be a multiple of the store size.
9123 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9125 unsigned SizeRatio = FromEltSz / ToEltSz;
9126 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9128 // Create a type on which we perform the shuffle.
9129 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9130 NumElems*SizeRatio);
9131 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9134 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9135 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9136 for (unsigned i = 0; i < NumElems; ++i)
9137 ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9139 // Can't shuffle using an illegal type.
9140 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9142 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9143 DAG.getUNDEF(WideVec.getValueType()),
9145 // At this point all of the data is stored at the bottom of the
9146 // register. We now need to save it to mem.
9148 // Find the largest store unit
9149 MVT StoreType = MVT::i8;
9150 for (MVT Tp : MVT::integer_valuetypes()) {
9151 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9154 // Didn't find a legal store type.
9155 if (!TLI.isTypeLegal(StoreType))
9158 // Bitcast the original vector into a vector of store-size units
9159 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9160 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9161 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9162 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9163 SmallVector<SDValue, 8> Chains;
9164 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9165 TLI.getPointerTy());
9166 SDValue BasePtr = St->getBasePtr();
9168 // Perform one or more big stores into memory.
9169 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9170 for (unsigned I = 0; I < E; I++) {
9171 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9172 StoreType, ShuffWide,
9173 DAG.getIntPtrConstant(I));
9174 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9175 St->getPointerInfo(), St->isVolatile(),
9176 St->isNonTemporal(), St->getAlignment());
9177 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9179 Chains.push_back(Ch);
9181 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9184 if (!ISD::isNormalStore(St))
9187 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9188 // ARM stores of arguments in the same cache line.
9189 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9190 StVal.getNode()->hasOneUse()) {
9191 SelectionDAG &DAG = DCI.DAG;
9192 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9194 SDValue BasePtr = St->getBasePtr();
9195 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9196 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9197 BasePtr, St->getPointerInfo(), St->isVolatile(),
9198 St->isNonTemporal(), St->getAlignment());
9200 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9201 DAG.getConstant(4, MVT::i32));
9202 return DAG.getStore(NewST1.getValue(0), DL,
9203 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9204 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9205 St->isNonTemporal(),
9206 std::min(4U, St->getAlignment() / 2));
9209 if (StVal.getValueType() == MVT::i64 &&
9210 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9212 // Bitcast an i64 store extracted from a vector to f64.
9213 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9214 SelectionDAG &DAG = DCI.DAG;
9216 SDValue IntVec = StVal.getOperand(0);
9217 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9218 IntVec.getValueType().getVectorNumElements());
9219 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9220 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9221 Vec, StVal.getOperand(1));
9223 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9224 // Make the DAGCombiner fold the bitcasts.
9225 DCI.AddToWorklist(Vec.getNode());
9226 DCI.AddToWorklist(ExtElt.getNode());
9227 DCI.AddToWorklist(V.getNode());
9228 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9229 St->getPointerInfo(), St->isVolatile(),
9230 St->isNonTemporal(), St->getAlignment(),
9234 // If this is a legal vector store, try to combine it into a VST1_UPD.
9235 if (ISD::isNormalStore(N) && VT.isVector() &&
9236 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9237 return CombineBaseUpdate(N, DCI);
9242 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9243 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9244 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9248 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9250 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9255 APFloat APF = C->getValueAPF();
9256 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9257 != APFloat::opOK || !isExact)
9260 c0 = (I == 0) ? cN : c0;
9261 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9268 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9269 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9270 /// when the VMUL has a constant operand that is a power of 2.
9272 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9273 /// vmul.f32 d16, d17, d16
9274 /// vcvt.s32.f32 d16, d16
9276 /// vcvt.s32.f32 d16, d16, #3
9277 static SDValue PerformVCVTCombine(SDNode *N,
9278 TargetLowering::DAGCombinerInfo &DCI,
9279 const ARMSubtarget *Subtarget) {
9280 SelectionDAG &DAG = DCI.DAG;
9281 SDValue Op = N->getOperand(0);
9283 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9284 Op.getOpcode() != ISD::FMUL)
9288 SDValue N0 = Op->getOperand(0);
9289 SDValue ConstVec = Op->getOperand(1);
9290 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9292 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9293 !isConstVecPow2(ConstVec, isSigned, C))
9296 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9297 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9298 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9299 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9301 // These instructions only exist converting from f32 to i32. We can handle
9302 // smaller integers by generating an extra truncate, but larger ones would
9303 // be lossy. We also can't handle more then 4 lanes, since these intructions
9304 // only support v2i32/v4i32 types.
9308 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9309 Intrinsic::arm_neon_vcvtfp2fxu;
9310 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9311 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9312 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9313 DAG.getConstant(Log2_64(C), MVT::i32));
9315 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9316 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9321 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9322 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9323 /// when the VDIV has a constant operand that is a power of 2.
9325 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9326 /// vcvt.f32.s32 d16, d16
9327 /// vdiv.f32 d16, d17, d16
9329 /// vcvt.f32.s32 d16, d16, #3
9330 static SDValue PerformVDIVCombine(SDNode *N,
9331 TargetLowering::DAGCombinerInfo &DCI,
9332 const ARMSubtarget *Subtarget) {
9333 SelectionDAG &DAG = DCI.DAG;
9334 SDValue Op = N->getOperand(0);
9335 unsigned OpOpcode = Op.getNode()->getOpcode();
9337 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9338 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9342 SDValue ConstVec = N->getOperand(1);
9343 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9345 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9346 !isConstVecPow2(ConstVec, isSigned, C))
9349 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9350 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9351 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9352 // These instructions only exist converting from i32 to f32. We can handle
9353 // smaller integers by generating an extra extend, but larger ones would
9358 SDValue ConvInput = Op.getOperand(0);
9359 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9360 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9361 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9362 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9365 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9366 Intrinsic::arm_neon_vcvtfxu2fp;
9367 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9369 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9370 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9373 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9374 /// operand of a vector shift operation, where all the elements of the
9375 /// build_vector must have the same constant integer value.
9376 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9377 // Ignore bit_converts.
9378 while (Op.getOpcode() == ISD::BITCAST)
9379 Op = Op.getOperand(0);
9380 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9381 APInt SplatBits, SplatUndef;
9382 unsigned SplatBitSize;
9384 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9385 HasAnyUndefs, ElementBits) ||
9386 SplatBitSize > ElementBits)
9388 Cnt = SplatBits.getSExtValue();
9392 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9393 /// operand of a vector shift left operation. That value must be in the range:
9394 /// 0 <= Value < ElementBits for a left shift; or
9395 /// 0 <= Value <= ElementBits for a long left shift.
9396 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9397 assert(VT.isVector() && "vector shift count is not a vector type");
9398 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9399 if (! getVShiftImm(Op, ElementBits, Cnt))
9401 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9404 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9405 /// operand of a vector shift right operation. For a shift opcode, the value
9406 /// is positive, but for an intrinsic the value count must be negative. The
9407 /// absolute value must be in the range:
9408 /// 1 <= |Value| <= ElementBits for a right shift; or
9409 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9410 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9412 assert(VT.isVector() && "vector shift count is not a vector type");
9413 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9414 if (! getVShiftImm(Op, ElementBits, Cnt))
9418 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9421 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9422 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9423 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9426 // Don't do anything for most intrinsics.
9429 // Vector shifts: check for immediate versions and lower them.
9430 // Note: This is done during DAG combining instead of DAG legalizing because
9431 // the build_vectors for 64-bit vector element shift counts are generally
9432 // not legal, and it is hard to see their values after they get legalized to
9433 // loads from a constant pool.
9434 case Intrinsic::arm_neon_vshifts:
9435 case Intrinsic::arm_neon_vshiftu:
9436 case Intrinsic::arm_neon_vrshifts:
9437 case Intrinsic::arm_neon_vrshiftu:
9438 case Intrinsic::arm_neon_vrshiftn:
9439 case Intrinsic::arm_neon_vqshifts:
9440 case Intrinsic::arm_neon_vqshiftu:
9441 case Intrinsic::arm_neon_vqshiftsu:
9442 case Intrinsic::arm_neon_vqshiftns:
9443 case Intrinsic::arm_neon_vqshiftnu:
9444 case Intrinsic::arm_neon_vqshiftnsu:
9445 case Intrinsic::arm_neon_vqrshiftns:
9446 case Intrinsic::arm_neon_vqrshiftnu:
9447 case Intrinsic::arm_neon_vqrshiftnsu: {
9448 EVT VT = N->getOperand(1).getValueType();
9450 unsigned VShiftOpc = 0;
9453 case Intrinsic::arm_neon_vshifts:
9454 case Intrinsic::arm_neon_vshiftu:
9455 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9456 VShiftOpc = ARMISD::VSHL;
9459 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9460 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9461 ARMISD::VSHRs : ARMISD::VSHRu);
9466 case Intrinsic::arm_neon_vrshifts:
9467 case Intrinsic::arm_neon_vrshiftu:
9468 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9472 case Intrinsic::arm_neon_vqshifts:
9473 case Intrinsic::arm_neon_vqshiftu:
9474 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9478 case Intrinsic::arm_neon_vqshiftsu:
9479 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9481 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9483 case Intrinsic::arm_neon_vrshiftn:
9484 case Intrinsic::arm_neon_vqshiftns:
9485 case Intrinsic::arm_neon_vqshiftnu:
9486 case Intrinsic::arm_neon_vqshiftnsu:
9487 case Intrinsic::arm_neon_vqrshiftns:
9488 case Intrinsic::arm_neon_vqrshiftnu:
9489 case Intrinsic::arm_neon_vqrshiftnsu:
9490 // Narrowing shifts require an immediate right shift.
9491 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9493 llvm_unreachable("invalid shift count for narrowing vector shift "
9497 llvm_unreachable("unhandled vector shift");
9501 case Intrinsic::arm_neon_vshifts:
9502 case Intrinsic::arm_neon_vshiftu:
9503 // Opcode already set above.
9505 case Intrinsic::arm_neon_vrshifts:
9506 VShiftOpc = ARMISD::VRSHRs; break;
9507 case Intrinsic::arm_neon_vrshiftu:
9508 VShiftOpc = ARMISD::VRSHRu; break;
9509 case Intrinsic::arm_neon_vrshiftn:
9510 VShiftOpc = ARMISD::VRSHRN; break;
9511 case Intrinsic::arm_neon_vqshifts:
9512 VShiftOpc = ARMISD::VQSHLs; break;
9513 case Intrinsic::arm_neon_vqshiftu:
9514 VShiftOpc = ARMISD::VQSHLu; break;
9515 case Intrinsic::arm_neon_vqshiftsu:
9516 VShiftOpc = ARMISD::VQSHLsu; break;
9517 case Intrinsic::arm_neon_vqshiftns:
9518 VShiftOpc = ARMISD::VQSHRNs; break;
9519 case Intrinsic::arm_neon_vqshiftnu:
9520 VShiftOpc = ARMISD::VQSHRNu; break;
9521 case Intrinsic::arm_neon_vqshiftnsu:
9522 VShiftOpc = ARMISD::VQSHRNsu; break;
9523 case Intrinsic::arm_neon_vqrshiftns:
9524 VShiftOpc = ARMISD::VQRSHRNs; break;
9525 case Intrinsic::arm_neon_vqrshiftnu:
9526 VShiftOpc = ARMISD::VQRSHRNu; break;
9527 case Intrinsic::arm_neon_vqrshiftnsu:
9528 VShiftOpc = ARMISD::VQRSHRNsu; break;
9531 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9532 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9535 case Intrinsic::arm_neon_vshiftins: {
9536 EVT VT = N->getOperand(1).getValueType();
9538 unsigned VShiftOpc = 0;
9540 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9541 VShiftOpc = ARMISD::VSLI;
9542 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9543 VShiftOpc = ARMISD::VSRI;
9545 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9548 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9549 N->getOperand(1), N->getOperand(2),
9550 DAG.getConstant(Cnt, MVT::i32));
9553 case Intrinsic::arm_neon_vqrshifts:
9554 case Intrinsic::arm_neon_vqrshiftu:
9555 // No immediate versions of these to check for.
9562 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9563 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9564 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9565 /// vector element shift counts are generally not legal, and it is hard to see
9566 /// their values after they get legalized to loads from a constant pool.
9567 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9568 const ARMSubtarget *ST) {
9569 EVT VT = N->getValueType(0);
9570 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9571 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9572 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9573 SDValue N1 = N->getOperand(1);
9574 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9575 SDValue N0 = N->getOperand(0);
9576 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9577 DAG.MaskedValueIsZero(N0.getOperand(0),
9578 APInt::getHighBitsSet(32, 16)))
9579 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9583 // Nothing to be done for scalar shifts.
9584 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9585 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9588 assert(ST->hasNEON() && "unexpected vector shift");
9591 switch (N->getOpcode()) {
9592 default: llvm_unreachable("unexpected shift opcode");
9595 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9596 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9597 DAG.getConstant(Cnt, MVT::i32));
9602 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9603 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9604 ARMISD::VSHRs : ARMISD::VSHRu);
9605 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9606 DAG.getConstant(Cnt, MVT::i32));
9612 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9613 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9614 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9615 const ARMSubtarget *ST) {
9616 SDValue N0 = N->getOperand(0);
9618 // Check for sign- and zero-extensions of vector extract operations of 8-
9619 // and 16-bit vector elements. NEON supports these directly. They are
9620 // handled during DAG combining because type legalization will promote them
9621 // to 32-bit types and it is messy to recognize the operations after that.
9622 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9623 SDValue Vec = N0.getOperand(0);
9624 SDValue Lane = N0.getOperand(1);
9625 EVT VT = N->getValueType(0);
9626 EVT EltVT = N0.getValueType();
9627 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9629 if (VT == MVT::i32 &&
9630 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9631 TLI.isTypeLegal(Vec.getValueType()) &&
9632 isa<ConstantSDNode>(Lane)) {
9635 switch (N->getOpcode()) {
9636 default: llvm_unreachable("unexpected opcode");
9637 case ISD::SIGN_EXTEND:
9638 Opc = ARMISD::VGETLANEs;
9640 case ISD::ZERO_EXTEND:
9641 case ISD::ANY_EXTEND:
9642 Opc = ARMISD::VGETLANEu;
9645 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9652 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9653 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9654 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9655 const ARMSubtarget *ST) {
9656 // If the target supports NEON, try to use vmax/vmin instructions for f32
9657 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9658 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9659 // a NaN; only do the transformation when it matches that behavior.
9661 // For now only do this when using NEON for FP operations; if using VFP, it
9662 // is not obvious that the benefit outweighs the cost of switching to the
9664 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9665 N->getValueType(0) != MVT::f32)
9668 SDValue CondLHS = N->getOperand(0);
9669 SDValue CondRHS = N->getOperand(1);
9670 SDValue LHS = N->getOperand(2);
9671 SDValue RHS = N->getOperand(3);
9672 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9674 unsigned Opcode = 0;
9676 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9677 IsReversed = false; // x CC y ? x : y
9678 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9679 IsReversed = true ; // x CC y ? y : x
9693 // If LHS is NaN, an ordered comparison will be false and the result will
9694 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9695 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9696 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9697 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9699 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9700 // will return -0, so vmin can only be used for unsafe math or if one of
9701 // the operands is known to be nonzero.
9702 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9703 !DAG.getTarget().Options.UnsafeFPMath &&
9704 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9706 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9715 // If LHS is NaN, an ordered comparison will be false and the result will
9716 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9717 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9718 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9719 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9721 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9722 // will return +0, so vmax can only be used for unsafe math or if one of
9723 // the operands is known to be nonzero.
9724 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9725 !DAG.getTarget().Options.UnsafeFPMath &&
9726 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9728 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9734 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9737 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9739 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9740 SDValue Cmp = N->getOperand(4);
9741 if (Cmp.getOpcode() != ARMISD::CMPZ)
9742 // Only looking at EQ and NE cases.
9745 EVT VT = N->getValueType(0);
9747 SDValue LHS = Cmp.getOperand(0);
9748 SDValue RHS = Cmp.getOperand(1);
9749 SDValue FalseVal = N->getOperand(0);
9750 SDValue TrueVal = N->getOperand(1);
9751 SDValue ARMcc = N->getOperand(2);
9752 ARMCC::CondCodes CC =
9753 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9771 /// FIXME: Turn this into a target neutral optimization?
9773 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9774 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9775 N->getOperand(3), Cmp);
9776 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9778 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9779 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9780 N->getOperand(3), NewCmp);
9783 if (Res.getNode()) {
9784 APInt KnownZero, KnownOne;
9785 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9786 // Capture demanded bits information that would be otherwise lost.
9787 if (KnownZero == 0xfffffffe)
9788 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9789 DAG.getValueType(MVT::i1));
9790 else if (KnownZero == 0xffffff00)
9791 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9792 DAG.getValueType(MVT::i8));
9793 else if (KnownZero == 0xffff0000)
9794 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9795 DAG.getValueType(MVT::i16));
9801 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9802 DAGCombinerInfo &DCI) const {
9803 switch (N->getOpcode()) {
9805 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9806 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9807 case ISD::SUB: return PerformSUBCombine(N, DCI);
9808 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9809 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9810 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9811 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9812 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9813 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9814 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9815 case ISD::STORE: return PerformSTORECombine(N, DCI);
9816 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9817 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9818 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9819 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9820 case ISD::FP_TO_SINT:
9821 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9822 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9823 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9826 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9827 case ISD::SIGN_EXTEND:
9828 case ISD::ZERO_EXTEND:
9829 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9830 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9831 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9832 case ISD::LOAD: return PerformLOADCombine(N, DCI);
9833 case ARMISD::VLD2DUP:
9834 case ARMISD::VLD3DUP:
9835 case ARMISD::VLD4DUP:
9836 return PerformVLDCombine(N, DCI);
9837 case ARMISD::BUILD_VECTOR:
9838 return PerformARMBUILD_VECTORCombine(N, DCI);
9839 case ISD::INTRINSIC_VOID:
9840 case ISD::INTRINSIC_W_CHAIN:
9841 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9842 case Intrinsic::arm_neon_vld1:
9843 case Intrinsic::arm_neon_vld2:
9844 case Intrinsic::arm_neon_vld3:
9845 case Intrinsic::arm_neon_vld4:
9846 case Intrinsic::arm_neon_vld2lane:
9847 case Intrinsic::arm_neon_vld3lane:
9848 case Intrinsic::arm_neon_vld4lane:
9849 case Intrinsic::arm_neon_vst1:
9850 case Intrinsic::arm_neon_vst2:
9851 case Intrinsic::arm_neon_vst3:
9852 case Intrinsic::arm_neon_vst4:
9853 case Intrinsic::arm_neon_vst2lane:
9854 case Intrinsic::arm_neon_vst3lane:
9855 case Intrinsic::arm_neon_vst4lane:
9856 return PerformVLDCombine(N, DCI);
9864 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9866 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9869 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9873 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9874 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9876 switch (VT.getSimpleVT().SimpleTy) {
9882 // Unaligned access can use (for example) LRDB, LRDH, LDR
9883 if (AllowsUnaligned) {
9885 *Fast = Subtarget->hasV7Ops();
9892 // For any little-endian targets with neon, we can support unaligned ld/st
9893 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9894 // A big-endian target may also explicitly support unaligned accesses
9895 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9905 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9906 unsigned AlignCheck) {
9907 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9908 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9911 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9912 unsigned DstAlign, unsigned SrcAlign,
9913 bool IsMemset, bool ZeroMemset,
9915 MachineFunction &MF) const {
9916 const Function *F = MF.getFunction();
9918 // See if we can use NEON instructions for this...
9919 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
9920 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
9923 (memOpAlign(SrcAlign, DstAlign, 16) ||
9924 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9926 } else if (Size >= 8 &&
9927 (memOpAlign(SrcAlign, DstAlign, 8) ||
9928 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9934 // Lowering to i32/i16 if the size permits.
9940 // Let the target-independent logic figure it out.
9944 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9945 if (Val.getOpcode() != ISD::LOAD)
9948 EVT VT1 = Val.getValueType();
9949 if (!VT1.isSimple() || !VT1.isInteger() ||
9950 !VT2.isSimple() || !VT2.isInteger())
9953 switch (VT1.getSimpleVT().SimpleTy) {
9958 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9965 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
9966 EVT VT = ExtVal.getValueType();
9968 if (!isTypeLegal(VT))
9971 // Don't create a loadext if we can fold the extension into a wide/long
9973 // If there's more than one user instruction, the loadext is desirable no
9974 // matter what. There can be two uses by the same instruction.
9975 if (ExtVal->use_empty() ||
9976 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
9979 SDNode *U = *ExtVal->use_begin();
9980 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
9981 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
9987 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9988 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9991 if (!isTypeLegal(EVT::getEVT(Ty1)))
9994 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9996 // Assuming the caller doesn't have a zeroext or signext return parameter,
9997 // truncation all the way down to i1 is valid.
10002 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10006 unsigned Scale = 1;
10007 switch (VT.getSimpleVT().SimpleTy) {
10008 default: return false;
10023 if ((V & (Scale - 1)) != 0)
10026 return V == (V & ((1LL << 5) - 1));
10029 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10030 const ARMSubtarget *Subtarget) {
10031 bool isNeg = false;
10037 switch (VT.getSimpleVT().SimpleTy) {
10038 default: return false;
10043 // + imm12 or - imm8
10045 return V == (V & ((1LL << 8) - 1));
10046 return V == (V & ((1LL << 12) - 1));
10049 // Same as ARM mode. FIXME: NEON?
10050 if (!Subtarget->hasVFP2())
10055 return V == (V & ((1LL << 8) - 1));
10059 /// isLegalAddressImmediate - Return true if the integer value can be used
10060 /// as the offset of the target addressing mode for load / store of the
10062 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10063 const ARMSubtarget *Subtarget) {
10067 if (!VT.isSimple())
10070 if (Subtarget->isThumb1Only())
10071 return isLegalT1AddressImmediate(V, VT);
10072 else if (Subtarget->isThumb2())
10073 return isLegalT2AddressImmediate(V, VT, Subtarget);
10078 switch (VT.getSimpleVT().SimpleTy) {
10079 default: return false;
10084 return V == (V & ((1LL << 12) - 1));
10087 return V == (V & ((1LL << 8) - 1));
10090 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10095 return V == (V & ((1LL << 8) - 1));
10099 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10101 int Scale = AM.Scale;
10105 switch (VT.getSimpleVT().SimpleTy) {
10106 default: return false;
10114 Scale = Scale & ~1;
10115 return Scale == 2 || Scale == 4 || Scale == 8;
10118 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10122 // Note, we allow "void" uses (basically, uses that aren't loads or
10123 // stores), because arm allows folding a scale into many arithmetic
10124 // operations. This should be made more precise and revisited later.
10126 // Allow r << imm, but the imm has to be a multiple of two.
10127 if (Scale & 1) return false;
10128 return isPowerOf2_32(Scale);
10132 /// isLegalAddressingMode - Return true if the addressing mode represented
10133 /// by AM is legal for this target, for a load/store of the specified type.
10134 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10136 EVT VT = getValueType(Ty, true);
10137 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10140 // Can never fold addr of global into load/store.
10144 switch (AM.Scale) {
10145 case 0: // no scale reg, must be "r+i" or "r", or "i".
10148 if (Subtarget->isThumb1Only())
10152 // ARM doesn't support any R+R*scale+imm addr modes.
10156 if (!VT.isSimple())
10159 if (Subtarget->isThumb2())
10160 return isLegalT2ScaledAddressingMode(AM, VT);
10162 int Scale = AM.Scale;
10163 switch (VT.getSimpleVT().SimpleTy) {
10164 default: return false;
10168 if (Scale < 0) Scale = -Scale;
10172 return isPowerOf2_32(Scale & ~1);
10176 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10181 // Note, we allow "void" uses (basically, uses that aren't loads or
10182 // stores), because arm allows folding a scale into many arithmetic
10183 // operations. This should be made more precise and revisited later.
10185 // Allow r << imm, but the imm has to be a multiple of two.
10186 if (Scale & 1) return false;
10187 return isPowerOf2_32(Scale);
10193 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10194 /// icmp immediate, that is the target has icmp instructions which can compare
10195 /// a register against the immediate without having to materialize the
10196 /// immediate into a register.
10197 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10198 // Thumb2 and ARM modes can use cmn for negative immediates.
10199 if (!Subtarget->isThumb())
10200 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10201 if (Subtarget->isThumb2())
10202 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10203 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10204 return Imm >= 0 && Imm <= 255;
10207 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10208 /// *or sub* immediate, that is the target has add or sub instructions which can
10209 /// add a register with the immediate without having to materialize the
10210 /// immediate into a register.
10211 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10212 // Same encoding for add/sub, just flip the sign.
10213 int64_t AbsImm = std::abs(Imm);
10214 if (!Subtarget->isThumb())
10215 return ARM_AM::getSOImmVal(AbsImm) != -1;
10216 if (Subtarget->isThumb2())
10217 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10218 // Thumb1 only has 8-bit unsigned immediate.
10219 return AbsImm >= 0 && AbsImm <= 255;
10222 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10223 bool isSEXTLoad, SDValue &Base,
10224 SDValue &Offset, bool &isInc,
10225 SelectionDAG &DAG) {
10226 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10229 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10230 // AddressingMode 3
10231 Base = Ptr->getOperand(0);
10232 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10233 int RHSC = (int)RHS->getZExtValue();
10234 if (RHSC < 0 && RHSC > -256) {
10235 assert(Ptr->getOpcode() == ISD::ADD);
10237 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10241 isInc = (Ptr->getOpcode() == ISD::ADD);
10242 Offset = Ptr->getOperand(1);
10244 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10245 // AddressingMode 2
10246 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10247 int RHSC = (int)RHS->getZExtValue();
10248 if (RHSC < 0 && RHSC > -0x1000) {
10249 assert(Ptr->getOpcode() == ISD::ADD);
10251 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10252 Base = Ptr->getOperand(0);
10257 if (Ptr->getOpcode() == ISD::ADD) {
10259 ARM_AM::ShiftOpc ShOpcVal=
10260 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10261 if (ShOpcVal != ARM_AM::no_shift) {
10262 Base = Ptr->getOperand(1);
10263 Offset = Ptr->getOperand(0);
10265 Base = Ptr->getOperand(0);
10266 Offset = Ptr->getOperand(1);
10271 isInc = (Ptr->getOpcode() == ISD::ADD);
10272 Base = Ptr->getOperand(0);
10273 Offset = Ptr->getOperand(1);
10277 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10281 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10282 bool isSEXTLoad, SDValue &Base,
10283 SDValue &Offset, bool &isInc,
10284 SelectionDAG &DAG) {
10285 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10288 Base = Ptr->getOperand(0);
10289 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10290 int RHSC = (int)RHS->getZExtValue();
10291 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10292 assert(Ptr->getOpcode() == ISD::ADD);
10294 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10296 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10297 isInc = Ptr->getOpcode() == ISD::ADD;
10298 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10306 /// getPreIndexedAddressParts - returns true by value, base pointer and
10307 /// offset pointer and addressing mode by reference if the node's address
10308 /// can be legally represented as pre-indexed load / store address.
10310 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10312 ISD::MemIndexedMode &AM,
10313 SelectionDAG &DAG) const {
10314 if (Subtarget->isThumb1Only())
10319 bool isSEXTLoad = false;
10320 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10321 Ptr = LD->getBasePtr();
10322 VT = LD->getMemoryVT();
10323 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10324 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10325 Ptr = ST->getBasePtr();
10326 VT = ST->getMemoryVT();
10331 bool isLegal = false;
10332 if (Subtarget->isThumb2())
10333 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10334 Offset, isInc, DAG);
10336 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10337 Offset, isInc, DAG);
10341 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10345 /// getPostIndexedAddressParts - returns true by value, base pointer and
10346 /// offset pointer and addressing mode by reference if this node can be
10347 /// combined with a load / store to form a post-indexed load / store.
10348 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10351 ISD::MemIndexedMode &AM,
10352 SelectionDAG &DAG) const {
10353 if (Subtarget->isThumb1Only())
10358 bool isSEXTLoad = false;
10359 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10360 VT = LD->getMemoryVT();
10361 Ptr = LD->getBasePtr();
10362 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10363 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10364 VT = ST->getMemoryVT();
10365 Ptr = ST->getBasePtr();
10370 bool isLegal = false;
10371 if (Subtarget->isThumb2())
10372 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10375 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10381 // Swap base ptr and offset to catch more post-index load / store when
10382 // it's legal. In Thumb2 mode, offset must be an immediate.
10383 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10384 !Subtarget->isThumb2())
10385 std::swap(Base, Offset);
10387 // Post-indexed load / store update the base pointer.
10392 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10396 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10399 const SelectionDAG &DAG,
10400 unsigned Depth) const {
10401 unsigned BitWidth = KnownOne.getBitWidth();
10402 KnownZero = KnownOne = APInt(BitWidth, 0);
10403 switch (Op.getOpcode()) {
10409 // These nodes' second result is a boolean
10410 if (Op.getResNo() == 0)
10412 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10414 case ARMISD::CMOV: {
10415 // Bits are known zero/one if known on the LHS and RHS.
10416 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10417 if (KnownZero == 0 && KnownOne == 0) return;
10419 APInt KnownZeroRHS, KnownOneRHS;
10420 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10421 KnownZero &= KnownZeroRHS;
10422 KnownOne &= KnownOneRHS;
10425 case ISD::INTRINSIC_W_CHAIN: {
10426 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10427 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10430 case Intrinsic::arm_ldaex:
10431 case Intrinsic::arm_ldrex: {
10432 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10433 unsigned MemBits = VT.getScalarType().getSizeInBits();
10434 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10442 //===----------------------------------------------------------------------===//
10443 // ARM Inline Assembly Support
10444 //===----------------------------------------------------------------------===//
10446 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10447 // Looking for "rev" which is V6+.
10448 if (!Subtarget->hasV6Ops())
10451 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10452 std::string AsmStr = IA->getAsmString();
10453 SmallVector<StringRef, 4> AsmPieces;
10454 SplitString(AsmStr, AsmPieces, ";\n");
10456 switch (AsmPieces.size()) {
10457 default: return false;
10459 AsmStr = AsmPieces[0];
10461 SplitString(AsmStr, AsmPieces, " \t,");
10464 if (AsmPieces.size() == 3 &&
10465 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10466 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10467 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10468 if (Ty && Ty->getBitWidth() == 32)
10469 return IntrinsicLowering::LowerToByteSwap(CI);
10477 /// getConstraintType - Given a constraint letter, return the type of
10478 /// constraint it is for this target.
10479 ARMTargetLowering::ConstraintType
10480 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10481 if (Constraint.size() == 1) {
10482 switch (Constraint[0]) {
10484 case 'l': return C_RegisterClass;
10485 case 'w': return C_RegisterClass;
10486 case 'h': return C_RegisterClass;
10487 case 'x': return C_RegisterClass;
10488 case 't': return C_RegisterClass;
10489 case 'j': return C_Other; // Constant for movw.
10490 // An address with a single base register. Due to the way we
10491 // currently handle addresses it is the same as an 'r' memory constraint.
10492 case 'Q': return C_Memory;
10494 } else if (Constraint.size() == 2) {
10495 switch (Constraint[0]) {
10497 // All 'U+' constraints are addresses.
10498 case 'U': return C_Memory;
10501 return TargetLowering::getConstraintType(Constraint);
10504 /// Examine constraint type and operand type and determine a weight value.
10505 /// This object must already have been set up with the operand type
10506 /// and the current alternative constraint selected.
10507 TargetLowering::ConstraintWeight
10508 ARMTargetLowering::getSingleConstraintMatchWeight(
10509 AsmOperandInfo &info, const char *constraint) const {
10510 ConstraintWeight weight = CW_Invalid;
10511 Value *CallOperandVal = info.CallOperandVal;
10512 // If we don't have a value, we can't do a match,
10513 // but allow it at the lowest weight.
10514 if (!CallOperandVal)
10516 Type *type = CallOperandVal->getType();
10517 // Look at the constraint type.
10518 switch (*constraint) {
10520 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10523 if (type->isIntegerTy()) {
10524 if (Subtarget->isThumb())
10525 weight = CW_SpecificReg;
10527 weight = CW_Register;
10531 if (type->isFloatingPointTy())
10532 weight = CW_Register;
10538 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10540 ARMTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10541 const std::string &Constraint,
10543 if (Constraint.size() == 1) {
10544 // GCC ARM Constraint Letters
10545 switch (Constraint[0]) {
10546 case 'l': // Low regs or general regs.
10547 if (Subtarget->isThumb())
10548 return RCPair(0U, &ARM::tGPRRegClass);
10549 return RCPair(0U, &ARM::GPRRegClass);
10550 case 'h': // High regs or no regs.
10551 if (Subtarget->isThumb())
10552 return RCPair(0U, &ARM::hGPRRegClass);
10555 if (Subtarget->isThumb1Only())
10556 return RCPair(0U, &ARM::tGPRRegClass);
10557 return RCPair(0U, &ARM::GPRRegClass);
10559 if (VT == MVT::Other)
10561 if (VT == MVT::f32)
10562 return RCPair(0U, &ARM::SPRRegClass);
10563 if (VT.getSizeInBits() == 64)
10564 return RCPair(0U, &ARM::DPRRegClass);
10565 if (VT.getSizeInBits() == 128)
10566 return RCPair(0U, &ARM::QPRRegClass);
10569 if (VT == MVT::Other)
10571 if (VT == MVT::f32)
10572 return RCPair(0U, &ARM::SPR_8RegClass);
10573 if (VT.getSizeInBits() == 64)
10574 return RCPair(0U, &ARM::DPR_8RegClass);
10575 if (VT.getSizeInBits() == 128)
10576 return RCPair(0U, &ARM::QPR_8RegClass);
10579 if (VT == MVT::f32)
10580 return RCPair(0U, &ARM::SPRRegClass);
10584 if (StringRef("{cc}").equals_lower(Constraint))
10585 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10587 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10590 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10591 /// vector. If it is invalid, don't add anything to Ops.
10592 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10593 std::string &Constraint,
10594 std::vector<SDValue>&Ops,
10595 SelectionDAG &DAG) const {
10598 // Currently only support length 1 constraints.
10599 if (Constraint.length() != 1) return;
10601 char ConstraintLetter = Constraint[0];
10602 switch (ConstraintLetter) {
10605 case 'I': case 'J': case 'K': case 'L':
10606 case 'M': case 'N': case 'O':
10607 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10611 int64_t CVal64 = C->getSExtValue();
10612 int CVal = (int) CVal64;
10613 // None of these constraints allow values larger than 32 bits. Check
10614 // that the value fits in an int.
10615 if (CVal != CVal64)
10618 switch (ConstraintLetter) {
10620 // Constant suitable for movw, must be between 0 and
10622 if (Subtarget->hasV6T2Ops())
10623 if (CVal >= 0 && CVal <= 65535)
10627 if (Subtarget->isThumb1Only()) {
10628 // This must be a constant between 0 and 255, for ADD
10630 if (CVal >= 0 && CVal <= 255)
10632 } else if (Subtarget->isThumb2()) {
10633 // A constant that can be used as an immediate value in a
10634 // data-processing instruction.
10635 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10638 // A constant that can be used as an immediate value in a
10639 // data-processing instruction.
10640 if (ARM_AM::getSOImmVal(CVal) != -1)
10646 if (Subtarget->isThumb()) { // FIXME thumb2
10647 // This must be a constant between -255 and -1, for negated ADD
10648 // immediates. This can be used in GCC with an "n" modifier that
10649 // prints the negated value, for use with SUB instructions. It is
10650 // not useful otherwise but is implemented for compatibility.
10651 if (CVal >= -255 && CVal <= -1)
10654 // This must be a constant between -4095 and 4095. It is not clear
10655 // what this constraint is intended for. Implemented for
10656 // compatibility with GCC.
10657 if (CVal >= -4095 && CVal <= 4095)
10663 if (Subtarget->isThumb1Only()) {
10664 // A 32-bit value where only one byte has a nonzero value. Exclude
10665 // zero to match GCC. This constraint is used by GCC internally for
10666 // constants that can be loaded with a move/shift combination.
10667 // It is not useful otherwise but is implemented for compatibility.
10668 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10670 } else if (Subtarget->isThumb2()) {
10671 // A constant whose bitwise inverse can be used as an immediate
10672 // value in a data-processing instruction. This can be used in GCC
10673 // with a "B" modifier that prints the inverted value, for use with
10674 // BIC and MVN instructions. It is not useful otherwise but is
10675 // implemented for compatibility.
10676 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10679 // A constant whose bitwise inverse can be used as an immediate
10680 // value in a data-processing instruction. This can be used in GCC
10681 // with a "B" modifier that prints the inverted value, for use with
10682 // BIC and MVN instructions. It is not useful otherwise but is
10683 // implemented for compatibility.
10684 if (ARM_AM::getSOImmVal(~CVal) != -1)
10690 if (Subtarget->isThumb1Only()) {
10691 // This must be a constant between -7 and 7,
10692 // for 3-operand ADD/SUB immediate instructions.
10693 if (CVal >= -7 && CVal < 7)
10695 } else if (Subtarget->isThumb2()) {
10696 // A constant whose negation can be used as an immediate value in a
10697 // data-processing instruction. This can be used in GCC with an "n"
10698 // modifier that prints the negated value, for use with SUB
10699 // instructions. It is not useful otherwise but is implemented for
10701 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10704 // A constant whose negation can be used as an immediate value in a
10705 // data-processing instruction. This can be used in GCC with an "n"
10706 // modifier that prints the negated value, for use with SUB
10707 // instructions. It is not useful otherwise but is implemented for
10709 if (ARM_AM::getSOImmVal(-CVal) != -1)
10715 if (Subtarget->isThumb()) { // FIXME thumb2
10716 // This must be a multiple of 4 between 0 and 1020, for
10717 // ADD sp + immediate.
10718 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10721 // A power of two or a constant between 0 and 32. This is used in
10722 // GCC for the shift amount on shifted register operands, but it is
10723 // useful in general for any shift amounts.
10724 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10730 if (Subtarget->isThumb()) { // FIXME thumb2
10731 // This must be a constant between 0 and 31, for shift amounts.
10732 if (CVal >= 0 && CVal <= 31)
10738 if (Subtarget->isThumb()) { // FIXME thumb2
10739 // This must be a multiple of 4 between -508 and 508, for
10740 // ADD/SUB sp = sp + immediate.
10741 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10746 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10750 if (Result.getNode()) {
10751 Ops.push_back(Result);
10754 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10757 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10758 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10759 unsigned Opcode = Op->getOpcode();
10760 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10761 "Invalid opcode for Div/Rem lowering");
10762 bool isSigned = (Opcode == ISD::SDIVREM);
10763 EVT VT = Op->getValueType(0);
10764 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10767 switch (VT.getSimpleVT().SimpleTy) {
10768 default: llvm_unreachable("Unexpected request for libcall!");
10769 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10770 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10771 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10772 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10775 SDValue InChain = DAG.getEntryNode();
10777 TargetLowering::ArgListTy Args;
10778 TargetLowering::ArgListEntry Entry;
10779 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10780 EVT ArgVT = Op->getOperand(i).getValueType();
10781 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10782 Entry.Node = Op->getOperand(i);
10784 Entry.isSExt = isSigned;
10785 Entry.isZExt = !isSigned;
10786 Args.push_back(Entry);
10789 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10792 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10795 TargetLowering::CallLoweringInfo CLI(DAG);
10796 CLI.setDebugLoc(dl).setChain(InChain)
10797 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10798 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10800 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10801 return CallInfo.first;
10805 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10806 assert(Subtarget->isTargetWindows() && "unsupported target platform");
10810 SDValue Chain = Op.getOperand(0);
10811 SDValue Size = Op.getOperand(1);
10813 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10814 DAG.getConstant(2, MVT::i32));
10817 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10818 Flag = Chain.getValue(1);
10820 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10821 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10823 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10824 Chain = NewSP.getValue(1);
10826 SDValue Ops[2] = { NewSP, Chain };
10827 return DAG.getMergeValues(Ops, DL);
10830 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10831 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10832 "Unexpected type for custom-lowering FP_EXTEND");
10835 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10837 SDValue SrcVal = Op.getOperand(0);
10838 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10839 /*isSigned*/ false, SDLoc(Op)).first;
10842 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10843 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10844 Subtarget->isFPOnlySP() &&
10845 "Unexpected type for custom-lowering FP_ROUND");
10848 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10850 SDValue SrcVal = Op.getOperand(0);
10851 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10852 /*isSigned*/ false, SDLoc(Op)).first;
10856 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10857 // The ARM target isn't yet aware of offsets.
10861 bool ARM::isBitFieldInvertedMask(unsigned v) {
10862 if (v == 0xffffffff)
10865 // there can be 1's on either or both "outsides", all the "inside"
10866 // bits must be 0's
10867 return isShiftedMask_32(~v);
10870 /// isFPImmLegal - Returns true if the target can instruction select the
10871 /// specified FP immediate natively. If false, the legalizer will
10872 /// materialize the FP immediate as a load from a constant pool.
10873 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10874 if (!Subtarget->hasVFP3())
10876 if (VT == MVT::f32)
10877 return ARM_AM::getFP32Imm(Imm) != -1;
10878 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10879 return ARM_AM::getFP64Imm(Imm) != -1;
10883 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10884 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10885 /// specified in the intrinsic calls.
10886 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10888 unsigned Intrinsic) const {
10889 switch (Intrinsic) {
10890 case Intrinsic::arm_neon_vld1:
10891 case Intrinsic::arm_neon_vld2:
10892 case Intrinsic::arm_neon_vld3:
10893 case Intrinsic::arm_neon_vld4:
10894 case Intrinsic::arm_neon_vld2lane:
10895 case Intrinsic::arm_neon_vld3lane:
10896 case Intrinsic::arm_neon_vld4lane: {
10897 Info.opc = ISD::INTRINSIC_W_CHAIN;
10898 // Conservatively set memVT to the entire set of vectors loaded.
10899 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10900 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10901 Info.ptrVal = I.getArgOperand(0);
10903 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10904 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10905 Info.vol = false; // volatile loads with NEON intrinsics not supported
10906 Info.readMem = true;
10907 Info.writeMem = false;
10910 case Intrinsic::arm_neon_vst1:
10911 case Intrinsic::arm_neon_vst2:
10912 case Intrinsic::arm_neon_vst3:
10913 case Intrinsic::arm_neon_vst4:
10914 case Intrinsic::arm_neon_vst2lane:
10915 case Intrinsic::arm_neon_vst3lane:
10916 case Intrinsic::arm_neon_vst4lane: {
10917 Info.opc = ISD::INTRINSIC_VOID;
10918 // Conservatively set memVT to the entire set of vectors stored.
10919 unsigned NumElts = 0;
10920 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10921 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10922 if (!ArgTy->isVectorTy())
10924 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10926 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10927 Info.ptrVal = I.getArgOperand(0);
10929 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10930 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10931 Info.vol = false; // volatile stores with NEON intrinsics not supported
10932 Info.readMem = false;
10933 Info.writeMem = true;
10936 case Intrinsic::arm_ldaex:
10937 case Intrinsic::arm_ldrex: {
10938 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10939 Info.opc = ISD::INTRINSIC_W_CHAIN;
10940 Info.memVT = MVT::getVT(PtrTy->getElementType());
10941 Info.ptrVal = I.getArgOperand(0);
10943 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10945 Info.readMem = true;
10946 Info.writeMem = false;
10949 case Intrinsic::arm_stlex:
10950 case Intrinsic::arm_strex: {
10951 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10952 Info.opc = ISD::INTRINSIC_W_CHAIN;
10953 Info.memVT = MVT::getVT(PtrTy->getElementType());
10954 Info.ptrVal = I.getArgOperand(1);
10956 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10958 Info.readMem = false;
10959 Info.writeMem = true;
10962 case Intrinsic::arm_stlexd:
10963 case Intrinsic::arm_strexd: {
10964 Info.opc = ISD::INTRINSIC_W_CHAIN;
10965 Info.memVT = MVT::i64;
10966 Info.ptrVal = I.getArgOperand(2);
10970 Info.readMem = false;
10971 Info.writeMem = true;
10974 case Intrinsic::arm_ldaexd:
10975 case Intrinsic::arm_ldrexd: {
10976 Info.opc = ISD::INTRINSIC_W_CHAIN;
10977 Info.memVT = MVT::i64;
10978 Info.ptrVal = I.getArgOperand(0);
10982 Info.readMem = true;
10983 Info.writeMem = false;
10993 /// \brief Returns true if it is beneficial to convert a load of a constant
10994 /// to just the constant itself.
10995 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10997 assert(Ty->isIntegerTy());
10999 unsigned Bits = Ty->getPrimitiveSizeInBits();
11000 if (Bits == 0 || Bits > 32)
11005 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11007 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11008 ARM_MB::MemBOpt Domain) const {
11009 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11011 // First, if the target has no DMB, see what fallback we can use.
11012 if (!Subtarget->hasDataBarrier()) {
11013 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11014 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11016 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11017 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11018 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11019 Builder.getInt32(0), Builder.getInt32(7),
11020 Builder.getInt32(10), Builder.getInt32(5)};
11021 return Builder.CreateCall(MCR, args);
11023 // Instead of using barriers, atomic accesses on these subtargets use
11025 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11028 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11029 // Only a full system barrier exists in the M-class architectures.
11030 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11031 Constant *CDomain = Builder.getInt32(Domain);
11032 return Builder.CreateCall(DMB, CDomain);
11036 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11037 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11038 AtomicOrdering Ord, bool IsStore,
11039 bool IsLoad) const {
11040 if (!getInsertFencesForAtomic())
11046 llvm_unreachable("Invalid fence: unordered/non-atomic");
11049 return nullptr; // Nothing to do
11050 case SequentiallyConsistent:
11052 return nullptr; // Nothing to do
11055 case AcquireRelease:
11056 if (Subtarget->isSwift())
11057 return makeDMB(Builder, ARM_MB::ISHST);
11058 // FIXME: add a comment with a link to documentation justifying this.
11060 return makeDMB(Builder, ARM_MB::ISH);
11062 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11065 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11066 AtomicOrdering Ord, bool IsStore,
11067 bool IsLoad) const {
11068 if (!getInsertFencesForAtomic())
11074 llvm_unreachable("Invalid fence: unordered/not-atomic");
11077 return nullptr; // Nothing to do
11079 case AcquireRelease:
11080 case SequentiallyConsistent:
11081 return makeDMB(Builder, ARM_MB::ISH);
11083 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11086 // Loads and stores less than 64-bits are already atomic; ones above that
11087 // are doomed anyway, so defer to the default libcall and blame the OS when
11088 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11089 // anything for those.
11090 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11091 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11092 return (Size == 64) && !Subtarget->isMClass();
11095 // Loads and stores less than 64-bits are already atomic; ones above that
11096 // are doomed anyway, so defer to the default libcall and blame the OS when
11097 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11098 // anything for those.
11099 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11100 // guarantee, see DDI0406C ARM architecture reference manual,
11101 // sections A8.8.72-74 LDRD)
11102 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11103 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11104 return (Size == 64) && !Subtarget->isMClass();
11107 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11108 // and up to 64 bits on the non-M profiles
11109 TargetLoweringBase::AtomicRMWExpansionKind
11110 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11111 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11112 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11113 ? AtomicRMWExpansionKind::LLSC
11114 : AtomicRMWExpansionKind::None;
11117 // This has so far only been implemented for MachO.
11118 bool ARMTargetLowering::useLoadStackGuardNode() const {
11119 return Subtarget->isTargetMachO();
11122 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11123 unsigned &Cost) const {
11124 // If we do not have NEON, vector types are not natively supported.
11125 if (!Subtarget->hasNEON())
11128 // Floating point values and vector values map to the same register file.
11129 // Therefore, althought we could do a store extract of a vector type, this is
11130 // better to leave at float as we have more freedom in the addressing mode for
11132 if (VectorTy->isFPOrFPVectorTy())
11135 // If the index is unknown at compile time, this is very expensive to lower
11136 // and it is not possible to combine the store with the extract.
11137 if (!isa<ConstantInt>(Idx))
11140 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11141 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11142 // We can do a store + vector extract on any vector that fits perfectly in a D
11144 if (BitWidth == 64 || BitWidth == 128) {
11151 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11152 AtomicOrdering Ord) const {
11153 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11154 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11155 bool IsAcquire = isAtLeastAcquire(Ord);
11157 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11158 // intrinsic must return {i32, i32} and we have to recombine them into a
11159 // single i64 here.
11160 if (ValTy->getPrimitiveSizeInBits() == 64) {
11161 Intrinsic::ID Int =
11162 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11163 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11165 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11166 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11168 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11169 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11170 if (!Subtarget->isLittle())
11171 std::swap (Lo, Hi);
11172 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11173 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11174 return Builder.CreateOr(
11175 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11178 Type *Tys[] = { Addr->getType() };
11179 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11180 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11182 return Builder.CreateTruncOrBitCast(
11183 Builder.CreateCall(Ldrex, Addr),
11184 cast<PointerType>(Addr->getType())->getElementType());
11187 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11189 AtomicOrdering Ord) const {
11190 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11191 bool IsRelease = isAtLeastRelease(Ord);
11193 // Since the intrinsics must have legal type, the i64 intrinsics take two
11194 // parameters: "i32, i32". We must marshal Val into the appropriate form
11195 // before the call.
11196 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11197 Intrinsic::ID Int =
11198 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11199 Function *Strex = Intrinsic::getDeclaration(M, Int);
11200 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11202 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11203 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11204 if (!Subtarget->isLittle())
11205 std::swap (Lo, Hi);
11206 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11207 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11210 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11211 Type *Tys[] = { Addr->getType() };
11212 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11214 return Builder.CreateCall2(
11215 Strex, Builder.CreateZExtOrBitCast(
11216 Val, Strex->getFunctionType()->getParamType(0)),
11228 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11229 uint64_t &Members) {
11230 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11231 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11232 uint64_t SubMembers = 0;
11233 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11235 Members += SubMembers;
11237 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11238 uint64_t SubMembers = 0;
11239 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11241 Members += SubMembers * AT->getNumElements();
11242 } else if (Ty->isFloatTy()) {
11243 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11247 } else if (Ty->isDoubleTy()) {
11248 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11252 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11259 return VT->getBitWidth() == 64;
11261 return VT->getBitWidth() == 128;
11263 switch (VT->getBitWidth()) {
11276 return (Members > 0 && Members <= 4);
11279 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11280 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11281 /// passing according to AAPCS rules.
11282 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11283 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11284 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11285 CallingConv::ARM_AAPCS_VFP)
11288 HABaseType Base = HA_UNKNOWN;
11289 uint64_t Members = 0;
11290 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11291 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11293 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11294 return IsHA || IsIntArray;