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/IntrinsicInst.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/MC/MCSectionMachO.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Target/TargetOptions.h"
56 #define DEBUG_TYPE "arm-isel"
58 STATISTIC(NumTailCalls, "Number of tail calls");
59 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
60 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
63 EnableARMLongCalls("arm-long-calls", cl::Hidden,
64 cl::desc("Generate calls via indirect call instructions"),
68 ARMInterworking("arm-interworking", cl::Hidden,
69 cl::desc("Enable / disable ARM interworking (for debugging only)"),
73 class ARMCCState : public CCState {
75 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
76 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
78 : CCState(CC, isVarArg, MF, locs, C) {
79 assert(((PC == Call) || (PC == Prologue)) &&
80 "ARMCCState users must specify whether their context is call"
81 "or prologue generation.");
87 // The APCS parameter registers.
88 static const MCPhysReg GPRArgRegs[] = {
89 ARM::R0, ARM::R1, ARM::R2, ARM::R3
92 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
93 MVT PromotedBitwiseVT) {
94 if (VT != PromotedLdStVT) {
95 setOperationAction(ISD::LOAD, VT, Promote);
96 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
98 setOperationAction(ISD::STORE, VT, Promote);
99 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
102 MVT ElemTy = VT.getVectorElementType();
103 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
104 setOperationAction(ISD::SETCC, VT, Custom);
105 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
106 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
107 if (ElemTy == MVT::i32) {
108 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
109 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
110 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
111 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
113 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
114 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
115 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
116 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
118 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
119 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
120 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
121 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
122 setOperationAction(ISD::SELECT, VT, Expand);
123 setOperationAction(ISD::SELECT_CC, VT, Expand);
124 setOperationAction(ISD::VSELECT, VT, Expand);
125 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
126 if (VT.isInteger()) {
127 setOperationAction(ISD::SHL, VT, Custom);
128 setOperationAction(ISD::SRA, VT, Custom);
129 setOperationAction(ISD::SRL, VT, Custom);
132 // Promote all bit-wise operations.
133 if (VT.isInteger() && VT != PromotedBitwiseVT) {
134 setOperationAction(ISD::AND, VT, Promote);
135 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
136 setOperationAction(ISD::OR, VT, Promote);
137 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
138 setOperationAction(ISD::XOR, VT, Promote);
139 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
142 // Neon does not support vector divide/remainder operations.
143 setOperationAction(ISD::SDIV, VT, Expand);
144 setOperationAction(ISD::UDIV, VT, Expand);
145 setOperationAction(ISD::FDIV, VT, Expand);
146 setOperationAction(ISD::SREM, VT, Expand);
147 setOperationAction(ISD::UREM, VT, Expand);
148 setOperationAction(ISD::FREM, VT, Expand);
151 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
152 addRegisterClass(VT, &ARM::DPRRegClass);
153 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
156 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
157 addRegisterClass(VT, &ARM::DPairRegClass);
158 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
161 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
162 const ARMSubtarget &STI)
163 : TargetLowering(TM), Subtarget(&STI) {
164 RegInfo = Subtarget->getRegisterInfo();
165 Itins = Subtarget->getInstrItineraryData();
167 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
169 if (Subtarget->isTargetMachO()) {
170 // Uses VFP for Thumb libfuncs if available.
171 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
172 Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
173 // Single-precision floating-point arithmetic.
174 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
175 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
176 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
177 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
179 // Double-precision floating-point arithmetic.
180 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
181 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
182 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
183 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
185 // Single-precision comparisons.
186 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
187 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
188 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
189 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
190 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
191 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
192 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
193 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
195 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
196 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
197 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
198 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
199 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
200 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
201 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
202 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
204 // Double-precision comparisons.
205 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
206 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
207 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
208 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
209 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
210 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
211 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
212 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
214 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
215 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
216 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
217 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
218 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
219 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
220 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
221 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
223 // Floating-point to integer conversions.
224 // i64 conversions are done via library routines even when generating VFP
225 // instructions, so use the same ones.
226 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
227 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
228 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
229 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
231 // Conversions between floating types.
232 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
233 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
235 // Integer to floating-point conversions.
236 // i64 conversions are done via library routines even when generating VFP
237 // instructions, so use the same ones.
238 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
239 // e.g., __floatunsidf vs. __floatunssidfvfp.
240 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
241 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
242 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
243 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
247 // These libcalls are not available in 32-bit.
248 setLibcallName(RTLIB::SHL_I128, nullptr);
249 setLibcallName(RTLIB::SRL_I128, nullptr);
250 setLibcallName(RTLIB::SRA_I128, nullptr);
252 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
253 !Subtarget->isTargetWindows()) {
254 static const struct {
255 const RTLIB::Libcall Op;
256 const char * const Name;
257 const CallingConv::ID CC;
258 const ISD::CondCode Cond;
260 // Double-precision floating-point arithmetic helper functions
261 // RTABI chapter 4.1.2, Table 2
262 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
263 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
267 // Double-precision floating-point comparison helper functions
268 // RTABI chapter 4.1.2, Table 3
269 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
270 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
271 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
272 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
273 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
274 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
275 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
276 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
278 // Single-precision floating-point arithmetic helper functions
279 // RTABI chapter 4.1.2, Table 4
280 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
281 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
285 // Single-precision floating-point comparison helper functions
286 // RTABI chapter 4.1.2, Table 5
287 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
288 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
289 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
290 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
291 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
292 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
293 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
294 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
296 // Floating-point to integer conversions.
297 // RTABI chapter 4.1.2, Table 6
298 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307 // Conversions between floating types.
308 // RTABI chapter 4.1.2, Table 7
309 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313 // Integer to floating-point conversions.
314 // RTABI chapter 4.1.2, Table 8
315 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324 // Long long helper functions
325 // RTABI chapter 4.2, Table 9
326 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331 // Integer division functions
332 // RTABI chapter 4.3.1
333 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343 // RTABI chapter 4.3.4
344 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
349 for (const auto &LC : LibraryCalls) {
350 setLibcallName(LC.Op, LC.Name);
351 setLibcallCallingConv(LC.Op, LC.CC);
352 if (LC.Cond != ISD::SETCC_INVALID)
353 setCmpLibcallCC(LC.Op, LC.Cond);
357 if (Subtarget->isTargetWindows()) {
358 static const struct {
359 const RTLIB::Libcall Op;
360 const char * const Name;
361 const CallingConv::ID CC;
363 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
364 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
365 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
366 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
367 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
368 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
369 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
370 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
373 for (const auto &LC : LibraryCalls) {
374 setLibcallName(LC.Op, LC.Name);
375 setLibcallCallingConv(LC.Op, LC.CC);
379 // Use divmod compiler-rt calls for iOS 5.0 and later.
380 if (Subtarget->getTargetTriple().isiOS() &&
381 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
382 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
383 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
386 // The half <-> float conversion functions are always soft-float, but are
387 // needed for some targets which use a hard-float calling convention by
389 if (Subtarget->isAAPCS_ABI()) {
390 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
394 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
395 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
396 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
399 if (Subtarget->isThumb1Only())
400 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
402 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
403 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
404 !Subtarget->isThumb1Only()) {
405 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
406 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
409 for (MVT VT : MVT::vector_valuetypes()) {
410 for (MVT InnerVT : MVT::vector_valuetypes()) {
411 setTruncStoreAction(VT, InnerVT, Expand);
412 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
413 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
414 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
417 setOperationAction(ISD::MULHS, VT, Expand);
418 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
419 setOperationAction(ISD::MULHU, VT, Expand);
420 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
422 setOperationAction(ISD::BSWAP, VT, Expand);
425 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
426 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
428 if (Subtarget->hasNEON()) {
429 addDRTypeForNEON(MVT::v2f32);
430 addDRTypeForNEON(MVT::v8i8);
431 addDRTypeForNEON(MVT::v4i16);
432 addDRTypeForNEON(MVT::v2i32);
433 addDRTypeForNEON(MVT::v1i64);
435 addQRTypeForNEON(MVT::v4f32);
436 addQRTypeForNEON(MVT::v2f64);
437 addQRTypeForNEON(MVT::v16i8);
438 addQRTypeForNEON(MVT::v8i16);
439 addQRTypeForNEON(MVT::v4i32);
440 addQRTypeForNEON(MVT::v2i64);
442 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
443 // neither Neon nor VFP support any arithmetic operations on it.
444 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
445 // supported for v4f32.
446 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
447 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
448 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
449 // FIXME: Code duplication: FDIV and FREM are expanded always, see
450 // ARMTargetLowering::addTypeForNEON method for details.
451 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
452 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
453 // FIXME: Create unittest.
454 // In another words, find a way when "copysign" appears in DAG with vector
456 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
457 // FIXME: Code duplication: SETCC has custom operation action, see
458 // ARMTargetLowering::addTypeForNEON method for details.
459 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
460 // FIXME: Create unittest for FNEG and for FABS.
461 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
462 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
463 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
464 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
465 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
466 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
467 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
468 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
469 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
470 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
471 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
472 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
473 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
474 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
475 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
476 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
477 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
478 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
479 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
481 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
482 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
483 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
484 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
485 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
486 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
487 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
488 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
489 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
490 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
491 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
492 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
493 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
494 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
495 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
497 // Mark v2f32 intrinsics.
498 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
499 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
500 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
501 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
502 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
503 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
504 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
505 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
506 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
507 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
508 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
509 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
510 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
511 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
512 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
514 // Neon does not support some operations on v1i64 and v2i64 types.
515 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
516 // Custom handling for some quad-vector types to detect VMULL.
517 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
518 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
519 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
520 // Custom handling for some vector types to avoid expensive expansions
521 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
522 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
523 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
524 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
525 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
526 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
527 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
528 // a destination type that is wider than the source, and nor does
529 // it have a FP_TO_[SU]INT instruction with a narrower destination than
531 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
532 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
533 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
534 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
536 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
537 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
539 // NEON does not have single instruction CTPOP for vectors with element
540 // types wider than 8-bits. However, custom lowering can leverage the
541 // v8i8/v16i8 vcnt instruction.
542 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
543 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
544 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
545 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
547 // NEON only has FMA instructions as of VFP4.
548 if (!Subtarget->hasVFP4()) {
549 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
550 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
553 setTargetDAGCombine(ISD::INTRINSIC_VOID);
554 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
555 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
556 setTargetDAGCombine(ISD::SHL);
557 setTargetDAGCombine(ISD::SRL);
558 setTargetDAGCombine(ISD::SRA);
559 setTargetDAGCombine(ISD::SIGN_EXTEND);
560 setTargetDAGCombine(ISD::ZERO_EXTEND);
561 setTargetDAGCombine(ISD::ANY_EXTEND);
562 setTargetDAGCombine(ISD::SELECT_CC);
563 setTargetDAGCombine(ISD::BUILD_VECTOR);
564 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
565 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
566 setTargetDAGCombine(ISD::STORE);
567 setTargetDAGCombine(ISD::FP_TO_SINT);
568 setTargetDAGCombine(ISD::FP_TO_UINT);
569 setTargetDAGCombine(ISD::FDIV);
570 setTargetDAGCombine(ISD::LOAD);
572 // It is legal to extload from v4i8 to v4i16 or v4i32.
573 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
575 for (MVT VT : MVT::integer_vector_valuetypes()) {
576 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
577 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
578 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
583 // ARM and Thumb2 support UMLAL/SMLAL.
584 if (!Subtarget->isThumb1Only())
585 setTargetDAGCombine(ISD::ADDC);
587 if (Subtarget->isFPOnlySP()) {
588 // When targetting a floating-point unit with only single-precision
589 // operations, f64 is legal for the few double-precision instructions which
590 // are present However, no double-precision operations other than moves,
591 // loads and stores are provided by the hardware.
592 setOperationAction(ISD::FADD, MVT::f64, Expand);
593 setOperationAction(ISD::FSUB, MVT::f64, Expand);
594 setOperationAction(ISD::FMUL, MVT::f64, Expand);
595 setOperationAction(ISD::FMA, MVT::f64, Expand);
596 setOperationAction(ISD::FDIV, MVT::f64, Expand);
597 setOperationAction(ISD::FREM, MVT::f64, Expand);
598 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
599 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
600 setOperationAction(ISD::FNEG, MVT::f64, Expand);
601 setOperationAction(ISD::FABS, MVT::f64, Expand);
602 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
603 setOperationAction(ISD::FSIN, MVT::f64, Expand);
604 setOperationAction(ISD::FCOS, MVT::f64, Expand);
605 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
606 setOperationAction(ISD::FPOW, MVT::f64, Expand);
607 setOperationAction(ISD::FLOG, MVT::f64, Expand);
608 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
609 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
610 setOperationAction(ISD::FEXP, MVT::f64, Expand);
611 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
612 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
613 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
614 setOperationAction(ISD::FRINT, MVT::f64, Expand);
615 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
616 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
617 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
618 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
619 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
620 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
621 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
622 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
623 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
624 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
627 computeRegisterProperties(Subtarget->getRegisterInfo());
629 // ARM does not have floating-point extending loads.
630 for (MVT VT : MVT::fp_valuetypes()) {
631 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
632 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
635 // ... or truncating stores
636 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
637 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
638 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
640 // ARM does not have i1 sign extending load.
641 for (MVT VT : MVT::integer_valuetypes())
642 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
644 // ARM supports all 4 flavors of integer indexed load / store.
645 if (!Subtarget->isThumb1Only()) {
646 for (unsigned im = (unsigned)ISD::PRE_INC;
647 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
648 setIndexedLoadAction(im, MVT::i1, Legal);
649 setIndexedLoadAction(im, MVT::i8, Legal);
650 setIndexedLoadAction(im, MVT::i16, Legal);
651 setIndexedLoadAction(im, MVT::i32, Legal);
652 setIndexedStoreAction(im, MVT::i1, Legal);
653 setIndexedStoreAction(im, MVT::i8, Legal);
654 setIndexedStoreAction(im, MVT::i16, Legal);
655 setIndexedStoreAction(im, MVT::i32, Legal);
659 setOperationAction(ISD::SADDO, MVT::i32, Custom);
660 setOperationAction(ISD::UADDO, MVT::i32, Custom);
661 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
662 setOperationAction(ISD::USUBO, MVT::i32, Custom);
664 // i64 operation support.
665 setOperationAction(ISD::MUL, MVT::i64, Expand);
666 setOperationAction(ISD::MULHU, MVT::i32, Expand);
667 if (Subtarget->isThumb1Only()) {
668 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
669 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
671 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
672 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
673 setOperationAction(ISD::MULHS, MVT::i32, Expand);
675 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
676 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
677 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
678 setOperationAction(ISD::SRL, MVT::i64, Custom);
679 setOperationAction(ISD::SRA, MVT::i64, Custom);
681 if (!Subtarget->isThumb1Only()) {
682 // FIXME: We should do this for Thumb1 as well.
683 setOperationAction(ISD::ADDC, MVT::i32, Custom);
684 setOperationAction(ISD::ADDE, MVT::i32, Custom);
685 setOperationAction(ISD::SUBC, MVT::i32, Custom);
686 setOperationAction(ISD::SUBE, MVT::i32, Custom);
689 // ARM does not have ROTL.
690 setOperationAction(ISD::ROTL, MVT::i32, Expand);
691 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
692 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
693 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
694 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
696 // These just redirect to CTTZ and CTLZ on ARM.
697 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
698 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
700 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
702 // Only ARMv6 has BSWAP.
703 if (!Subtarget->hasV6Ops())
704 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
706 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
707 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
708 // These are expanded into libcalls if the cpu doesn't have HW divider.
709 setOperationAction(ISD::SDIV, MVT::i32, Expand);
710 setOperationAction(ISD::UDIV, MVT::i32, Expand);
713 // FIXME: Also set divmod for SREM on EABI
714 setOperationAction(ISD::SREM, MVT::i32, Expand);
715 setOperationAction(ISD::UREM, MVT::i32, Expand);
716 // Register based DivRem for AEABI (RTABI 4.2)
717 if (Subtarget->isTargetAEABI()) {
718 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
719 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
720 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
721 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
722 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
723 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
724 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
725 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
727 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
728 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
729 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
730 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
731 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
732 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
733 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
734 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
736 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
737 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
739 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
740 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
743 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
744 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
745 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
746 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
747 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
749 setOperationAction(ISD::TRAP, MVT::Other, Legal);
751 // Use the default implementation.
752 setOperationAction(ISD::VASTART, MVT::Other, Custom);
753 setOperationAction(ISD::VAARG, MVT::Other, Expand);
754 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
755 setOperationAction(ISD::VAEND, MVT::Other, Expand);
756 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
757 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
759 if (!Subtarget->isTargetMachO()) {
760 // Non-MachO platforms may return values in these registers via the
761 // personality function.
762 setExceptionPointerRegister(ARM::R0);
763 setExceptionSelectorRegister(ARM::R1);
766 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
767 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
769 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
771 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
772 // the default expansion. If we are targeting a single threaded system,
773 // then set them all for expand so we can lower them later into their
775 if (TM.Options.ThreadModel == ThreadModel::Single)
776 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
777 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
778 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
779 // to ldrex/strex loops already.
780 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
782 // On v8, we have particularly efficient implementations of atomic fences
783 // if they can be combined with nearby atomic loads and stores.
784 if (!Subtarget->hasV8Ops()) {
785 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
786 setInsertFencesForAtomic(true);
789 // If there's anything we can use as a barrier, go through custom lowering
791 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
792 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
794 // Set them all for expansion, which will force libcalls.
795 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
796 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
797 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
798 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
799 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
800 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
801 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
802 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
803 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
804 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
805 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
806 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
807 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
808 // Unordered/Monotonic case.
809 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
810 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
813 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
815 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
816 if (!Subtarget->hasV6Ops()) {
817 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
818 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
820 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
822 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
823 !Subtarget->isThumb1Only()) {
824 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
825 // iff target supports vfp2.
826 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
827 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
830 // We want to custom lower some of our intrinsics.
831 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
832 if (Subtarget->isTargetDarwin()) {
833 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
834 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
835 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
838 setOperationAction(ISD::SETCC, MVT::i32, Expand);
839 setOperationAction(ISD::SETCC, MVT::f32, Expand);
840 setOperationAction(ISD::SETCC, MVT::f64, Expand);
841 setOperationAction(ISD::SELECT, MVT::i32, Custom);
842 setOperationAction(ISD::SELECT, MVT::f32, Custom);
843 setOperationAction(ISD::SELECT, MVT::f64, Custom);
844 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
845 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
846 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
848 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
849 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
850 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
851 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
852 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
854 // We don't support sin/cos/fmod/copysign/pow
855 setOperationAction(ISD::FSIN, MVT::f64, Expand);
856 setOperationAction(ISD::FSIN, MVT::f32, Expand);
857 setOperationAction(ISD::FCOS, MVT::f32, Expand);
858 setOperationAction(ISD::FCOS, MVT::f64, Expand);
859 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
860 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
861 setOperationAction(ISD::FREM, MVT::f64, Expand);
862 setOperationAction(ISD::FREM, MVT::f32, Expand);
863 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
864 !Subtarget->isThumb1Only()) {
865 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
866 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
868 setOperationAction(ISD::FPOW, MVT::f64, Expand);
869 setOperationAction(ISD::FPOW, MVT::f32, Expand);
871 if (!Subtarget->hasVFP4()) {
872 setOperationAction(ISD::FMA, MVT::f64, Expand);
873 setOperationAction(ISD::FMA, MVT::f32, Expand);
876 // Various VFP goodness
877 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
878 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
879 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
880 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
881 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
884 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
885 if (!Subtarget->hasFP16()) {
886 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
887 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
891 // Combine sin / cos into one node or libcall if possible.
892 if (Subtarget->hasSinCos()) {
893 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
894 setLibcallName(RTLIB::SINCOS_F64, "sincos");
895 if (Subtarget->getTargetTriple().isiOS()) {
896 // For iOS, we don't want to the normal expansion of a libcall to
897 // sincos. We want to issue a libcall to __sincos_stret.
898 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
899 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
903 // FP-ARMv8 implements a lot of rounding-like FP operations.
904 if (Subtarget->hasFPARMv8()) {
905 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
906 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
907 setOperationAction(ISD::FROUND, MVT::f32, Legal);
908 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
909 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
910 setOperationAction(ISD::FRINT, MVT::f32, Legal);
911 if (!Subtarget->isFPOnlySP()) {
912 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
913 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
914 setOperationAction(ISD::FROUND, MVT::f64, Legal);
915 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
916 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
917 setOperationAction(ISD::FRINT, MVT::f64, Legal);
920 // We have target-specific dag combine patterns for the following nodes:
921 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
922 setTargetDAGCombine(ISD::ADD);
923 setTargetDAGCombine(ISD::SUB);
924 setTargetDAGCombine(ISD::MUL);
925 setTargetDAGCombine(ISD::AND);
926 setTargetDAGCombine(ISD::OR);
927 setTargetDAGCombine(ISD::XOR);
929 if (Subtarget->hasV6Ops())
930 setTargetDAGCombine(ISD::SRL);
932 setStackPointerRegisterToSaveRestore(ARM::SP);
934 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
935 !Subtarget->hasVFP2())
936 setSchedulingPreference(Sched::RegPressure);
938 setSchedulingPreference(Sched::Hybrid);
940 //// temporary - rewrite interface to use type
941 MaxStoresPerMemset = 8;
942 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
943 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
944 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
945 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
946 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
948 // On ARM arguments smaller than 4 bytes are extended, so all arguments
949 // are at least 4 bytes aligned.
950 setMinStackArgumentAlignment(4);
952 // Prefer likely predicted branches to selects on out-of-order cores.
953 PredictableSelectIsExpensive = Subtarget->isLikeA9();
955 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
958 // FIXME: It might make sense to define the representative register class as the
959 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
960 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
961 // SPR's representative would be DPR_VFP2. This should work well if register
962 // pressure tracking were modified such that a register use would increment the
963 // pressure of the register class's representative and all of it's super
964 // classes' representatives transitively. We have not implemented this because
965 // of the difficulty prior to coalescing of modeling operand register classes
966 // due to the common occurrence of cross class copies and subregister insertions
968 std::pair<const TargetRegisterClass *, uint8_t>
969 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
971 const TargetRegisterClass *RRC = nullptr;
973 switch (VT.SimpleTy) {
975 return TargetLowering::findRepresentativeClass(TRI, VT);
976 // Use DPR as representative register class for all floating point
977 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
978 // the cost is 1 for both f32 and f64.
979 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
980 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
981 RRC = &ARM::DPRRegClass;
982 // When NEON is used for SP, only half of the register file is available
983 // because operations that define both SP and DP results will be constrained
984 // to the VFP2 class (D0-D15). We currently model this constraint prior to
985 // coalescing by double-counting the SP regs. See the FIXME above.
986 if (Subtarget->useNEONForSinglePrecisionFP())
989 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
990 case MVT::v4f32: case MVT::v2f64:
991 RRC = &ARM::DPRRegClass;
995 RRC = &ARM::DPRRegClass;
999 RRC = &ARM::DPRRegClass;
1003 return std::make_pair(RRC, Cost);
1006 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1008 default: return nullptr;
1009 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1010 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1011 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1012 case ARMISD::CALL: return "ARMISD::CALL";
1013 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1014 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1015 case ARMISD::tCALL: return "ARMISD::tCALL";
1016 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1017 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1018 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1019 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1020 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1021 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1022 case ARMISD::CMP: return "ARMISD::CMP";
1023 case ARMISD::CMN: return "ARMISD::CMN";
1024 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1025 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1026 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1027 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1028 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1030 case ARMISD::CMOV: return "ARMISD::CMOV";
1032 case ARMISD::RBIT: return "ARMISD::RBIT";
1034 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1035 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1036 case ARMISD::RRX: return "ARMISD::RRX";
1038 case ARMISD::ADDC: return "ARMISD::ADDC";
1039 case ARMISD::ADDE: return "ARMISD::ADDE";
1040 case ARMISD::SUBC: return "ARMISD::SUBC";
1041 case ARMISD::SUBE: return "ARMISD::SUBE";
1043 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1044 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1046 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1047 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1049 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1051 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1053 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1055 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1057 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1059 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1061 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1062 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1063 case ARMISD::VCGE: return "ARMISD::VCGE";
1064 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1065 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1066 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1067 case ARMISD::VCGT: return "ARMISD::VCGT";
1068 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1069 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1070 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1071 case ARMISD::VTST: return "ARMISD::VTST";
1073 case ARMISD::VSHL: return "ARMISD::VSHL";
1074 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1075 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1076 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1077 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1078 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1079 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1080 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1081 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1082 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1083 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1084 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1085 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1086 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1087 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1088 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1089 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1090 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1091 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1092 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1093 case ARMISD::VDUP: return "ARMISD::VDUP";
1094 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1095 case ARMISD::VEXT: return "ARMISD::VEXT";
1096 case ARMISD::VREV64: return "ARMISD::VREV64";
1097 case ARMISD::VREV32: return "ARMISD::VREV32";
1098 case ARMISD::VREV16: return "ARMISD::VREV16";
1099 case ARMISD::VZIP: return "ARMISD::VZIP";
1100 case ARMISD::VUZP: return "ARMISD::VUZP";
1101 case ARMISD::VTRN: return "ARMISD::VTRN";
1102 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1103 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1104 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1105 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1106 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1107 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1108 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1109 case ARMISD::FMAX: return "ARMISD::FMAX";
1110 case ARMISD::FMIN: return "ARMISD::FMIN";
1111 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1112 case ARMISD::VMINNM: return "ARMISD::VMIN";
1113 case ARMISD::BFI: return "ARMISD::BFI";
1114 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1115 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1116 case ARMISD::VBSL: return "ARMISD::VBSL";
1117 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1118 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1119 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1120 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1121 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1122 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1123 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1124 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1125 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1126 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1127 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1128 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1129 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1130 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1131 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1132 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1133 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1134 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1135 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1136 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1140 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1141 if (!VT.isVector()) return getPointerTy();
1142 return VT.changeVectorElementTypeToInteger();
1145 /// getRegClassFor - Return the register class that should be used for the
1146 /// specified value type.
1147 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1148 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1149 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1150 // load / store 4 to 8 consecutive D registers.
1151 if (Subtarget->hasNEON()) {
1152 if (VT == MVT::v4i64)
1153 return &ARM::QQPRRegClass;
1154 if (VT == MVT::v8i64)
1155 return &ARM::QQQQPRRegClass;
1157 return TargetLowering::getRegClassFor(VT);
1160 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1161 // source/dest is aligned and the copy size is large enough. We therefore want
1162 // to align such objects passed to memory intrinsics.
1163 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1164 unsigned &PrefAlign) const {
1165 if (!isa<MemIntrinsic>(CI))
1168 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1169 // cycle faster than 4-byte aligned LDM.
1170 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1174 // Create a fast isel object.
1176 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1177 const TargetLibraryInfo *libInfo) const {
1178 return ARM::createFastISel(funcInfo, libInfo);
1181 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1182 unsigned NumVals = N->getNumValues();
1184 return Sched::RegPressure;
1186 for (unsigned i = 0; i != NumVals; ++i) {
1187 EVT VT = N->getValueType(i);
1188 if (VT == MVT::Glue || VT == MVT::Other)
1190 if (VT.isFloatingPoint() || VT.isVector())
1194 if (!N->isMachineOpcode())
1195 return Sched::RegPressure;
1197 // Load are scheduled for latency even if there instruction itinerary
1198 // is not available.
1199 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1200 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1202 if (MCID.getNumDefs() == 0)
1203 return Sched::RegPressure;
1204 if (!Itins->isEmpty() &&
1205 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1208 return Sched::RegPressure;
1211 //===----------------------------------------------------------------------===//
1213 //===----------------------------------------------------------------------===//
1215 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1216 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1218 default: llvm_unreachable("Unknown condition code!");
1219 case ISD::SETNE: return ARMCC::NE;
1220 case ISD::SETEQ: return ARMCC::EQ;
1221 case ISD::SETGT: return ARMCC::GT;
1222 case ISD::SETGE: return ARMCC::GE;
1223 case ISD::SETLT: return ARMCC::LT;
1224 case ISD::SETLE: return ARMCC::LE;
1225 case ISD::SETUGT: return ARMCC::HI;
1226 case ISD::SETUGE: return ARMCC::HS;
1227 case ISD::SETULT: return ARMCC::LO;
1228 case ISD::SETULE: return ARMCC::LS;
1232 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1233 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1234 ARMCC::CondCodes &CondCode2) {
1235 CondCode2 = ARMCC::AL;
1237 default: llvm_unreachable("Unknown FP condition!");
1239 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1241 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1243 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1244 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1245 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1246 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1247 case ISD::SETO: CondCode = ARMCC::VC; break;
1248 case ISD::SETUO: CondCode = ARMCC::VS; break;
1249 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1250 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1251 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1253 case ISD::SETULT: CondCode = ARMCC::LT; break;
1255 case ISD::SETULE: CondCode = ARMCC::LE; break;
1257 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1261 //===----------------------------------------------------------------------===//
1262 // Calling Convention Implementation
1263 //===----------------------------------------------------------------------===//
1265 #include "ARMGenCallingConv.inc"
1267 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1268 /// account presence of floating point hardware and calling convention
1269 /// limitations, such as support for variadic functions.
1271 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1272 bool isVarArg) const {
1275 llvm_unreachable("Unsupported calling convention");
1276 case CallingConv::ARM_AAPCS:
1277 case CallingConv::ARM_APCS:
1278 case CallingConv::GHC:
1280 case CallingConv::ARM_AAPCS_VFP:
1281 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1282 case CallingConv::C:
1283 if (!Subtarget->isAAPCS_ABI())
1284 return CallingConv::ARM_APCS;
1285 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1286 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1288 return CallingConv::ARM_AAPCS_VFP;
1290 return CallingConv::ARM_AAPCS;
1291 case CallingConv::Fast:
1292 if (!Subtarget->isAAPCS_ABI()) {
1293 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1294 return CallingConv::Fast;
1295 return CallingConv::ARM_APCS;
1296 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1297 return CallingConv::ARM_AAPCS_VFP;
1299 return CallingConv::ARM_AAPCS;
1303 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1304 /// CallingConvention.
1305 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1307 bool isVarArg) const {
1308 switch (getEffectiveCallingConv(CC, isVarArg)) {
1310 llvm_unreachable("Unsupported calling convention");
1311 case CallingConv::ARM_APCS:
1312 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1313 case CallingConv::ARM_AAPCS:
1314 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1315 case CallingConv::ARM_AAPCS_VFP:
1316 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1317 case CallingConv::Fast:
1318 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1319 case CallingConv::GHC:
1320 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1324 /// LowerCallResult - Lower the result values of a call into the
1325 /// appropriate copies out of appropriate physical registers.
1327 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1328 CallingConv::ID CallConv, bool isVarArg,
1329 const SmallVectorImpl<ISD::InputArg> &Ins,
1330 SDLoc dl, SelectionDAG &DAG,
1331 SmallVectorImpl<SDValue> &InVals,
1332 bool isThisReturn, SDValue ThisVal) const {
1334 // Assign locations to each value returned by this call.
1335 SmallVector<CCValAssign, 16> RVLocs;
1336 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1337 *DAG.getContext(), Call);
1338 CCInfo.AnalyzeCallResult(Ins,
1339 CCAssignFnForNode(CallConv, /* Return*/ true,
1342 // Copy all of the result registers out of their specified physreg.
1343 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1344 CCValAssign VA = RVLocs[i];
1346 // Pass 'this' value directly from the argument to return value, to avoid
1347 // reg unit interference
1348 if (i == 0 && isThisReturn) {
1349 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1350 "unexpected return calling convention register assignment");
1351 InVals.push_back(ThisVal);
1356 if (VA.needsCustom()) {
1357 // Handle f64 or half of a v2f64.
1358 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1360 Chain = Lo.getValue(1);
1361 InFlag = Lo.getValue(2);
1362 VA = RVLocs[++i]; // skip ahead to next loc
1363 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1365 Chain = Hi.getValue(1);
1366 InFlag = Hi.getValue(2);
1367 if (!Subtarget->isLittle())
1369 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1371 if (VA.getLocVT() == MVT::v2f64) {
1372 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1373 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1374 DAG.getConstant(0, MVT::i32));
1376 VA = RVLocs[++i]; // skip ahead to next loc
1377 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1378 Chain = Lo.getValue(1);
1379 InFlag = Lo.getValue(2);
1380 VA = RVLocs[++i]; // skip ahead to next loc
1381 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1382 Chain = Hi.getValue(1);
1383 InFlag = Hi.getValue(2);
1384 if (!Subtarget->isLittle())
1386 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1387 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1388 DAG.getConstant(1, MVT::i32));
1391 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1393 Chain = Val.getValue(1);
1394 InFlag = Val.getValue(2);
1397 switch (VA.getLocInfo()) {
1398 default: llvm_unreachable("Unknown loc info!");
1399 case CCValAssign::Full: break;
1400 case CCValAssign::BCvt:
1401 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1405 InVals.push_back(Val);
1411 /// LowerMemOpCallTo - Store the argument to the stack.
1413 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1414 SDValue StackPtr, SDValue Arg,
1415 SDLoc dl, SelectionDAG &DAG,
1416 const CCValAssign &VA,
1417 ISD::ArgFlagsTy Flags) const {
1418 unsigned LocMemOffset = VA.getLocMemOffset();
1419 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1420 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1421 return DAG.getStore(Chain, dl, Arg, PtrOff,
1422 MachinePointerInfo::getStack(LocMemOffset),
1426 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1427 SDValue Chain, SDValue &Arg,
1428 RegsToPassVector &RegsToPass,
1429 CCValAssign &VA, CCValAssign &NextVA,
1431 SmallVectorImpl<SDValue> &MemOpChains,
1432 ISD::ArgFlagsTy Flags) const {
1434 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1435 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1436 unsigned id = Subtarget->isLittle() ? 0 : 1;
1437 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1439 if (NextVA.isRegLoc())
1440 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1442 assert(NextVA.isMemLoc());
1443 if (!StackPtr.getNode())
1444 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1446 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1452 /// LowerCall - Lowering a call into a callseq_start <-
1453 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1456 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1457 SmallVectorImpl<SDValue> &InVals) const {
1458 SelectionDAG &DAG = CLI.DAG;
1460 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1461 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1462 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1463 SDValue Chain = CLI.Chain;
1464 SDValue Callee = CLI.Callee;
1465 bool &isTailCall = CLI.IsTailCall;
1466 CallingConv::ID CallConv = CLI.CallConv;
1467 bool doesNotRet = CLI.DoesNotReturn;
1468 bool isVarArg = CLI.IsVarArg;
1470 MachineFunction &MF = DAG.getMachineFunction();
1471 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1472 bool isThisReturn = false;
1473 bool isSibCall = false;
1475 // Disable tail calls if they're not supported.
1476 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1480 // Check if it's really possible to do a tail call.
1481 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1482 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1483 Outs, OutVals, Ins, DAG);
1484 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1485 report_fatal_error("failed to perform tail call elimination on a call "
1486 "site marked musttail");
1487 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1488 // detected sibcalls.
1495 // Analyze operands of the call, assigning locations to each operand.
1496 SmallVector<CCValAssign, 16> ArgLocs;
1497 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1498 *DAG.getContext(), Call);
1499 CCInfo.AnalyzeCallOperands(Outs,
1500 CCAssignFnForNode(CallConv, /* Return*/ false,
1503 // Get a count of how many bytes are to be pushed on the stack.
1504 unsigned NumBytes = CCInfo.getNextStackOffset();
1506 // For tail calls, memory operands are available in our caller's stack.
1510 // Adjust the stack pointer for the new arguments...
1511 // These operations are automatically eliminated by the prolog/epilog pass
1513 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1516 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1518 RegsToPassVector RegsToPass;
1519 SmallVector<SDValue, 8> MemOpChains;
1521 // Walk the register/memloc assignments, inserting copies/loads. In the case
1522 // of tail call optimization, arguments are handled later.
1523 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1525 ++i, ++realArgIdx) {
1526 CCValAssign &VA = ArgLocs[i];
1527 SDValue Arg = OutVals[realArgIdx];
1528 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1529 bool isByVal = Flags.isByVal();
1531 // Promote the value if needed.
1532 switch (VA.getLocInfo()) {
1533 default: llvm_unreachable("Unknown loc info!");
1534 case CCValAssign::Full: break;
1535 case CCValAssign::SExt:
1536 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1538 case CCValAssign::ZExt:
1539 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1541 case CCValAssign::AExt:
1542 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1544 case CCValAssign::BCvt:
1545 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1549 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1550 if (VA.needsCustom()) {
1551 if (VA.getLocVT() == MVT::v2f64) {
1552 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1553 DAG.getConstant(0, MVT::i32));
1554 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1555 DAG.getConstant(1, MVT::i32));
1557 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1558 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1560 VA = ArgLocs[++i]; // skip ahead to next loc
1561 if (VA.isRegLoc()) {
1562 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1563 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1565 assert(VA.isMemLoc());
1567 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1568 dl, DAG, VA, Flags));
1571 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1572 StackPtr, MemOpChains, Flags);
1574 } else if (VA.isRegLoc()) {
1575 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1576 assert(VA.getLocVT() == MVT::i32 &&
1577 "unexpected calling convention register assignment");
1578 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1579 "unexpected use of 'returned'");
1580 isThisReturn = true;
1582 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1583 } else if (isByVal) {
1584 assert(VA.isMemLoc());
1585 unsigned offset = 0;
1587 // True if this byval aggregate will be split between registers
1589 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1590 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1592 if (CurByValIdx < ByValArgsCount) {
1594 unsigned RegBegin, RegEnd;
1595 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1597 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1599 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1600 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1601 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1602 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1603 MachinePointerInfo(),
1604 false, false, false,
1605 DAG.InferPtrAlignment(AddArg));
1606 MemOpChains.push_back(Load.getValue(1));
1607 RegsToPass.push_back(std::make_pair(j, Load));
1610 // If parameter size outsides register area, "offset" value
1611 // helps us to calculate stack slot for remained part properly.
1612 offset = RegEnd - RegBegin;
1614 CCInfo.nextInRegsParam();
1617 if (Flags.getByValSize() > 4*offset) {
1618 unsigned LocMemOffset = VA.getLocMemOffset();
1619 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1620 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1622 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1623 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1624 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1626 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1628 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1629 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1630 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1633 } else if (!isSibCall) {
1634 assert(VA.isMemLoc());
1636 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1637 dl, DAG, VA, Flags));
1641 if (!MemOpChains.empty())
1642 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1644 // Build a sequence of copy-to-reg nodes chained together with token chain
1645 // and flag operands which copy the outgoing args into the appropriate regs.
1647 // Tail call byval lowering might overwrite argument registers so in case of
1648 // tail call optimization the copies to registers are lowered later.
1650 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1651 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1652 RegsToPass[i].second, InFlag);
1653 InFlag = Chain.getValue(1);
1656 // For tail calls lower the arguments to the 'real' stack slot.
1658 // Force all the incoming stack arguments to be loaded from the stack
1659 // before any new outgoing arguments are stored to the stack, because the
1660 // outgoing stack slots may alias the incoming argument stack slots, and
1661 // the alias isn't otherwise explicit. This is slightly more conservative
1662 // than necessary, because it means that each store effectively depends
1663 // on every argument instead of just those arguments it would clobber.
1665 // Do not flag preceding copytoreg stuff together with the following stuff.
1667 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1668 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1669 RegsToPass[i].second, InFlag);
1670 InFlag = Chain.getValue(1);
1675 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1676 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1677 // node so that legalize doesn't hack it.
1678 bool isDirect = false;
1679 bool isARMFunc = false;
1680 bool isLocalARMFunc = false;
1681 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1683 if (EnableARMLongCalls) {
1684 assert((Subtarget->isTargetWindows() ||
1685 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1686 "long-calls with non-static relocation model!");
1687 // Handle a global address or an external symbol. If it's not one of
1688 // those, the target's already in a register, so we don't need to do
1690 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1691 const GlobalValue *GV = G->getGlobal();
1692 // Create a constant pool entry for the callee address
1693 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1694 ARMConstantPoolValue *CPV =
1695 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1697 // Get the address of the callee into a register
1698 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1699 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1700 Callee = DAG.getLoad(getPointerTy(), dl,
1701 DAG.getEntryNode(), CPAddr,
1702 MachinePointerInfo::getConstantPool(),
1703 false, false, false, 0);
1704 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1705 const char *Sym = S->getSymbol();
1707 // Create a constant pool entry for the callee address
1708 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1709 ARMConstantPoolValue *CPV =
1710 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1711 ARMPCLabelIndex, 0);
1712 // Get the address of the callee into a register
1713 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1714 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1715 Callee = DAG.getLoad(getPointerTy(), dl,
1716 DAG.getEntryNode(), CPAddr,
1717 MachinePointerInfo::getConstantPool(),
1718 false, false, false, 0);
1720 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1721 const GlobalValue *GV = G->getGlobal();
1723 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1724 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1725 getTargetMachine().getRelocationModel() != Reloc::Static;
1726 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1727 // ARM call to a local ARM function is predicable.
1728 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1729 // tBX takes a register source operand.
1730 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1731 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1732 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1733 DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1734 0, ARMII::MO_NONLAZY));
1735 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1736 MachinePointerInfo::getGOT(), false, false, true, 0);
1737 } else if (Subtarget->isTargetCOFF()) {
1738 assert(Subtarget->isTargetWindows() &&
1739 "Windows is the only supported COFF target");
1740 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1741 ? ARMII::MO_DLLIMPORT
1742 : ARMII::MO_NO_FLAG;
1743 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1745 if (GV->hasDLLImportStorageClass())
1746 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1747 DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1748 Callee), MachinePointerInfo::getGOT(),
1749 false, false, false, 0);
1751 // On ELF targets for PIC code, direct calls should go through the PLT
1752 unsigned OpFlags = 0;
1753 if (Subtarget->isTargetELF() &&
1754 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1755 OpFlags = ARMII::MO_PLT;
1756 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1758 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1760 bool isStub = Subtarget->isTargetMachO() &&
1761 getTargetMachine().getRelocationModel() != Reloc::Static;
1762 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1763 // tBX takes a register source operand.
1764 const char *Sym = S->getSymbol();
1765 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1766 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1767 ARMConstantPoolValue *CPV =
1768 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1769 ARMPCLabelIndex, 4);
1770 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1771 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1772 Callee = DAG.getLoad(getPointerTy(), dl,
1773 DAG.getEntryNode(), CPAddr,
1774 MachinePointerInfo::getConstantPool(),
1775 false, false, false, 0);
1776 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1777 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1778 getPointerTy(), Callee, PICLabel);
1780 unsigned OpFlags = 0;
1781 // On ELF targets for PIC code, direct calls should go through the PLT
1782 if (Subtarget->isTargetELF() &&
1783 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1784 OpFlags = ARMII::MO_PLT;
1785 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1789 // FIXME: handle tail calls differently.
1791 bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1792 if (Subtarget->isThumb()) {
1793 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1794 CallOpc = ARMISD::CALL_NOLINK;
1796 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1798 if (!isDirect && !Subtarget->hasV5TOps())
1799 CallOpc = ARMISD::CALL_NOLINK;
1800 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1801 // Emit regular call when code size is the priority
1803 // "mov lr, pc; b _foo" to avoid confusing the RSP
1804 CallOpc = ARMISD::CALL_NOLINK;
1806 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1809 std::vector<SDValue> Ops;
1810 Ops.push_back(Chain);
1811 Ops.push_back(Callee);
1813 // Add argument registers to the end of the list so that they are known live
1815 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1816 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1817 RegsToPass[i].second.getValueType()));
1819 // Add a register mask operand representing the call-preserved registers.
1821 const uint32_t *Mask;
1822 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1824 // For 'this' returns, use the R0-preserving mask if applicable
1825 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1827 // Set isThisReturn to false if the calling convention is not one that
1828 // allows 'returned' to be modeled in this way, so LowerCallResult does
1829 // not try to pass 'this' straight through
1830 isThisReturn = false;
1831 Mask = ARI->getCallPreservedMask(MF, CallConv);
1834 Mask = ARI->getCallPreservedMask(MF, CallConv);
1836 assert(Mask && "Missing call preserved mask for calling convention");
1837 Ops.push_back(DAG.getRegisterMask(Mask));
1840 if (InFlag.getNode())
1841 Ops.push_back(InFlag);
1843 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1845 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1847 // Returns a chain and a flag for retval copy to use.
1848 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1849 InFlag = Chain.getValue(1);
1851 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1852 DAG.getIntPtrConstant(0, true), InFlag, dl);
1854 InFlag = Chain.getValue(1);
1856 // Handle result values, copying them out of physregs into vregs that we
1858 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1859 InVals, isThisReturn,
1860 isThisReturn ? OutVals[0] : SDValue());
1863 /// HandleByVal - Every parameter *after* a byval parameter is passed
1864 /// on the stack. Remember the next parameter register to allocate,
1865 /// and then confiscate the rest of the parameter registers to insure
1867 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1868 unsigned Align) const {
1869 assert((State->getCallOrPrologue() == Prologue ||
1870 State->getCallOrPrologue() == Call) &&
1871 "unhandled ParmContext");
1873 // Byval (as with any stack) slots are always at least 4 byte aligned.
1874 Align = std::max(Align, 4U);
1876 unsigned Reg = State->AllocateReg(GPRArgRegs);
1880 unsigned AlignInRegs = Align / 4;
1881 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1882 for (unsigned i = 0; i < Waste; ++i)
1883 Reg = State->AllocateReg(GPRArgRegs);
1888 unsigned Excess = 4 * (ARM::R4 - Reg);
1890 // Special case when NSAA != SP and parameter size greater than size of
1891 // all remained GPR regs. In that case we can't split parameter, we must
1892 // send it to stack. We also must set NCRN to R4, so waste all
1893 // remained registers.
1894 const unsigned NSAAOffset = State->getNextStackOffset();
1895 if (NSAAOffset != 0 && Size > Excess) {
1896 while (State->AllocateReg(GPRArgRegs))
1901 // First register for byval parameter is the first register that wasn't
1902 // allocated before this method call, so it would be "reg".
1903 // If parameter is small enough to be saved in range [reg, r4), then
1904 // the end (first after last) register would be reg + param-size-in-regs,
1905 // else parameter would be splitted between registers and stack,
1906 // end register would be r4 in this case.
1907 unsigned ByValRegBegin = Reg;
1908 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1909 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1910 // Note, first register is allocated in the beginning of function already,
1911 // allocate remained amount of registers we need.
1912 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1913 State->AllocateReg(GPRArgRegs);
1914 // A byval parameter that is split between registers and memory needs its
1915 // size truncated here.
1916 // In the case where the entire structure fits in registers, we set the
1917 // size in memory to zero.
1918 Size = std::max<int>(Size - Excess, 0);
1922 /// MatchingStackOffset - Return true if the given stack call argument is
1923 /// already available in the same position (relatively) of the caller's
1924 /// incoming argument stack.
1926 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1927 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1928 const TargetInstrInfo *TII) {
1929 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1931 if (Arg.getOpcode() == ISD::CopyFromReg) {
1932 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1933 if (!TargetRegisterInfo::isVirtualRegister(VR))
1935 MachineInstr *Def = MRI->getVRegDef(VR);
1938 if (!Flags.isByVal()) {
1939 if (!TII->isLoadFromStackSlot(Def, FI))
1944 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1945 if (Flags.isByVal())
1946 // ByVal argument is passed in as a pointer but it's now being
1947 // dereferenced. e.g.
1948 // define @foo(%struct.X* %A) {
1949 // tail call @bar(%struct.X* byval %A)
1952 SDValue Ptr = Ld->getBasePtr();
1953 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1956 FI = FINode->getIndex();
1960 assert(FI != INT_MAX);
1961 if (!MFI->isFixedObjectIndex(FI))
1963 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1966 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1967 /// for tail call optimization. Targets which want to do tail call
1968 /// optimization should implement this function.
1970 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1971 CallingConv::ID CalleeCC,
1973 bool isCalleeStructRet,
1974 bool isCallerStructRet,
1975 const SmallVectorImpl<ISD::OutputArg> &Outs,
1976 const SmallVectorImpl<SDValue> &OutVals,
1977 const SmallVectorImpl<ISD::InputArg> &Ins,
1978 SelectionDAG& DAG) const {
1979 const Function *CallerF = DAG.getMachineFunction().getFunction();
1980 CallingConv::ID CallerCC = CallerF->getCallingConv();
1981 bool CCMatch = CallerCC == CalleeCC;
1983 // Look for obvious safe cases to perform tail call optimization that do not
1984 // require ABI changes. This is what gcc calls sibcall.
1986 // Do not sibcall optimize vararg calls unless the call site is not passing
1988 if (isVarArg && !Outs.empty())
1991 // Exception-handling functions need a special set of instructions to indicate
1992 // a return to the hardware. Tail-calling another function would probably
1994 if (CallerF->hasFnAttribute("interrupt"))
1997 // Also avoid sibcall optimization if either caller or callee uses struct
1998 // return semantics.
1999 if (isCalleeStructRet || isCallerStructRet)
2002 // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2003 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2004 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2005 // support in the assembler and linker to be used. This would need to be
2006 // fixed to fully support tail calls in Thumb1.
2008 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2009 // LR. This means if we need to reload LR, it takes an extra instructions,
2010 // which outweighs the value of the tail call; but here we don't know yet
2011 // whether LR is going to be used. Probably the right approach is to
2012 // generate the tail call here and turn it back into CALL/RET in
2013 // emitEpilogue if LR is used.
2015 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2016 // but we need to make sure there are enough registers; the only valid
2017 // registers are the 4 used for parameters. We don't currently do this
2019 if (Subtarget->isThumb1Only())
2022 // Externally-defined functions with weak linkage should not be
2023 // tail-called on ARM when the OS does not support dynamic
2024 // pre-emption of symbols, as the AAELF spec requires normal calls
2025 // to undefined weak functions to be replaced with a NOP or jump to the
2026 // next instruction. The behaviour of branch instructions in this
2027 // situation (as used for tail calls) is implementation-defined, so we
2028 // cannot rely on the linker replacing the tail call with a return.
2029 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2030 const GlobalValue *GV = G->getGlobal();
2031 const Triple TT(getTargetMachine().getTargetTriple());
2032 if (GV->hasExternalWeakLinkage() &&
2033 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2037 // If the calling conventions do not match, then we'd better make sure the
2038 // results are returned in the same way as what the caller expects.
2040 SmallVector<CCValAssign, 16> RVLocs1;
2041 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2042 *DAG.getContext(), Call);
2043 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2045 SmallVector<CCValAssign, 16> RVLocs2;
2046 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2047 *DAG.getContext(), Call);
2048 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2050 if (RVLocs1.size() != RVLocs2.size())
2052 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2053 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2055 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2057 if (RVLocs1[i].isRegLoc()) {
2058 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2061 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2067 // If Caller's vararg or byval argument has been split between registers and
2068 // stack, do not perform tail call, since part of the argument is in caller's
2070 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2071 getInfo<ARMFunctionInfo>();
2072 if (AFI_Caller->getArgRegsSaveSize())
2075 // If the callee takes no arguments then go on to check the results of the
2077 if (!Outs.empty()) {
2078 // Check if stack adjustment is needed. For now, do not do this if any
2079 // argument is passed on the stack.
2080 SmallVector<CCValAssign, 16> ArgLocs;
2081 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2082 *DAG.getContext(), Call);
2083 CCInfo.AnalyzeCallOperands(Outs,
2084 CCAssignFnForNode(CalleeCC, false, isVarArg));
2085 if (CCInfo.getNextStackOffset()) {
2086 MachineFunction &MF = DAG.getMachineFunction();
2088 // Check if the arguments are already laid out in the right way as
2089 // the caller's fixed stack objects.
2090 MachineFrameInfo *MFI = MF.getFrameInfo();
2091 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2092 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2093 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2095 ++i, ++realArgIdx) {
2096 CCValAssign &VA = ArgLocs[i];
2097 EVT RegVT = VA.getLocVT();
2098 SDValue Arg = OutVals[realArgIdx];
2099 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2100 if (VA.getLocInfo() == CCValAssign::Indirect)
2102 if (VA.needsCustom()) {
2103 // f64 and vector types are split into multiple registers or
2104 // register/stack-slot combinations. The types will not match
2105 // the registers; give up on memory f64 refs until we figure
2106 // out what to do about this.
2109 if (!ArgLocs[++i].isRegLoc())
2111 if (RegVT == MVT::v2f64) {
2112 if (!ArgLocs[++i].isRegLoc())
2114 if (!ArgLocs[++i].isRegLoc())
2117 } else if (!VA.isRegLoc()) {
2118 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2130 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2131 MachineFunction &MF, bool isVarArg,
2132 const SmallVectorImpl<ISD::OutputArg> &Outs,
2133 LLVMContext &Context) const {
2134 SmallVector<CCValAssign, 16> RVLocs;
2135 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2136 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2140 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2141 SDLoc DL, SelectionDAG &DAG) {
2142 const MachineFunction &MF = DAG.getMachineFunction();
2143 const Function *F = MF.getFunction();
2145 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2147 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2148 // version of the "preferred return address". These offsets affect the return
2149 // instruction if this is a return from PL1 without hypervisor extensions.
2150 // IRQ/FIQ: +4 "subs pc, lr, #4"
2151 // SWI: 0 "subs pc, lr, #0"
2152 // ABORT: +4 "subs pc, lr, #4"
2153 // UNDEF: +4/+2 "subs pc, lr, #0"
2154 // UNDEF varies depending on where the exception came from ARM or Thumb
2155 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2158 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2161 else if (IntKind == "SWI" || IntKind == "UNDEF")
2164 report_fatal_error("Unsupported interrupt attribute. If present, value "
2165 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2167 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2169 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2173 ARMTargetLowering::LowerReturn(SDValue Chain,
2174 CallingConv::ID CallConv, bool isVarArg,
2175 const SmallVectorImpl<ISD::OutputArg> &Outs,
2176 const SmallVectorImpl<SDValue> &OutVals,
2177 SDLoc dl, SelectionDAG &DAG) const {
2179 // CCValAssign - represent the assignment of the return value to a location.
2180 SmallVector<CCValAssign, 16> RVLocs;
2182 // CCState - Info about the registers and stack slots.
2183 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2184 *DAG.getContext(), Call);
2186 // Analyze outgoing return values.
2187 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2191 SmallVector<SDValue, 4> RetOps;
2192 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2193 bool isLittleEndian = Subtarget->isLittle();
2195 MachineFunction &MF = DAG.getMachineFunction();
2196 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2197 AFI->setReturnRegsCount(RVLocs.size());
2199 // Copy the result values into the output registers.
2200 for (unsigned i = 0, realRVLocIdx = 0;
2202 ++i, ++realRVLocIdx) {
2203 CCValAssign &VA = RVLocs[i];
2204 assert(VA.isRegLoc() && "Can only return in registers!");
2206 SDValue Arg = OutVals[realRVLocIdx];
2208 switch (VA.getLocInfo()) {
2209 default: llvm_unreachable("Unknown loc info!");
2210 case CCValAssign::Full: break;
2211 case CCValAssign::BCvt:
2212 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2216 if (VA.needsCustom()) {
2217 if (VA.getLocVT() == MVT::v2f64) {
2218 // Extract the first half and return it in two registers.
2219 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2220 DAG.getConstant(0, MVT::i32));
2221 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2222 DAG.getVTList(MVT::i32, MVT::i32), Half);
2224 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2225 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2227 Flag = Chain.getValue(1);
2228 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2229 VA = RVLocs[++i]; // skip ahead to next loc
2230 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2231 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2233 Flag = Chain.getValue(1);
2234 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2235 VA = RVLocs[++i]; // skip ahead to next loc
2237 // Extract the 2nd half and fall through to handle it as an f64 value.
2238 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2239 DAG.getConstant(1, MVT::i32));
2241 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2243 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2244 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2245 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2246 fmrrd.getValue(isLittleEndian ? 0 : 1),
2248 Flag = Chain.getValue(1);
2249 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2250 VA = RVLocs[++i]; // skip ahead to next loc
2251 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2252 fmrrd.getValue(isLittleEndian ? 1 : 0),
2255 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2257 // Guarantee that all emitted copies are
2258 // stuck together, avoiding something bad.
2259 Flag = Chain.getValue(1);
2260 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2263 // Update chain and glue.
2266 RetOps.push_back(Flag);
2268 // CPUs which aren't M-class use a special sequence to return from
2269 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2270 // though we use "subs pc, lr, #N").
2272 // M-class CPUs actually use a normal return sequence with a special
2273 // (hardware-provided) value in LR, so the normal code path works.
2274 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2275 !Subtarget->isMClass()) {
2276 if (Subtarget->isThumb1Only())
2277 report_fatal_error("interrupt attribute is not supported in Thumb1");
2278 return LowerInterruptReturn(RetOps, dl, DAG);
2281 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2284 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2285 if (N->getNumValues() != 1)
2287 if (!N->hasNUsesOfValue(1, 0))
2290 SDValue TCChain = Chain;
2291 SDNode *Copy = *N->use_begin();
2292 if (Copy->getOpcode() == ISD::CopyToReg) {
2293 // If the copy has a glue operand, we conservatively assume it isn't safe to
2294 // perform a tail call.
2295 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2297 TCChain = Copy->getOperand(0);
2298 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2299 SDNode *VMov = Copy;
2300 // f64 returned in a pair of GPRs.
2301 SmallPtrSet<SDNode*, 2> Copies;
2302 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2304 if (UI->getOpcode() != ISD::CopyToReg)
2308 if (Copies.size() > 2)
2311 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2313 SDValue UseChain = UI->getOperand(0);
2314 if (Copies.count(UseChain.getNode()))
2318 // We are at the top of this chain.
2319 // If the copy has a glue operand, we conservatively assume it
2320 // isn't safe to perform a tail call.
2321 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2327 } else if (Copy->getOpcode() == ISD::BITCAST) {
2328 // f32 returned in a single GPR.
2329 if (!Copy->hasOneUse())
2331 Copy = *Copy->use_begin();
2332 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2334 // If the copy has a glue operand, we conservatively assume it isn't safe to
2335 // perform a tail call.
2336 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2338 TCChain = Copy->getOperand(0);
2343 bool HasRet = false;
2344 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2346 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2347 UI->getOpcode() != ARMISD::INTRET_FLAG)
2359 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2360 if (!Subtarget->supportsTailCall())
2363 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2366 return !Subtarget->isThumb1Only();
2369 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2370 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2371 // one of the above mentioned nodes. It has to be wrapped because otherwise
2372 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2373 // be used to form addressing mode. These wrapped nodes will be selected
2375 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2376 EVT PtrVT = Op.getValueType();
2377 // FIXME there is no actual debug info here
2379 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2381 if (CP->isMachineConstantPoolEntry())
2382 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2383 CP->getAlignment());
2385 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2386 CP->getAlignment());
2387 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2390 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2391 return MachineJumpTableInfo::EK_Inline;
2394 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2395 SelectionDAG &DAG) const {
2396 MachineFunction &MF = DAG.getMachineFunction();
2397 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2398 unsigned ARMPCLabelIndex = 0;
2400 EVT PtrVT = getPointerTy();
2401 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2402 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2404 if (RelocM == Reloc::Static) {
2405 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2407 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2408 ARMPCLabelIndex = AFI->createPICLabelUId();
2409 ARMConstantPoolValue *CPV =
2410 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2411 ARMCP::CPBlockAddress, PCAdj);
2412 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2414 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2415 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2416 MachinePointerInfo::getConstantPool(),
2417 false, false, false, 0);
2418 if (RelocM == Reloc::Static)
2420 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2421 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2424 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2426 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2427 SelectionDAG &DAG) const {
2429 EVT PtrVT = getPointerTy();
2430 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2431 MachineFunction &MF = DAG.getMachineFunction();
2432 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2433 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2434 ARMConstantPoolValue *CPV =
2435 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2436 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2437 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2438 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2439 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2440 MachinePointerInfo::getConstantPool(),
2441 false, false, false, 0);
2442 SDValue Chain = Argument.getValue(1);
2444 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2445 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2447 // call __tls_get_addr.
2450 Entry.Node = Argument;
2451 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2452 Args.push_back(Entry);
2454 // FIXME: is there useful debug info available here?
2455 TargetLowering::CallLoweringInfo CLI(DAG);
2456 CLI.setDebugLoc(dl).setChain(Chain)
2457 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2458 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2461 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2462 return CallResult.first;
2465 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2466 // "local exec" model.
2468 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2470 TLSModel::Model model) const {
2471 const GlobalValue *GV = GA->getGlobal();
2474 SDValue Chain = DAG.getEntryNode();
2475 EVT PtrVT = getPointerTy();
2476 // Get the Thread Pointer
2477 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2479 if (model == TLSModel::InitialExec) {
2480 MachineFunction &MF = DAG.getMachineFunction();
2481 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2482 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2483 // Initial exec model.
2484 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2485 ARMConstantPoolValue *CPV =
2486 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2487 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2489 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2490 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2491 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2492 MachinePointerInfo::getConstantPool(),
2493 false, false, false, 0);
2494 Chain = Offset.getValue(1);
2496 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2497 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2499 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2500 MachinePointerInfo::getConstantPool(),
2501 false, false, false, 0);
2504 assert(model == TLSModel::LocalExec);
2505 ARMConstantPoolValue *CPV =
2506 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2507 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2508 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2509 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2510 MachinePointerInfo::getConstantPool(),
2511 false, false, false, 0);
2514 // The address of the thread local variable is the add of the thread
2515 // pointer with the offset of the variable.
2516 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2520 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2521 // TODO: implement the "local dynamic" model
2522 assert(Subtarget->isTargetELF() &&
2523 "TLS not implemented for non-ELF targets");
2524 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2526 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2529 case TLSModel::GeneralDynamic:
2530 case TLSModel::LocalDynamic:
2531 return LowerToTLSGeneralDynamicModel(GA, DAG);
2532 case TLSModel::InitialExec:
2533 case TLSModel::LocalExec:
2534 return LowerToTLSExecModels(GA, DAG, model);
2536 llvm_unreachable("bogus TLS model");
2539 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2540 SelectionDAG &DAG) const {
2541 EVT PtrVT = getPointerTy();
2543 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2544 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2545 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2546 ARMConstantPoolValue *CPV =
2547 ARMConstantPoolConstant::Create(GV,
2548 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2549 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2550 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2551 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2553 MachinePointerInfo::getConstantPool(),
2554 false, false, false, 0);
2555 SDValue Chain = Result.getValue(1);
2556 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2557 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2559 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2560 MachinePointerInfo::getGOT(),
2561 false, false, false, 0);
2565 // If we have T2 ops, we can materialize the address directly via movt/movw
2566 // pair. This is always cheaper.
2567 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2569 // FIXME: Once remat is capable of dealing with instructions with register
2570 // operands, expand this into two nodes.
2571 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2572 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2574 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2575 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2576 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2577 MachinePointerInfo::getConstantPool(),
2578 false, false, false, 0);
2582 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2583 SelectionDAG &DAG) const {
2584 EVT PtrVT = getPointerTy();
2586 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2587 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2589 if (Subtarget->useMovt(DAG.getMachineFunction()))
2592 // FIXME: Once remat is capable of dealing with instructions with register
2593 // operands, expand this into multiple nodes
2595 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2597 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2598 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2600 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2601 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2602 MachinePointerInfo::getGOT(), false, false, false, 0);
2606 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2607 SelectionDAG &DAG) const {
2608 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2609 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2610 "Windows on ARM expects to use movw/movt");
2612 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2613 const ARMII::TOF TargetFlags =
2614 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2615 EVT PtrVT = getPointerTy();
2621 // FIXME: Once remat is capable of dealing with instructions with register
2622 // operands, expand this into two nodes.
2623 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2624 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2626 if (GV->hasDLLImportStorageClass())
2627 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2628 MachinePointerInfo::getGOT(), false, false, false, 0);
2632 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2633 SelectionDAG &DAG) const {
2634 assert(Subtarget->isTargetELF() &&
2635 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2636 MachineFunction &MF = DAG.getMachineFunction();
2637 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2638 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2639 EVT PtrVT = getPointerTy();
2641 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2642 ARMConstantPoolValue *CPV =
2643 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2644 ARMPCLabelIndex, PCAdj);
2645 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2646 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2647 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2648 MachinePointerInfo::getConstantPool(),
2649 false, false, false, 0);
2650 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2651 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2655 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2657 SDValue Val = DAG.getConstant(0, MVT::i32);
2658 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2659 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2660 Op.getOperand(1), Val);
2664 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2666 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2667 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2671 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2672 const ARMSubtarget *Subtarget) const {
2673 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2676 default: return SDValue(); // Don't custom lower most intrinsics.
2677 case Intrinsic::arm_rbit: {
2678 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2679 "RBIT intrinsic must have i32 type!");
2680 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2682 case Intrinsic::arm_thread_pointer: {
2683 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2684 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2686 case Intrinsic::eh_sjlj_lsda: {
2687 MachineFunction &MF = DAG.getMachineFunction();
2688 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2689 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2690 EVT PtrVT = getPointerTy();
2691 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2693 unsigned PCAdj = (RelocM != Reloc::PIC_)
2694 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2695 ARMConstantPoolValue *CPV =
2696 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2697 ARMCP::CPLSDA, PCAdj);
2698 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2699 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2701 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2702 MachinePointerInfo::getConstantPool(),
2703 false, false, false, 0);
2705 if (RelocM == Reloc::PIC_) {
2706 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2707 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2711 case Intrinsic::arm_neon_vmulls:
2712 case Intrinsic::arm_neon_vmullu: {
2713 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2714 ? ARMISD::VMULLs : ARMISD::VMULLu;
2715 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2716 Op.getOperand(1), Op.getOperand(2));
2721 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2722 const ARMSubtarget *Subtarget) {
2723 // FIXME: handle "fence singlethread" more efficiently.
2725 if (!Subtarget->hasDataBarrier()) {
2726 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2727 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2729 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2730 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2731 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2732 DAG.getConstant(0, MVT::i32));
2735 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2736 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2737 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2738 if (Subtarget->isMClass()) {
2739 // Only a full system barrier exists in the M-class architectures.
2740 Domain = ARM_MB::SY;
2741 } else if (Subtarget->isSwift() && Ord == Release) {
2742 // Swift happens to implement ISHST barriers in a way that's compatible with
2743 // Release semantics but weaker than ISH so we'd be fools not to use
2744 // it. Beware: other processors probably don't!
2745 Domain = ARM_MB::ISHST;
2748 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2749 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2750 DAG.getConstant(Domain, MVT::i32));
2753 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2754 const ARMSubtarget *Subtarget) {
2755 // ARM pre v5TE and Thumb1 does not have preload instructions.
2756 if (!(Subtarget->isThumb2() ||
2757 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2758 // Just preserve the chain.
2759 return Op.getOperand(0);
2762 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2764 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2765 // ARMv7 with MP extension has PLDW.
2766 return Op.getOperand(0);
2768 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2769 if (Subtarget->isThumb()) {
2771 isRead = ~isRead & 1;
2772 isData = ~isData & 1;
2775 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2776 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2777 DAG.getConstant(isData, MVT::i32));
2780 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2781 MachineFunction &MF = DAG.getMachineFunction();
2782 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2784 // vastart just stores the address of the VarArgsFrameIndex slot into the
2785 // memory location argument.
2787 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2788 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2789 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2790 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2791 MachinePointerInfo(SV), false, false, 0);
2795 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2796 SDValue &Root, SelectionDAG &DAG,
2798 MachineFunction &MF = DAG.getMachineFunction();
2799 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2801 const TargetRegisterClass *RC;
2802 if (AFI->isThumb1OnlyFunction())
2803 RC = &ARM::tGPRRegClass;
2805 RC = &ARM::GPRRegClass;
2807 // Transform the arguments stored in physical registers into virtual ones.
2808 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2809 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2812 if (NextVA.isMemLoc()) {
2813 MachineFrameInfo *MFI = MF.getFrameInfo();
2814 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2816 // Create load node to retrieve arguments from the stack.
2817 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2818 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2819 MachinePointerInfo::getFixedStack(FI),
2820 false, false, false, 0);
2822 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2823 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2825 if (!Subtarget->isLittle())
2826 std::swap (ArgValue, ArgValue2);
2827 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2830 // The remaining GPRs hold either the beginning of variable-argument
2831 // data, or the beginning of an aggregate passed by value (usually
2832 // byval). Either way, we allocate stack slots adjacent to the data
2833 // provided by our caller, and store the unallocated registers there.
2834 // If this is a variadic function, the va_list pointer will begin with
2835 // these values; otherwise, this reassembles a (byval) structure that
2836 // was split between registers and memory.
2837 // Return: The frame index registers were stored into.
2839 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2840 SDLoc dl, SDValue &Chain,
2841 const Value *OrigArg,
2842 unsigned InRegsParamRecordIdx,
2844 unsigned ArgSize) const {
2845 // Currently, two use-cases possible:
2846 // Case #1. Non-var-args function, and we meet first byval parameter.
2847 // Setup first unallocated register as first byval register;
2848 // eat all remained registers
2849 // (these two actions are performed by HandleByVal method).
2850 // Then, here, we initialize stack frame with
2851 // "store-reg" instructions.
2852 // Case #2. Var-args function, that doesn't contain byval parameters.
2853 // The same: eat all remained unallocated registers,
2854 // initialize stack frame.
2856 MachineFunction &MF = DAG.getMachineFunction();
2857 MachineFrameInfo *MFI = MF.getFrameInfo();
2858 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2859 unsigned RBegin, REnd;
2860 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2861 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2863 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2864 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2869 ArgOffset = -4 * (ARM::R4 - RBegin);
2871 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2872 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2874 SmallVector<SDValue, 4> MemOps;
2875 const TargetRegisterClass *RC =
2876 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2878 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2879 unsigned VReg = MF.addLiveIn(Reg, RC);
2880 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2882 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2883 MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2884 MemOps.push_back(Store);
2885 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2886 DAG.getConstant(4, getPointerTy()));
2889 if (!MemOps.empty())
2890 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2894 // Setup stack frame, the va_list pointer will start from.
2896 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2897 SDLoc dl, SDValue &Chain,
2899 unsigned TotalArgRegsSaveSize,
2900 bool ForceMutable) const {
2901 MachineFunction &MF = DAG.getMachineFunction();
2902 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2904 // Try to store any remaining integer argument regs
2905 // to their spots on the stack so that they may be loaded by deferencing
2906 // the result of va_next.
2907 // If there is no regs to be stored, just point address after last
2908 // argument passed via stack.
2909 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2910 CCInfo.getInRegsParamsCount(),
2911 CCInfo.getNextStackOffset(), 4);
2912 AFI->setVarArgsFrameIndex(FrameIndex);
2916 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2917 CallingConv::ID CallConv, bool isVarArg,
2918 const SmallVectorImpl<ISD::InputArg>
2920 SDLoc dl, SelectionDAG &DAG,
2921 SmallVectorImpl<SDValue> &InVals)
2923 MachineFunction &MF = DAG.getMachineFunction();
2924 MachineFrameInfo *MFI = MF.getFrameInfo();
2926 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2928 // Assign locations to all of the incoming arguments.
2929 SmallVector<CCValAssign, 16> ArgLocs;
2930 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2931 *DAG.getContext(), Prologue);
2932 CCInfo.AnalyzeFormalArguments(Ins,
2933 CCAssignFnForNode(CallConv, /* Return*/ false,
2936 SmallVector<SDValue, 16> ArgValues;
2938 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2939 unsigned CurArgIdx = 0;
2941 // Initially ArgRegsSaveSize is zero.
2942 // Then we increase this value each time we meet byval parameter.
2943 // We also increase this value in case of varargs function.
2944 AFI->setArgRegsSaveSize(0);
2946 // Calculate the amount of stack space that we need to allocate to store
2947 // byval and variadic arguments that are passed in registers.
2948 // We need to know this before we allocate the first byval or variadic
2949 // argument, as they will be allocated a stack slot below the CFA (Canonical
2950 // Frame Address, the stack pointer at entry to the function).
2951 unsigned ArgRegBegin = ARM::R4;
2952 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2953 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
2956 CCValAssign &VA = ArgLocs[i];
2957 unsigned Index = VA.getValNo();
2958 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
2959 if (!Flags.isByVal())
2962 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
2963 unsigned RBegin, REnd;
2964 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
2965 ArgRegBegin = std::min(ArgRegBegin, RBegin);
2967 CCInfo.nextInRegsParam();
2969 CCInfo.rewindByValRegsInfo();
2971 int lastInsIndex = -1;
2972 if (isVarArg && MFI->hasVAStart()) {
2973 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2974 if (RegIdx != array_lengthof(GPRArgRegs))
2975 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
2978 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
2979 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
2981 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2982 CCValAssign &VA = ArgLocs[i];
2983 if (Ins[VA.getValNo()].isOrigArg()) {
2984 std::advance(CurOrigArg,
2985 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
2986 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
2988 // Arguments stored in registers.
2989 if (VA.isRegLoc()) {
2990 EVT RegVT = VA.getLocVT();
2992 if (VA.needsCustom()) {
2993 // f64 and vector types are split up into multiple registers or
2994 // combinations of registers and stack slots.
2995 if (VA.getLocVT() == MVT::v2f64) {
2996 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2998 VA = ArgLocs[++i]; // skip ahead to next loc
3000 if (VA.isMemLoc()) {
3001 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3002 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3003 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3004 MachinePointerInfo::getFixedStack(FI),
3005 false, false, false, 0);
3007 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3010 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3011 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3012 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3013 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3014 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3016 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3019 const TargetRegisterClass *RC;
3021 if (RegVT == MVT::f32)
3022 RC = &ARM::SPRRegClass;
3023 else if (RegVT == MVT::f64)
3024 RC = &ARM::DPRRegClass;
3025 else if (RegVT == MVT::v2f64)
3026 RC = &ARM::QPRRegClass;
3027 else if (RegVT == MVT::i32)
3028 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3029 : &ARM::GPRRegClass;
3031 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3033 // Transform the arguments in physical registers into virtual ones.
3034 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3035 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3038 // If this is an 8 or 16-bit value, it is really passed promoted
3039 // to 32 bits. Insert an assert[sz]ext to capture this, then
3040 // truncate to the right size.
3041 switch (VA.getLocInfo()) {
3042 default: llvm_unreachable("Unknown loc info!");
3043 case CCValAssign::Full: break;
3044 case CCValAssign::BCvt:
3045 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3047 case CCValAssign::SExt:
3048 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3049 DAG.getValueType(VA.getValVT()));
3050 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3052 case CCValAssign::ZExt:
3053 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3054 DAG.getValueType(VA.getValVT()));
3055 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3059 InVals.push_back(ArgValue);
3061 } else { // VA.isRegLoc()
3064 assert(VA.isMemLoc());
3065 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3067 int index = VA.getValNo();
3069 // Some Ins[] entries become multiple ArgLoc[] entries.
3070 // Process them only once.
3071 if (index != lastInsIndex)
3073 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3074 // FIXME: For now, all byval parameter objects are marked mutable.
3075 // This can be changed with more analysis.
3076 // In case of tail call optimization mark all arguments mutable.
3077 // Since they could be overwritten by lowering of arguments in case of
3079 if (Flags.isByVal()) {
3080 assert(Ins[index].isOrigArg() &&
3081 "Byval arguments cannot be implicit");
3082 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3084 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3085 CurByValIndex, VA.getLocMemOffset(),
3086 Flags.getByValSize());
3087 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3088 CCInfo.nextInRegsParam();
3090 unsigned FIOffset = VA.getLocMemOffset();
3091 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3094 // Create load nodes to retrieve arguments from the stack.
3095 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3096 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3097 MachinePointerInfo::getFixedStack(FI),
3098 false, false, false, 0));
3100 lastInsIndex = index;
3106 if (isVarArg && MFI->hasVAStart())
3107 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3108 CCInfo.getNextStackOffset(),
3109 TotalArgRegsSaveSize);
3111 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3116 /// isFloatingPointZero - Return true if this is +0.0.
3117 static bool isFloatingPointZero(SDValue Op) {
3118 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3119 return CFP->getValueAPF().isPosZero();
3120 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3121 // Maybe this has already been legalized into the constant pool?
3122 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3123 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3124 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3125 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3126 return CFP->getValueAPF().isPosZero();
3128 } else if (Op->getOpcode() == ISD::BITCAST &&
3129 Op->getValueType(0) == MVT::f64) {
3130 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3131 // created by LowerConstantFP().
3132 SDValue BitcastOp = Op->getOperand(0);
3133 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3134 SDValue MoveOp = BitcastOp->getOperand(0);
3135 if (MoveOp->getOpcode() == ISD::TargetConstant &&
3136 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3144 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3145 /// the given operands.
3147 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3148 SDValue &ARMcc, SelectionDAG &DAG,
3150 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3151 unsigned C = RHSC->getZExtValue();
3152 if (!isLegalICmpImmediate(C)) {
3153 // Constant does not fit, try adjusting it by one?
3158 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3159 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3160 RHS = DAG.getConstant(C-1, MVT::i32);
3165 if (C != 0 && isLegalICmpImmediate(C-1)) {
3166 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3167 RHS = DAG.getConstant(C-1, MVT::i32);
3172 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3173 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3174 RHS = DAG.getConstant(C+1, MVT::i32);
3179 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3180 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3181 RHS = DAG.getConstant(C+1, MVT::i32);
3188 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3189 ARMISD::NodeType CompareType;
3192 CompareType = ARMISD::CMP;
3197 CompareType = ARMISD::CMPZ;
3200 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3201 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3204 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3206 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3208 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3210 if (!isFloatingPointZero(RHS))
3211 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3213 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3214 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3217 /// duplicateCmp - Glue values can have only one use, so this function
3218 /// duplicates a comparison node.
3220 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3221 unsigned Opc = Cmp.getOpcode();
3223 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3224 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3226 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3227 Cmp = Cmp.getOperand(0);
3228 Opc = Cmp.getOpcode();
3229 if (Opc == ARMISD::CMPFP)
3230 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3232 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3233 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3235 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3238 std::pair<SDValue, SDValue>
3239 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3240 SDValue &ARMcc) const {
3241 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3243 SDValue Value, OverflowCmp;
3244 SDValue LHS = Op.getOperand(0);
3245 SDValue RHS = Op.getOperand(1);
3248 // FIXME: We are currently always generating CMPs because we don't support
3249 // generating CMN through the backend. This is not as good as the natural
3250 // CMP case because it causes a register dependency and cannot be folded
3253 switch (Op.getOpcode()) {
3255 llvm_unreachable("Unknown overflow instruction!");
3257 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3258 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3259 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3262 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3263 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3264 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3267 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3268 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3269 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3272 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3273 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3274 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3278 return std::make_pair(Value, OverflowCmp);
3283 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3284 // Let legalize expand this if it isn't a legal type yet.
3285 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3288 SDValue Value, OverflowCmp;
3290 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3291 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3292 // We use 0 and 1 as false and true values.
3293 SDValue TVal = DAG.getConstant(1, MVT::i32);
3294 SDValue FVal = DAG.getConstant(0, MVT::i32);
3295 EVT VT = Op.getValueType();
3297 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3298 ARMcc, CCR, OverflowCmp);
3300 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3301 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3305 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3306 SDValue Cond = Op.getOperand(0);
3307 SDValue SelectTrue = Op.getOperand(1);
3308 SDValue SelectFalse = Op.getOperand(2);
3310 unsigned Opc = Cond.getOpcode();
3312 if (Cond.getResNo() == 1 &&
3313 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3314 Opc == ISD::USUBO)) {
3315 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3318 SDValue Value, OverflowCmp;
3320 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3321 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3322 EVT VT = Op.getValueType();
3324 return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3330 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3331 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3333 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3334 const ConstantSDNode *CMOVTrue =
3335 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3336 const ConstantSDNode *CMOVFalse =
3337 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3339 if (CMOVTrue && CMOVFalse) {
3340 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3341 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3345 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3347 False = SelectFalse;
3348 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3353 if (True.getNode() && False.getNode()) {
3354 EVT VT = Op.getValueType();
3355 SDValue ARMcc = Cond.getOperand(2);
3356 SDValue CCR = Cond.getOperand(3);
3357 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3358 assert(True.getValueType() == VT);
3359 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3364 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3365 // undefined bits before doing a full-word comparison with zero.
3366 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3367 DAG.getConstant(1, Cond.getValueType()));
3369 return DAG.getSelectCC(dl, Cond,
3370 DAG.getConstant(0, Cond.getValueType()),
3371 SelectTrue, SelectFalse, ISD::SETNE);
3374 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3375 if (CC == ISD::SETNE)
3377 return ISD::getSetCCInverse(CC, true);
3380 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3381 bool &swpCmpOps, bool &swpVselOps) {
3382 // Start by selecting the GE condition code for opcodes that return true for
3384 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3386 CondCode = ARMCC::GE;
3388 // and GT for opcodes that return false for 'equality'.
3389 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3391 CondCode = ARMCC::GT;
3393 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3394 // to swap the compare operands.
3395 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3399 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3400 // If we have an unordered opcode, we need to swap the operands to the VSEL
3401 // instruction (effectively negating the condition).
3403 // This also has the effect of swapping which one of 'less' or 'greater'
3404 // returns true, so we also swap the compare operands. It also switches
3405 // whether we return true for 'equality', so we compensate by picking the
3406 // opposite condition code to our original choice.
3407 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3408 CC == ISD::SETUGT) {
3409 swpCmpOps = !swpCmpOps;
3410 swpVselOps = !swpVselOps;
3411 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3414 // 'ordered' is 'anything but unordered', so use the VS condition code and
3415 // swap the VSEL operands.
3416 if (CC == ISD::SETO) {
3417 CondCode = ARMCC::VS;
3421 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3422 // code and swap the VSEL operands.
3423 if (CC == ISD::SETUNE) {
3424 CondCode = ARMCC::EQ;
3429 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3430 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3431 SDValue Cmp, SelectionDAG &DAG) const {
3432 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3433 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3434 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3435 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3436 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3438 SDValue TrueLow = TrueVal.getValue(0);
3439 SDValue TrueHigh = TrueVal.getValue(1);
3440 SDValue FalseLow = FalseVal.getValue(0);
3441 SDValue FalseHigh = FalseVal.getValue(1);
3443 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3445 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3446 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3448 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3450 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3455 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3456 EVT VT = Op.getValueType();
3457 SDValue LHS = Op.getOperand(0);
3458 SDValue RHS = Op.getOperand(1);
3459 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3460 SDValue TrueVal = Op.getOperand(2);
3461 SDValue FalseVal = Op.getOperand(3);
3464 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3465 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3468 // If softenSetCCOperands only returned one value, we should compare it to
3470 if (!RHS.getNode()) {
3471 RHS = DAG.getConstant(0, LHS.getValueType());
3476 if (LHS.getValueType() == MVT::i32) {
3477 // Try to generate VSEL on ARMv8.
3478 // The VSEL instruction can't use all the usual ARM condition
3479 // codes: it only has two bits to select the condition code, so it's
3480 // constrained to use only GE, GT, VS and EQ.
3482 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3483 // swap the operands of the previous compare instruction (effectively
3484 // inverting the compare condition, swapping 'less' and 'greater') and
3485 // sometimes need to swap the operands to the VSEL (which inverts the
3486 // condition in the sense of firing whenever the previous condition didn't)
3487 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3488 TrueVal.getValueType() == MVT::f64)) {
3489 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3490 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3491 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3492 CC = getInverseCCForVSEL(CC);
3493 std::swap(TrueVal, FalseVal);
3498 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3499 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3500 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3503 ARMCC::CondCodes CondCode, CondCode2;
3504 FPCCToARMCC(CC, CondCode, CondCode2);
3506 // Try to generate VSEL on ARMv8.
3507 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3508 TrueVal.getValueType() == MVT::f64)) {
3509 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3510 // same operands, as follows:
3511 // c = fcmp [ogt, olt, ugt, ult] a, b
3513 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3514 // handled differently than the original code sequence.
3515 if (getTargetMachine().Options.UnsafeFPMath) {
3516 if (LHS == TrueVal && RHS == FalseVal) {
3517 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3518 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3519 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3520 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3521 } else if (LHS == FalseVal && RHS == TrueVal) {
3522 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3523 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3524 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3525 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3529 bool swpCmpOps = false;
3530 bool swpVselOps = false;
3531 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3533 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3534 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3536 std::swap(LHS, RHS);
3538 std::swap(TrueVal, FalseVal);
3542 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3543 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3544 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3545 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3546 if (CondCode2 != ARMCC::AL) {
3547 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3548 // FIXME: Needs another CMP because flag can have but one use.
3549 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3550 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3555 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3556 /// to morph to an integer compare sequence.
3557 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3558 const ARMSubtarget *Subtarget) {
3559 SDNode *N = Op.getNode();
3560 if (!N->hasOneUse())
3561 // Otherwise it requires moving the value from fp to integer registers.
3563 if (!N->getNumValues())
3565 EVT VT = Op.getValueType();
3566 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3567 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3568 // vmrs are very slow, e.g. cortex-a8.
3571 if (isFloatingPointZero(Op)) {
3575 return ISD::isNormalLoad(N);
3578 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3579 if (isFloatingPointZero(Op))
3580 return DAG.getConstant(0, MVT::i32);
3582 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3583 return DAG.getLoad(MVT::i32, SDLoc(Op),
3584 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3585 Ld->isVolatile(), Ld->isNonTemporal(),
3586 Ld->isInvariant(), Ld->getAlignment());
3588 llvm_unreachable("Unknown VFP cmp argument!");
3591 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3592 SDValue &RetVal1, SDValue &RetVal2) {
3593 if (isFloatingPointZero(Op)) {
3594 RetVal1 = DAG.getConstant(0, MVT::i32);
3595 RetVal2 = DAG.getConstant(0, MVT::i32);
3599 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3600 SDValue Ptr = Ld->getBasePtr();
3601 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3602 Ld->getChain(), Ptr,
3603 Ld->getPointerInfo(),
3604 Ld->isVolatile(), Ld->isNonTemporal(),
3605 Ld->isInvariant(), Ld->getAlignment());
3607 EVT PtrType = Ptr.getValueType();
3608 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3609 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3610 PtrType, Ptr, DAG.getConstant(4, PtrType));
3611 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3612 Ld->getChain(), NewPtr,
3613 Ld->getPointerInfo().getWithOffset(4),
3614 Ld->isVolatile(), Ld->isNonTemporal(),
3615 Ld->isInvariant(), NewAlign);
3619 llvm_unreachable("Unknown VFP cmp argument!");
3622 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3623 /// f32 and even f64 comparisons to integer ones.
3625 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3626 SDValue Chain = Op.getOperand(0);
3627 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3628 SDValue LHS = Op.getOperand(2);
3629 SDValue RHS = Op.getOperand(3);
3630 SDValue Dest = Op.getOperand(4);
3633 bool LHSSeenZero = false;
3634 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3635 bool RHSSeenZero = false;
3636 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3637 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3638 // If unsafe fp math optimization is enabled and there are no other uses of
3639 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3640 // to an integer comparison.
3641 if (CC == ISD::SETOEQ)
3643 else if (CC == ISD::SETUNE)
3646 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3648 if (LHS.getValueType() == MVT::f32) {
3649 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3650 bitcastf32Toi32(LHS, DAG), Mask);
3651 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3652 bitcastf32Toi32(RHS, DAG), Mask);
3653 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3654 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3655 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3656 Chain, Dest, ARMcc, CCR, Cmp);
3661 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3662 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3663 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3664 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3665 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3666 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3667 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3668 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3669 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3675 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3676 SDValue Chain = Op.getOperand(0);
3677 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3678 SDValue LHS = Op.getOperand(2);
3679 SDValue RHS = Op.getOperand(3);
3680 SDValue Dest = Op.getOperand(4);
3683 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3684 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3687 // If softenSetCCOperands only returned one value, we should compare it to
3689 if (!RHS.getNode()) {
3690 RHS = DAG.getConstant(0, LHS.getValueType());
3695 if (LHS.getValueType() == MVT::i32) {
3697 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3698 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3699 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3700 Chain, Dest, ARMcc, CCR, Cmp);
3703 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3705 if (getTargetMachine().Options.UnsafeFPMath &&
3706 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3707 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3708 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3709 if (Result.getNode())
3713 ARMCC::CondCodes CondCode, CondCode2;
3714 FPCCToARMCC(CC, CondCode, CondCode2);
3716 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3717 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3718 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3719 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3720 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3721 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3722 if (CondCode2 != ARMCC::AL) {
3723 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3724 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3725 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3730 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3731 SDValue Chain = Op.getOperand(0);
3732 SDValue Table = Op.getOperand(1);
3733 SDValue Index = Op.getOperand(2);
3736 EVT PTy = getPointerTy();
3737 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3738 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3739 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3740 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3741 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3742 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3743 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3744 if (Subtarget->isThumb2()) {
3745 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3746 // which does another jump to the destination. This also makes it easier
3747 // to translate it to TBB / TBH later.
3748 // FIXME: This might not work if the function is extremely large.
3749 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3750 Addr, Op.getOperand(2), JTI, UId);
3752 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3753 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3754 MachinePointerInfo::getJumpTable(),
3755 false, false, false, 0);
3756 Chain = Addr.getValue(1);
3757 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3758 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3760 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3761 MachinePointerInfo::getJumpTable(),
3762 false, false, false, 0);
3763 Chain = Addr.getValue(1);
3764 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3768 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3769 EVT VT = Op.getValueType();
3772 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3773 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3775 return DAG.UnrollVectorOp(Op.getNode());
3778 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3779 "Invalid type for custom lowering!");
3780 if (VT != MVT::v4i16)
3781 return DAG.UnrollVectorOp(Op.getNode());
3783 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3784 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3787 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3788 EVT VT = Op.getValueType();
3790 return LowerVectorFP_TO_INT(Op, DAG);
3791 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3793 if (Op.getOpcode() == ISD::FP_TO_SINT)
3794 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3797 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3799 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3800 /*isSigned*/ false, SDLoc(Op)).first;
3806 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3807 EVT VT = Op.getValueType();
3810 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3811 if (VT.getVectorElementType() == MVT::f32)
3813 return DAG.UnrollVectorOp(Op.getNode());
3816 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3817 "Invalid type for custom lowering!");
3818 if (VT != MVT::v4f32)
3819 return DAG.UnrollVectorOp(Op.getNode());
3823 switch (Op.getOpcode()) {
3824 default: llvm_unreachable("Invalid opcode!");
3825 case ISD::SINT_TO_FP:
3826 CastOpc = ISD::SIGN_EXTEND;
3827 Opc = ISD::SINT_TO_FP;
3829 case ISD::UINT_TO_FP:
3830 CastOpc = ISD::ZERO_EXTEND;
3831 Opc = ISD::UINT_TO_FP;
3835 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3836 return DAG.getNode(Opc, dl, VT, Op);
3839 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3840 EVT VT = Op.getValueType();
3842 return LowerVectorINT_TO_FP(Op, DAG);
3843 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3845 if (Op.getOpcode() == ISD::SINT_TO_FP)
3846 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3849 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3851 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3852 /*isSigned*/ false, SDLoc(Op)).first;
3858 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3859 // Implement fcopysign with a fabs and a conditional fneg.
3860 SDValue Tmp0 = Op.getOperand(0);
3861 SDValue Tmp1 = Op.getOperand(1);
3863 EVT VT = Op.getValueType();
3864 EVT SrcVT = Tmp1.getValueType();
3865 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3866 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3867 bool UseNEON = !InGPR && Subtarget->hasNEON();
3870 // Use VBSL to copy the sign bit.
3871 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3872 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3873 DAG.getTargetConstant(EncodedVal, MVT::i32));
3874 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3876 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3877 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3878 DAG.getConstant(32, MVT::i32));
3879 else /*if (VT == MVT::f32)*/
3880 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3881 if (SrcVT == MVT::f32) {
3882 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3884 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3885 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3886 DAG.getConstant(32, MVT::i32));
3887 } else if (VT == MVT::f32)
3888 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3889 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3890 DAG.getConstant(32, MVT::i32));
3891 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3892 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3894 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3896 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3897 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3898 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3900 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3901 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3902 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3903 if (VT == MVT::f32) {
3904 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3905 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3906 DAG.getConstant(0, MVT::i32));
3908 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3914 // Bitcast operand 1 to i32.
3915 if (SrcVT == MVT::f64)
3916 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3918 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3920 // Or in the signbit with integer operations.
3921 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3922 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3923 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3924 if (VT == MVT::f32) {
3925 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3926 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3927 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3928 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3931 // f64: Or the high part with signbit and then combine two parts.
3932 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3934 SDValue Lo = Tmp0.getValue(0);
3935 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3936 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3937 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3940 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3941 MachineFunction &MF = DAG.getMachineFunction();
3942 MachineFrameInfo *MFI = MF.getFrameInfo();
3943 MFI->setReturnAddressIsTaken(true);
3945 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3948 EVT VT = Op.getValueType();
3950 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3952 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3953 SDValue Offset = DAG.getConstant(4, MVT::i32);
3954 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3955 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3956 MachinePointerInfo(), false, false, false, 0);
3959 // Return LR, which contains the return address. Mark it an implicit live-in.
3960 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3961 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3964 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3965 const ARMBaseRegisterInfo &ARI =
3966 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3967 MachineFunction &MF = DAG.getMachineFunction();
3968 MachineFrameInfo *MFI = MF.getFrameInfo();
3969 MFI->setFrameAddressIsTaken(true);
3971 EVT VT = Op.getValueType();
3972 SDLoc dl(Op); // FIXME probably not meaningful
3973 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3974 unsigned FrameReg = ARI.getFrameRegister(MF);
3975 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3977 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3978 MachinePointerInfo(),
3979 false, false, false, 0);
3983 // FIXME? Maybe this could be a TableGen attribute on some registers and
3984 // this table could be generated automatically from RegInfo.
3985 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3987 unsigned Reg = StringSwitch<unsigned>(RegName)
3988 .Case("sp", ARM::SP)
3992 report_fatal_error("Invalid register name global variable");
3995 /// ExpandBITCAST - If the target supports VFP, this function is called to
3996 /// expand a bit convert where either the source or destination type is i64 to
3997 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3998 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3999 /// vectors), since the legalizer won't know what to do with that.
4000 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4001 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4003 SDValue Op = N->getOperand(0);
4005 // This function is only supposed to be called for i64 types, either as the
4006 // source or destination of the bit convert.
4007 EVT SrcVT = Op.getValueType();
4008 EVT DstVT = N->getValueType(0);
4009 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4010 "ExpandBITCAST called for non-i64 type");
4012 // Turn i64->f64 into VMOVDRR.
4013 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4014 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4015 DAG.getConstant(0, MVT::i32));
4016 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4017 DAG.getConstant(1, MVT::i32));
4018 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4019 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4022 // Turn f64->i64 into VMOVRRD.
4023 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4025 if (TLI.isBigEndian() && SrcVT.isVector() &&
4026 SrcVT.getVectorNumElements() > 1)
4027 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4028 DAG.getVTList(MVT::i32, MVT::i32),
4029 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4031 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4032 DAG.getVTList(MVT::i32, MVT::i32), Op);
4033 // Merge the pieces into a single i64 value.
4034 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4040 /// getZeroVector - Returns a vector of specified type with all zero elements.
4041 /// Zero vectors are used to represent vector negation and in those cases
4042 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4043 /// not support i64 elements, so sometimes the zero vectors will need to be
4044 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4046 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4047 assert(VT.isVector() && "Expected a vector type");
4048 // The canonical modified immediate encoding of a zero vector is....0!
4049 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4050 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4051 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4052 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4055 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4056 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4057 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4058 SelectionDAG &DAG) const {
4059 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4060 EVT VT = Op.getValueType();
4061 unsigned VTBits = VT.getSizeInBits();
4063 SDValue ShOpLo = Op.getOperand(0);
4064 SDValue ShOpHi = Op.getOperand(1);
4065 SDValue ShAmt = Op.getOperand(2);
4067 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4069 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4071 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4072 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4073 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4074 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4075 DAG.getConstant(VTBits, MVT::i32));
4076 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4077 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4078 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4080 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4081 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4083 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4084 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4087 SDValue Ops[2] = { Lo, Hi };
4088 return DAG.getMergeValues(Ops, dl);
4091 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4092 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4093 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4094 SelectionDAG &DAG) const {
4095 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4096 EVT VT = Op.getValueType();
4097 unsigned VTBits = VT.getSizeInBits();
4099 SDValue ShOpLo = Op.getOperand(0);
4100 SDValue ShOpHi = Op.getOperand(1);
4101 SDValue ShAmt = Op.getOperand(2);
4104 assert(Op.getOpcode() == ISD::SHL_PARTS);
4105 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4106 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4107 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4108 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4109 DAG.getConstant(VTBits, MVT::i32));
4110 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4111 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4113 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4114 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4115 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4117 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4118 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4121 SDValue Ops[2] = { Lo, Hi };
4122 return DAG.getMergeValues(Ops, dl);
4125 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4126 SelectionDAG &DAG) const {
4127 // The rounding mode is in bits 23:22 of the FPSCR.
4128 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4129 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4130 // so that the shift + and get folded into a bitfield extract.
4132 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4133 DAG.getConstant(Intrinsic::arm_get_fpscr,
4135 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4136 DAG.getConstant(1U << 22, MVT::i32));
4137 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4138 DAG.getConstant(22, MVT::i32));
4139 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4140 DAG.getConstant(3, MVT::i32));
4143 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4144 const ARMSubtarget *ST) {
4145 EVT VT = N->getValueType(0);
4148 if (!ST->hasV6T2Ops())
4151 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4152 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4155 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4156 /// for each 16-bit element from operand, repeated. The basic idea is to
4157 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4159 /// Trace for v4i16:
4160 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4161 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4162 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4163 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4164 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4165 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4166 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4167 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4168 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4169 EVT VT = N->getValueType(0);
4172 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4173 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4174 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4175 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4176 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4177 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4180 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4181 /// bit-count for each 16-bit element from the operand. We need slightly
4182 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4183 /// 64/128-bit registers.
4185 /// Trace for v4i16:
4186 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4187 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4188 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4189 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4190 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4191 EVT VT = N->getValueType(0);
4194 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4195 if (VT.is64BitVector()) {
4196 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4197 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4198 DAG.getIntPtrConstant(0));
4200 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4201 BitCounts, DAG.getIntPtrConstant(0));
4202 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4206 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4207 /// bit-count for each 32-bit element from the operand. The idea here is
4208 /// to split the vector into 16-bit elements, leverage the 16-bit count
4209 /// routine, and then combine the results.
4211 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4212 /// input = [v0 v1 ] (vi: 32-bit elements)
4213 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4214 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4215 /// vrev: N0 = [k1 k0 k3 k2 ]
4217 /// N1 =+[k1 k0 k3 k2 ]
4219 /// N2 =+[k1 k3 k0 k2 ]
4221 /// Extended =+[k1 k3 k0 k2 ]
4223 /// Extracted=+[k1 k3 ]
4225 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4226 EVT VT = N->getValueType(0);
4229 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4231 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4232 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4233 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4234 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4235 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4237 if (VT.is64BitVector()) {
4238 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4239 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4240 DAG.getIntPtrConstant(0));
4242 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4243 DAG.getIntPtrConstant(0));
4244 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4248 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4249 const ARMSubtarget *ST) {
4250 EVT VT = N->getValueType(0);
4252 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4253 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4254 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4255 "Unexpected type for custom ctpop lowering");
4257 if (VT.getVectorElementType() == MVT::i32)
4258 return lowerCTPOP32BitElements(N, DAG);
4260 return lowerCTPOP16BitElements(N, DAG);
4263 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4264 const ARMSubtarget *ST) {
4265 EVT VT = N->getValueType(0);
4271 // Lower vector shifts on NEON to use VSHL.
4272 assert(ST->hasNEON() && "unexpected vector shift");
4274 // Left shifts translate directly to the vshiftu intrinsic.
4275 if (N->getOpcode() == ISD::SHL)
4276 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4277 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4278 N->getOperand(0), N->getOperand(1));
4280 assert((N->getOpcode() == ISD::SRA ||
4281 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4283 // NEON uses the same intrinsics for both left and right shifts. For
4284 // right shifts, the shift amounts are negative, so negate the vector of
4286 EVT ShiftVT = N->getOperand(1).getValueType();
4287 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4288 getZeroVector(ShiftVT, DAG, dl),
4290 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4291 Intrinsic::arm_neon_vshifts :
4292 Intrinsic::arm_neon_vshiftu);
4293 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4294 DAG.getConstant(vshiftInt, MVT::i32),
4295 N->getOperand(0), NegatedCount);
4298 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4299 const ARMSubtarget *ST) {
4300 EVT VT = N->getValueType(0);
4303 // We can get here for a node like i32 = ISD::SHL i32, i64
4307 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4308 "Unknown shift to lower!");
4310 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4311 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4312 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4315 // If we are in thumb mode, we don't have RRX.
4316 if (ST->isThumb1Only()) return SDValue();
4318 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4319 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4320 DAG.getConstant(0, MVT::i32));
4321 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4322 DAG.getConstant(1, MVT::i32));
4324 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4325 // captures the result into a carry flag.
4326 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4327 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4329 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4330 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4332 // Merge the pieces into a single i64 value.
4333 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4336 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4337 SDValue TmpOp0, TmpOp1;
4338 bool Invert = false;
4342 SDValue Op0 = Op.getOperand(0);
4343 SDValue Op1 = Op.getOperand(1);
4344 SDValue CC = Op.getOperand(2);
4345 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4346 EVT VT = Op.getValueType();
4347 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4350 if (Op1.getValueType().isFloatingPoint()) {
4351 switch (SetCCOpcode) {
4352 default: llvm_unreachable("Illegal FP comparison");
4354 case ISD::SETNE: Invert = true; // Fallthrough
4356 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4358 case ISD::SETLT: Swap = true; // Fallthrough
4360 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4362 case ISD::SETLE: Swap = true; // Fallthrough
4364 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4365 case ISD::SETUGE: Swap = true; // Fallthrough
4366 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4367 case ISD::SETUGT: Swap = true; // Fallthrough
4368 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4369 case ISD::SETUEQ: Invert = true; // Fallthrough
4371 // Expand this to (OLT | OGT).
4375 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4376 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4378 case ISD::SETUO: Invert = true; // Fallthrough
4380 // Expand this to (OLT | OGE).
4384 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4385 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4389 // Integer comparisons.
4390 switch (SetCCOpcode) {
4391 default: llvm_unreachable("Illegal integer comparison");
4392 case ISD::SETNE: Invert = true;
4393 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4394 case ISD::SETLT: Swap = true;
4395 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4396 case ISD::SETLE: Swap = true;
4397 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4398 case ISD::SETULT: Swap = true;
4399 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4400 case ISD::SETULE: Swap = true;
4401 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4404 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4405 if (Opc == ARMISD::VCEQ) {
4408 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4410 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4413 // Ignore bitconvert.
4414 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4415 AndOp = AndOp.getOperand(0);
4417 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4419 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4420 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4427 std::swap(Op0, Op1);
4429 // If one of the operands is a constant vector zero, attempt to fold the
4430 // comparison to a specialized compare-against-zero form.
4432 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4434 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4435 if (Opc == ARMISD::VCGE)
4436 Opc = ARMISD::VCLEZ;
4437 else if (Opc == ARMISD::VCGT)
4438 Opc = ARMISD::VCLTZ;
4443 if (SingleOp.getNode()) {
4446 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4448 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4450 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4452 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4454 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4456 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4459 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4462 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4465 Result = DAG.getNOT(dl, Result, VT);
4470 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4471 /// valid vector constant for a NEON instruction with a "modified immediate"
4472 /// operand (e.g., VMOV). If so, return the encoded value.
4473 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4474 unsigned SplatBitSize, SelectionDAG &DAG,
4475 EVT &VT, bool is128Bits, NEONModImmType type) {
4476 unsigned OpCmode, Imm;
4478 // SplatBitSize is set to the smallest size that splats the vector, so a
4479 // zero vector will always have SplatBitSize == 8. However, NEON modified
4480 // immediate instructions others than VMOV do not support the 8-bit encoding
4481 // of a zero vector, and the default encoding of zero is supposed to be the
4486 switch (SplatBitSize) {
4488 if (type != VMOVModImm)
4490 // Any 1-byte value is OK. Op=0, Cmode=1110.
4491 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4494 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4498 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4499 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4500 if ((SplatBits & ~0xff) == 0) {
4501 // Value = 0x00nn: Op=x, Cmode=100x.
4506 if ((SplatBits & ~0xff00) == 0) {
4507 // Value = 0xnn00: Op=x, Cmode=101x.
4509 Imm = SplatBits >> 8;
4515 // NEON's 32-bit VMOV supports splat values where:
4516 // * only one byte is nonzero, or
4517 // * the least significant byte is 0xff and the second byte is nonzero, or
4518 // * the least significant 2 bytes are 0xff and the third is nonzero.
4519 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4520 if ((SplatBits & ~0xff) == 0) {
4521 // Value = 0x000000nn: Op=x, Cmode=000x.
4526 if ((SplatBits & ~0xff00) == 0) {
4527 // Value = 0x0000nn00: Op=x, Cmode=001x.
4529 Imm = SplatBits >> 8;
4532 if ((SplatBits & ~0xff0000) == 0) {
4533 // Value = 0x00nn0000: Op=x, Cmode=010x.
4535 Imm = SplatBits >> 16;
4538 if ((SplatBits & ~0xff000000) == 0) {
4539 // Value = 0xnn000000: Op=x, Cmode=011x.
4541 Imm = SplatBits >> 24;
4545 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4546 if (type == OtherModImm) return SDValue();
4548 if ((SplatBits & ~0xffff) == 0 &&
4549 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4550 // Value = 0x0000nnff: Op=x, Cmode=1100.
4552 Imm = SplatBits >> 8;
4556 if ((SplatBits & ~0xffffff) == 0 &&
4557 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4558 // Value = 0x00nnffff: Op=x, Cmode=1101.
4560 Imm = SplatBits >> 16;
4564 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4565 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4566 // VMOV.I32. A (very) minor optimization would be to replicate the value
4567 // and fall through here to test for a valid 64-bit splat. But, then the
4568 // caller would also need to check and handle the change in size.
4572 if (type != VMOVModImm)
4574 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4575 uint64_t BitMask = 0xff;
4577 unsigned ImmMask = 1;
4579 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4580 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4583 } else if ((SplatBits & BitMask) != 0) {
4590 if (DAG.getTargetLoweringInfo().isBigEndian())
4591 // swap higher and lower 32 bit word
4592 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4594 // Op=1, Cmode=1110.
4596 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4601 llvm_unreachable("unexpected size for isNEONModifiedImm");
4604 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4605 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4608 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4609 const ARMSubtarget *ST) const {
4613 bool IsDouble = Op.getValueType() == MVT::f64;
4614 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4616 // Use the default (constant pool) lowering for double constants when we have
4618 if (IsDouble && Subtarget->isFPOnlySP())
4621 // Try splatting with a VMOV.f32...
4622 APFloat FPVal = CFP->getValueAPF();
4623 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4626 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4627 // We have code in place to select a valid ConstantFP already, no need to
4632 // It's a float and we are trying to use NEON operations where
4633 // possible. Lower it to a splat followed by an extract.
4635 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4636 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4638 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4639 DAG.getConstant(0, MVT::i32));
4642 // The rest of our options are NEON only, make sure that's allowed before
4644 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4648 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4650 // It wouldn't really be worth bothering for doubles except for one very
4651 // important value, which does happen to match: 0.0. So make sure we don't do
4653 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4656 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4657 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4659 if (NewVal != SDValue()) {
4661 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4664 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4666 // It's a float: cast and extract a vector element.
4667 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4669 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4670 DAG.getConstant(0, MVT::i32));
4673 // Finally, try a VMVN.i32
4674 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4676 if (NewVal != SDValue()) {
4678 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4681 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4683 // It's a float: cast and extract a vector element.
4684 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4686 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4687 DAG.getConstant(0, MVT::i32));
4693 // check if an VEXT instruction can handle the shuffle mask when the
4694 // vector sources of the shuffle are the same.
4695 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4696 unsigned NumElts = VT.getVectorNumElements();
4698 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4704 // If this is a VEXT shuffle, the immediate value is the index of the first
4705 // element. The other shuffle indices must be the successive elements after
4707 unsigned ExpectedElt = Imm;
4708 for (unsigned i = 1; i < NumElts; ++i) {
4709 // Increment the expected index. If it wraps around, just follow it
4710 // back to index zero and keep going.
4712 if (ExpectedElt == NumElts)
4715 if (M[i] < 0) continue; // ignore UNDEF indices
4716 if (ExpectedElt != static_cast<unsigned>(M[i]))
4724 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4725 bool &ReverseVEXT, unsigned &Imm) {
4726 unsigned NumElts = VT.getVectorNumElements();
4727 ReverseVEXT = false;
4729 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4735 // If this is a VEXT shuffle, the immediate value is the index of the first
4736 // element. The other shuffle indices must be the successive elements after
4738 unsigned ExpectedElt = Imm;
4739 for (unsigned i = 1; i < NumElts; ++i) {
4740 // Increment the expected index. If it wraps around, it may still be
4741 // a VEXT but the source vectors must be swapped.
4743 if (ExpectedElt == NumElts * 2) {
4748 if (M[i] < 0) continue; // ignore UNDEF indices
4749 if (ExpectedElt != static_cast<unsigned>(M[i]))
4753 // Adjust the index value if the source operands will be swapped.
4760 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4761 /// instruction with the specified blocksize. (The order of the elements
4762 /// within each block of the vector is reversed.)
4763 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4764 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4765 "Only possible block sizes for VREV are: 16, 32, 64");
4767 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4771 unsigned NumElts = VT.getVectorNumElements();
4772 unsigned BlockElts = M[0] + 1;
4773 // If the first shuffle index is UNDEF, be optimistic.
4775 BlockElts = BlockSize / EltSz;
4777 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4780 for (unsigned i = 0; i < NumElts; ++i) {
4781 if (M[i] < 0) continue; // ignore UNDEF indices
4782 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4789 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4790 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4791 // range, then 0 is placed into the resulting vector. So pretty much any mask
4792 // of 8 elements can work here.
4793 return VT == MVT::v8i8 && M.size() == 8;
4796 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4797 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4801 unsigned NumElts = VT.getVectorNumElements();
4802 WhichResult = (M[0] == 0 ? 0 : 1);
4803 for (unsigned i = 0; i < NumElts; i += 2) {
4804 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4805 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4811 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4812 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4813 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4814 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4815 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4819 unsigned NumElts = VT.getVectorNumElements();
4820 WhichResult = (M[0] == 0 ? 0 : 1);
4821 for (unsigned i = 0; i < NumElts; i += 2) {
4822 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4823 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4829 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4830 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4834 unsigned NumElts = VT.getVectorNumElements();
4835 WhichResult = (M[0] == 0 ? 0 : 1);
4836 for (unsigned i = 0; i != NumElts; ++i) {
4837 if (M[i] < 0) continue; // ignore UNDEF indices
4838 if ((unsigned) M[i] != 2 * i + WhichResult)
4842 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4843 if (VT.is64BitVector() && EltSz == 32)
4849 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4850 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4851 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4852 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4853 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4857 unsigned Half = VT.getVectorNumElements() / 2;
4858 WhichResult = (M[0] == 0 ? 0 : 1);
4859 for (unsigned j = 0; j != 2; ++j) {
4860 unsigned Idx = WhichResult;
4861 for (unsigned i = 0; i != Half; ++i) {
4862 int MIdx = M[i + j * Half];
4863 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4869 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4870 if (VT.is64BitVector() && EltSz == 32)
4876 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4877 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4881 unsigned NumElts = VT.getVectorNumElements();
4882 WhichResult = (M[0] == 0 ? 0 : 1);
4883 unsigned Idx = WhichResult * NumElts / 2;
4884 for (unsigned i = 0; i != NumElts; i += 2) {
4885 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4886 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4891 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4892 if (VT.is64BitVector() && EltSz == 32)
4898 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4899 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4900 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4901 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4902 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4906 unsigned NumElts = VT.getVectorNumElements();
4907 WhichResult = (M[0] == 0 ? 0 : 1);
4908 unsigned Idx = WhichResult * NumElts / 2;
4909 for (unsigned i = 0; i != NumElts; i += 2) {
4910 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4911 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4916 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4917 if (VT.is64BitVector() && EltSz == 32)
4923 /// \return true if this is a reverse operation on an vector.
4924 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4925 unsigned NumElts = VT.getVectorNumElements();
4926 // Make sure the mask has the right size.
4927 if (NumElts != M.size())
4930 // Look for <15, ..., 3, -1, 1, 0>.
4931 for (unsigned i = 0; i != NumElts; ++i)
4932 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4938 // If N is an integer constant that can be moved into a register in one
4939 // instruction, return an SDValue of such a constant (will become a MOV
4940 // instruction). Otherwise return null.
4941 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4942 const ARMSubtarget *ST, SDLoc dl) {
4944 if (!isa<ConstantSDNode>(N))
4946 Val = cast<ConstantSDNode>(N)->getZExtValue();
4948 if (ST->isThumb1Only()) {
4949 if (Val <= 255 || ~Val <= 255)
4950 return DAG.getConstant(Val, MVT::i32);
4952 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4953 return DAG.getConstant(Val, MVT::i32);
4958 // If this is a case we can't handle, return null and let the default
4959 // expansion code take care of it.
4960 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4961 const ARMSubtarget *ST) const {
4962 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4964 EVT VT = Op.getValueType();
4966 APInt SplatBits, SplatUndef;
4967 unsigned SplatBitSize;
4969 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4970 if (SplatBitSize <= 64) {
4971 // Check if an immediate VMOV works.
4973 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4974 SplatUndef.getZExtValue(), SplatBitSize,
4975 DAG, VmovVT, VT.is128BitVector(),
4977 if (Val.getNode()) {
4978 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4979 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4982 // Try an immediate VMVN.
4983 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4984 Val = isNEONModifiedImm(NegatedImm,
4985 SplatUndef.getZExtValue(), SplatBitSize,
4986 DAG, VmovVT, VT.is128BitVector(),
4988 if (Val.getNode()) {
4989 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4990 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4993 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4994 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4995 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4997 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4998 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5004 // Scan through the operands to see if only one value is used.
5006 // As an optimisation, even if more than one value is used it may be more
5007 // profitable to splat with one value then change some lanes.
5009 // Heuristically we decide to do this if the vector has a "dominant" value,
5010 // defined as splatted to more than half of the lanes.
5011 unsigned NumElts = VT.getVectorNumElements();
5012 bool isOnlyLowElement = true;
5013 bool usesOnlyOneValue = true;
5014 bool hasDominantValue = false;
5015 bool isConstant = true;
5017 // Map of the number of times a particular SDValue appears in the
5019 DenseMap<SDValue, unsigned> ValueCounts;
5021 for (unsigned i = 0; i < NumElts; ++i) {
5022 SDValue V = Op.getOperand(i);
5023 if (V.getOpcode() == ISD::UNDEF)
5026 isOnlyLowElement = false;
5027 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5030 ValueCounts.insert(std::make_pair(V, 0));
5031 unsigned &Count = ValueCounts[V];
5033 // Is this value dominant? (takes up more than half of the lanes)
5034 if (++Count > (NumElts / 2)) {
5035 hasDominantValue = true;
5039 if (ValueCounts.size() != 1)
5040 usesOnlyOneValue = false;
5041 if (!Value.getNode() && ValueCounts.size() > 0)
5042 Value = ValueCounts.begin()->first;
5044 if (ValueCounts.size() == 0)
5045 return DAG.getUNDEF(VT);
5047 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5048 // Keep going if we are hitting this case.
5049 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5050 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5052 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5054 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5055 // i32 and try again.
5056 if (hasDominantValue && EltSize <= 32) {
5060 // If we are VDUPing a value that comes directly from a vector, that will
5061 // cause an unnecessary move to and from a GPR, where instead we could
5062 // just use VDUPLANE. We can only do this if the lane being extracted
5063 // is at a constant index, as the VDUP from lane instructions only have
5064 // constant-index forms.
5065 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5066 isa<ConstantSDNode>(Value->getOperand(1))) {
5067 // We need to create a new undef vector to use for the VDUPLANE if the
5068 // size of the vector from which we get the value is different than the
5069 // size of the vector that we need to create. We will insert the element
5070 // such that the register coalescer will remove unnecessary copies.
5071 if (VT != Value->getOperand(0).getValueType()) {
5072 ConstantSDNode *constIndex;
5073 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5074 assert(constIndex && "The index is not a constant!");
5075 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5076 VT.getVectorNumElements();
5077 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5078 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5079 Value, DAG.getConstant(index, MVT::i32)),
5080 DAG.getConstant(index, MVT::i32));
5082 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5083 Value->getOperand(0), Value->getOperand(1));
5085 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5087 if (!usesOnlyOneValue) {
5088 // The dominant value was splatted as 'N', but we now have to insert
5089 // all differing elements.
5090 for (unsigned I = 0; I < NumElts; ++I) {
5091 if (Op.getOperand(I) == Value)
5093 SmallVector<SDValue, 3> Ops;
5095 Ops.push_back(Op.getOperand(I));
5096 Ops.push_back(DAG.getConstant(I, MVT::i32));
5097 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5102 if (VT.getVectorElementType().isFloatingPoint()) {
5103 SmallVector<SDValue, 8> Ops;
5104 for (unsigned i = 0; i < NumElts; ++i)
5105 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5107 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5108 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5109 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5111 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5113 if (usesOnlyOneValue) {
5114 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5115 if (isConstant && Val.getNode())
5116 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5120 // If all elements are constants and the case above didn't get hit, fall back
5121 // to the default expansion, which will generate a load from the constant
5126 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5128 SDValue shuffle = ReconstructShuffle(Op, DAG);
5129 if (shuffle != SDValue())
5133 // Vectors with 32- or 64-bit elements can be built by directly assigning
5134 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5135 // will be legalized.
5136 if (EltSize >= 32) {
5137 // Do the expansion with floating-point types, since that is what the VFP
5138 // registers are defined to use, and since i64 is not legal.
5139 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5140 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5141 SmallVector<SDValue, 8> Ops;
5142 for (unsigned i = 0; i < NumElts; ++i)
5143 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5144 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5145 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5148 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5149 // know the default expansion would otherwise fall back on something even
5150 // worse. For a vector with one or two non-undef values, that's
5151 // scalar_to_vector for the elements followed by a shuffle (provided the
5152 // shuffle is valid for the target) and materialization element by element
5153 // on the stack followed by a load for everything else.
5154 if (!isConstant && !usesOnlyOneValue) {
5155 SDValue Vec = DAG.getUNDEF(VT);
5156 for (unsigned i = 0 ; i < NumElts; ++i) {
5157 SDValue V = Op.getOperand(i);
5158 if (V.getOpcode() == ISD::UNDEF)
5160 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5161 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5169 // Gather data to see if the operation can be modelled as a
5170 // shuffle in combination with VEXTs.
5171 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5172 SelectionDAG &DAG) const {
5174 EVT VT = Op.getValueType();
5175 unsigned NumElts = VT.getVectorNumElements();
5177 SmallVector<SDValue, 2> SourceVecs;
5178 SmallVector<unsigned, 2> MinElts;
5179 SmallVector<unsigned, 2> MaxElts;
5181 for (unsigned i = 0; i < NumElts; ++i) {
5182 SDValue V = Op.getOperand(i);
5183 if (V.getOpcode() == ISD::UNDEF)
5185 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5186 // A shuffle can only come from building a vector from various
5187 // elements of other vectors.
5189 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5190 VT.getVectorElementType()) {
5191 // This code doesn't know how to handle shuffles where the vector
5192 // element types do not match (this happens because type legalization
5193 // promotes the return type of EXTRACT_VECTOR_ELT).
5194 // FIXME: It might be appropriate to extend this code to handle
5195 // mismatched types.
5199 // Record this extraction against the appropriate vector if possible...
5200 SDValue SourceVec = V.getOperand(0);
5201 // If the element number isn't a constant, we can't effectively
5202 // analyze what's going on.
5203 if (!isa<ConstantSDNode>(V.getOperand(1)))
5205 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5206 bool FoundSource = false;
5207 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5208 if (SourceVecs[j] == SourceVec) {
5209 if (MinElts[j] > EltNo)
5211 if (MaxElts[j] < EltNo)
5218 // Or record a new source if not...
5220 SourceVecs.push_back(SourceVec);
5221 MinElts.push_back(EltNo);
5222 MaxElts.push_back(EltNo);
5226 // Currently only do something sane when at most two source vectors
5228 if (SourceVecs.size() > 2)
5231 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5232 int VEXTOffsets[2] = {0, 0};
5234 // This loop extracts the usage patterns of the source vectors
5235 // and prepares appropriate SDValues for a shuffle if possible.
5236 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5237 if (SourceVecs[i].getValueType() == VT) {
5238 // No VEXT necessary
5239 ShuffleSrcs[i] = SourceVecs[i];
5242 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5243 // It probably isn't worth padding out a smaller vector just to
5244 // break it down again in a shuffle.
5248 // Since only 64-bit and 128-bit vectors are legal on ARM and
5249 // we've eliminated the other cases...
5250 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5251 "unexpected vector sizes in ReconstructShuffle");
5253 if (MaxElts[i] - MinElts[i] >= NumElts) {
5254 // Span too large for a VEXT to cope
5258 if (MinElts[i] >= NumElts) {
5259 // The extraction can just take the second half
5260 VEXTOffsets[i] = NumElts;
5261 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5263 DAG.getIntPtrConstant(NumElts));
5264 } else if (MaxElts[i] < NumElts) {
5265 // The extraction can just take the first half
5267 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5269 DAG.getIntPtrConstant(0));
5271 // An actual VEXT is needed
5272 VEXTOffsets[i] = MinElts[i];
5273 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5275 DAG.getIntPtrConstant(0));
5276 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5278 DAG.getIntPtrConstant(NumElts));
5279 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5280 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5284 SmallVector<int, 8> Mask;
5286 for (unsigned i = 0; i < NumElts; ++i) {
5287 SDValue Entry = Op.getOperand(i);
5288 if (Entry.getOpcode() == ISD::UNDEF) {
5293 SDValue ExtractVec = Entry.getOperand(0);
5294 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5295 .getOperand(1))->getSExtValue();
5296 if (ExtractVec == SourceVecs[0]) {
5297 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5299 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5303 // Final check before we try to produce nonsense...
5304 if (isShuffleMaskLegal(Mask, VT))
5305 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5311 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5312 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5313 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5314 /// are assumed to be legal.
5316 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5318 if (VT.getVectorNumElements() == 4 &&
5319 (VT.is128BitVector() || VT.is64BitVector())) {
5320 unsigned PFIndexes[4];
5321 for (unsigned i = 0; i != 4; ++i) {
5325 PFIndexes[i] = M[i];
5328 // Compute the index in the perfect shuffle table.
5329 unsigned PFTableIndex =
5330 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5331 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5332 unsigned Cost = (PFEntry >> 30);
5339 unsigned Imm, WhichResult;
5341 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5342 return (EltSize >= 32 ||
5343 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5344 isVREVMask(M, VT, 64) ||
5345 isVREVMask(M, VT, 32) ||
5346 isVREVMask(M, VT, 16) ||
5347 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5348 isVTBLMask(M, VT) ||
5349 isVTRNMask(M, VT, WhichResult) ||
5350 isVUZPMask(M, VT, WhichResult) ||
5351 isVZIPMask(M, VT, WhichResult) ||
5352 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5353 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5354 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5355 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5358 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5359 /// the specified operations to build the shuffle.
5360 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5361 SDValue RHS, SelectionDAG &DAG,
5363 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5364 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5365 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5368 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5377 OP_VUZPL, // VUZP, left result
5378 OP_VUZPR, // VUZP, right result
5379 OP_VZIPL, // VZIP, left result
5380 OP_VZIPR, // VZIP, right result
5381 OP_VTRNL, // VTRN, left result
5382 OP_VTRNR // VTRN, right result
5385 if (OpNum == OP_COPY) {
5386 if (LHSID == (1*9+2)*9+3) return LHS;
5387 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5391 SDValue OpLHS, OpRHS;
5392 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5393 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5394 EVT VT = OpLHS.getValueType();
5397 default: llvm_unreachable("Unknown shuffle opcode!");
5399 // VREV divides the vector in half and swaps within the half.
5400 if (VT.getVectorElementType() == MVT::i32 ||
5401 VT.getVectorElementType() == MVT::f32)
5402 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5403 // vrev <4 x i16> -> VREV32
5404 if (VT.getVectorElementType() == MVT::i16)
5405 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5406 // vrev <4 x i8> -> VREV16
5407 assert(VT.getVectorElementType() == MVT::i8);
5408 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5413 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5414 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5418 return DAG.getNode(ARMISD::VEXT, dl, VT,
5420 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5423 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5424 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5427 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5428 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5431 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5432 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5436 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5437 ArrayRef<int> ShuffleMask,
5438 SelectionDAG &DAG) {
5439 // Check to see if we can use the VTBL instruction.
5440 SDValue V1 = Op.getOperand(0);
5441 SDValue V2 = Op.getOperand(1);
5444 SmallVector<SDValue, 8> VTBLMask;
5445 for (ArrayRef<int>::iterator
5446 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5447 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5449 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5450 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5451 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5453 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5454 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5457 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5458 SelectionDAG &DAG) {
5460 SDValue OpLHS = Op.getOperand(0);
5461 EVT VT = OpLHS.getValueType();
5463 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5464 "Expect an v8i16/v16i8 type");
5465 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5466 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5467 // extract the first 8 bytes into the top double word and the last 8 bytes
5468 // into the bottom double word. The v8i16 case is similar.
5469 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5470 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5471 DAG.getConstant(ExtractNum, MVT::i32));
5474 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5475 SDValue V1 = Op.getOperand(0);
5476 SDValue V2 = Op.getOperand(1);
5478 EVT VT = Op.getValueType();
5479 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5481 // Convert shuffles that are directly supported on NEON to target-specific
5482 // DAG nodes, instead of keeping them as shuffles and matching them again
5483 // during code selection. This is more efficient and avoids the possibility
5484 // of inconsistencies between legalization and selection.
5485 // FIXME: floating-point vectors should be canonicalized to integer vectors
5486 // of the same time so that they get CSEd properly.
5487 ArrayRef<int> ShuffleMask = SVN->getMask();
5489 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5490 if (EltSize <= 32) {
5491 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5492 int Lane = SVN->getSplatIndex();
5493 // If this is undef splat, generate it via "just" vdup, if possible.
5494 if (Lane == -1) Lane = 0;
5496 // Test if V1 is a SCALAR_TO_VECTOR.
5497 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5498 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5500 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5501 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5503 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5504 !isa<ConstantSDNode>(V1.getOperand(0))) {
5505 bool IsScalarToVector = true;
5506 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5507 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5508 IsScalarToVector = false;
5511 if (IsScalarToVector)
5512 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5514 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5515 DAG.getConstant(Lane, MVT::i32));
5520 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5523 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5524 DAG.getConstant(Imm, MVT::i32));
5527 if (isVREVMask(ShuffleMask, VT, 64))
5528 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5529 if (isVREVMask(ShuffleMask, VT, 32))
5530 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5531 if (isVREVMask(ShuffleMask, VT, 16))
5532 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5534 if (V2->getOpcode() == ISD::UNDEF &&
5535 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5536 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5537 DAG.getConstant(Imm, MVT::i32));
5540 // Check for Neon shuffles that modify both input vectors in place.
5541 // If both results are used, i.e., if there are two shuffles with the same
5542 // source operands and with masks corresponding to both results of one of
5543 // these operations, DAG memoization will ensure that a single node is
5544 // used for both shuffles.
5545 unsigned WhichResult;
5546 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5547 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5548 V1, V2).getValue(WhichResult);
5549 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5550 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5551 V1, V2).getValue(WhichResult);
5552 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5553 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5554 V1, V2).getValue(WhichResult);
5556 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5557 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5558 V1, V1).getValue(WhichResult);
5559 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5560 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5561 V1, V1).getValue(WhichResult);
5562 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5563 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5564 V1, V1).getValue(WhichResult);
5567 // If the shuffle is not directly supported and it has 4 elements, use
5568 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5569 unsigned NumElts = VT.getVectorNumElements();
5571 unsigned PFIndexes[4];
5572 for (unsigned i = 0; i != 4; ++i) {
5573 if (ShuffleMask[i] < 0)
5576 PFIndexes[i] = ShuffleMask[i];
5579 // Compute the index in the perfect shuffle table.
5580 unsigned PFTableIndex =
5581 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5582 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5583 unsigned Cost = (PFEntry >> 30);
5586 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5589 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5590 if (EltSize >= 32) {
5591 // Do the expansion with floating-point types, since that is what the VFP
5592 // registers are defined to use, and since i64 is not legal.
5593 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5594 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5595 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5596 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5597 SmallVector<SDValue, 8> Ops;
5598 for (unsigned i = 0; i < NumElts; ++i) {
5599 if (ShuffleMask[i] < 0)
5600 Ops.push_back(DAG.getUNDEF(EltVT));
5602 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5603 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5604 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5607 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5608 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5611 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5612 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5614 if (VT == MVT::v8i8) {
5615 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5616 if (NewOp.getNode())
5623 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5624 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5625 SDValue Lane = Op.getOperand(2);
5626 if (!isa<ConstantSDNode>(Lane))
5632 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5633 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5634 SDValue Lane = Op.getOperand(1);
5635 if (!isa<ConstantSDNode>(Lane))
5638 SDValue Vec = Op.getOperand(0);
5639 if (Op.getValueType() == MVT::i32 &&
5640 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5642 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5648 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5649 // The only time a CONCAT_VECTORS operation can have legal types is when
5650 // two 64-bit vectors are concatenated to a 128-bit vector.
5651 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5652 "unexpected CONCAT_VECTORS");
5654 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5655 SDValue Op0 = Op.getOperand(0);
5656 SDValue Op1 = Op.getOperand(1);
5657 if (Op0.getOpcode() != ISD::UNDEF)
5658 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5659 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5660 DAG.getIntPtrConstant(0));
5661 if (Op1.getOpcode() != ISD::UNDEF)
5662 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5663 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5664 DAG.getIntPtrConstant(1));
5665 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5668 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5669 /// element has been zero/sign-extended, depending on the isSigned parameter,
5670 /// from an integer type half its size.
5671 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5673 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5674 EVT VT = N->getValueType(0);
5675 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5676 SDNode *BVN = N->getOperand(0).getNode();
5677 if (BVN->getValueType(0) != MVT::v4i32 ||
5678 BVN->getOpcode() != ISD::BUILD_VECTOR)
5680 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5681 unsigned HiElt = 1 - LoElt;
5682 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5683 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5684 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5685 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5686 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5689 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5690 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5693 if (Hi0->isNullValue() && Hi1->isNullValue())
5699 if (N->getOpcode() != ISD::BUILD_VECTOR)
5702 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5703 SDNode *Elt = N->getOperand(i).getNode();
5704 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5705 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5706 unsigned HalfSize = EltSize / 2;
5708 if (!isIntN(HalfSize, C->getSExtValue()))
5711 if (!isUIntN(HalfSize, C->getZExtValue()))
5722 /// isSignExtended - Check if a node is a vector value that is sign-extended
5723 /// or a constant BUILD_VECTOR with sign-extended elements.
5724 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5725 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5727 if (isExtendedBUILD_VECTOR(N, DAG, true))
5732 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5733 /// or a constant BUILD_VECTOR with zero-extended elements.
5734 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5735 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5737 if (isExtendedBUILD_VECTOR(N, DAG, false))
5742 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5743 if (OrigVT.getSizeInBits() >= 64)
5746 assert(OrigVT.isSimple() && "Expecting a simple value type");
5748 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5749 switch (OrigSimpleTy) {
5750 default: llvm_unreachable("Unexpected Vector Type");
5759 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5760 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5761 /// We insert the required extension here to get the vector to fill a D register.
5762 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5765 unsigned ExtOpcode) {
5766 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5767 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5768 // 64-bits we need to insert a new extension so that it will be 64-bits.
5769 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5770 if (OrigTy.getSizeInBits() >= 64)
5773 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5774 EVT NewVT = getExtensionTo64Bits(OrigTy);
5776 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5779 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5780 /// does not do any sign/zero extension. If the original vector is less
5781 /// than 64 bits, an appropriate extension will be added after the load to
5782 /// reach a total size of 64 bits. We have to add the extension separately
5783 /// because ARM does not have a sign/zero extending load for vectors.
5784 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5785 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5787 // The load already has the right type.
5788 if (ExtendedTy == LD->getMemoryVT())
5789 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5790 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5791 LD->isNonTemporal(), LD->isInvariant(),
5792 LD->getAlignment());
5794 // We need to create a zextload/sextload. We cannot just create a load
5795 // followed by a zext/zext node because LowerMUL is also run during normal
5796 // operation legalization where we can't create illegal types.
5797 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5798 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5799 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5800 LD->isNonTemporal(), LD->getAlignment());
5803 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5804 /// extending load, or BUILD_VECTOR with extended elements, return the
5805 /// unextended value. The unextended vector should be 64 bits so that it can
5806 /// be used as an operand to a VMULL instruction. If the original vector size
5807 /// before extension is less than 64 bits we add a an extension to resize
5808 /// the vector to 64 bits.
5809 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5810 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5811 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5812 N->getOperand(0)->getValueType(0),
5816 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5817 return SkipLoadExtensionForVMULL(LD, DAG);
5819 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5820 // have been legalized as a BITCAST from v4i32.
5821 if (N->getOpcode() == ISD::BITCAST) {
5822 SDNode *BVN = N->getOperand(0).getNode();
5823 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5824 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5825 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5826 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5827 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5829 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5830 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5831 EVT VT = N->getValueType(0);
5832 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5833 unsigned NumElts = VT.getVectorNumElements();
5834 MVT TruncVT = MVT::getIntegerVT(EltSize);
5835 SmallVector<SDValue, 8> Ops;
5836 for (unsigned i = 0; i != NumElts; ++i) {
5837 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5838 const APInt &CInt = C->getAPIntValue();
5839 // Element types smaller than 32 bits are not legal, so use i32 elements.
5840 // The values are implicitly truncated so sext vs. zext doesn't matter.
5841 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5843 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5844 MVT::getVectorVT(TruncVT, NumElts), Ops);
5847 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5848 unsigned Opcode = N->getOpcode();
5849 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5850 SDNode *N0 = N->getOperand(0).getNode();
5851 SDNode *N1 = N->getOperand(1).getNode();
5852 return N0->hasOneUse() && N1->hasOneUse() &&
5853 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5858 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5859 unsigned Opcode = N->getOpcode();
5860 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5861 SDNode *N0 = N->getOperand(0).getNode();
5862 SDNode *N1 = N->getOperand(1).getNode();
5863 return N0->hasOneUse() && N1->hasOneUse() &&
5864 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5869 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5870 // Multiplications are only custom-lowered for 128-bit vectors so that
5871 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5872 EVT VT = Op.getValueType();
5873 assert(VT.is128BitVector() && VT.isInteger() &&
5874 "unexpected type for custom-lowering ISD::MUL");
5875 SDNode *N0 = Op.getOperand(0).getNode();
5876 SDNode *N1 = Op.getOperand(1).getNode();
5877 unsigned NewOpc = 0;
5879 bool isN0SExt = isSignExtended(N0, DAG);
5880 bool isN1SExt = isSignExtended(N1, DAG);
5881 if (isN0SExt && isN1SExt)
5882 NewOpc = ARMISD::VMULLs;
5884 bool isN0ZExt = isZeroExtended(N0, DAG);
5885 bool isN1ZExt = isZeroExtended(N1, DAG);
5886 if (isN0ZExt && isN1ZExt)
5887 NewOpc = ARMISD::VMULLu;
5888 else if (isN1SExt || isN1ZExt) {
5889 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5890 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5891 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5892 NewOpc = ARMISD::VMULLs;
5894 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5895 NewOpc = ARMISD::VMULLu;
5897 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5899 NewOpc = ARMISD::VMULLu;
5905 if (VT == MVT::v2i64)
5906 // Fall through to expand this. It is not legal.
5909 // Other vector multiplications are legal.
5914 // Legalize to a VMULL instruction.
5917 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5919 Op0 = SkipExtensionForVMULL(N0, DAG);
5920 assert(Op0.getValueType().is64BitVector() &&
5921 Op1.getValueType().is64BitVector() &&
5922 "unexpected types for extended operands to VMULL");
5923 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5926 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5927 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5934 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5935 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5936 EVT Op1VT = Op1.getValueType();
5937 return DAG.getNode(N0->getOpcode(), DL, VT,
5938 DAG.getNode(NewOpc, DL, VT,
5939 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5940 DAG.getNode(NewOpc, DL, VT,
5941 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5945 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5947 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5948 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5949 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5950 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5951 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5952 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5953 // Get reciprocal estimate.
5954 // float4 recip = vrecpeq_f32(yf);
5955 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5956 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5957 // Because char has a smaller range than uchar, we can actually get away
5958 // without any newton steps. This requires that we use a weird bias
5959 // of 0xb000, however (again, this has been exhaustively tested).
5960 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5961 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5962 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5963 Y = DAG.getConstant(0xb000, MVT::i32);
5964 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5965 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5966 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5967 // Convert back to short.
5968 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5969 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5974 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5976 // Convert to float.
5977 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5978 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5979 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5980 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5981 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5982 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5984 // Use reciprocal estimate and one refinement step.
5985 // float4 recip = vrecpeq_f32(yf);
5986 // recip *= vrecpsq_f32(yf, recip);
5987 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5988 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5989 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5990 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5992 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5993 // Because short has a smaller range than ushort, we can actually get away
5994 // with only a single newton step. This requires that we use a weird bias
5995 // of 89, however (again, this has been exhaustively tested).
5996 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5997 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5998 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5999 N1 = DAG.getConstant(0x89, MVT::i32);
6000 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6001 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6002 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6003 // Convert back to integer and return.
6004 // return vmovn_s32(vcvt_s32_f32(result));
6005 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6006 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6010 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6011 EVT VT = Op.getValueType();
6012 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6013 "unexpected type for custom-lowering ISD::SDIV");
6016 SDValue N0 = Op.getOperand(0);
6017 SDValue N1 = Op.getOperand(1);
6020 if (VT == MVT::v8i8) {
6021 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6022 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6024 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6025 DAG.getIntPtrConstant(4));
6026 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6027 DAG.getIntPtrConstant(4));
6028 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6029 DAG.getIntPtrConstant(0));
6030 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6031 DAG.getIntPtrConstant(0));
6033 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6034 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6036 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6037 N0 = LowerCONCAT_VECTORS(N0, DAG);
6039 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6042 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6045 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6046 EVT VT = Op.getValueType();
6047 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6048 "unexpected type for custom-lowering ISD::UDIV");
6051 SDValue N0 = Op.getOperand(0);
6052 SDValue N1 = Op.getOperand(1);
6055 if (VT == MVT::v8i8) {
6056 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6057 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6059 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6060 DAG.getIntPtrConstant(4));
6061 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6062 DAG.getIntPtrConstant(4));
6063 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6064 DAG.getIntPtrConstant(0));
6065 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6066 DAG.getIntPtrConstant(0));
6068 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6069 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6071 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6072 N0 = LowerCONCAT_VECTORS(N0, DAG);
6074 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6075 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6080 // v4i16 sdiv ... Convert to float.
6081 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6082 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6083 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6084 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6085 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6086 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6088 // Use reciprocal estimate and two refinement steps.
6089 // float4 recip = vrecpeq_f32(yf);
6090 // recip *= vrecpsq_f32(yf, recip);
6091 // recip *= vrecpsq_f32(yf, recip);
6092 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6093 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6094 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6095 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6097 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6098 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6099 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6101 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6102 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6103 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6104 // and that it will never cause us to return an answer too large).
6105 // float4 result = as_float4(as_int4(xf*recip) + 2);
6106 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6107 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6108 N1 = DAG.getConstant(2, MVT::i32);
6109 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6110 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6111 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6112 // Convert back to integer and return.
6113 // return vmovn_u32(vcvt_s32_f32(result));
6114 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6115 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6119 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6120 EVT VT = Op.getNode()->getValueType(0);
6121 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6124 bool ExtraOp = false;
6125 switch (Op.getOpcode()) {
6126 default: llvm_unreachable("Invalid code");
6127 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6128 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6129 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6130 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6134 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6136 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6137 Op.getOperand(1), Op.getOperand(2));
6140 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6141 assert(Subtarget->isTargetDarwin());
6143 // For iOS, we want to call an alternative entry point: __sincos_stret,
6144 // return values are passed via sret.
6146 SDValue Arg = Op.getOperand(0);
6147 EVT ArgVT = Arg.getValueType();
6148 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6150 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6151 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6153 // Pair of floats / doubles used to pass the result.
6154 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6156 // Create stack object for sret.
6157 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6158 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6159 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6160 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6166 Entry.Ty = RetTy->getPointerTo();
6167 Entry.isSExt = false;
6168 Entry.isZExt = false;
6169 Entry.isSRet = true;
6170 Args.push_back(Entry);
6174 Entry.isSExt = false;
6175 Entry.isZExt = false;
6176 Args.push_back(Entry);
6178 const char *LibcallName = (ArgVT == MVT::f64)
6179 ? "__sincos_stret" : "__sincosf_stret";
6180 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6182 TargetLowering::CallLoweringInfo CLI(DAG);
6183 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6184 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6186 .setDiscardResult();
6188 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6190 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6191 MachinePointerInfo(), false, false, false, 0);
6193 // Address of cos field.
6194 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6195 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6196 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6197 MachinePointerInfo(), false, false, false, 0);
6199 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6200 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6201 LoadSin.getValue(0), LoadCos.getValue(0));
6204 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6205 // Monotonic load/store is legal for all targets
6206 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6209 // Acquire/Release load/store is not legal for targets without a
6210 // dmb or equivalent available.
6214 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6215 SmallVectorImpl<SDValue> &Results,
6217 const ARMSubtarget *Subtarget) {
6219 SDValue Cycles32, OutChain;
6221 if (Subtarget->hasPerfMon()) {
6222 // Under Power Management extensions, the cycle-count is:
6223 // mrc p15, #0, <Rt>, c9, c13, #0
6224 SDValue Ops[] = { N->getOperand(0), // Chain
6225 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6226 DAG.getConstant(15, MVT::i32),
6227 DAG.getConstant(0, MVT::i32),
6228 DAG.getConstant(9, MVT::i32),
6229 DAG.getConstant(13, MVT::i32),
6230 DAG.getConstant(0, MVT::i32)
6233 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6234 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6235 OutChain = Cycles32.getValue(1);
6237 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6238 // there are older ARM CPUs that have implementation-specific ways of
6239 // obtaining this information (FIXME!).
6240 Cycles32 = DAG.getConstant(0, MVT::i32);
6241 OutChain = DAG.getEntryNode();
6245 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6246 Cycles32, DAG.getConstant(0, MVT::i32));
6247 Results.push_back(Cycles64);
6248 Results.push_back(OutChain);
6251 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6252 switch (Op.getOpcode()) {
6253 default: llvm_unreachable("Don't know how to custom lower this!");
6254 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6255 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6256 case ISD::GlobalAddress:
6257 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6258 default: llvm_unreachable("unknown object format");
6260 return LowerGlobalAddressWindows(Op, DAG);
6262 return LowerGlobalAddressELF(Op, DAG);
6264 return LowerGlobalAddressDarwin(Op, DAG);
6266 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6267 case ISD::SELECT: return LowerSELECT(Op, DAG);
6268 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6269 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6270 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6271 case ISD::VASTART: return LowerVASTART(Op, DAG);
6272 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6273 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6274 case ISD::SINT_TO_FP:
6275 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6276 case ISD::FP_TO_SINT:
6277 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6278 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6279 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6280 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6281 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6282 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6283 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6284 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6286 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6289 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6290 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6291 case ISD::SRL_PARTS:
6292 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6293 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6294 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6295 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6296 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6297 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6298 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6299 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6300 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6301 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6302 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6303 case ISD::MUL: return LowerMUL(Op, DAG);
6304 case ISD::SDIV: return LowerSDIV(Op, DAG);
6305 case ISD::UDIV: return LowerUDIV(Op, DAG);
6309 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6314 return LowerXALUO(Op, DAG);
6315 case ISD::ATOMIC_LOAD:
6316 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6317 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6319 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6320 case ISD::DYNAMIC_STACKALLOC:
6321 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6322 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6323 llvm_unreachable("Don't know how to custom lower this!");
6324 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6325 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6329 /// ReplaceNodeResults - Replace the results of node with an illegal result
6330 /// type with new values built out of custom code.
6331 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6332 SmallVectorImpl<SDValue>&Results,
6333 SelectionDAG &DAG) const {
6335 switch (N->getOpcode()) {
6337 llvm_unreachable("Don't know how to custom expand this!");
6339 Res = ExpandBITCAST(N, DAG);
6343 Res = Expand64BitShift(N, DAG, Subtarget);
6345 case ISD::READCYCLECOUNTER:
6346 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6350 Results.push_back(Res);
6353 //===----------------------------------------------------------------------===//
6354 // ARM Scheduler Hooks
6355 //===----------------------------------------------------------------------===//
6357 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6358 /// registers the function context.
6359 void ARMTargetLowering::
6360 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6361 MachineBasicBlock *DispatchBB, int FI) const {
6362 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6363 DebugLoc dl = MI->getDebugLoc();
6364 MachineFunction *MF = MBB->getParent();
6365 MachineRegisterInfo *MRI = &MF->getRegInfo();
6366 MachineConstantPool *MCP = MF->getConstantPool();
6367 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6368 const Function *F = MF->getFunction();
6370 bool isThumb = Subtarget->isThumb();
6371 bool isThumb2 = Subtarget->isThumb2();
6373 unsigned PCLabelId = AFI->createPICLabelUId();
6374 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6375 ARMConstantPoolValue *CPV =
6376 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6377 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6379 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6380 : &ARM::GPRRegClass;
6382 // Grab constant pool and fixed stack memory operands.
6383 MachineMemOperand *CPMMO =
6384 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6385 MachineMemOperand::MOLoad, 4, 4);
6387 MachineMemOperand *FIMMOSt =
6388 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6389 MachineMemOperand::MOStore, 4, 4);
6391 // Load the address of the dispatch MBB into the jump buffer.
6393 // Incoming value: jbuf
6394 // ldr.n r5, LCPI1_1
6397 // str r5, [$jbuf, #+4] ; &jbuf[1]
6398 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6399 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6400 .addConstantPoolIndex(CPI)
6401 .addMemOperand(CPMMO));
6402 // Set the low bit because of thumb mode.
6403 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6405 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6406 .addReg(NewVReg1, RegState::Kill)
6408 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6409 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6410 .addReg(NewVReg2, RegState::Kill)
6412 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6413 .addReg(NewVReg3, RegState::Kill)
6415 .addImm(36) // &jbuf[1] :: pc
6416 .addMemOperand(FIMMOSt));
6417 } else if (isThumb) {
6418 // Incoming value: jbuf
6419 // ldr.n r1, LCPI1_4
6423 // add r2, $jbuf, #+4 ; &jbuf[1]
6425 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6426 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6427 .addConstantPoolIndex(CPI)
6428 .addMemOperand(CPMMO));
6429 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6430 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6431 .addReg(NewVReg1, RegState::Kill)
6433 // Set the low bit because of thumb mode.
6434 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6435 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6436 .addReg(ARM::CPSR, RegState::Define)
6438 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6439 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6440 .addReg(ARM::CPSR, RegState::Define)
6441 .addReg(NewVReg2, RegState::Kill)
6442 .addReg(NewVReg3, RegState::Kill));
6443 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6444 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6446 .addImm(36); // &jbuf[1] :: pc
6447 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6448 .addReg(NewVReg4, RegState::Kill)
6449 .addReg(NewVReg5, RegState::Kill)
6451 .addMemOperand(FIMMOSt));
6453 // Incoming value: jbuf
6456 // str r1, [$jbuf, #+4] ; &jbuf[1]
6457 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6458 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6459 .addConstantPoolIndex(CPI)
6461 .addMemOperand(CPMMO));
6462 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6463 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6464 .addReg(NewVReg1, RegState::Kill)
6465 .addImm(PCLabelId));
6466 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6467 .addReg(NewVReg2, RegState::Kill)
6469 .addImm(36) // &jbuf[1] :: pc
6470 .addMemOperand(FIMMOSt));
6474 MachineBasicBlock *ARMTargetLowering::
6475 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6476 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6477 DebugLoc dl = MI->getDebugLoc();
6478 MachineFunction *MF = MBB->getParent();
6479 MachineRegisterInfo *MRI = &MF->getRegInfo();
6480 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6481 MachineFrameInfo *MFI = MF->getFrameInfo();
6482 int FI = MFI->getFunctionContextIndex();
6484 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6485 : &ARM::GPRnopcRegClass;
6487 // Get a mapping of the call site numbers to all of the landing pads they're
6489 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6490 unsigned MaxCSNum = 0;
6491 MachineModuleInfo &MMI = MF->getMMI();
6492 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6494 if (!BB->isLandingPad()) continue;
6496 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6498 for (MachineBasicBlock::iterator
6499 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6500 if (!II->isEHLabel()) continue;
6502 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6503 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6505 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6506 for (SmallVectorImpl<unsigned>::iterator
6507 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6508 CSI != CSE; ++CSI) {
6509 CallSiteNumToLPad[*CSI].push_back(BB);
6510 MaxCSNum = std::max(MaxCSNum, *CSI);
6516 // Get an ordered list of the machine basic blocks for the jump table.
6517 std::vector<MachineBasicBlock*> LPadList;
6518 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6519 LPadList.reserve(CallSiteNumToLPad.size());
6520 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6521 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6522 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6523 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6524 LPadList.push_back(*II);
6525 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6529 assert(!LPadList.empty() &&
6530 "No landing pad destinations for the dispatch jump table!");
6532 // Create the jump table and associated information.
6533 MachineJumpTableInfo *JTI =
6534 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6535 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6536 unsigned UId = AFI->createJumpTableUId();
6537 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6539 // Create the MBBs for the dispatch code.
6541 // Shove the dispatch's address into the return slot in the function context.
6542 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6543 DispatchBB->setIsLandingPad();
6545 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6546 unsigned trap_opcode;
6547 if (Subtarget->isThumb())
6548 trap_opcode = ARM::tTRAP;
6550 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6552 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6553 DispatchBB->addSuccessor(TrapBB);
6555 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6556 DispatchBB->addSuccessor(DispContBB);
6559 MF->insert(MF->end(), DispatchBB);
6560 MF->insert(MF->end(), DispContBB);
6561 MF->insert(MF->end(), TrapBB);
6563 // Insert code into the entry block that creates and registers the function
6565 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6567 MachineMemOperand *FIMMOLd =
6568 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6569 MachineMemOperand::MOLoad |
6570 MachineMemOperand::MOVolatile, 4, 4);
6572 MachineInstrBuilder MIB;
6573 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6575 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6576 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6578 // Add a register mask with no preserved registers. This results in all
6579 // registers being marked as clobbered.
6580 MIB.addRegMask(RI.getNoPreservedMask());
6582 unsigned NumLPads = LPadList.size();
6583 if (Subtarget->isThumb2()) {
6584 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6585 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6588 .addMemOperand(FIMMOLd));
6590 if (NumLPads < 256) {
6591 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6593 .addImm(LPadList.size()));
6595 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6596 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6597 .addImm(NumLPads & 0xFFFF));
6599 unsigned VReg2 = VReg1;
6600 if ((NumLPads & 0xFFFF0000) != 0) {
6601 VReg2 = MRI->createVirtualRegister(TRC);
6602 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6604 .addImm(NumLPads >> 16));
6607 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6612 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6617 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6618 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6619 .addJumpTableIndex(MJTI)
6622 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6625 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6626 .addReg(NewVReg3, RegState::Kill)
6628 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6630 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6631 .addReg(NewVReg4, RegState::Kill)
6633 .addJumpTableIndex(MJTI)
6635 } else if (Subtarget->isThumb()) {
6636 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6637 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6640 .addMemOperand(FIMMOLd));
6642 if (NumLPads < 256) {
6643 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6647 MachineConstantPool *ConstantPool = MF->getConstantPool();
6648 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6649 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6651 // MachineConstantPool wants an explicit alignment.
6652 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6654 Align = getDataLayout()->getTypeAllocSize(C->getType());
6655 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6657 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6658 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6659 .addReg(VReg1, RegState::Define)
6660 .addConstantPoolIndex(Idx));
6661 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6666 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6671 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6672 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6673 .addReg(ARM::CPSR, RegState::Define)
6677 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6678 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6679 .addJumpTableIndex(MJTI)
6682 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6683 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6684 .addReg(ARM::CPSR, RegState::Define)
6685 .addReg(NewVReg2, RegState::Kill)
6688 MachineMemOperand *JTMMOLd =
6689 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6690 MachineMemOperand::MOLoad, 4, 4);
6692 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6693 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6694 .addReg(NewVReg4, RegState::Kill)
6696 .addMemOperand(JTMMOLd));
6698 unsigned NewVReg6 = NewVReg5;
6699 if (RelocM == Reloc::PIC_) {
6700 NewVReg6 = MRI->createVirtualRegister(TRC);
6701 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6702 .addReg(ARM::CPSR, RegState::Define)
6703 .addReg(NewVReg5, RegState::Kill)
6707 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6708 .addReg(NewVReg6, RegState::Kill)
6709 .addJumpTableIndex(MJTI)
6712 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6713 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6716 .addMemOperand(FIMMOLd));
6718 if (NumLPads < 256) {
6719 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6722 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6723 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6724 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6725 .addImm(NumLPads & 0xFFFF));
6727 unsigned VReg2 = VReg1;
6728 if ((NumLPads & 0xFFFF0000) != 0) {
6729 VReg2 = MRI->createVirtualRegister(TRC);
6730 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6732 .addImm(NumLPads >> 16));
6735 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6739 MachineConstantPool *ConstantPool = MF->getConstantPool();
6740 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6741 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6743 // MachineConstantPool wants an explicit alignment.
6744 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6746 Align = getDataLayout()->getTypeAllocSize(C->getType());
6747 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6749 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6750 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6751 .addReg(VReg1, RegState::Define)
6752 .addConstantPoolIndex(Idx)
6754 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6756 .addReg(VReg1, RegState::Kill));
6759 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6764 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6766 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6768 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6769 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6770 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6771 .addJumpTableIndex(MJTI)
6774 MachineMemOperand *JTMMOLd =
6775 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6776 MachineMemOperand::MOLoad, 4, 4);
6777 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6779 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6780 .addReg(NewVReg3, RegState::Kill)
6783 .addMemOperand(JTMMOLd));
6785 if (RelocM == Reloc::PIC_) {
6786 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6787 .addReg(NewVReg5, RegState::Kill)
6789 .addJumpTableIndex(MJTI)
6792 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6793 .addReg(NewVReg5, RegState::Kill)
6794 .addJumpTableIndex(MJTI)
6799 // Add the jump table entries as successors to the MBB.
6800 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6801 for (std::vector<MachineBasicBlock*>::iterator
6802 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6803 MachineBasicBlock *CurMBB = *I;
6804 if (SeenMBBs.insert(CurMBB).second)
6805 DispContBB->addSuccessor(CurMBB);
6808 // N.B. the order the invoke BBs are processed in doesn't matter here.
6809 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6810 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6811 for (MachineBasicBlock *BB : InvokeBBs) {
6813 // Remove the landing pad successor from the invoke block and replace it
6814 // with the new dispatch block.
6815 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6817 while (!Successors.empty()) {
6818 MachineBasicBlock *SMBB = Successors.pop_back_val();
6819 if (SMBB->isLandingPad()) {
6820 BB->removeSuccessor(SMBB);
6821 MBBLPads.push_back(SMBB);
6825 BB->addSuccessor(DispatchBB);
6827 // Find the invoke call and mark all of the callee-saved registers as
6828 // 'implicit defined' so that they're spilled. This prevents code from
6829 // moving instructions to before the EH block, where they will never be
6831 for (MachineBasicBlock::reverse_iterator
6832 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6833 if (!II->isCall()) continue;
6835 DenseMap<unsigned, bool> DefRegs;
6836 for (MachineInstr::mop_iterator
6837 OI = II->operands_begin(), OE = II->operands_end();
6839 if (!OI->isReg()) continue;
6840 DefRegs[OI->getReg()] = true;
6843 MachineInstrBuilder MIB(*MF, &*II);
6845 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6846 unsigned Reg = SavedRegs[i];
6847 if (Subtarget->isThumb2() &&
6848 !ARM::tGPRRegClass.contains(Reg) &&
6849 !ARM::hGPRRegClass.contains(Reg))
6851 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6853 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6856 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6863 // Mark all former landing pads as non-landing pads. The dispatch is the only
6865 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6866 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6867 (*I)->setIsLandingPad(false);
6869 // The instruction is gone now.
6870 MI->eraseFromParent();
6876 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6877 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6878 E = MBB->succ_end(); I != E; ++I)
6881 llvm_unreachable("Expecting a BB with two successors!");
6884 /// Return the load opcode for a given load size. If load size >= 8,
6885 /// neon opcode will be returned.
6886 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6888 return LdSize == 16 ? ARM::VLD1q32wb_fixed
6889 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6891 return LdSize == 4 ? ARM::tLDRi
6892 : LdSize == 2 ? ARM::tLDRHi
6893 : LdSize == 1 ? ARM::tLDRBi : 0;
6895 return LdSize == 4 ? ARM::t2LDR_POST
6896 : LdSize == 2 ? ARM::t2LDRH_POST
6897 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6898 return LdSize == 4 ? ARM::LDR_POST_IMM
6899 : LdSize == 2 ? ARM::LDRH_POST
6900 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6903 /// Return the store opcode for a given store size. If store size >= 8,
6904 /// neon opcode will be returned.
6905 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6907 return StSize == 16 ? ARM::VST1q32wb_fixed
6908 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6910 return StSize == 4 ? ARM::tSTRi
6911 : StSize == 2 ? ARM::tSTRHi
6912 : StSize == 1 ? ARM::tSTRBi : 0;
6914 return StSize == 4 ? ARM::t2STR_POST
6915 : StSize == 2 ? ARM::t2STRH_POST
6916 : StSize == 1 ? ARM::t2STRB_POST : 0;
6917 return StSize == 4 ? ARM::STR_POST_IMM
6918 : StSize == 2 ? ARM::STRH_POST
6919 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6922 /// Emit a post-increment load operation with given size. The instructions
6923 /// will be added to BB at Pos.
6924 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6925 const TargetInstrInfo *TII, DebugLoc dl,
6926 unsigned LdSize, unsigned Data, unsigned AddrIn,
6927 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6928 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6929 assert(LdOpc != 0 && "Should have a load opcode");
6931 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6932 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6934 } else if (IsThumb1) {
6935 // load + update AddrIn
6936 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6937 .addReg(AddrIn).addImm(0));
6938 MachineInstrBuilder MIB =
6939 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6940 MIB = AddDefaultT1CC(MIB);
6941 MIB.addReg(AddrIn).addImm(LdSize);
6942 AddDefaultPred(MIB);
6943 } else if (IsThumb2) {
6944 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6945 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6948 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6949 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6950 .addReg(0).addImm(LdSize));
6954 /// Emit a post-increment store operation with given size. The instructions
6955 /// will be added to BB at Pos.
6956 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6957 const TargetInstrInfo *TII, DebugLoc dl,
6958 unsigned StSize, unsigned Data, unsigned AddrIn,
6959 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6960 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6961 assert(StOpc != 0 && "Should have a store opcode");
6963 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6964 .addReg(AddrIn).addImm(0).addReg(Data));
6965 } else if (IsThumb1) {
6966 // store + update AddrIn
6967 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6968 .addReg(AddrIn).addImm(0));
6969 MachineInstrBuilder MIB =
6970 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6971 MIB = AddDefaultT1CC(MIB);
6972 MIB.addReg(AddrIn).addImm(StSize);
6973 AddDefaultPred(MIB);
6974 } else if (IsThumb2) {
6975 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6976 .addReg(Data).addReg(AddrIn).addImm(StSize));
6978 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6979 .addReg(Data).addReg(AddrIn).addReg(0)
6985 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6986 MachineBasicBlock *BB) const {
6987 // This pseudo instruction has 3 operands: dst, src, size
6988 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6989 // Otherwise, we will generate unrolled scalar copies.
6990 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6991 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6992 MachineFunction::iterator It = BB;
6995 unsigned dest = MI->getOperand(0).getReg();
6996 unsigned src = MI->getOperand(1).getReg();
6997 unsigned SizeVal = MI->getOperand(2).getImm();
6998 unsigned Align = MI->getOperand(3).getImm();
6999 DebugLoc dl = MI->getDebugLoc();
7001 MachineFunction *MF = BB->getParent();
7002 MachineRegisterInfo &MRI = MF->getRegInfo();
7003 unsigned UnitSize = 0;
7004 const TargetRegisterClass *TRC = nullptr;
7005 const TargetRegisterClass *VecTRC = nullptr;
7007 bool IsThumb1 = Subtarget->isThumb1Only();
7008 bool IsThumb2 = Subtarget->isThumb2();
7012 } else if (Align & 2) {
7015 // Check whether we can use NEON instructions.
7016 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7017 Subtarget->hasNEON()) {
7018 if ((Align % 16 == 0) && SizeVal >= 16)
7020 else if ((Align % 8 == 0) && SizeVal >= 8)
7023 // Can't use NEON instructions.
7028 // Select the correct opcode and register class for unit size load/store
7029 bool IsNeon = UnitSize >= 8;
7030 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7032 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7033 : UnitSize == 8 ? &ARM::DPRRegClass
7036 unsigned BytesLeft = SizeVal % UnitSize;
7037 unsigned LoopSize = SizeVal - BytesLeft;
7039 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7040 // Use LDR and STR to copy.
7041 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7042 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7043 unsigned srcIn = src;
7044 unsigned destIn = dest;
7045 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7046 unsigned srcOut = MRI.createVirtualRegister(TRC);
7047 unsigned destOut = MRI.createVirtualRegister(TRC);
7048 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7049 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7050 IsThumb1, IsThumb2);
7051 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7052 IsThumb1, IsThumb2);
7057 // Handle the leftover bytes with LDRB and STRB.
7058 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7059 // [destOut] = STRB_POST(scratch, destIn, 1)
7060 for (unsigned i = 0; i < BytesLeft; i++) {
7061 unsigned srcOut = MRI.createVirtualRegister(TRC);
7062 unsigned destOut = MRI.createVirtualRegister(TRC);
7063 unsigned scratch = MRI.createVirtualRegister(TRC);
7064 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7065 IsThumb1, IsThumb2);
7066 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7067 IsThumb1, IsThumb2);
7071 MI->eraseFromParent(); // The instruction is gone now.
7075 // Expand the pseudo op to a loop.
7078 // movw varEnd, # --> with thumb2
7080 // ldrcp varEnd, idx --> without thumb2
7081 // fallthrough --> loopMBB
7083 // PHI varPhi, varEnd, varLoop
7084 // PHI srcPhi, src, srcLoop
7085 // PHI destPhi, dst, destLoop
7086 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7087 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7088 // subs varLoop, varPhi, #UnitSize
7090 // fallthrough --> exitMBB
7092 // epilogue to handle left-over bytes
7093 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7094 // [destOut] = STRB_POST(scratch, destLoop, 1)
7095 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7096 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7097 MF->insert(It, loopMBB);
7098 MF->insert(It, exitMBB);
7100 // Transfer the remainder of BB and its successor edges to exitMBB.
7101 exitMBB->splice(exitMBB->begin(), BB,
7102 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7103 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7105 // Load an immediate to varEnd.
7106 unsigned varEnd = MRI.createVirtualRegister(TRC);
7108 unsigned Vtmp = varEnd;
7109 if ((LoopSize & 0xFFFF0000) != 0)
7110 Vtmp = MRI.createVirtualRegister(TRC);
7111 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7112 .addImm(LoopSize & 0xFFFF));
7114 if ((LoopSize & 0xFFFF0000) != 0)
7115 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7116 .addReg(Vtmp).addImm(LoopSize >> 16));
7118 MachineConstantPool *ConstantPool = MF->getConstantPool();
7119 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7120 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7122 // MachineConstantPool wants an explicit alignment.
7123 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7125 Align = getDataLayout()->getTypeAllocSize(C->getType());
7126 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7129 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7130 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7132 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7133 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7135 BB->addSuccessor(loopMBB);
7137 // Generate the loop body:
7138 // varPhi = PHI(varLoop, varEnd)
7139 // srcPhi = PHI(srcLoop, src)
7140 // destPhi = PHI(destLoop, dst)
7141 MachineBasicBlock *entryBB = BB;
7143 unsigned varLoop = MRI.createVirtualRegister(TRC);
7144 unsigned varPhi = MRI.createVirtualRegister(TRC);
7145 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7146 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7147 unsigned destLoop = MRI.createVirtualRegister(TRC);
7148 unsigned destPhi = MRI.createVirtualRegister(TRC);
7150 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7151 .addReg(varLoop).addMBB(loopMBB)
7152 .addReg(varEnd).addMBB(entryBB);
7153 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7154 .addReg(srcLoop).addMBB(loopMBB)
7155 .addReg(src).addMBB(entryBB);
7156 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7157 .addReg(destLoop).addMBB(loopMBB)
7158 .addReg(dest).addMBB(entryBB);
7160 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7161 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7162 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7163 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7164 IsThumb1, IsThumb2);
7165 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7166 IsThumb1, IsThumb2);
7168 // Decrement loop variable by UnitSize.
7170 MachineInstrBuilder MIB =
7171 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7172 MIB = AddDefaultT1CC(MIB);
7173 MIB.addReg(varPhi).addImm(UnitSize);
7174 AddDefaultPred(MIB);
7176 MachineInstrBuilder MIB =
7177 BuildMI(*BB, BB->end(), dl,
7178 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7179 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7180 MIB->getOperand(5).setReg(ARM::CPSR);
7181 MIB->getOperand(5).setIsDef(true);
7183 BuildMI(*BB, BB->end(), dl,
7184 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7185 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7187 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7188 BB->addSuccessor(loopMBB);
7189 BB->addSuccessor(exitMBB);
7191 // Add epilogue to handle BytesLeft.
7193 MachineInstr *StartOfExit = exitMBB->begin();
7195 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7196 // [destOut] = STRB_POST(scratch, destLoop, 1)
7197 unsigned srcIn = srcLoop;
7198 unsigned destIn = destLoop;
7199 for (unsigned i = 0; i < BytesLeft; i++) {
7200 unsigned srcOut = MRI.createVirtualRegister(TRC);
7201 unsigned destOut = MRI.createVirtualRegister(TRC);
7202 unsigned scratch = MRI.createVirtualRegister(TRC);
7203 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7204 IsThumb1, IsThumb2);
7205 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7206 IsThumb1, IsThumb2);
7211 MI->eraseFromParent(); // The instruction is gone now.
7216 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7217 MachineBasicBlock *MBB) const {
7218 const TargetMachine &TM = getTargetMachine();
7219 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7220 DebugLoc DL = MI->getDebugLoc();
7222 assert(Subtarget->isTargetWindows() &&
7223 "__chkstk is only supported on Windows");
7224 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7226 // __chkstk takes the number of words to allocate on the stack in R4, and
7227 // returns the stack adjustment in number of bytes in R4. This will not
7228 // clober any other registers (other than the obvious lr).
7230 // Although, technically, IP should be considered a register which may be
7231 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7232 // thumb-2 environment, so there is no interworking required. As a result, we
7233 // do not expect a veneer to be emitted by the linker, clobbering IP.
7235 // Each module receives its own copy of __chkstk, so no import thunk is
7236 // required, again, ensuring that IP is not clobbered.
7238 // Finally, although some linkers may theoretically provide a trampoline for
7239 // out of range calls (which is quite common due to a 32M range limitation of
7240 // branches for Thumb), we can generate the long-call version via
7241 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7244 switch (TM.getCodeModel()) {
7245 case CodeModel::Small:
7246 case CodeModel::Medium:
7247 case CodeModel::Default:
7248 case CodeModel::Kernel:
7249 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7250 .addImm((unsigned)ARMCC::AL).addReg(0)
7251 .addExternalSymbol("__chkstk")
7252 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7253 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7254 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7256 case CodeModel::Large:
7257 case CodeModel::JITDefault: {
7258 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7259 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7261 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7262 .addExternalSymbol("__chkstk");
7263 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7264 .addImm((unsigned)ARMCC::AL).addReg(0)
7265 .addReg(Reg, RegState::Kill)
7266 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7267 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7268 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7273 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7275 .addReg(ARM::SP).addReg(ARM::R4)));
7277 MI->eraseFromParent();
7282 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7283 MachineBasicBlock *BB) const {
7284 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7285 DebugLoc dl = MI->getDebugLoc();
7286 bool isThumb2 = Subtarget->isThumb2();
7287 switch (MI->getOpcode()) {
7290 llvm_unreachable("Unexpected instr type to insert");
7292 // The Thumb2 pre-indexed stores have the same MI operands, they just
7293 // define them differently in the .td files from the isel patterns, so
7294 // they need pseudos.
7295 case ARM::t2STR_preidx:
7296 MI->setDesc(TII->get(ARM::t2STR_PRE));
7298 case ARM::t2STRB_preidx:
7299 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7301 case ARM::t2STRH_preidx:
7302 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7305 case ARM::STRi_preidx:
7306 case ARM::STRBi_preidx: {
7307 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7308 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7309 // Decode the offset.
7310 unsigned Offset = MI->getOperand(4).getImm();
7311 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7312 Offset = ARM_AM::getAM2Offset(Offset);
7316 MachineMemOperand *MMO = *MI->memoperands_begin();
7317 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7318 .addOperand(MI->getOperand(0)) // Rn_wb
7319 .addOperand(MI->getOperand(1)) // Rt
7320 .addOperand(MI->getOperand(2)) // Rn
7321 .addImm(Offset) // offset (skip GPR==zero_reg)
7322 .addOperand(MI->getOperand(5)) // pred
7323 .addOperand(MI->getOperand(6))
7324 .addMemOperand(MMO);
7325 MI->eraseFromParent();
7328 case ARM::STRr_preidx:
7329 case ARM::STRBr_preidx:
7330 case ARM::STRH_preidx: {
7332 switch (MI->getOpcode()) {
7333 default: llvm_unreachable("unexpected opcode!");
7334 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7335 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7336 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7338 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7339 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7340 MIB.addOperand(MI->getOperand(i));
7341 MI->eraseFromParent();
7345 case ARM::tMOVCCr_pseudo: {
7346 // To "insert" a SELECT_CC instruction, we actually have to insert the
7347 // diamond control-flow pattern. The incoming instruction knows the
7348 // destination vreg to set, the condition code register to branch on, the
7349 // true/false values to select between, and a branch opcode to use.
7350 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7351 MachineFunction::iterator It = BB;
7357 // cmpTY ccX, r1, r2
7359 // fallthrough --> copy0MBB
7360 MachineBasicBlock *thisMBB = BB;
7361 MachineFunction *F = BB->getParent();
7362 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7363 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7364 F->insert(It, copy0MBB);
7365 F->insert(It, sinkMBB);
7367 // Transfer the remainder of BB and its successor edges to sinkMBB.
7368 sinkMBB->splice(sinkMBB->begin(), BB,
7369 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7370 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7372 BB->addSuccessor(copy0MBB);
7373 BB->addSuccessor(sinkMBB);
7375 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7376 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7379 // %FalseValue = ...
7380 // # fallthrough to sinkMBB
7383 // Update machine-CFG edges
7384 BB->addSuccessor(sinkMBB);
7387 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7390 BuildMI(*BB, BB->begin(), dl,
7391 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7392 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7393 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7395 MI->eraseFromParent(); // The pseudo instruction is gone now.
7400 case ARM::BCCZi64: {
7401 // If there is an unconditional branch to the other successor, remove it.
7402 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7404 // Compare both parts that make up the double comparison separately for
7406 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7408 unsigned LHS1 = MI->getOperand(1).getReg();
7409 unsigned LHS2 = MI->getOperand(2).getReg();
7411 AddDefaultPred(BuildMI(BB, dl,
7412 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7413 .addReg(LHS1).addImm(0));
7414 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7415 .addReg(LHS2).addImm(0)
7416 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7418 unsigned RHS1 = MI->getOperand(3).getReg();
7419 unsigned RHS2 = MI->getOperand(4).getReg();
7420 AddDefaultPred(BuildMI(BB, dl,
7421 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7422 .addReg(LHS1).addReg(RHS1));
7423 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7424 .addReg(LHS2).addReg(RHS2)
7425 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7428 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7429 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7430 if (MI->getOperand(0).getImm() == ARMCC::NE)
7431 std::swap(destMBB, exitMBB);
7433 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7434 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7436 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7438 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7440 MI->eraseFromParent(); // The pseudo instruction is gone now.
7444 case ARM::Int_eh_sjlj_setjmp:
7445 case ARM::Int_eh_sjlj_setjmp_nofp:
7446 case ARM::tInt_eh_sjlj_setjmp:
7447 case ARM::t2Int_eh_sjlj_setjmp:
7448 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7449 EmitSjLjDispatchBlock(MI, BB);
7454 // To insert an ABS instruction, we have to insert the
7455 // diamond control-flow pattern. The incoming instruction knows the
7456 // source vreg to test against 0, the destination vreg to set,
7457 // the condition code register to branch on, the
7458 // true/false values to select between, and a branch opcode to use.
7463 // BCC (branch to SinkBB if V0 >= 0)
7464 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7465 // SinkBB: V1 = PHI(V2, V3)
7466 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7467 MachineFunction::iterator BBI = BB;
7469 MachineFunction *Fn = BB->getParent();
7470 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7471 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7472 Fn->insert(BBI, RSBBB);
7473 Fn->insert(BBI, SinkBB);
7475 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7476 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7477 bool isThumb2 = Subtarget->isThumb2();
7478 MachineRegisterInfo &MRI = Fn->getRegInfo();
7479 // In Thumb mode S must not be specified if source register is the SP or
7480 // PC and if destination register is the SP, so restrict register class
7481 unsigned NewRsbDstReg =
7482 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7484 // Transfer the remainder of BB and its successor edges to sinkMBB.
7485 SinkBB->splice(SinkBB->begin(), BB,
7486 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7487 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7489 BB->addSuccessor(RSBBB);
7490 BB->addSuccessor(SinkBB);
7492 // fall through to SinkMBB
7493 RSBBB->addSuccessor(SinkBB);
7495 // insert a cmp at the end of BB
7496 AddDefaultPred(BuildMI(BB, dl,
7497 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7498 .addReg(ABSSrcReg).addImm(0));
7500 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7502 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7503 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7505 // insert rsbri in RSBBB
7506 // Note: BCC and rsbri will be converted into predicated rsbmi
7507 // by if-conversion pass
7508 BuildMI(*RSBBB, RSBBB->begin(), dl,
7509 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7510 .addReg(ABSSrcReg, RegState::Kill)
7511 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7513 // insert PHI in SinkBB,
7514 // reuse ABSDstReg to not change uses of ABS instruction
7515 BuildMI(*SinkBB, SinkBB->begin(), dl,
7516 TII->get(ARM::PHI), ABSDstReg)
7517 .addReg(NewRsbDstReg).addMBB(RSBBB)
7518 .addReg(ABSSrcReg).addMBB(BB);
7520 // remove ABS instruction
7521 MI->eraseFromParent();
7523 // return last added BB
7526 case ARM::COPY_STRUCT_BYVAL_I32:
7528 return EmitStructByval(MI, BB);
7529 case ARM::WIN__CHKSTK:
7530 return EmitLowered__chkstk(MI, BB);
7534 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7535 SDNode *Node) const {
7536 const MCInstrDesc *MCID = &MI->getDesc();
7537 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7538 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7539 // operand is still set to noreg. If needed, set the optional operand's
7540 // register to CPSR, and remove the redundant implicit def.
7542 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7544 // Rename pseudo opcodes.
7545 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7547 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7548 MCID = &TII->get(NewOpc);
7550 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7551 "converted opcode should be the same except for cc_out");
7555 // Add the optional cc_out operand
7556 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7558 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7560 // Any ARM instruction that sets the 's' bit should specify an optional
7561 // "cc_out" operand in the last operand position.
7562 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7563 assert(!NewOpc && "Optional cc_out operand required");
7566 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7567 // since we already have an optional CPSR def.
7568 bool definesCPSR = false;
7569 bool deadCPSR = false;
7570 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7572 const MachineOperand &MO = MI->getOperand(i);
7573 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7577 MI->RemoveOperand(i);
7582 assert(!NewOpc && "Optional cc_out operand required");
7585 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7587 assert(!MI->getOperand(ccOutIdx).getReg() &&
7588 "expect uninitialized optional cc_out operand");
7592 // If this instruction was defined with an optional CPSR def and its dag node
7593 // had a live implicit CPSR def, then activate the optional CPSR def.
7594 MachineOperand &MO = MI->getOperand(ccOutIdx);
7595 MO.setReg(ARM::CPSR);
7599 //===----------------------------------------------------------------------===//
7600 // ARM Optimization Hooks
7601 //===----------------------------------------------------------------------===//
7603 // Helper function that checks if N is a null or all ones constant.
7604 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7605 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7608 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7611 // Return true if N is conditionally 0 or all ones.
7612 // Detects these expressions where cc is an i1 value:
7614 // (select cc 0, y) [AllOnes=0]
7615 // (select cc y, 0) [AllOnes=0]
7616 // (zext cc) [AllOnes=0]
7617 // (sext cc) [AllOnes=0/1]
7618 // (select cc -1, y) [AllOnes=1]
7619 // (select cc y, -1) [AllOnes=1]
7621 // Invert is set when N is the null/all ones constant when CC is false.
7622 // OtherOp is set to the alternative value of N.
7623 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7624 SDValue &CC, bool &Invert,
7626 SelectionDAG &DAG) {
7627 switch (N->getOpcode()) {
7628 default: return false;
7630 CC = N->getOperand(0);
7631 SDValue N1 = N->getOperand(1);
7632 SDValue N2 = N->getOperand(2);
7633 if (isZeroOrAllOnes(N1, AllOnes)) {
7638 if (isZeroOrAllOnes(N2, AllOnes)) {
7645 case ISD::ZERO_EXTEND:
7646 // (zext cc) can never be the all ones value.
7650 case ISD::SIGN_EXTEND: {
7651 EVT VT = N->getValueType(0);
7652 CC = N->getOperand(0);
7653 if (CC.getValueType() != MVT::i1)
7657 // When looking for an AllOnes constant, N is an sext, and the 'other'
7659 OtherOp = DAG.getConstant(0, VT);
7660 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7661 // When looking for a 0 constant, N can be zext or sext.
7662 OtherOp = DAG.getConstant(1, VT);
7664 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7670 // Combine a constant select operand into its use:
7672 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7673 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7674 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7675 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7676 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7678 // The transform is rejected if the select doesn't have a constant operand that
7679 // is null, or all ones when AllOnes is set.
7681 // Also recognize sext/zext from i1:
7683 // (add (zext cc), x) -> (select cc (add x, 1), x)
7684 // (add (sext cc), x) -> (select cc (add x, -1), x)
7686 // These transformations eventually create predicated instructions.
7688 // @param N The node to transform.
7689 // @param Slct The N operand that is a select.
7690 // @param OtherOp The other N operand (x above).
7691 // @param DCI Context.
7692 // @param AllOnes Require the select constant to be all ones instead of null.
7693 // @returns The new node, or SDValue() on failure.
7695 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7696 TargetLowering::DAGCombinerInfo &DCI,
7697 bool AllOnes = false) {
7698 SelectionDAG &DAG = DCI.DAG;
7699 EVT VT = N->getValueType(0);
7700 SDValue NonConstantVal;
7703 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7704 NonConstantVal, DAG))
7707 // Slct is now know to be the desired identity constant when CC is true.
7708 SDValue TrueVal = OtherOp;
7709 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7710 OtherOp, NonConstantVal);
7711 // Unless SwapSelectOps says CC should be false.
7713 std::swap(TrueVal, FalseVal);
7715 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7716 CCOp, TrueVal, FalseVal);
7719 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7721 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7722 TargetLowering::DAGCombinerInfo &DCI) {
7723 SDValue N0 = N->getOperand(0);
7724 SDValue N1 = N->getOperand(1);
7725 if (N0.getNode()->hasOneUse()) {
7726 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7727 if (Result.getNode())
7730 if (N1.getNode()->hasOneUse()) {
7731 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7732 if (Result.getNode())
7738 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7739 // (only after legalization).
7740 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7741 TargetLowering::DAGCombinerInfo &DCI,
7742 const ARMSubtarget *Subtarget) {
7744 // Only perform optimization if after legalize, and if NEON is available. We
7745 // also expected both operands to be BUILD_VECTORs.
7746 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7747 || N0.getOpcode() != ISD::BUILD_VECTOR
7748 || N1.getOpcode() != ISD::BUILD_VECTOR)
7751 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7752 EVT VT = N->getValueType(0);
7753 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7756 // Check that the vector operands are of the right form.
7757 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7758 // operands, where N is the size of the formed vector.
7759 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7760 // index such that we have a pair wise add pattern.
7762 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7763 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7765 SDValue Vec = N0->getOperand(0)->getOperand(0);
7766 SDNode *V = Vec.getNode();
7767 unsigned nextIndex = 0;
7769 // For each operands to the ADD which are BUILD_VECTORs,
7770 // check to see if each of their operands are an EXTRACT_VECTOR with
7771 // the same vector and appropriate index.
7772 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7773 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7774 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7776 SDValue ExtVec0 = N0->getOperand(i);
7777 SDValue ExtVec1 = N1->getOperand(i);
7779 // First operand is the vector, verify its the same.
7780 if (V != ExtVec0->getOperand(0).getNode() ||
7781 V != ExtVec1->getOperand(0).getNode())
7784 // Second is the constant, verify its correct.
7785 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7786 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7788 // For the constant, we want to see all the even or all the odd.
7789 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7790 || C1->getZExtValue() != nextIndex+1)
7799 // Create VPADDL node.
7800 SelectionDAG &DAG = DCI.DAG;
7801 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7803 // Build operand list.
7804 SmallVector<SDValue, 8> Ops;
7805 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7806 TLI.getPointerTy()));
7808 // Input is the vector.
7811 // Get widened type and narrowed type.
7813 unsigned numElem = VT.getVectorNumElements();
7815 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7816 switch (inputLaneType.getSimpleVT().SimpleTy) {
7817 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7818 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7819 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7821 llvm_unreachable("Invalid vector element type for padd optimization.");
7824 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7825 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7826 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7829 static SDValue findMUL_LOHI(SDValue V) {
7830 if (V->getOpcode() == ISD::UMUL_LOHI ||
7831 V->getOpcode() == ISD::SMUL_LOHI)
7836 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7837 TargetLowering::DAGCombinerInfo &DCI,
7838 const ARMSubtarget *Subtarget) {
7840 if (Subtarget->isThumb1Only()) return SDValue();
7842 // Only perform the checks after legalize when the pattern is available.
7843 if (DCI.isBeforeLegalize()) return SDValue();
7845 // Look for multiply add opportunities.
7846 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7847 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7848 // a glue link from the first add to the second add.
7849 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7850 // a S/UMLAL instruction.
7853 // \ / \ [no multiline comment]
7859 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7860 SDValue AddcOp0 = AddcNode->getOperand(0);
7861 SDValue AddcOp1 = AddcNode->getOperand(1);
7863 // Check if the two operands are from the same mul_lohi node.
7864 if (AddcOp0.getNode() == AddcOp1.getNode())
7867 assert(AddcNode->getNumValues() == 2 &&
7868 AddcNode->getValueType(0) == MVT::i32 &&
7869 "Expect ADDC with two result values. First: i32");
7871 // Check that we have a glued ADDC node.
7872 if (AddcNode->getValueType(1) != MVT::Glue)
7875 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7876 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7877 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7878 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7879 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7882 // Look for the glued ADDE.
7883 SDNode* AddeNode = AddcNode->getGluedUser();
7887 // Make sure it is really an ADDE.
7888 if (AddeNode->getOpcode() != ISD::ADDE)
7891 assert(AddeNode->getNumOperands() == 3 &&
7892 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7893 "ADDE node has the wrong inputs");
7895 // Check for the triangle shape.
7896 SDValue AddeOp0 = AddeNode->getOperand(0);
7897 SDValue AddeOp1 = AddeNode->getOperand(1);
7899 // Make sure that the ADDE operands are not coming from the same node.
7900 if (AddeOp0.getNode() == AddeOp1.getNode())
7903 // Find the MUL_LOHI node walking up ADDE's operands.
7904 bool IsLeftOperandMUL = false;
7905 SDValue MULOp = findMUL_LOHI(AddeOp0);
7906 if (MULOp == SDValue())
7907 MULOp = findMUL_LOHI(AddeOp1);
7909 IsLeftOperandMUL = true;
7910 if (MULOp == SDValue())
7913 // Figure out the right opcode.
7914 unsigned Opc = MULOp->getOpcode();
7915 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7917 // Figure out the high and low input values to the MLAL node.
7918 SDValue* HiAdd = nullptr;
7919 SDValue* LoMul = nullptr;
7920 SDValue* LowAdd = nullptr;
7922 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
7923 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
7926 if (IsLeftOperandMUL)
7932 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
7933 // whose low result is fed to the ADDC we are checking.
7935 if (AddcOp0 == MULOp.getValue(0)) {
7939 if (AddcOp1 == MULOp.getValue(0)) {
7947 // Create the merged node.
7948 SelectionDAG &DAG = DCI.DAG;
7950 // Build operand list.
7951 SmallVector<SDValue, 8> Ops;
7952 Ops.push_back(LoMul->getOperand(0));
7953 Ops.push_back(LoMul->getOperand(1));
7954 Ops.push_back(*LowAdd);
7955 Ops.push_back(*HiAdd);
7957 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
7958 DAG.getVTList(MVT::i32, MVT::i32), Ops);
7960 // Replace the ADDs' nodes uses by the MLA node's values.
7961 SDValue HiMLALResult(MLALNode.getNode(), 1);
7962 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7964 SDValue LoMLALResult(MLALNode.getNode(), 0);
7965 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7967 // Return original node to notify the driver to stop replacing.
7968 SDValue resNode(AddcNode, 0);
7972 /// PerformADDCCombine - Target-specific dag combine transform from
7973 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7974 static SDValue PerformADDCCombine(SDNode *N,
7975 TargetLowering::DAGCombinerInfo &DCI,
7976 const ARMSubtarget *Subtarget) {
7978 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7982 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7983 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7984 /// called with the default operands, and if that fails, with commuted
7986 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7987 TargetLowering::DAGCombinerInfo &DCI,
7988 const ARMSubtarget *Subtarget){
7990 // Attempt to create vpaddl for this add.
7991 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7992 if (Result.getNode())
7995 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7996 if (N0.getNode()->hasOneUse()) {
7997 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7998 if (Result.getNode()) return Result;
8003 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8005 static SDValue PerformADDCombine(SDNode *N,
8006 TargetLowering::DAGCombinerInfo &DCI,
8007 const ARMSubtarget *Subtarget) {
8008 SDValue N0 = N->getOperand(0);
8009 SDValue N1 = N->getOperand(1);
8011 // First try with the default operand order.
8012 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8013 if (Result.getNode())
8016 // If that didn't work, try again with the operands commuted.
8017 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8020 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8022 static SDValue PerformSUBCombine(SDNode *N,
8023 TargetLowering::DAGCombinerInfo &DCI) {
8024 SDValue N0 = N->getOperand(0);
8025 SDValue N1 = N->getOperand(1);
8027 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8028 if (N1.getNode()->hasOneUse()) {
8029 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8030 if (Result.getNode()) return Result;
8036 /// PerformVMULCombine
8037 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8038 /// special multiplier accumulator forwarding.
8044 // However, for (A + B) * (A + B),
8051 static SDValue PerformVMULCombine(SDNode *N,
8052 TargetLowering::DAGCombinerInfo &DCI,
8053 const ARMSubtarget *Subtarget) {
8054 if (!Subtarget->hasVMLxForwarding())
8057 SelectionDAG &DAG = DCI.DAG;
8058 SDValue N0 = N->getOperand(0);
8059 SDValue N1 = N->getOperand(1);
8060 unsigned Opcode = N0.getOpcode();
8061 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8062 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8063 Opcode = N1.getOpcode();
8064 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8065 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8073 EVT VT = N->getValueType(0);
8075 SDValue N00 = N0->getOperand(0);
8076 SDValue N01 = N0->getOperand(1);
8077 return DAG.getNode(Opcode, DL, VT,
8078 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8079 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8082 static SDValue PerformMULCombine(SDNode *N,
8083 TargetLowering::DAGCombinerInfo &DCI,
8084 const ARMSubtarget *Subtarget) {
8085 SelectionDAG &DAG = DCI.DAG;
8087 if (Subtarget->isThumb1Only())
8090 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8093 EVT VT = N->getValueType(0);
8094 if (VT.is64BitVector() || VT.is128BitVector())
8095 return PerformVMULCombine(N, DCI, Subtarget);
8099 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8103 int64_t MulAmt = C->getSExtValue();
8104 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8106 ShiftAmt = ShiftAmt & (32 - 1);
8107 SDValue V = N->getOperand(0);
8111 MulAmt >>= ShiftAmt;
8114 if (isPowerOf2_32(MulAmt - 1)) {
8115 // (mul x, 2^N + 1) => (add (shl x, N), x)
8116 Res = DAG.getNode(ISD::ADD, DL, VT,
8118 DAG.getNode(ISD::SHL, DL, VT,
8120 DAG.getConstant(Log2_32(MulAmt - 1),
8122 } else if (isPowerOf2_32(MulAmt + 1)) {
8123 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8124 Res = DAG.getNode(ISD::SUB, DL, VT,
8125 DAG.getNode(ISD::SHL, DL, VT,
8127 DAG.getConstant(Log2_32(MulAmt + 1),
8133 uint64_t MulAmtAbs = -MulAmt;
8134 if (isPowerOf2_32(MulAmtAbs + 1)) {
8135 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8136 Res = DAG.getNode(ISD::SUB, DL, VT,
8138 DAG.getNode(ISD::SHL, DL, VT,
8140 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8142 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8143 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8144 Res = DAG.getNode(ISD::ADD, DL, VT,
8146 DAG.getNode(ISD::SHL, DL, VT,
8148 DAG.getConstant(Log2_32(MulAmtAbs-1),
8150 Res = DAG.getNode(ISD::SUB, DL, VT,
8151 DAG.getConstant(0, MVT::i32),Res);
8158 Res = DAG.getNode(ISD::SHL, DL, VT,
8159 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8161 // Do not add new nodes to DAG combiner worklist.
8162 DCI.CombineTo(N, Res, false);
8166 static SDValue PerformANDCombine(SDNode *N,
8167 TargetLowering::DAGCombinerInfo &DCI,
8168 const ARMSubtarget *Subtarget) {
8170 // Attempt to use immediate-form VBIC
8171 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8173 EVT VT = N->getValueType(0);
8174 SelectionDAG &DAG = DCI.DAG;
8176 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8179 APInt SplatBits, SplatUndef;
8180 unsigned SplatBitSize;
8183 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8184 if (SplatBitSize <= 64) {
8186 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8187 SplatUndef.getZExtValue(), SplatBitSize,
8188 DAG, VbicVT, VT.is128BitVector(),
8190 if (Val.getNode()) {
8192 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8193 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8194 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8199 if (!Subtarget->isThumb1Only()) {
8200 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8201 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8202 if (Result.getNode())
8209 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8210 static SDValue PerformORCombine(SDNode *N,
8211 TargetLowering::DAGCombinerInfo &DCI,
8212 const ARMSubtarget *Subtarget) {
8213 // Attempt to use immediate-form VORR
8214 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8216 EVT VT = N->getValueType(0);
8217 SelectionDAG &DAG = DCI.DAG;
8219 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8222 APInt SplatBits, SplatUndef;
8223 unsigned SplatBitSize;
8225 if (BVN && Subtarget->hasNEON() &&
8226 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8227 if (SplatBitSize <= 64) {
8229 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8230 SplatUndef.getZExtValue(), SplatBitSize,
8231 DAG, VorrVT, VT.is128BitVector(),
8233 if (Val.getNode()) {
8235 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8236 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8237 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8242 if (!Subtarget->isThumb1Only()) {
8243 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8244 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8245 if (Result.getNode())
8249 // The code below optimizes (or (and X, Y), Z).
8250 // The AND operand needs to have a single user to make these optimizations
8252 SDValue N0 = N->getOperand(0);
8253 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8255 SDValue N1 = N->getOperand(1);
8257 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8258 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8259 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8261 unsigned SplatBitSize;
8264 APInt SplatBits0, SplatBits1;
8265 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8266 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8267 // Ensure that the second operand of both ands are constants
8268 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8269 HasAnyUndefs) && !HasAnyUndefs) {
8270 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8271 HasAnyUndefs) && !HasAnyUndefs) {
8272 // Ensure that the bit width of the constants are the same and that
8273 // the splat arguments are logical inverses as per the pattern we
8274 // are trying to simplify.
8275 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8276 SplatBits0 == ~SplatBits1) {
8277 // Canonicalize the vector type to make instruction selection
8279 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8280 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8284 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8290 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8293 // BFI is only available on V6T2+
8294 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8298 // 1) or (and A, mask), val => ARMbfi A, val, mask
8299 // iff (val & mask) == val
8301 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8302 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8303 // && mask == ~mask2
8304 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8305 // && ~mask == mask2
8306 // (i.e., copy a bitfield value into another bitfield of the same width)
8311 SDValue N00 = N0.getOperand(0);
8313 // The value and the mask need to be constants so we can verify this is
8314 // actually a bitfield set. If the mask is 0xffff, we can do better
8315 // via a movt instruction, so don't use BFI in that case.
8316 SDValue MaskOp = N0.getOperand(1);
8317 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8320 unsigned Mask = MaskC->getZExtValue();
8324 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8325 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8327 unsigned Val = N1C->getZExtValue();
8328 if ((Val & ~Mask) != Val)
8331 if (ARM::isBitFieldInvertedMask(Mask)) {
8332 Val >>= countTrailingZeros(~Mask);
8334 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8335 DAG.getConstant(Val, MVT::i32),
8336 DAG.getConstant(Mask, MVT::i32));
8338 // Do not add new nodes to DAG combiner worklist.
8339 DCI.CombineTo(N, Res, false);
8342 } else if (N1.getOpcode() == ISD::AND) {
8343 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8344 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8347 unsigned Mask2 = N11C->getZExtValue();
8349 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8351 if (ARM::isBitFieldInvertedMask(Mask) &&
8353 // The pack halfword instruction works better for masks that fit it,
8354 // so use that when it's available.
8355 if (Subtarget->hasT2ExtractPack() &&
8356 (Mask == 0xffff || Mask == 0xffff0000))
8359 unsigned amt = countTrailingZeros(Mask2);
8360 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8361 DAG.getConstant(amt, MVT::i32));
8362 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8363 DAG.getConstant(Mask, MVT::i32));
8364 // Do not add new nodes to DAG combiner worklist.
8365 DCI.CombineTo(N, Res, false);
8367 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8369 // The pack halfword instruction works better for masks that fit it,
8370 // so use that when it's available.
8371 if (Subtarget->hasT2ExtractPack() &&
8372 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8375 unsigned lsb = countTrailingZeros(Mask);
8376 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8377 DAG.getConstant(lsb, MVT::i32));
8378 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8379 DAG.getConstant(Mask2, MVT::i32));
8380 // Do not add new nodes to DAG combiner worklist.
8381 DCI.CombineTo(N, Res, false);
8386 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8387 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8388 ARM::isBitFieldInvertedMask(~Mask)) {
8389 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8390 // where lsb(mask) == #shamt and masked bits of B are known zero.
8391 SDValue ShAmt = N00.getOperand(1);
8392 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8393 unsigned LSB = countTrailingZeros(Mask);
8397 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8398 DAG.getConstant(~Mask, MVT::i32));
8400 // Do not add new nodes to DAG combiner worklist.
8401 DCI.CombineTo(N, Res, false);
8407 static SDValue PerformXORCombine(SDNode *N,
8408 TargetLowering::DAGCombinerInfo &DCI,
8409 const ARMSubtarget *Subtarget) {
8410 EVT VT = N->getValueType(0);
8411 SelectionDAG &DAG = DCI.DAG;
8413 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8416 if (!Subtarget->isThumb1Only()) {
8417 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8418 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8419 if (Result.getNode())
8426 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8427 /// the bits being cleared by the AND are not demanded by the BFI.
8428 static SDValue PerformBFICombine(SDNode *N,
8429 TargetLowering::DAGCombinerInfo &DCI) {
8430 SDValue N1 = N->getOperand(1);
8431 if (N1.getOpcode() == ISD::AND) {
8432 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8435 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8436 unsigned LSB = countTrailingZeros(~InvMask);
8437 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8439 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8440 "undefined behavior");
8441 unsigned Mask = (1u << Width) - 1;
8442 unsigned Mask2 = N11C->getZExtValue();
8443 if ((Mask & (~Mask2)) == 0)
8444 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8445 N->getOperand(0), N1.getOperand(0),
8451 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8452 /// ARMISD::VMOVRRD.
8453 static SDValue PerformVMOVRRDCombine(SDNode *N,
8454 TargetLowering::DAGCombinerInfo &DCI,
8455 const ARMSubtarget *Subtarget) {
8456 // vmovrrd(vmovdrr x, y) -> x,y
8457 SDValue InDouble = N->getOperand(0);
8458 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8459 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8461 // vmovrrd(load f64) -> (load i32), (load i32)
8462 SDNode *InNode = InDouble.getNode();
8463 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8464 InNode->getValueType(0) == MVT::f64 &&
8465 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8466 !cast<LoadSDNode>(InNode)->isVolatile()) {
8467 // TODO: Should this be done for non-FrameIndex operands?
8468 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8470 SelectionDAG &DAG = DCI.DAG;
8472 SDValue BasePtr = LD->getBasePtr();
8473 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8474 LD->getPointerInfo(), LD->isVolatile(),
8475 LD->isNonTemporal(), LD->isInvariant(),
8476 LD->getAlignment());
8478 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8479 DAG.getConstant(4, MVT::i32));
8480 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8481 LD->getPointerInfo(), LD->isVolatile(),
8482 LD->isNonTemporal(), LD->isInvariant(),
8483 std::min(4U, LD->getAlignment() / 2));
8485 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8486 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8487 std::swap (NewLD1, NewLD2);
8488 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8495 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8496 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8497 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8498 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8499 SDValue Op0 = N->getOperand(0);
8500 SDValue Op1 = N->getOperand(1);
8501 if (Op0.getOpcode() == ISD::BITCAST)
8502 Op0 = Op0.getOperand(0);
8503 if (Op1.getOpcode() == ISD::BITCAST)
8504 Op1 = Op1.getOperand(0);
8505 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8506 Op0.getNode() == Op1.getNode() &&
8507 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8508 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8509 N->getValueType(0), Op0.getOperand(0));
8513 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8514 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8515 /// i64 vector to have f64 elements, since the value can then be loaded
8516 /// directly into a VFP register.
8517 static bool hasNormalLoadOperand(SDNode *N) {
8518 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8519 for (unsigned i = 0; i < NumElts; ++i) {
8520 SDNode *Elt = N->getOperand(i).getNode();
8521 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8527 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8528 /// ISD::BUILD_VECTOR.
8529 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8530 TargetLowering::DAGCombinerInfo &DCI,
8531 const ARMSubtarget *Subtarget) {
8532 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8533 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8534 // into a pair of GPRs, which is fine when the value is used as a scalar,
8535 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8536 SelectionDAG &DAG = DCI.DAG;
8537 if (N->getNumOperands() == 2) {
8538 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8543 // Load i64 elements as f64 values so that type legalization does not split
8544 // them up into i32 values.
8545 EVT VT = N->getValueType(0);
8546 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8549 SmallVector<SDValue, 8> Ops;
8550 unsigned NumElts = VT.getVectorNumElements();
8551 for (unsigned i = 0; i < NumElts; ++i) {
8552 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8554 // Make the DAGCombiner fold the bitcast.
8555 DCI.AddToWorklist(V.getNode());
8557 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8558 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8559 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8562 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8564 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8565 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8566 // At that time, we may have inserted bitcasts from integer to float.
8567 // If these bitcasts have survived DAGCombine, change the lowering of this
8568 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8569 // force to use floating point types.
8571 // Make sure we can change the type of the vector.
8572 // This is possible iff:
8573 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8574 // 1.1. Vector is used only once.
8575 // 1.2. Use is a bit convert to an integer type.
8576 // 2. The size of its operands are 32-bits (64-bits are not legal).
8577 EVT VT = N->getValueType(0);
8578 EVT EltVT = VT.getVectorElementType();
8580 // Check 1.1. and 2.
8581 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8584 // By construction, the input type must be float.
8585 assert(EltVT == MVT::f32 && "Unexpected type!");
8588 SDNode *Use = *N->use_begin();
8589 if (Use->getOpcode() != ISD::BITCAST ||
8590 Use->getValueType(0).isFloatingPoint())
8593 // Check profitability.
8594 // Model is, if more than half of the relevant operands are bitcast from
8595 // i32, turn the build_vector into a sequence of insert_vector_elt.
8596 // Relevant operands are everything that is not statically
8597 // (i.e., at compile time) bitcasted.
8598 unsigned NumOfBitCastedElts = 0;
8599 unsigned NumElts = VT.getVectorNumElements();
8600 unsigned NumOfRelevantElts = NumElts;
8601 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8602 SDValue Elt = N->getOperand(Idx);
8603 if (Elt->getOpcode() == ISD::BITCAST) {
8604 // Assume only bit cast to i32 will go away.
8605 if (Elt->getOperand(0).getValueType() == MVT::i32)
8606 ++NumOfBitCastedElts;
8607 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8608 // Constants are statically casted, thus do not count them as
8609 // relevant operands.
8610 --NumOfRelevantElts;
8613 // Check if more than half of the elements require a non-free bitcast.
8614 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8617 SelectionDAG &DAG = DCI.DAG;
8618 // Create the new vector type.
8619 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8620 // Check if the type is legal.
8621 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8622 if (!TLI.isTypeLegal(VecVT))
8626 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8627 // => BITCAST INSERT_VECTOR_ELT
8628 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8630 SDValue Vec = DAG.getUNDEF(VecVT);
8632 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8633 SDValue V = N->getOperand(Idx);
8634 if (V.getOpcode() == ISD::UNDEF)
8636 if (V.getOpcode() == ISD::BITCAST &&
8637 V->getOperand(0).getValueType() == MVT::i32)
8638 // Fold obvious case.
8639 V = V.getOperand(0);
8641 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8642 // Make the DAGCombiner fold the bitcasts.
8643 DCI.AddToWorklist(V.getNode());
8645 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8646 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8648 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8649 // Make the DAGCombiner fold the bitcasts.
8650 DCI.AddToWorklist(Vec.getNode());
8654 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8655 /// ISD::INSERT_VECTOR_ELT.
8656 static SDValue PerformInsertEltCombine(SDNode *N,
8657 TargetLowering::DAGCombinerInfo &DCI) {
8658 // Bitcast an i64 load inserted into a vector to f64.
8659 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8660 EVT VT = N->getValueType(0);
8661 SDNode *Elt = N->getOperand(1).getNode();
8662 if (VT.getVectorElementType() != MVT::i64 ||
8663 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8666 SelectionDAG &DAG = DCI.DAG;
8668 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8669 VT.getVectorNumElements());
8670 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8671 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8672 // Make the DAGCombiner fold the bitcasts.
8673 DCI.AddToWorklist(Vec.getNode());
8674 DCI.AddToWorklist(V.getNode());
8675 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8676 Vec, V, N->getOperand(2));
8677 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8680 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8681 /// ISD::VECTOR_SHUFFLE.
8682 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8683 // The LLVM shufflevector instruction does not require the shuffle mask
8684 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8685 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8686 // operands do not match the mask length, they are extended by concatenating
8687 // them with undef vectors. That is probably the right thing for other
8688 // targets, but for NEON it is better to concatenate two double-register
8689 // size vector operands into a single quad-register size vector. Do that
8690 // transformation here:
8691 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8692 // shuffle(concat(v1, v2), undef)
8693 SDValue Op0 = N->getOperand(0);
8694 SDValue Op1 = N->getOperand(1);
8695 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8696 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8697 Op0.getNumOperands() != 2 ||
8698 Op1.getNumOperands() != 2)
8700 SDValue Concat0Op1 = Op0.getOperand(1);
8701 SDValue Concat1Op1 = Op1.getOperand(1);
8702 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8703 Concat1Op1.getOpcode() != ISD::UNDEF)
8705 // Skip the transformation if any of the types are illegal.
8706 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8707 EVT VT = N->getValueType(0);
8708 if (!TLI.isTypeLegal(VT) ||
8709 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8710 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8713 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8714 Op0.getOperand(0), Op1.getOperand(0));
8715 // Translate the shuffle mask.
8716 SmallVector<int, 16> NewMask;
8717 unsigned NumElts = VT.getVectorNumElements();
8718 unsigned HalfElts = NumElts/2;
8719 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8720 for (unsigned n = 0; n < NumElts; ++n) {
8721 int MaskElt = SVN->getMaskElt(n);
8723 if (MaskElt < (int)HalfElts)
8725 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8726 NewElt = HalfElts + MaskElt - NumElts;
8727 NewMask.push_back(NewElt);
8729 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8730 DAG.getUNDEF(VT), NewMask.data());
8733 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8734 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8735 /// base address updates.
8736 /// For generic load/stores, the memory type is assumed to be a vector.
8737 /// The caller is assumed to have checked legality.
8738 static SDValue CombineBaseUpdate(SDNode *N,
8739 TargetLowering::DAGCombinerInfo &DCI) {
8740 SelectionDAG &DAG = DCI.DAG;
8741 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8742 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8743 const bool isStore = N->getOpcode() == ISD::STORE;
8744 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8745 SDValue Addr = N->getOperand(AddrOpIdx);
8746 MemSDNode *MemN = cast<MemSDNode>(N);
8748 // Search for a use of the address operand that is an increment.
8749 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8750 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8752 if (User->getOpcode() != ISD::ADD ||
8753 UI.getUse().getResNo() != Addr.getResNo())
8756 // Check that the add is independent of the load/store. Otherwise, folding
8757 // it would create a cycle.
8758 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8761 // Find the new opcode for the updating load/store.
8762 bool isLoadOp = true;
8763 bool isLaneOp = false;
8764 unsigned NewOpc = 0;
8765 unsigned NumVecs = 0;
8767 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8769 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8770 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8772 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8774 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8776 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8778 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8779 NumVecs = 2; isLaneOp = true; break;
8780 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8781 NumVecs = 3; isLaneOp = true; break;
8782 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8783 NumVecs = 4; isLaneOp = true; break;
8784 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8785 NumVecs = 1; isLoadOp = false; break;
8786 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8787 NumVecs = 2; isLoadOp = false; break;
8788 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8789 NumVecs = 3; isLoadOp = false; break;
8790 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8791 NumVecs = 4; isLoadOp = false; break;
8792 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8793 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8794 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8795 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8796 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8797 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8801 switch (N->getOpcode()) {
8802 default: llvm_unreachable("unexpected opcode for Neon base update");
8803 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8804 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8805 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8806 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
8807 NumVecs = 1; isLaneOp = false; break;
8808 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
8809 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
8813 // Find the size of memory referenced by the load/store.
8816 VecTy = N->getValueType(0);
8817 } else if (isIntrinsic) {
8818 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8820 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
8821 VecTy = N->getOperand(1).getValueType();
8824 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8826 NumBytes /= VecTy.getVectorNumElements();
8828 // If the increment is a constant, it must match the memory ref size.
8829 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8830 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8831 uint64_t IncVal = CInc->getZExtValue();
8832 if (IncVal != NumBytes)
8834 } else if (NumBytes >= 3 * 16) {
8835 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8836 // separate instructions that make it harder to use a non-constant update.
8840 // OK, we found an ADD we can fold into the base update.
8841 // Now, create a _UPD node, taking care of not breaking alignment.
8843 EVT AlignedVecTy = VecTy;
8844 unsigned Alignment = MemN->getAlignment();
8846 // If this is a less-than-standard-aligned load/store, change the type to
8847 // match the standard alignment.
8848 // The alignment is overlooked when selecting _UPD variants; and it's
8849 // easier to introduce bitcasts here than fix that.
8850 // There are 3 ways to get to this base-update combine:
8851 // - intrinsics: they are assumed to be properly aligned (to the standard
8852 // alignment of the memory type), so we don't need to do anything.
8853 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
8854 // intrinsics, so, likewise, there's nothing to do.
8855 // - generic load/store instructions: the alignment is specified as an
8856 // explicit operand, rather than implicitly as the standard alignment
8857 // of the memory type (like the intrisics). We need to change the
8858 // memory type to match the explicit alignment. That way, we don't
8859 // generate non-standard-aligned ARMISD::VLDx nodes.
8860 if (isa<LSBaseSDNode>(N)) {
8863 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
8864 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
8865 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
8866 assert(!isLaneOp && "Unexpected generic load/store lane.");
8867 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
8868 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
8870 // Don't set an explicit alignment on regular load/stores that we want
8871 // to transform to VLD/VST 1_UPD nodes.
8872 // This matches the behavior of regular load/stores, which only get an
8873 // explicit alignment if the MMO alignment is larger than the standard
8874 // alignment of the memory type.
8875 // Intrinsics, however, always get an explicit alignment, set to the
8876 // alignment of the MMO.
8880 // Create the new updating load/store node.
8881 // First, create an SDVTList for the new updating node's results.
8883 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
8885 for (n = 0; n < NumResultVecs; ++n)
8886 Tys[n] = AlignedVecTy;
8887 Tys[n++] = MVT::i32;
8888 Tys[n] = MVT::Other;
8889 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
8891 // Then, gather the new node's operands.
8892 SmallVector<SDValue, 8> Ops;
8893 Ops.push_back(N->getOperand(0)); // incoming chain
8894 Ops.push_back(N->getOperand(AddrOpIdx));
8897 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
8898 // Try to match the intrinsic's signature
8899 Ops.push_back(StN->getValue());
8901 // Loads (and of course intrinsics) match the intrinsics' signature,
8902 // so just add all but the alignment operand.
8903 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
8904 Ops.push_back(N->getOperand(i));
8907 // For all node types, the alignment operand is always the last one.
8908 Ops.push_back(DAG.getConstant(Alignment, MVT::i32));
8910 // If this is a non-standard-aligned STORE, the penultimate operand is the
8911 // stored value. Bitcast it to the aligned type.
8912 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
8913 SDValue &StVal = Ops[Ops.size()-2];
8914 StVal = DAG.getNode(ISD::BITCAST, SDLoc(N), AlignedVecTy, StVal);
8917 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8919 MemN->getMemOperand());
8922 SmallVector<SDValue, 5> NewResults;
8923 for (unsigned i = 0; i < NumResultVecs; ++i)
8924 NewResults.push_back(SDValue(UpdN.getNode(), i));
8926 // If this is an non-standard-aligned LOAD, the first result is the loaded
8927 // value. Bitcast it to the expected result type.
8928 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
8929 SDValue &LdVal = NewResults[0];
8930 LdVal = DAG.getNode(ISD::BITCAST, SDLoc(N), VecTy, LdVal);
8933 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8934 DCI.CombineTo(N, NewResults);
8935 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8942 static SDValue PerformVLDCombine(SDNode *N,
8943 TargetLowering::DAGCombinerInfo &DCI) {
8944 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8947 return CombineBaseUpdate(N, DCI);
8950 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8951 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8952 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8954 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8955 SelectionDAG &DAG = DCI.DAG;
8956 EVT VT = N->getValueType(0);
8957 // vldN-dup instructions only support 64-bit vectors for N > 1.
8958 if (!VT.is64BitVector())
8961 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8962 SDNode *VLD = N->getOperand(0).getNode();
8963 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8965 unsigned NumVecs = 0;
8966 unsigned NewOpc = 0;
8967 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8968 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8970 NewOpc = ARMISD::VLD2DUP;
8971 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8973 NewOpc = ARMISD::VLD3DUP;
8974 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8976 NewOpc = ARMISD::VLD4DUP;
8981 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8982 // numbers match the load.
8983 unsigned VLDLaneNo =
8984 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8985 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8987 // Ignore uses of the chain result.
8988 if (UI.getUse().getResNo() == NumVecs)
8991 if (User->getOpcode() != ARMISD::VDUPLANE ||
8992 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8996 // Create the vldN-dup node.
8999 for (n = 0; n < NumVecs; ++n)
9001 Tys[n] = MVT::Other;
9002 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9003 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9004 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9005 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9006 Ops, VLDMemInt->getMemoryVT(),
9007 VLDMemInt->getMemOperand());
9010 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9012 unsigned ResNo = UI.getUse().getResNo();
9013 // Ignore uses of the chain result.
9014 if (ResNo == NumVecs)
9017 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9020 // Now the vldN-lane intrinsic is dead except for its chain result.
9021 // Update uses of the chain.
9022 std::vector<SDValue> VLDDupResults;
9023 for (unsigned n = 0; n < NumVecs; ++n)
9024 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9025 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9026 DCI.CombineTo(VLD, VLDDupResults);
9031 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9032 /// ARMISD::VDUPLANE.
9033 static SDValue PerformVDUPLANECombine(SDNode *N,
9034 TargetLowering::DAGCombinerInfo &DCI) {
9035 SDValue Op = N->getOperand(0);
9037 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9038 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9039 if (CombineVLDDUP(N, DCI))
9040 return SDValue(N, 0);
9042 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9043 // redundant. Ignore bit_converts for now; element sizes are checked below.
9044 while (Op.getOpcode() == ISD::BITCAST)
9045 Op = Op.getOperand(0);
9046 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9049 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9050 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9051 // The canonical VMOV for a zero vector uses a 32-bit element size.
9052 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9054 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9056 EVT VT = N->getValueType(0);
9057 if (EltSize > VT.getVectorElementType().getSizeInBits())
9060 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9063 static SDValue PerformLOADCombine(SDNode *N,
9064 TargetLowering::DAGCombinerInfo &DCI) {
9065 EVT VT = N->getValueType(0);
9067 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9068 if (ISD::isNormalLoad(N) && VT.isVector() &&
9069 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9070 return CombineBaseUpdate(N, DCI);
9075 /// PerformSTORECombine - Target-specific dag combine xforms for
9077 static SDValue PerformSTORECombine(SDNode *N,
9078 TargetLowering::DAGCombinerInfo &DCI) {
9079 StoreSDNode *St = cast<StoreSDNode>(N);
9080 if (St->isVolatile())
9083 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9084 // pack all of the elements in one place. Next, store to memory in fewer
9086 SDValue StVal = St->getValue();
9087 EVT VT = StVal.getValueType();
9088 if (St->isTruncatingStore() && VT.isVector()) {
9089 SelectionDAG &DAG = DCI.DAG;
9090 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9091 EVT StVT = St->getMemoryVT();
9092 unsigned NumElems = VT.getVectorNumElements();
9093 assert(StVT != VT && "Cannot truncate to the same type");
9094 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9095 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9097 // From, To sizes and ElemCount must be pow of two
9098 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9100 // We are going to use the original vector elt for storing.
9101 // Accumulated smaller vector elements must be a multiple of the store size.
9102 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9104 unsigned SizeRatio = FromEltSz / ToEltSz;
9105 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9107 // Create a type on which we perform the shuffle.
9108 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9109 NumElems*SizeRatio);
9110 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9113 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9114 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9115 for (unsigned i = 0; i < NumElems; ++i)
9116 ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9118 // Can't shuffle using an illegal type.
9119 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9121 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9122 DAG.getUNDEF(WideVec.getValueType()),
9124 // At this point all of the data is stored at the bottom of the
9125 // register. We now need to save it to mem.
9127 // Find the largest store unit
9128 MVT StoreType = MVT::i8;
9129 for (MVT Tp : MVT::integer_valuetypes()) {
9130 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9133 // Didn't find a legal store type.
9134 if (!TLI.isTypeLegal(StoreType))
9137 // Bitcast the original vector into a vector of store-size units
9138 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9139 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9140 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9141 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9142 SmallVector<SDValue, 8> Chains;
9143 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9144 TLI.getPointerTy());
9145 SDValue BasePtr = St->getBasePtr();
9147 // Perform one or more big stores into memory.
9148 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9149 for (unsigned I = 0; I < E; I++) {
9150 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9151 StoreType, ShuffWide,
9152 DAG.getIntPtrConstant(I));
9153 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9154 St->getPointerInfo(), St->isVolatile(),
9155 St->isNonTemporal(), St->getAlignment());
9156 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9158 Chains.push_back(Ch);
9160 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9163 if (!ISD::isNormalStore(St))
9166 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9167 // ARM stores of arguments in the same cache line.
9168 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9169 StVal.getNode()->hasOneUse()) {
9170 SelectionDAG &DAG = DCI.DAG;
9171 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9173 SDValue BasePtr = St->getBasePtr();
9174 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9175 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9176 BasePtr, St->getPointerInfo(), St->isVolatile(),
9177 St->isNonTemporal(), St->getAlignment());
9179 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9180 DAG.getConstant(4, MVT::i32));
9181 return DAG.getStore(NewST1.getValue(0), DL,
9182 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9183 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9184 St->isNonTemporal(),
9185 std::min(4U, St->getAlignment() / 2));
9188 if (StVal.getValueType() == MVT::i64 &&
9189 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9191 // Bitcast an i64 store extracted from a vector to f64.
9192 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9193 SelectionDAG &DAG = DCI.DAG;
9195 SDValue IntVec = StVal.getOperand(0);
9196 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9197 IntVec.getValueType().getVectorNumElements());
9198 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9199 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9200 Vec, StVal.getOperand(1));
9202 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9203 // Make the DAGCombiner fold the bitcasts.
9204 DCI.AddToWorklist(Vec.getNode());
9205 DCI.AddToWorklist(ExtElt.getNode());
9206 DCI.AddToWorklist(V.getNode());
9207 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9208 St->getPointerInfo(), St->isVolatile(),
9209 St->isNonTemporal(), St->getAlignment(),
9213 // If this is a legal vector store, try to combine it into a VST1_UPD.
9214 if (ISD::isNormalStore(N) && VT.isVector() &&
9215 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9216 return CombineBaseUpdate(N, DCI);
9221 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9222 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9223 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9227 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9229 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9234 APFloat APF = C->getValueAPF();
9235 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9236 != APFloat::opOK || !isExact)
9239 c0 = (I == 0) ? cN : c0;
9240 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9247 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9248 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9249 /// when the VMUL has a constant operand that is a power of 2.
9251 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9252 /// vmul.f32 d16, d17, d16
9253 /// vcvt.s32.f32 d16, d16
9255 /// vcvt.s32.f32 d16, d16, #3
9256 static SDValue PerformVCVTCombine(SDNode *N,
9257 TargetLowering::DAGCombinerInfo &DCI,
9258 const ARMSubtarget *Subtarget) {
9259 SelectionDAG &DAG = DCI.DAG;
9260 SDValue Op = N->getOperand(0);
9262 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9263 Op.getOpcode() != ISD::FMUL)
9267 SDValue N0 = Op->getOperand(0);
9268 SDValue ConstVec = Op->getOperand(1);
9269 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9271 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9272 !isConstVecPow2(ConstVec, isSigned, C))
9275 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9276 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9277 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9278 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9280 // These instructions only exist converting from f32 to i32. We can handle
9281 // smaller integers by generating an extra truncate, but larger ones would
9282 // be lossy. We also can't handle more then 4 lanes, since these intructions
9283 // only support v2i32/v4i32 types.
9287 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9288 Intrinsic::arm_neon_vcvtfp2fxu;
9289 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9290 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9291 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9292 DAG.getConstant(Log2_64(C), MVT::i32));
9294 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9295 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9300 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9301 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9302 /// when the VDIV has a constant operand that is a power of 2.
9304 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9305 /// vcvt.f32.s32 d16, d16
9306 /// vdiv.f32 d16, d17, d16
9308 /// vcvt.f32.s32 d16, d16, #3
9309 static SDValue PerformVDIVCombine(SDNode *N,
9310 TargetLowering::DAGCombinerInfo &DCI,
9311 const ARMSubtarget *Subtarget) {
9312 SelectionDAG &DAG = DCI.DAG;
9313 SDValue Op = N->getOperand(0);
9314 unsigned OpOpcode = Op.getNode()->getOpcode();
9316 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9317 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9321 SDValue ConstVec = N->getOperand(1);
9322 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9324 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9325 !isConstVecPow2(ConstVec, isSigned, C))
9328 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9329 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9330 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9331 // These instructions only exist converting from i32 to f32. We can handle
9332 // smaller integers by generating an extra extend, but larger ones would
9337 SDValue ConvInput = Op.getOperand(0);
9338 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9339 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9340 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9341 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9344 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9345 Intrinsic::arm_neon_vcvtfxu2fp;
9346 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9348 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9349 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9352 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9353 /// operand of a vector shift operation, where all the elements of the
9354 /// build_vector must have the same constant integer value.
9355 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9356 // Ignore bit_converts.
9357 while (Op.getOpcode() == ISD::BITCAST)
9358 Op = Op.getOperand(0);
9359 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9360 APInt SplatBits, SplatUndef;
9361 unsigned SplatBitSize;
9363 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9364 HasAnyUndefs, ElementBits) ||
9365 SplatBitSize > ElementBits)
9367 Cnt = SplatBits.getSExtValue();
9371 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9372 /// operand of a vector shift left operation. That value must be in the range:
9373 /// 0 <= Value < ElementBits for a left shift; or
9374 /// 0 <= Value <= ElementBits for a long left shift.
9375 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9376 assert(VT.isVector() && "vector shift count is not a vector type");
9377 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9378 if (! getVShiftImm(Op, ElementBits, Cnt))
9380 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9383 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9384 /// operand of a vector shift right operation. For a shift opcode, the value
9385 /// is positive, but for an intrinsic the value count must be negative. The
9386 /// absolute value must be in the range:
9387 /// 1 <= |Value| <= ElementBits for a right shift; or
9388 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9389 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9391 assert(VT.isVector() && "vector shift count is not a vector type");
9392 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9393 if (! getVShiftImm(Op, ElementBits, Cnt))
9397 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9400 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9401 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9402 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9405 // Don't do anything for most intrinsics.
9408 // Vector shifts: check for immediate versions and lower them.
9409 // Note: This is done during DAG combining instead of DAG legalizing because
9410 // the build_vectors for 64-bit vector element shift counts are generally
9411 // not legal, and it is hard to see their values after they get legalized to
9412 // loads from a constant pool.
9413 case Intrinsic::arm_neon_vshifts:
9414 case Intrinsic::arm_neon_vshiftu:
9415 case Intrinsic::arm_neon_vrshifts:
9416 case Intrinsic::arm_neon_vrshiftu:
9417 case Intrinsic::arm_neon_vrshiftn:
9418 case Intrinsic::arm_neon_vqshifts:
9419 case Intrinsic::arm_neon_vqshiftu:
9420 case Intrinsic::arm_neon_vqshiftsu:
9421 case Intrinsic::arm_neon_vqshiftns:
9422 case Intrinsic::arm_neon_vqshiftnu:
9423 case Intrinsic::arm_neon_vqshiftnsu:
9424 case Intrinsic::arm_neon_vqrshiftns:
9425 case Intrinsic::arm_neon_vqrshiftnu:
9426 case Intrinsic::arm_neon_vqrshiftnsu: {
9427 EVT VT = N->getOperand(1).getValueType();
9429 unsigned VShiftOpc = 0;
9432 case Intrinsic::arm_neon_vshifts:
9433 case Intrinsic::arm_neon_vshiftu:
9434 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9435 VShiftOpc = ARMISD::VSHL;
9438 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9439 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9440 ARMISD::VSHRs : ARMISD::VSHRu);
9445 case Intrinsic::arm_neon_vrshifts:
9446 case Intrinsic::arm_neon_vrshiftu:
9447 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9451 case Intrinsic::arm_neon_vqshifts:
9452 case Intrinsic::arm_neon_vqshiftu:
9453 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9457 case Intrinsic::arm_neon_vqshiftsu:
9458 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9460 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9462 case Intrinsic::arm_neon_vrshiftn:
9463 case Intrinsic::arm_neon_vqshiftns:
9464 case Intrinsic::arm_neon_vqshiftnu:
9465 case Intrinsic::arm_neon_vqshiftnsu:
9466 case Intrinsic::arm_neon_vqrshiftns:
9467 case Intrinsic::arm_neon_vqrshiftnu:
9468 case Intrinsic::arm_neon_vqrshiftnsu:
9469 // Narrowing shifts require an immediate right shift.
9470 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9472 llvm_unreachable("invalid shift count for narrowing vector shift "
9476 llvm_unreachable("unhandled vector shift");
9480 case Intrinsic::arm_neon_vshifts:
9481 case Intrinsic::arm_neon_vshiftu:
9482 // Opcode already set above.
9484 case Intrinsic::arm_neon_vrshifts:
9485 VShiftOpc = ARMISD::VRSHRs; break;
9486 case Intrinsic::arm_neon_vrshiftu:
9487 VShiftOpc = ARMISD::VRSHRu; break;
9488 case Intrinsic::arm_neon_vrshiftn:
9489 VShiftOpc = ARMISD::VRSHRN; break;
9490 case Intrinsic::arm_neon_vqshifts:
9491 VShiftOpc = ARMISD::VQSHLs; break;
9492 case Intrinsic::arm_neon_vqshiftu:
9493 VShiftOpc = ARMISD::VQSHLu; break;
9494 case Intrinsic::arm_neon_vqshiftsu:
9495 VShiftOpc = ARMISD::VQSHLsu; break;
9496 case Intrinsic::arm_neon_vqshiftns:
9497 VShiftOpc = ARMISD::VQSHRNs; break;
9498 case Intrinsic::arm_neon_vqshiftnu:
9499 VShiftOpc = ARMISD::VQSHRNu; break;
9500 case Intrinsic::arm_neon_vqshiftnsu:
9501 VShiftOpc = ARMISD::VQSHRNsu; break;
9502 case Intrinsic::arm_neon_vqrshiftns:
9503 VShiftOpc = ARMISD::VQRSHRNs; break;
9504 case Intrinsic::arm_neon_vqrshiftnu:
9505 VShiftOpc = ARMISD::VQRSHRNu; break;
9506 case Intrinsic::arm_neon_vqrshiftnsu:
9507 VShiftOpc = ARMISD::VQRSHRNsu; break;
9510 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9511 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9514 case Intrinsic::arm_neon_vshiftins: {
9515 EVT VT = N->getOperand(1).getValueType();
9517 unsigned VShiftOpc = 0;
9519 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9520 VShiftOpc = ARMISD::VSLI;
9521 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9522 VShiftOpc = ARMISD::VSRI;
9524 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9527 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9528 N->getOperand(1), N->getOperand(2),
9529 DAG.getConstant(Cnt, MVT::i32));
9532 case Intrinsic::arm_neon_vqrshifts:
9533 case Intrinsic::arm_neon_vqrshiftu:
9534 // No immediate versions of these to check for.
9541 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9542 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9543 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9544 /// vector element shift counts are generally not legal, and it is hard to see
9545 /// their values after they get legalized to loads from a constant pool.
9546 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9547 const ARMSubtarget *ST) {
9548 EVT VT = N->getValueType(0);
9549 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9550 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9551 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9552 SDValue N1 = N->getOperand(1);
9553 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9554 SDValue N0 = N->getOperand(0);
9555 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9556 DAG.MaskedValueIsZero(N0.getOperand(0),
9557 APInt::getHighBitsSet(32, 16)))
9558 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9562 // Nothing to be done for scalar shifts.
9563 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9564 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9567 assert(ST->hasNEON() && "unexpected vector shift");
9570 switch (N->getOpcode()) {
9571 default: llvm_unreachable("unexpected shift opcode");
9574 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9575 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9576 DAG.getConstant(Cnt, MVT::i32));
9581 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9582 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9583 ARMISD::VSHRs : ARMISD::VSHRu);
9584 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9585 DAG.getConstant(Cnt, MVT::i32));
9591 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9592 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9593 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9594 const ARMSubtarget *ST) {
9595 SDValue N0 = N->getOperand(0);
9597 // Check for sign- and zero-extensions of vector extract operations of 8-
9598 // and 16-bit vector elements. NEON supports these directly. They are
9599 // handled during DAG combining because type legalization will promote them
9600 // to 32-bit types and it is messy to recognize the operations after that.
9601 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9602 SDValue Vec = N0.getOperand(0);
9603 SDValue Lane = N0.getOperand(1);
9604 EVT VT = N->getValueType(0);
9605 EVT EltVT = N0.getValueType();
9606 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9608 if (VT == MVT::i32 &&
9609 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9610 TLI.isTypeLegal(Vec.getValueType()) &&
9611 isa<ConstantSDNode>(Lane)) {
9614 switch (N->getOpcode()) {
9615 default: llvm_unreachable("unexpected opcode");
9616 case ISD::SIGN_EXTEND:
9617 Opc = ARMISD::VGETLANEs;
9619 case ISD::ZERO_EXTEND:
9620 case ISD::ANY_EXTEND:
9621 Opc = ARMISD::VGETLANEu;
9624 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9631 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9632 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9633 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9634 const ARMSubtarget *ST) {
9635 // If the target supports NEON, try to use vmax/vmin instructions for f32
9636 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9637 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9638 // a NaN; only do the transformation when it matches that behavior.
9640 // For now only do this when using NEON for FP operations; if using VFP, it
9641 // is not obvious that the benefit outweighs the cost of switching to the
9643 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9644 N->getValueType(0) != MVT::f32)
9647 SDValue CondLHS = N->getOperand(0);
9648 SDValue CondRHS = N->getOperand(1);
9649 SDValue LHS = N->getOperand(2);
9650 SDValue RHS = N->getOperand(3);
9651 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9653 unsigned Opcode = 0;
9655 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9656 IsReversed = false; // x CC y ? x : y
9657 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9658 IsReversed = true ; // x CC y ? y : x
9672 // If LHS is NaN, an ordered comparison will be false and the result will
9673 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9674 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9675 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9676 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9678 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9679 // will return -0, so vmin can only be used for unsafe math or if one of
9680 // the operands is known to be nonzero.
9681 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9682 !DAG.getTarget().Options.UnsafeFPMath &&
9683 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9685 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9694 // If LHS is NaN, an ordered comparison will be false and the result will
9695 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9696 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9697 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9698 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9700 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9701 // will return +0, so vmax can only be used for unsafe math or if one of
9702 // the operands is known to be nonzero.
9703 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9704 !DAG.getTarget().Options.UnsafeFPMath &&
9705 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9707 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9713 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9716 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9718 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9719 SDValue Cmp = N->getOperand(4);
9720 if (Cmp.getOpcode() != ARMISD::CMPZ)
9721 // Only looking at EQ and NE cases.
9724 EVT VT = N->getValueType(0);
9726 SDValue LHS = Cmp.getOperand(0);
9727 SDValue RHS = Cmp.getOperand(1);
9728 SDValue FalseVal = N->getOperand(0);
9729 SDValue TrueVal = N->getOperand(1);
9730 SDValue ARMcc = N->getOperand(2);
9731 ARMCC::CondCodes CC =
9732 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9750 /// FIXME: Turn this into a target neutral optimization?
9752 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9753 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9754 N->getOperand(3), Cmp);
9755 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9757 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9758 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9759 N->getOperand(3), NewCmp);
9762 if (Res.getNode()) {
9763 APInt KnownZero, KnownOne;
9764 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9765 // Capture demanded bits information that would be otherwise lost.
9766 if (KnownZero == 0xfffffffe)
9767 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9768 DAG.getValueType(MVT::i1));
9769 else if (KnownZero == 0xffffff00)
9770 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9771 DAG.getValueType(MVT::i8));
9772 else if (KnownZero == 0xffff0000)
9773 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9774 DAG.getValueType(MVT::i16));
9780 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9781 DAGCombinerInfo &DCI) const {
9782 switch (N->getOpcode()) {
9784 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9785 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9786 case ISD::SUB: return PerformSUBCombine(N, DCI);
9787 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9788 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9789 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9790 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9791 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9792 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9793 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9794 case ISD::STORE: return PerformSTORECombine(N, DCI);
9795 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9796 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9797 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9798 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9799 case ISD::FP_TO_SINT:
9800 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9801 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9802 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9805 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9806 case ISD::SIGN_EXTEND:
9807 case ISD::ZERO_EXTEND:
9808 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9809 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9810 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9811 case ISD::LOAD: return PerformLOADCombine(N, DCI);
9812 case ARMISD::VLD2DUP:
9813 case ARMISD::VLD3DUP:
9814 case ARMISD::VLD4DUP:
9815 return PerformVLDCombine(N, DCI);
9816 case ARMISD::BUILD_VECTOR:
9817 return PerformARMBUILD_VECTORCombine(N, DCI);
9818 case ISD::INTRINSIC_VOID:
9819 case ISD::INTRINSIC_W_CHAIN:
9820 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9821 case Intrinsic::arm_neon_vld1:
9822 case Intrinsic::arm_neon_vld2:
9823 case Intrinsic::arm_neon_vld3:
9824 case Intrinsic::arm_neon_vld4:
9825 case Intrinsic::arm_neon_vld2lane:
9826 case Intrinsic::arm_neon_vld3lane:
9827 case Intrinsic::arm_neon_vld4lane:
9828 case Intrinsic::arm_neon_vst1:
9829 case Intrinsic::arm_neon_vst2:
9830 case Intrinsic::arm_neon_vst3:
9831 case Intrinsic::arm_neon_vst4:
9832 case Intrinsic::arm_neon_vst2lane:
9833 case Intrinsic::arm_neon_vst3lane:
9834 case Intrinsic::arm_neon_vst4lane:
9835 return PerformVLDCombine(N, DCI);
9843 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9845 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9848 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9852 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9853 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9855 switch (VT.getSimpleVT().SimpleTy) {
9861 // Unaligned access can use (for example) LRDB, LRDH, LDR
9862 if (AllowsUnaligned) {
9864 *Fast = Subtarget->hasV7Ops();
9871 // For any little-endian targets with neon, we can support unaligned ld/st
9872 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9873 // A big-endian target may also explicitly support unaligned accesses
9874 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9884 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9885 unsigned AlignCheck) {
9886 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9887 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9890 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9891 unsigned DstAlign, unsigned SrcAlign,
9892 bool IsMemset, bool ZeroMemset,
9894 MachineFunction &MF) const {
9895 const Function *F = MF.getFunction();
9897 // See if we can use NEON instructions for this...
9898 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
9899 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
9902 (memOpAlign(SrcAlign, DstAlign, 16) ||
9903 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9905 } else if (Size >= 8 &&
9906 (memOpAlign(SrcAlign, DstAlign, 8) ||
9907 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9913 // Lowering to i32/i16 if the size permits.
9919 // Let the target-independent logic figure it out.
9923 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9924 if (Val.getOpcode() != ISD::LOAD)
9927 EVT VT1 = Val.getValueType();
9928 if (!VT1.isSimple() || !VT1.isInteger() ||
9929 !VT2.isSimple() || !VT2.isInteger())
9932 switch (VT1.getSimpleVT().SimpleTy) {
9937 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9944 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
9945 EVT VT = ExtVal.getValueType();
9947 if (!isTypeLegal(VT))
9950 // Don't create a loadext if we can fold the extension into a wide/long
9952 // If there's more than one user instruction, the loadext is desirable no
9953 // matter what. There can be two uses by the same instruction.
9954 if (ExtVal->use_empty() ||
9955 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
9958 SDNode *U = *ExtVal->use_begin();
9959 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
9960 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
9966 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9967 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9970 if (!isTypeLegal(EVT::getEVT(Ty1)))
9973 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9975 // Assuming the caller doesn't have a zeroext or signext return parameter,
9976 // truncation all the way down to i1 is valid.
9981 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9986 switch (VT.getSimpleVT().SimpleTy) {
9987 default: return false;
10002 if ((V & (Scale - 1)) != 0)
10005 return V == (V & ((1LL << 5) - 1));
10008 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10009 const ARMSubtarget *Subtarget) {
10010 bool isNeg = false;
10016 switch (VT.getSimpleVT().SimpleTy) {
10017 default: return false;
10022 // + imm12 or - imm8
10024 return V == (V & ((1LL << 8) - 1));
10025 return V == (V & ((1LL << 12) - 1));
10028 // Same as ARM mode. FIXME: NEON?
10029 if (!Subtarget->hasVFP2())
10034 return V == (V & ((1LL << 8) - 1));
10038 /// isLegalAddressImmediate - Return true if the integer value can be used
10039 /// as the offset of the target addressing mode for load / store of the
10041 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10042 const ARMSubtarget *Subtarget) {
10046 if (!VT.isSimple())
10049 if (Subtarget->isThumb1Only())
10050 return isLegalT1AddressImmediate(V, VT);
10051 else if (Subtarget->isThumb2())
10052 return isLegalT2AddressImmediate(V, VT, Subtarget);
10057 switch (VT.getSimpleVT().SimpleTy) {
10058 default: return false;
10063 return V == (V & ((1LL << 12) - 1));
10066 return V == (V & ((1LL << 8) - 1));
10069 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10074 return V == (V & ((1LL << 8) - 1));
10078 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10080 int Scale = AM.Scale;
10084 switch (VT.getSimpleVT().SimpleTy) {
10085 default: return false;
10093 Scale = Scale & ~1;
10094 return Scale == 2 || Scale == 4 || Scale == 8;
10097 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10101 // Note, we allow "void" uses (basically, uses that aren't loads or
10102 // stores), because arm allows folding a scale into many arithmetic
10103 // operations. This should be made more precise and revisited later.
10105 // Allow r << imm, but the imm has to be a multiple of two.
10106 if (Scale & 1) return false;
10107 return isPowerOf2_32(Scale);
10111 /// isLegalAddressingMode - Return true if the addressing mode represented
10112 /// by AM is legal for this target, for a load/store of the specified type.
10113 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10115 EVT VT = getValueType(Ty, true);
10116 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10119 // Can never fold addr of global into load/store.
10123 switch (AM.Scale) {
10124 case 0: // no scale reg, must be "r+i" or "r", or "i".
10127 if (Subtarget->isThumb1Only())
10131 // ARM doesn't support any R+R*scale+imm addr modes.
10135 if (!VT.isSimple())
10138 if (Subtarget->isThumb2())
10139 return isLegalT2ScaledAddressingMode(AM, VT);
10141 int Scale = AM.Scale;
10142 switch (VT.getSimpleVT().SimpleTy) {
10143 default: return false;
10147 if (Scale < 0) Scale = -Scale;
10151 return isPowerOf2_32(Scale & ~1);
10155 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10160 // Note, we allow "void" uses (basically, uses that aren't loads or
10161 // stores), because arm allows folding a scale into many arithmetic
10162 // operations. This should be made more precise and revisited later.
10164 // Allow r << imm, but the imm has to be a multiple of two.
10165 if (Scale & 1) return false;
10166 return isPowerOf2_32(Scale);
10172 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10173 /// icmp immediate, that is the target has icmp instructions which can compare
10174 /// a register against the immediate without having to materialize the
10175 /// immediate into a register.
10176 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10177 // Thumb2 and ARM modes can use cmn for negative immediates.
10178 if (!Subtarget->isThumb())
10179 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10180 if (Subtarget->isThumb2())
10181 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10182 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10183 return Imm >= 0 && Imm <= 255;
10186 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10187 /// *or sub* immediate, that is the target has add or sub instructions which can
10188 /// add a register with the immediate without having to materialize the
10189 /// immediate into a register.
10190 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10191 // Same encoding for add/sub, just flip the sign.
10192 int64_t AbsImm = std::abs(Imm);
10193 if (!Subtarget->isThumb())
10194 return ARM_AM::getSOImmVal(AbsImm) != -1;
10195 if (Subtarget->isThumb2())
10196 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10197 // Thumb1 only has 8-bit unsigned immediate.
10198 return AbsImm >= 0 && AbsImm <= 255;
10201 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10202 bool isSEXTLoad, SDValue &Base,
10203 SDValue &Offset, bool &isInc,
10204 SelectionDAG &DAG) {
10205 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10208 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10209 // AddressingMode 3
10210 Base = Ptr->getOperand(0);
10211 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10212 int RHSC = (int)RHS->getZExtValue();
10213 if (RHSC < 0 && RHSC > -256) {
10214 assert(Ptr->getOpcode() == ISD::ADD);
10216 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10220 isInc = (Ptr->getOpcode() == ISD::ADD);
10221 Offset = Ptr->getOperand(1);
10223 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10224 // AddressingMode 2
10225 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10226 int RHSC = (int)RHS->getZExtValue();
10227 if (RHSC < 0 && RHSC > -0x1000) {
10228 assert(Ptr->getOpcode() == ISD::ADD);
10230 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10231 Base = Ptr->getOperand(0);
10236 if (Ptr->getOpcode() == ISD::ADD) {
10238 ARM_AM::ShiftOpc ShOpcVal=
10239 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10240 if (ShOpcVal != ARM_AM::no_shift) {
10241 Base = Ptr->getOperand(1);
10242 Offset = Ptr->getOperand(0);
10244 Base = Ptr->getOperand(0);
10245 Offset = Ptr->getOperand(1);
10250 isInc = (Ptr->getOpcode() == ISD::ADD);
10251 Base = Ptr->getOperand(0);
10252 Offset = Ptr->getOperand(1);
10256 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10260 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10261 bool isSEXTLoad, SDValue &Base,
10262 SDValue &Offset, bool &isInc,
10263 SelectionDAG &DAG) {
10264 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10267 Base = Ptr->getOperand(0);
10268 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10269 int RHSC = (int)RHS->getZExtValue();
10270 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10271 assert(Ptr->getOpcode() == ISD::ADD);
10273 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10275 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10276 isInc = Ptr->getOpcode() == ISD::ADD;
10277 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10285 /// getPreIndexedAddressParts - returns true by value, base pointer and
10286 /// offset pointer and addressing mode by reference if the node's address
10287 /// can be legally represented as pre-indexed load / store address.
10289 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10291 ISD::MemIndexedMode &AM,
10292 SelectionDAG &DAG) const {
10293 if (Subtarget->isThumb1Only())
10298 bool isSEXTLoad = false;
10299 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10300 Ptr = LD->getBasePtr();
10301 VT = LD->getMemoryVT();
10302 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10303 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10304 Ptr = ST->getBasePtr();
10305 VT = ST->getMemoryVT();
10310 bool isLegal = false;
10311 if (Subtarget->isThumb2())
10312 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10313 Offset, isInc, DAG);
10315 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10316 Offset, isInc, DAG);
10320 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10324 /// getPostIndexedAddressParts - returns true by value, base pointer and
10325 /// offset pointer and addressing mode by reference if this node can be
10326 /// combined with a load / store to form a post-indexed load / store.
10327 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10330 ISD::MemIndexedMode &AM,
10331 SelectionDAG &DAG) const {
10332 if (Subtarget->isThumb1Only())
10337 bool isSEXTLoad = false;
10338 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10339 VT = LD->getMemoryVT();
10340 Ptr = LD->getBasePtr();
10341 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10342 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10343 VT = ST->getMemoryVT();
10344 Ptr = ST->getBasePtr();
10349 bool isLegal = false;
10350 if (Subtarget->isThumb2())
10351 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10354 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10360 // Swap base ptr and offset to catch more post-index load / store when
10361 // it's legal. In Thumb2 mode, offset must be an immediate.
10362 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10363 !Subtarget->isThumb2())
10364 std::swap(Base, Offset);
10366 // Post-indexed load / store update the base pointer.
10371 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10375 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10378 const SelectionDAG &DAG,
10379 unsigned Depth) const {
10380 unsigned BitWidth = KnownOne.getBitWidth();
10381 KnownZero = KnownOne = APInt(BitWidth, 0);
10382 switch (Op.getOpcode()) {
10388 // These nodes' second result is a boolean
10389 if (Op.getResNo() == 0)
10391 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10393 case ARMISD::CMOV: {
10394 // Bits are known zero/one if known on the LHS and RHS.
10395 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10396 if (KnownZero == 0 && KnownOne == 0) return;
10398 APInt KnownZeroRHS, KnownOneRHS;
10399 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10400 KnownZero &= KnownZeroRHS;
10401 KnownOne &= KnownOneRHS;
10404 case ISD::INTRINSIC_W_CHAIN: {
10405 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10406 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10409 case Intrinsic::arm_ldaex:
10410 case Intrinsic::arm_ldrex: {
10411 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10412 unsigned MemBits = VT.getScalarType().getSizeInBits();
10413 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10421 //===----------------------------------------------------------------------===//
10422 // ARM Inline Assembly Support
10423 //===----------------------------------------------------------------------===//
10425 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10426 // Looking for "rev" which is V6+.
10427 if (!Subtarget->hasV6Ops())
10430 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10431 std::string AsmStr = IA->getAsmString();
10432 SmallVector<StringRef, 4> AsmPieces;
10433 SplitString(AsmStr, AsmPieces, ";\n");
10435 switch (AsmPieces.size()) {
10436 default: return false;
10438 AsmStr = AsmPieces[0];
10440 SplitString(AsmStr, AsmPieces, " \t,");
10443 if (AsmPieces.size() == 3 &&
10444 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10445 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10446 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10447 if (Ty && Ty->getBitWidth() == 32)
10448 return IntrinsicLowering::LowerToByteSwap(CI);
10456 /// getConstraintType - Given a constraint letter, return the type of
10457 /// constraint it is for this target.
10458 ARMTargetLowering::ConstraintType
10459 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10460 if (Constraint.size() == 1) {
10461 switch (Constraint[0]) {
10463 case 'l': return C_RegisterClass;
10464 case 'w': return C_RegisterClass;
10465 case 'h': return C_RegisterClass;
10466 case 'x': return C_RegisterClass;
10467 case 't': return C_RegisterClass;
10468 case 'j': return C_Other; // Constant for movw.
10469 // An address with a single base register. Due to the way we
10470 // currently handle addresses it is the same as an 'r' memory constraint.
10471 case 'Q': return C_Memory;
10473 } else if (Constraint.size() == 2) {
10474 switch (Constraint[0]) {
10476 // All 'U+' constraints are addresses.
10477 case 'U': return C_Memory;
10480 return TargetLowering::getConstraintType(Constraint);
10483 /// Examine constraint type and operand type and determine a weight value.
10484 /// This object must already have been set up with the operand type
10485 /// and the current alternative constraint selected.
10486 TargetLowering::ConstraintWeight
10487 ARMTargetLowering::getSingleConstraintMatchWeight(
10488 AsmOperandInfo &info, const char *constraint) const {
10489 ConstraintWeight weight = CW_Invalid;
10490 Value *CallOperandVal = info.CallOperandVal;
10491 // If we don't have a value, we can't do a match,
10492 // but allow it at the lowest weight.
10493 if (!CallOperandVal)
10495 Type *type = CallOperandVal->getType();
10496 // Look at the constraint type.
10497 switch (*constraint) {
10499 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10502 if (type->isIntegerTy()) {
10503 if (Subtarget->isThumb())
10504 weight = CW_SpecificReg;
10506 weight = CW_Register;
10510 if (type->isFloatingPointTy())
10511 weight = CW_Register;
10517 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10519 ARMTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10520 const std::string &Constraint,
10522 if (Constraint.size() == 1) {
10523 // GCC ARM Constraint Letters
10524 switch (Constraint[0]) {
10525 case 'l': // Low regs or general regs.
10526 if (Subtarget->isThumb())
10527 return RCPair(0U, &ARM::tGPRRegClass);
10528 return RCPair(0U, &ARM::GPRRegClass);
10529 case 'h': // High regs or no regs.
10530 if (Subtarget->isThumb())
10531 return RCPair(0U, &ARM::hGPRRegClass);
10534 if (Subtarget->isThumb1Only())
10535 return RCPair(0U, &ARM::tGPRRegClass);
10536 return RCPair(0U, &ARM::GPRRegClass);
10538 if (VT == MVT::Other)
10540 if (VT == MVT::f32)
10541 return RCPair(0U, &ARM::SPRRegClass);
10542 if (VT.getSizeInBits() == 64)
10543 return RCPair(0U, &ARM::DPRRegClass);
10544 if (VT.getSizeInBits() == 128)
10545 return RCPair(0U, &ARM::QPRRegClass);
10548 if (VT == MVT::Other)
10550 if (VT == MVT::f32)
10551 return RCPair(0U, &ARM::SPR_8RegClass);
10552 if (VT.getSizeInBits() == 64)
10553 return RCPair(0U, &ARM::DPR_8RegClass);
10554 if (VT.getSizeInBits() == 128)
10555 return RCPair(0U, &ARM::QPR_8RegClass);
10558 if (VT == MVT::f32)
10559 return RCPair(0U, &ARM::SPRRegClass);
10563 if (StringRef("{cc}").equals_lower(Constraint))
10564 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10566 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10569 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10570 /// vector. If it is invalid, don't add anything to Ops.
10571 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10572 std::string &Constraint,
10573 std::vector<SDValue>&Ops,
10574 SelectionDAG &DAG) const {
10577 // Currently only support length 1 constraints.
10578 if (Constraint.length() != 1) return;
10580 char ConstraintLetter = Constraint[0];
10581 switch (ConstraintLetter) {
10584 case 'I': case 'J': case 'K': case 'L':
10585 case 'M': case 'N': case 'O':
10586 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10590 int64_t CVal64 = C->getSExtValue();
10591 int CVal = (int) CVal64;
10592 // None of these constraints allow values larger than 32 bits. Check
10593 // that the value fits in an int.
10594 if (CVal != CVal64)
10597 switch (ConstraintLetter) {
10599 // Constant suitable for movw, must be between 0 and
10601 if (Subtarget->hasV6T2Ops())
10602 if (CVal >= 0 && CVal <= 65535)
10606 if (Subtarget->isThumb1Only()) {
10607 // This must be a constant between 0 and 255, for ADD
10609 if (CVal >= 0 && CVal <= 255)
10611 } else if (Subtarget->isThumb2()) {
10612 // A constant that can be used as an immediate value in a
10613 // data-processing instruction.
10614 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10617 // A constant that can be used as an immediate value in a
10618 // data-processing instruction.
10619 if (ARM_AM::getSOImmVal(CVal) != -1)
10625 if (Subtarget->isThumb()) { // FIXME thumb2
10626 // This must be a constant between -255 and -1, for negated ADD
10627 // immediates. This can be used in GCC with an "n" modifier that
10628 // prints the negated value, for use with SUB instructions. It is
10629 // not useful otherwise but is implemented for compatibility.
10630 if (CVal >= -255 && CVal <= -1)
10633 // This must be a constant between -4095 and 4095. It is not clear
10634 // what this constraint is intended for. Implemented for
10635 // compatibility with GCC.
10636 if (CVal >= -4095 && CVal <= 4095)
10642 if (Subtarget->isThumb1Only()) {
10643 // A 32-bit value where only one byte has a nonzero value. Exclude
10644 // zero to match GCC. This constraint is used by GCC internally for
10645 // constants that can be loaded with a move/shift combination.
10646 // It is not useful otherwise but is implemented for compatibility.
10647 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10649 } else if (Subtarget->isThumb2()) {
10650 // A constant whose bitwise inverse can be used as an immediate
10651 // value in a data-processing instruction. This can be used in GCC
10652 // with a "B" modifier that prints the inverted value, for use with
10653 // BIC and MVN instructions. It is not useful otherwise but is
10654 // implemented for compatibility.
10655 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10658 // A constant whose bitwise inverse can be used as an immediate
10659 // value in a data-processing instruction. This can be used in GCC
10660 // with a "B" modifier that prints the inverted value, for use with
10661 // BIC and MVN instructions. It is not useful otherwise but is
10662 // implemented for compatibility.
10663 if (ARM_AM::getSOImmVal(~CVal) != -1)
10669 if (Subtarget->isThumb1Only()) {
10670 // This must be a constant between -7 and 7,
10671 // for 3-operand ADD/SUB immediate instructions.
10672 if (CVal >= -7 && CVal < 7)
10674 } else if (Subtarget->isThumb2()) {
10675 // A constant whose negation can be used as an immediate value in a
10676 // data-processing instruction. This can be used in GCC with an "n"
10677 // modifier that prints the negated value, for use with SUB
10678 // instructions. It is not useful otherwise but is implemented for
10680 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10683 // A constant whose negation can be used as an immediate value in a
10684 // data-processing instruction. This can be used in GCC with an "n"
10685 // modifier that prints the negated value, for use with SUB
10686 // instructions. It is not useful otherwise but is implemented for
10688 if (ARM_AM::getSOImmVal(-CVal) != -1)
10694 if (Subtarget->isThumb()) { // FIXME thumb2
10695 // This must be a multiple of 4 between 0 and 1020, for
10696 // ADD sp + immediate.
10697 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10700 // A power of two or a constant between 0 and 32. This is used in
10701 // GCC for the shift amount on shifted register operands, but it is
10702 // useful in general for any shift amounts.
10703 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10709 if (Subtarget->isThumb()) { // FIXME thumb2
10710 // This must be a constant between 0 and 31, for shift amounts.
10711 if (CVal >= 0 && CVal <= 31)
10717 if (Subtarget->isThumb()) { // FIXME thumb2
10718 // This must be a multiple of 4 between -508 and 508, for
10719 // ADD/SUB sp = sp + immediate.
10720 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10725 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10729 if (Result.getNode()) {
10730 Ops.push_back(Result);
10733 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10736 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10737 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10738 unsigned Opcode = Op->getOpcode();
10739 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10740 "Invalid opcode for Div/Rem lowering");
10741 bool isSigned = (Opcode == ISD::SDIVREM);
10742 EVT VT = Op->getValueType(0);
10743 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10746 switch (VT.getSimpleVT().SimpleTy) {
10747 default: llvm_unreachable("Unexpected request for libcall!");
10748 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10749 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10750 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10751 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10754 SDValue InChain = DAG.getEntryNode();
10756 TargetLowering::ArgListTy Args;
10757 TargetLowering::ArgListEntry Entry;
10758 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10759 EVT ArgVT = Op->getOperand(i).getValueType();
10760 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10761 Entry.Node = Op->getOperand(i);
10763 Entry.isSExt = isSigned;
10764 Entry.isZExt = !isSigned;
10765 Args.push_back(Entry);
10768 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10771 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10774 TargetLowering::CallLoweringInfo CLI(DAG);
10775 CLI.setDebugLoc(dl).setChain(InChain)
10776 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10777 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10779 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10780 return CallInfo.first;
10784 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10785 assert(Subtarget->isTargetWindows() && "unsupported target platform");
10789 SDValue Chain = Op.getOperand(0);
10790 SDValue Size = Op.getOperand(1);
10792 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10793 DAG.getConstant(2, MVT::i32));
10796 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10797 Flag = Chain.getValue(1);
10799 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10800 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10802 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10803 Chain = NewSP.getValue(1);
10805 SDValue Ops[2] = { NewSP, Chain };
10806 return DAG.getMergeValues(Ops, DL);
10809 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10810 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10811 "Unexpected type for custom-lowering FP_EXTEND");
10814 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10816 SDValue SrcVal = Op.getOperand(0);
10817 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10818 /*isSigned*/ false, SDLoc(Op)).first;
10821 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10822 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10823 Subtarget->isFPOnlySP() &&
10824 "Unexpected type for custom-lowering FP_ROUND");
10827 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10829 SDValue SrcVal = Op.getOperand(0);
10830 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10831 /*isSigned*/ false, SDLoc(Op)).first;
10835 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10836 // The ARM target isn't yet aware of offsets.
10840 bool ARM::isBitFieldInvertedMask(unsigned v) {
10841 if (v == 0xffffffff)
10844 // there can be 1's on either or both "outsides", all the "inside"
10845 // bits must be 0's
10846 return isShiftedMask_32(~v);
10849 /// isFPImmLegal - Returns true if the target can instruction select the
10850 /// specified FP immediate natively. If false, the legalizer will
10851 /// materialize the FP immediate as a load from a constant pool.
10852 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10853 if (!Subtarget->hasVFP3())
10855 if (VT == MVT::f32)
10856 return ARM_AM::getFP32Imm(Imm) != -1;
10857 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10858 return ARM_AM::getFP64Imm(Imm) != -1;
10862 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10863 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10864 /// specified in the intrinsic calls.
10865 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10867 unsigned Intrinsic) const {
10868 switch (Intrinsic) {
10869 case Intrinsic::arm_neon_vld1:
10870 case Intrinsic::arm_neon_vld2:
10871 case Intrinsic::arm_neon_vld3:
10872 case Intrinsic::arm_neon_vld4:
10873 case Intrinsic::arm_neon_vld2lane:
10874 case Intrinsic::arm_neon_vld3lane:
10875 case Intrinsic::arm_neon_vld4lane: {
10876 Info.opc = ISD::INTRINSIC_W_CHAIN;
10877 // Conservatively set memVT to the entire set of vectors loaded.
10878 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10879 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10880 Info.ptrVal = I.getArgOperand(0);
10882 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10883 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10884 Info.vol = false; // volatile loads with NEON intrinsics not supported
10885 Info.readMem = true;
10886 Info.writeMem = false;
10889 case Intrinsic::arm_neon_vst1:
10890 case Intrinsic::arm_neon_vst2:
10891 case Intrinsic::arm_neon_vst3:
10892 case Intrinsic::arm_neon_vst4:
10893 case Intrinsic::arm_neon_vst2lane:
10894 case Intrinsic::arm_neon_vst3lane:
10895 case Intrinsic::arm_neon_vst4lane: {
10896 Info.opc = ISD::INTRINSIC_VOID;
10897 // Conservatively set memVT to the entire set of vectors stored.
10898 unsigned NumElts = 0;
10899 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10900 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10901 if (!ArgTy->isVectorTy())
10903 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10905 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10906 Info.ptrVal = I.getArgOperand(0);
10908 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10909 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10910 Info.vol = false; // volatile stores with NEON intrinsics not supported
10911 Info.readMem = false;
10912 Info.writeMem = true;
10915 case Intrinsic::arm_ldaex:
10916 case Intrinsic::arm_ldrex: {
10917 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10918 Info.opc = ISD::INTRINSIC_W_CHAIN;
10919 Info.memVT = MVT::getVT(PtrTy->getElementType());
10920 Info.ptrVal = I.getArgOperand(0);
10922 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10924 Info.readMem = true;
10925 Info.writeMem = false;
10928 case Intrinsic::arm_stlex:
10929 case Intrinsic::arm_strex: {
10930 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10931 Info.opc = ISD::INTRINSIC_W_CHAIN;
10932 Info.memVT = MVT::getVT(PtrTy->getElementType());
10933 Info.ptrVal = I.getArgOperand(1);
10935 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10937 Info.readMem = false;
10938 Info.writeMem = true;
10941 case Intrinsic::arm_stlexd:
10942 case Intrinsic::arm_strexd: {
10943 Info.opc = ISD::INTRINSIC_W_CHAIN;
10944 Info.memVT = MVT::i64;
10945 Info.ptrVal = I.getArgOperand(2);
10949 Info.readMem = false;
10950 Info.writeMem = true;
10953 case Intrinsic::arm_ldaexd:
10954 case Intrinsic::arm_ldrexd: {
10955 Info.opc = ISD::INTRINSIC_W_CHAIN;
10956 Info.memVT = MVT::i64;
10957 Info.ptrVal = I.getArgOperand(0);
10961 Info.readMem = true;
10962 Info.writeMem = false;
10972 /// \brief Returns true if it is beneficial to convert a load of a constant
10973 /// to just the constant itself.
10974 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10976 assert(Ty->isIntegerTy());
10978 unsigned Bits = Ty->getPrimitiveSizeInBits();
10979 if (Bits == 0 || Bits > 32)
10984 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
10986 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
10987 ARM_MB::MemBOpt Domain) const {
10988 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10990 // First, if the target has no DMB, see what fallback we can use.
10991 if (!Subtarget->hasDataBarrier()) {
10992 // Some ARMv6 cpus can support data barriers with an mcr instruction.
10993 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
10995 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
10996 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
10997 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
10998 Builder.getInt32(0), Builder.getInt32(7),
10999 Builder.getInt32(10), Builder.getInt32(5)};
11000 return Builder.CreateCall(MCR, args);
11002 // Instead of using barriers, atomic accesses on these subtargets use
11004 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11007 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11008 // Only a full system barrier exists in the M-class architectures.
11009 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11010 Constant *CDomain = Builder.getInt32(Domain);
11011 return Builder.CreateCall(DMB, CDomain);
11015 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11016 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11017 AtomicOrdering Ord, bool IsStore,
11018 bool IsLoad) const {
11019 if (!getInsertFencesForAtomic())
11025 llvm_unreachable("Invalid fence: unordered/non-atomic");
11028 return nullptr; // Nothing to do
11029 case SequentiallyConsistent:
11031 return nullptr; // Nothing to do
11034 case AcquireRelease:
11035 if (Subtarget->isSwift())
11036 return makeDMB(Builder, ARM_MB::ISHST);
11037 // FIXME: add a comment with a link to documentation justifying this.
11039 return makeDMB(Builder, ARM_MB::ISH);
11041 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11044 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11045 AtomicOrdering Ord, bool IsStore,
11046 bool IsLoad) const {
11047 if (!getInsertFencesForAtomic())
11053 llvm_unreachable("Invalid fence: unordered/not-atomic");
11056 return nullptr; // Nothing to do
11058 case AcquireRelease:
11059 case SequentiallyConsistent:
11060 return makeDMB(Builder, ARM_MB::ISH);
11062 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11065 // Loads and stores less than 64-bits are already atomic; ones above that
11066 // are doomed anyway, so defer to the default libcall and blame the OS when
11067 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11068 // anything for those.
11069 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11070 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11071 return (Size == 64) && !Subtarget->isMClass();
11074 // Loads and stores less than 64-bits are already atomic; ones above that
11075 // are doomed anyway, so defer to the default libcall and blame the OS when
11076 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11077 // anything for those.
11078 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11079 // guarantee, see DDI0406C ARM architecture reference manual,
11080 // sections A8.8.72-74 LDRD)
11081 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11082 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11083 return (Size == 64) && !Subtarget->isMClass();
11086 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11087 // and up to 64 bits on the non-M profiles
11088 TargetLoweringBase::AtomicRMWExpansionKind
11089 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11090 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11091 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11092 ? AtomicRMWExpansionKind::LLSC
11093 : AtomicRMWExpansionKind::None;
11096 // This has so far only been implemented for MachO.
11097 bool ARMTargetLowering::useLoadStackGuardNode() const {
11098 return Subtarget->isTargetMachO();
11101 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11102 unsigned &Cost) const {
11103 // If we do not have NEON, vector types are not natively supported.
11104 if (!Subtarget->hasNEON())
11107 // Floating point values and vector values map to the same register file.
11108 // Therefore, althought we could do a store extract of a vector type, this is
11109 // better to leave at float as we have more freedom in the addressing mode for
11111 if (VectorTy->isFPOrFPVectorTy())
11114 // If the index is unknown at compile time, this is very expensive to lower
11115 // and it is not possible to combine the store with the extract.
11116 if (!isa<ConstantInt>(Idx))
11119 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11120 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11121 // We can do a store + vector extract on any vector that fits perfectly in a D
11123 if (BitWidth == 64 || BitWidth == 128) {
11130 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11131 AtomicOrdering Ord) const {
11132 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11133 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11134 bool IsAcquire = isAtLeastAcquire(Ord);
11136 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11137 // intrinsic must return {i32, i32} and we have to recombine them into a
11138 // single i64 here.
11139 if (ValTy->getPrimitiveSizeInBits() == 64) {
11140 Intrinsic::ID Int =
11141 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11142 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11144 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11145 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11147 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11148 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11149 if (!Subtarget->isLittle())
11150 std::swap (Lo, Hi);
11151 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11152 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11153 return Builder.CreateOr(
11154 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11157 Type *Tys[] = { Addr->getType() };
11158 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11159 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11161 return Builder.CreateTruncOrBitCast(
11162 Builder.CreateCall(Ldrex, Addr),
11163 cast<PointerType>(Addr->getType())->getElementType());
11166 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11168 AtomicOrdering Ord) const {
11169 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11170 bool IsRelease = isAtLeastRelease(Ord);
11172 // Since the intrinsics must have legal type, the i64 intrinsics take two
11173 // parameters: "i32, i32". We must marshal Val into the appropriate form
11174 // before the call.
11175 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11176 Intrinsic::ID Int =
11177 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11178 Function *Strex = Intrinsic::getDeclaration(M, Int);
11179 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11181 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11182 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11183 if (!Subtarget->isLittle())
11184 std::swap (Lo, Hi);
11185 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11186 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11189 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11190 Type *Tys[] = { Addr->getType() };
11191 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11193 return Builder.CreateCall2(
11194 Strex, Builder.CreateZExtOrBitCast(
11195 Val, Strex->getFunctionType()->getParamType(0)),
11207 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11208 uint64_t &Members) {
11209 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11210 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11211 uint64_t SubMembers = 0;
11212 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11214 Members += SubMembers;
11216 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11217 uint64_t SubMembers = 0;
11218 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11220 Members += SubMembers * AT->getNumElements();
11221 } else if (Ty->isFloatTy()) {
11222 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11226 } else if (Ty->isDoubleTy()) {
11227 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11231 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11238 return VT->getBitWidth() == 64;
11240 return VT->getBitWidth() == 128;
11242 switch (VT->getBitWidth()) {
11255 return (Members > 0 && Members <= 4);
11258 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11259 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11260 /// passing according to AAPCS rules.
11261 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11262 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11263 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11264 CallingConv::ARM_AAPCS_VFP)
11267 HABaseType Base = HA_UNKNOWN;
11268 uint64_t Members = 0;
11269 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11270 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11272 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11273 return IsHA || IsIntArray;