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/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalValue.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
53 #define DEBUG_TYPE "arm-isel"
55 STATISTIC(NumTailCalls, "Number of tail calls");
56 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
57 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
60 EnableARMLongCalls("arm-long-calls", cl::Hidden,
61 cl::desc("Generate calls via indirect call instructions"),
65 ARMInterworking("arm-interworking", cl::Hidden,
66 cl::desc("Enable / disable ARM interworking (for debugging only)"),
70 class ARMCCState : public CCState {
72 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
73 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
75 : CCState(CC, isVarArg, MF, locs, C) {
76 assert(((PC == Call) || (PC == Prologue)) &&
77 "ARMCCState users must specify whether their context is call"
78 "or prologue generation.");
84 // The APCS parameter registers.
85 static const MCPhysReg GPRArgRegs[] = {
86 ARM::R0, ARM::R1, ARM::R2, ARM::R3
89 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
90 MVT PromotedBitwiseVT) {
91 if (VT != PromotedLdStVT) {
92 setOperationAction(ISD::LOAD, VT, Promote);
93 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
95 setOperationAction(ISD::STORE, VT, Promote);
96 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
99 MVT ElemTy = VT.getVectorElementType();
100 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
101 setOperationAction(ISD::SETCC, VT, Custom);
102 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
103 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
104 if (ElemTy == MVT::i32) {
105 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
106 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
107 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
108 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
110 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
111 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
112 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
113 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
115 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
116 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
117 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
118 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
119 setOperationAction(ISD::SELECT, VT, Expand);
120 setOperationAction(ISD::SELECT_CC, VT, Expand);
121 setOperationAction(ISD::VSELECT, VT, Expand);
122 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
123 if (VT.isInteger()) {
124 setOperationAction(ISD::SHL, VT, Custom);
125 setOperationAction(ISD::SRA, VT, Custom);
126 setOperationAction(ISD::SRL, VT, Custom);
129 // Promote all bit-wise operations.
130 if (VT.isInteger() && VT != PromotedBitwiseVT) {
131 setOperationAction(ISD::AND, VT, Promote);
132 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
133 setOperationAction(ISD::OR, VT, Promote);
134 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
135 setOperationAction(ISD::XOR, VT, Promote);
136 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
139 // Neon does not support vector divide/remainder operations.
140 setOperationAction(ISD::SDIV, VT, Expand);
141 setOperationAction(ISD::UDIV, VT, Expand);
142 setOperationAction(ISD::FDIV, VT, Expand);
143 setOperationAction(ISD::SREM, VT, Expand);
144 setOperationAction(ISD::UREM, VT, Expand);
145 setOperationAction(ISD::FREM, VT, Expand);
148 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
149 addRegisterClass(VT, &ARM::DPRRegClass);
150 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
153 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
154 addRegisterClass(VT, &ARM::DPairRegClass);
155 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
158 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
159 if (TT.isOSBinFormatMachO())
160 return new TargetLoweringObjectFileMachO();
161 if (TT.isOSWindows())
162 return new TargetLoweringObjectFileCOFF();
163 return new ARMElfTargetObjectFile();
166 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
167 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
168 Subtarget = &TM.getSubtarget<ARMSubtarget>();
169 RegInfo = TM.getSubtargetImpl()->getRegisterInfo();
170 Itins = TM.getSubtargetImpl()->getInstrItineraryData();
172 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
174 if (Subtarget->isTargetMachO()) {
175 // Uses VFP for Thumb libfuncs if available.
176 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
177 Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
178 // Single-precision floating-point arithmetic.
179 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
180 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
181 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
182 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
184 // Double-precision floating-point arithmetic.
185 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
186 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
187 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
188 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
190 // Single-precision comparisons.
191 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
192 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
193 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
194 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
195 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
196 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
197 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
198 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
200 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
201 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
202 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
203 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
204 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
209 // Double-precision comparisons.
210 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
211 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
212 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
213 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
214 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
215 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
216 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
217 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
219 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
220 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
221 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
222 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
223 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
228 // Floating-point to integer conversions.
229 // i64 conversions are done via library routines even when generating VFP
230 // instructions, so use the same ones.
231 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
232 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
233 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
234 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
236 // Conversions between floating types.
237 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
238 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
240 // Integer to floating-point conversions.
241 // i64 conversions are done via library routines even when generating VFP
242 // instructions, so use the same ones.
243 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
244 // e.g., __floatunsidf vs. __floatunssidfvfp.
245 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
246 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
247 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
248 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
252 // These libcalls are not available in 32-bit.
253 setLibcallName(RTLIB::SHL_I128, nullptr);
254 setLibcallName(RTLIB::SRL_I128, nullptr);
255 setLibcallName(RTLIB::SRA_I128, nullptr);
257 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
258 !Subtarget->isTargetWindows()) {
259 static const struct {
260 const RTLIB::Libcall Op;
261 const char * const Name;
262 const CallingConv::ID CC;
263 const ISD::CondCode Cond;
265 // Double-precision floating-point arithmetic helper functions
266 // RTABI chapter 4.1.2, Table 2
267 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
268 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
269 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
272 // Double-precision floating-point comparison helper functions
273 // RTABI chapter 4.1.2, Table 3
274 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
275 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
276 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
277 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
278 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
279 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
280 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
281 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
283 // Single-precision floating-point arithmetic helper functions
284 // RTABI chapter 4.1.2, Table 4
285 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
286 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
287 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
290 // Single-precision floating-point comparison helper functions
291 // RTABI chapter 4.1.2, Table 5
292 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
293 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
294 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
295 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
296 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
297 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
298 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
299 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
301 // Floating-point to integer conversions.
302 // RTABI chapter 4.1.2, Table 6
303 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312 // Conversions between floating types.
313 // RTABI chapter 4.1.2, Table 7
314 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318 // Integer to floating-point conversions.
319 // RTABI chapter 4.1.2, Table 8
320 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329 // Long long helper functions
330 // RTABI chapter 4.2, Table 9
331 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336 // Integer division functions
337 // RTABI chapter 4.3.1
338 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348 // RTABI chapter 4.3.4
349 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
354 for (const auto &LC : LibraryCalls) {
355 setLibcallName(LC.Op, LC.Name);
356 setLibcallCallingConv(LC.Op, LC.CC);
357 if (LC.Cond != ISD::SETCC_INVALID)
358 setCmpLibcallCC(LC.Op, LC.Cond);
362 if (Subtarget->isTargetWindows()) {
363 static const struct {
364 const RTLIB::Libcall Op;
365 const char * const Name;
366 const CallingConv::ID CC;
368 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
369 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
370 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
371 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
372 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
373 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
374 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
375 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
378 for (const auto &LC : LibraryCalls) {
379 setLibcallName(LC.Op, LC.Name);
380 setLibcallCallingConv(LC.Op, LC.CC);
384 // Use divmod compiler-rt calls for iOS 5.0 and later.
385 if (Subtarget->getTargetTriple().isiOS() &&
386 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
387 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
388 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
391 // The half <-> float conversion functions are always soft-float, but are
392 // needed for some targets which use a hard-float calling convention by
394 if (Subtarget->isAAPCS_ABI()) {
395 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
396 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
397 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
399 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
400 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
401 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
404 if (Subtarget->isThumb1Only())
405 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
407 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
408 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
409 !Subtarget->isThumb1Only()) {
410 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
411 if (!Subtarget->isFPOnlySP())
412 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
415 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
416 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
417 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
418 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
419 setTruncStoreAction((MVT::SimpleValueType)VT,
420 (MVT::SimpleValueType)InnerVT, Expand);
421 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
422 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
423 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
425 setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
426 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
427 setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
428 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
430 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
433 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
434 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
436 if (Subtarget->hasNEON()) {
437 addDRTypeForNEON(MVT::v2f32);
438 addDRTypeForNEON(MVT::v8i8);
439 addDRTypeForNEON(MVT::v4i16);
440 addDRTypeForNEON(MVT::v2i32);
441 addDRTypeForNEON(MVT::v1i64);
443 addQRTypeForNEON(MVT::v4f32);
444 addQRTypeForNEON(MVT::v2f64);
445 addQRTypeForNEON(MVT::v16i8);
446 addQRTypeForNEON(MVT::v8i16);
447 addQRTypeForNEON(MVT::v4i32);
448 addQRTypeForNEON(MVT::v2i64);
450 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
451 // neither Neon nor VFP support any arithmetic operations on it.
452 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
453 // supported for v4f32.
454 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
455 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
456 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
457 // FIXME: Code duplication: FDIV and FREM are expanded always, see
458 // ARMTargetLowering::addTypeForNEON method for details.
459 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
460 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
461 // FIXME: Create unittest.
462 // In another words, find a way when "copysign" appears in DAG with vector
464 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
465 // FIXME: Code duplication: SETCC has custom operation action, see
466 // ARMTargetLowering::addTypeForNEON method for details.
467 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
468 // FIXME: Create unittest for FNEG and for FABS.
469 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
470 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
471 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
472 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
473 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
474 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
475 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
476 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
477 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
478 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
479 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
480 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
481 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
482 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
483 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
484 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
485 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
486 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
487 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
489 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
490 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
491 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
492 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
493 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
494 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
495 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
496 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
497 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
498 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
499 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
500 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
501 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
502 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
503 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
505 // Mark v2f32 intrinsics.
506 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
507 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
508 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
509 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
510 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
511 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
512 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
513 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
514 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
515 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
516 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
517 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
518 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
519 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
520 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
522 // Neon does not support some operations on v1i64 and v2i64 types.
523 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
524 // Custom handling for some quad-vector types to detect VMULL.
525 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
526 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
527 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
528 // Custom handling for some vector types to avoid expensive expansions
529 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
530 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
531 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
532 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
533 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
534 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
535 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
536 // a destination type that is wider than the source, and nor does
537 // it have a FP_TO_[SU]INT instruction with a narrower destination than
539 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
540 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
541 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
542 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
544 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
545 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
547 // NEON does not have single instruction CTPOP for vectors with element
548 // types wider than 8-bits. However, custom lowering can leverage the
549 // v8i8/v16i8 vcnt instruction.
550 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
551 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
552 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
553 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
555 // NEON only has FMA instructions as of VFP4.
556 if (!Subtarget->hasVFP4()) {
557 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
558 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
561 setTargetDAGCombine(ISD::INTRINSIC_VOID);
562 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
563 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
564 setTargetDAGCombine(ISD::SHL);
565 setTargetDAGCombine(ISD::SRL);
566 setTargetDAGCombine(ISD::SRA);
567 setTargetDAGCombine(ISD::SIGN_EXTEND);
568 setTargetDAGCombine(ISD::ZERO_EXTEND);
569 setTargetDAGCombine(ISD::ANY_EXTEND);
570 setTargetDAGCombine(ISD::SELECT_CC);
571 setTargetDAGCombine(ISD::BUILD_VECTOR);
572 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
573 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
574 setTargetDAGCombine(ISD::STORE);
575 setTargetDAGCombine(ISD::FP_TO_SINT);
576 setTargetDAGCombine(ISD::FP_TO_UINT);
577 setTargetDAGCombine(ISD::FDIV);
579 // It is legal to extload from v4i8 to v4i16 or v4i32.
580 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
581 MVT::v4i16, MVT::v2i16,
583 for (unsigned i = 0; i < 6; ++i) {
584 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
585 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
586 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
590 // ARM and Thumb2 support UMLAL/SMLAL.
591 if (!Subtarget->isThumb1Only())
592 setTargetDAGCombine(ISD::ADDC);
595 computeRegisterProperties();
597 // ARM does not have floating-point extending loads.
598 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
599 setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
601 // ... or truncating stores
602 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
603 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
604 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
606 // ARM does not have i1 sign extending load.
607 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
609 // ARM supports all 4 flavors of integer indexed load / store.
610 if (!Subtarget->isThumb1Only()) {
611 for (unsigned im = (unsigned)ISD::PRE_INC;
612 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
613 setIndexedLoadAction(im, MVT::i1, Legal);
614 setIndexedLoadAction(im, MVT::i8, Legal);
615 setIndexedLoadAction(im, MVT::i16, Legal);
616 setIndexedLoadAction(im, MVT::i32, Legal);
617 setIndexedStoreAction(im, MVT::i1, Legal);
618 setIndexedStoreAction(im, MVT::i8, Legal);
619 setIndexedStoreAction(im, MVT::i16, Legal);
620 setIndexedStoreAction(im, MVT::i32, Legal);
624 setOperationAction(ISD::SADDO, MVT::i32, Custom);
625 setOperationAction(ISD::UADDO, MVT::i32, Custom);
626 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
627 setOperationAction(ISD::USUBO, MVT::i32, Custom);
629 // i64 operation support.
630 setOperationAction(ISD::MUL, MVT::i64, Expand);
631 setOperationAction(ISD::MULHU, MVT::i32, Expand);
632 if (Subtarget->isThumb1Only()) {
633 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
634 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
636 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
637 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
638 setOperationAction(ISD::MULHS, MVT::i32, Expand);
640 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
641 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
642 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
643 setOperationAction(ISD::SRL, MVT::i64, Custom);
644 setOperationAction(ISD::SRA, MVT::i64, Custom);
646 if (!Subtarget->isThumb1Only()) {
647 // FIXME: We should do this for Thumb1 as well.
648 setOperationAction(ISD::ADDC, MVT::i32, Custom);
649 setOperationAction(ISD::ADDE, MVT::i32, Custom);
650 setOperationAction(ISD::SUBC, MVT::i32, Custom);
651 setOperationAction(ISD::SUBE, MVT::i32, Custom);
654 // ARM does not have ROTL.
655 setOperationAction(ISD::ROTL, MVT::i32, Expand);
656 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
657 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
658 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
659 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
661 // These just redirect to CTTZ and CTLZ on ARM.
662 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
663 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
665 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
667 // Only ARMv6 has BSWAP.
668 if (!Subtarget->hasV6Ops())
669 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
671 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
672 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
673 // These are expanded into libcalls if the cpu doesn't have HW divider.
674 setOperationAction(ISD::SDIV, MVT::i32, Expand);
675 setOperationAction(ISD::UDIV, MVT::i32, Expand);
678 // FIXME: Also set divmod for SREM on EABI
679 setOperationAction(ISD::SREM, MVT::i32, Expand);
680 setOperationAction(ISD::UREM, MVT::i32, Expand);
681 // Register based DivRem for AEABI (RTABI 4.2)
682 if (Subtarget->isTargetAEABI()) {
683 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
684 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
685 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
686 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
687 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
688 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
689 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
690 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
692 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
693 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
694 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
695 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
696 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
697 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
698 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
699 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
701 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
702 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
704 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
705 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
708 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
709 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
710 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
711 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
712 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
714 setOperationAction(ISD::TRAP, MVT::Other, Legal);
716 // Use the default implementation.
717 setOperationAction(ISD::VASTART, MVT::Other, Custom);
718 setOperationAction(ISD::VAARG, MVT::Other, Expand);
719 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
720 setOperationAction(ISD::VAEND, MVT::Other, Expand);
721 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
722 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
724 if (!Subtarget->isTargetMachO()) {
725 // Non-MachO platforms may return values in these registers via the
726 // personality function.
727 setExceptionPointerRegister(ARM::R0);
728 setExceptionSelectorRegister(ARM::R1);
731 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
732 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
734 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
736 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
737 // the default expansion.
738 if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
739 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
740 // to ldrex/strex loops already.
741 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
743 // On v8, we have particularly efficient implementations of atomic fences
744 // if they can be combined with nearby atomic loads and stores.
745 if (!Subtarget->hasV8Ops()) {
746 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
747 setInsertFencesForAtomic(true);
750 // If there's anything we can use as a barrier, go through custom lowering
752 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
753 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
755 // Set them all for expansion, which will force libcalls.
756 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
757 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
758 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
759 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
760 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
761 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
762 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
763 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
764 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
765 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
766 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
767 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
768 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
769 // Unordered/Monotonic case.
770 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
771 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
774 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
776 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
777 if (!Subtarget->hasV6Ops()) {
778 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
779 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
781 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
783 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
784 !Subtarget->isThumb1Only()) {
785 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
786 // iff target supports vfp2.
787 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
788 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
791 // We want to custom lower some of our intrinsics.
792 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
793 if (Subtarget->isTargetDarwin()) {
794 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
795 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
796 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
799 setOperationAction(ISD::SETCC, MVT::i32, Expand);
800 setOperationAction(ISD::SETCC, MVT::f32, Expand);
801 setOperationAction(ISD::SETCC, MVT::f64, Expand);
802 setOperationAction(ISD::SELECT, MVT::i32, Custom);
803 setOperationAction(ISD::SELECT, MVT::f32, Custom);
804 setOperationAction(ISD::SELECT, MVT::f64, Custom);
805 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
806 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
807 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
809 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
810 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
811 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
812 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
813 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
815 // We don't support sin/cos/fmod/copysign/pow
816 setOperationAction(ISD::FSIN, MVT::f64, Expand);
817 setOperationAction(ISD::FSIN, MVT::f32, Expand);
818 setOperationAction(ISD::FCOS, MVT::f32, Expand);
819 setOperationAction(ISD::FCOS, MVT::f64, Expand);
820 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
821 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
822 setOperationAction(ISD::FREM, MVT::f64, Expand);
823 setOperationAction(ISD::FREM, MVT::f32, Expand);
824 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
825 !Subtarget->isThumb1Only()) {
826 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
827 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
829 setOperationAction(ISD::FPOW, MVT::f64, Expand);
830 setOperationAction(ISD::FPOW, MVT::f32, Expand);
832 if (!Subtarget->hasVFP4()) {
833 setOperationAction(ISD::FMA, MVT::f64, Expand);
834 setOperationAction(ISD::FMA, MVT::f32, Expand);
837 // Various VFP goodness
838 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
839 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
840 if (Subtarget->hasVFP2()) {
841 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
842 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
843 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
844 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
847 // v8 adds f64 <-> f16 conversion. Before that it should be expanded.
848 if (!Subtarget->hasV8Ops()) {
849 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
850 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
853 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
854 if (!Subtarget->hasFP16()) {
855 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
856 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
860 // Combine sin / cos into one node or libcall if possible.
861 if (Subtarget->hasSinCos()) {
862 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
863 setLibcallName(RTLIB::SINCOS_F64, "sincos");
864 if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
865 // For iOS, we don't want to the normal expansion of a libcall to
866 // sincos. We want to issue a libcall to __sincos_stret.
867 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
868 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
872 // ARMv8 implements a lot of rounding-like FP operations.
873 if (Subtarget->hasV8Ops()) {
874 static MVT RoundingTypes[] = {MVT::f32, MVT::f64};
875 for (const auto Ty : RoundingTypes) {
876 setOperationAction(ISD::FFLOOR, Ty, Legal);
877 setOperationAction(ISD::FCEIL, Ty, Legal);
878 setOperationAction(ISD::FROUND, Ty, Legal);
879 setOperationAction(ISD::FTRUNC, Ty, Legal);
880 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
881 setOperationAction(ISD::FRINT, Ty, Legal);
884 // We have target-specific dag combine patterns for the following nodes:
885 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
886 setTargetDAGCombine(ISD::ADD);
887 setTargetDAGCombine(ISD::SUB);
888 setTargetDAGCombine(ISD::MUL);
889 setTargetDAGCombine(ISD::AND);
890 setTargetDAGCombine(ISD::OR);
891 setTargetDAGCombine(ISD::XOR);
893 if (Subtarget->hasV6Ops())
894 setTargetDAGCombine(ISD::SRL);
896 setStackPointerRegisterToSaveRestore(ARM::SP);
898 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
899 !Subtarget->hasVFP2())
900 setSchedulingPreference(Sched::RegPressure);
902 setSchedulingPreference(Sched::Hybrid);
904 //// temporary - rewrite interface to use type
905 MaxStoresPerMemset = 8;
906 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
907 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
908 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
909 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
910 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
912 // On ARM arguments smaller than 4 bytes are extended, so all arguments
913 // are at least 4 bytes aligned.
914 setMinStackArgumentAlignment(4);
916 // Prefer likely predicted branches to selects on out-of-order cores.
917 PredictableSelectIsExpensive = Subtarget->isLikeA9();
919 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
922 // FIXME: It might make sense to define the representative register class as the
923 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
924 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
925 // SPR's representative would be DPR_VFP2. This should work well if register
926 // pressure tracking were modified such that a register use would increment the
927 // pressure of the register class's representative and all of it's super
928 // classes' representatives transitively. We have not implemented this because
929 // of the difficulty prior to coalescing of modeling operand register classes
930 // due to the common occurrence of cross class copies and subregister insertions
932 std::pair<const TargetRegisterClass*, uint8_t>
933 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
934 const TargetRegisterClass *RRC = nullptr;
936 switch (VT.SimpleTy) {
938 return TargetLowering::findRepresentativeClass(VT);
939 // Use DPR as representative register class for all floating point
940 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
941 // the cost is 1 for both f32 and f64.
942 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
943 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
944 RRC = &ARM::DPRRegClass;
945 // When NEON is used for SP, only half of the register file is available
946 // because operations that define both SP and DP results will be constrained
947 // to the VFP2 class (D0-D15). We currently model this constraint prior to
948 // coalescing by double-counting the SP regs. See the FIXME above.
949 if (Subtarget->useNEONForSinglePrecisionFP())
952 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
953 case MVT::v4f32: case MVT::v2f64:
954 RRC = &ARM::DPRRegClass;
958 RRC = &ARM::DPRRegClass;
962 RRC = &ARM::DPRRegClass;
966 return std::make_pair(RRC, Cost);
969 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
971 default: return nullptr;
972 case ARMISD::Wrapper: return "ARMISD::Wrapper";
973 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
974 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
975 case ARMISD::CALL: return "ARMISD::CALL";
976 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
977 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
978 case ARMISD::tCALL: return "ARMISD::tCALL";
979 case ARMISD::BRCOND: return "ARMISD::BRCOND";
980 case ARMISD::BR_JT: return "ARMISD::BR_JT";
981 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
982 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
983 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
984 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
985 case ARMISD::CMP: return "ARMISD::CMP";
986 case ARMISD::CMN: return "ARMISD::CMN";
987 case ARMISD::CMPZ: return "ARMISD::CMPZ";
988 case ARMISD::CMPFP: return "ARMISD::CMPFP";
989 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
990 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
991 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
993 case ARMISD::CMOV: return "ARMISD::CMOV";
995 case ARMISD::RBIT: return "ARMISD::RBIT";
997 case ARMISD::FTOSI: return "ARMISD::FTOSI";
998 case ARMISD::FTOUI: return "ARMISD::FTOUI";
999 case ARMISD::SITOF: return "ARMISD::SITOF";
1000 case ARMISD::UITOF: return "ARMISD::UITOF";
1002 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1003 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1004 case ARMISD::RRX: return "ARMISD::RRX";
1006 case ARMISD::ADDC: return "ARMISD::ADDC";
1007 case ARMISD::ADDE: return "ARMISD::ADDE";
1008 case ARMISD::SUBC: return "ARMISD::SUBC";
1009 case ARMISD::SUBE: return "ARMISD::SUBE";
1011 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1012 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1014 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1015 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1017 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1019 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1021 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1023 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1025 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1027 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1029 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1030 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1031 case ARMISD::VCGE: return "ARMISD::VCGE";
1032 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1033 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1034 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1035 case ARMISD::VCGT: return "ARMISD::VCGT";
1036 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1037 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1038 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1039 case ARMISD::VTST: return "ARMISD::VTST";
1041 case ARMISD::VSHL: return "ARMISD::VSHL";
1042 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1043 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1044 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1045 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1046 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1047 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1048 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1049 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1050 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1051 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1052 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1053 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1054 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1055 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1056 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1057 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1058 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1059 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1060 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1061 case ARMISD::VDUP: return "ARMISD::VDUP";
1062 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1063 case ARMISD::VEXT: return "ARMISD::VEXT";
1064 case ARMISD::VREV64: return "ARMISD::VREV64";
1065 case ARMISD::VREV32: return "ARMISD::VREV32";
1066 case ARMISD::VREV16: return "ARMISD::VREV16";
1067 case ARMISD::VZIP: return "ARMISD::VZIP";
1068 case ARMISD::VUZP: return "ARMISD::VUZP";
1069 case ARMISD::VTRN: return "ARMISD::VTRN";
1070 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1071 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1072 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1073 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1074 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1075 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1076 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1077 case ARMISD::FMAX: return "ARMISD::FMAX";
1078 case ARMISD::FMIN: return "ARMISD::FMIN";
1079 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1080 case ARMISD::VMINNM: return "ARMISD::VMIN";
1081 case ARMISD::BFI: return "ARMISD::BFI";
1082 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1083 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1084 case ARMISD::VBSL: return "ARMISD::VBSL";
1085 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1086 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1087 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1088 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1089 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1090 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1091 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1092 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1093 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1094 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1095 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1096 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1097 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1098 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1099 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1100 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1101 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1102 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1103 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1104 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1108 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1109 if (!VT.isVector()) return getPointerTy();
1110 return VT.changeVectorElementTypeToInteger();
1113 /// getRegClassFor - Return the register class that should be used for the
1114 /// specified value type.
1115 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1116 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1117 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1118 // load / store 4 to 8 consecutive D registers.
1119 if (Subtarget->hasNEON()) {
1120 if (VT == MVT::v4i64)
1121 return &ARM::QQPRRegClass;
1122 if (VT == MVT::v8i64)
1123 return &ARM::QQQQPRRegClass;
1125 return TargetLowering::getRegClassFor(VT);
1128 // Create a fast isel object.
1130 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1131 const TargetLibraryInfo *libInfo) const {
1132 return ARM::createFastISel(funcInfo, libInfo);
1135 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1136 /// be used for loads / stores from the global.
1137 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1138 return (Subtarget->isThumb1Only() ? 127 : 4095);
1141 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1142 unsigned NumVals = N->getNumValues();
1144 return Sched::RegPressure;
1146 for (unsigned i = 0; i != NumVals; ++i) {
1147 EVT VT = N->getValueType(i);
1148 if (VT == MVT::Glue || VT == MVT::Other)
1150 if (VT.isFloatingPoint() || VT.isVector())
1154 if (!N->isMachineOpcode())
1155 return Sched::RegPressure;
1157 // Load are scheduled for latency even if there instruction itinerary
1158 // is not available.
1159 const TargetInstrInfo *TII =
1160 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1161 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1163 if (MCID.getNumDefs() == 0)
1164 return Sched::RegPressure;
1165 if (!Itins->isEmpty() &&
1166 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1169 return Sched::RegPressure;
1172 //===----------------------------------------------------------------------===//
1174 //===----------------------------------------------------------------------===//
1176 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1177 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1179 default: llvm_unreachable("Unknown condition code!");
1180 case ISD::SETNE: return ARMCC::NE;
1181 case ISD::SETEQ: return ARMCC::EQ;
1182 case ISD::SETGT: return ARMCC::GT;
1183 case ISD::SETGE: return ARMCC::GE;
1184 case ISD::SETLT: return ARMCC::LT;
1185 case ISD::SETLE: return ARMCC::LE;
1186 case ISD::SETUGT: return ARMCC::HI;
1187 case ISD::SETUGE: return ARMCC::HS;
1188 case ISD::SETULT: return ARMCC::LO;
1189 case ISD::SETULE: return ARMCC::LS;
1193 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1194 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1195 ARMCC::CondCodes &CondCode2) {
1196 CondCode2 = ARMCC::AL;
1198 default: llvm_unreachable("Unknown FP condition!");
1200 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1202 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1204 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1205 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1206 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1207 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1208 case ISD::SETO: CondCode = ARMCC::VC; break;
1209 case ISD::SETUO: CondCode = ARMCC::VS; break;
1210 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1211 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1212 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1214 case ISD::SETULT: CondCode = ARMCC::LT; break;
1216 case ISD::SETULE: CondCode = ARMCC::LE; break;
1218 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1222 //===----------------------------------------------------------------------===//
1223 // Calling Convention Implementation
1224 //===----------------------------------------------------------------------===//
1226 #include "ARMGenCallingConv.inc"
1228 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1229 /// account presence of floating point hardware and calling convention
1230 /// limitations, such as support for variadic functions.
1232 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1233 bool isVarArg) const {
1236 llvm_unreachable("Unsupported calling convention");
1237 case CallingConv::ARM_AAPCS:
1238 case CallingConv::ARM_APCS:
1239 case CallingConv::GHC:
1241 case CallingConv::ARM_AAPCS_VFP:
1242 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1243 case CallingConv::C:
1244 if (!Subtarget->isAAPCS_ABI())
1245 return CallingConv::ARM_APCS;
1246 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1247 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1249 return CallingConv::ARM_AAPCS_VFP;
1251 return CallingConv::ARM_AAPCS;
1252 case CallingConv::Fast:
1253 if (!Subtarget->isAAPCS_ABI()) {
1254 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1255 return CallingConv::Fast;
1256 return CallingConv::ARM_APCS;
1257 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1258 return CallingConv::ARM_AAPCS_VFP;
1260 return CallingConv::ARM_AAPCS;
1264 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1265 /// CallingConvention.
1266 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1268 bool isVarArg) const {
1269 switch (getEffectiveCallingConv(CC, isVarArg)) {
1271 llvm_unreachable("Unsupported calling convention");
1272 case CallingConv::ARM_APCS:
1273 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1274 case CallingConv::ARM_AAPCS:
1275 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1276 case CallingConv::ARM_AAPCS_VFP:
1277 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1278 case CallingConv::Fast:
1279 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1280 case CallingConv::GHC:
1281 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1285 /// LowerCallResult - Lower the result values of a call into the
1286 /// appropriate copies out of appropriate physical registers.
1288 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1289 CallingConv::ID CallConv, bool isVarArg,
1290 const SmallVectorImpl<ISD::InputArg> &Ins,
1291 SDLoc dl, SelectionDAG &DAG,
1292 SmallVectorImpl<SDValue> &InVals,
1293 bool isThisReturn, SDValue ThisVal) const {
1295 // Assign locations to each value returned by this call.
1296 SmallVector<CCValAssign, 16> RVLocs;
1297 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1298 *DAG.getContext(), Call);
1299 CCInfo.AnalyzeCallResult(Ins,
1300 CCAssignFnForNode(CallConv, /* Return*/ true,
1303 // Copy all of the result registers out of their specified physreg.
1304 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1305 CCValAssign VA = RVLocs[i];
1307 // Pass 'this' value directly from the argument to return value, to avoid
1308 // reg unit interference
1309 if (i == 0 && isThisReturn) {
1310 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1311 "unexpected return calling convention register assignment");
1312 InVals.push_back(ThisVal);
1317 if (VA.needsCustom()) {
1318 // Handle f64 or half of a v2f64.
1319 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1321 Chain = Lo.getValue(1);
1322 InFlag = Lo.getValue(2);
1323 VA = RVLocs[++i]; // skip ahead to next loc
1324 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1326 Chain = Hi.getValue(1);
1327 InFlag = Hi.getValue(2);
1328 if (!Subtarget->isLittle())
1330 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1332 if (VA.getLocVT() == MVT::v2f64) {
1333 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1334 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1335 DAG.getConstant(0, MVT::i32));
1337 VA = RVLocs[++i]; // skip ahead to next loc
1338 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1339 Chain = Lo.getValue(1);
1340 InFlag = Lo.getValue(2);
1341 VA = RVLocs[++i]; // skip ahead to next loc
1342 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1343 Chain = Hi.getValue(1);
1344 InFlag = Hi.getValue(2);
1345 if (!Subtarget->isLittle())
1347 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1348 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1349 DAG.getConstant(1, MVT::i32));
1352 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1354 Chain = Val.getValue(1);
1355 InFlag = Val.getValue(2);
1358 switch (VA.getLocInfo()) {
1359 default: llvm_unreachable("Unknown loc info!");
1360 case CCValAssign::Full: break;
1361 case CCValAssign::BCvt:
1362 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1366 InVals.push_back(Val);
1372 /// LowerMemOpCallTo - Store the argument to the stack.
1374 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1375 SDValue StackPtr, SDValue Arg,
1376 SDLoc dl, SelectionDAG &DAG,
1377 const CCValAssign &VA,
1378 ISD::ArgFlagsTy Flags) const {
1379 unsigned LocMemOffset = VA.getLocMemOffset();
1380 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1381 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1382 return DAG.getStore(Chain, dl, Arg, PtrOff,
1383 MachinePointerInfo::getStack(LocMemOffset),
1387 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1388 SDValue Chain, SDValue &Arg,
1389 RegsToPassVector &RegsToPass,
1390 CCValAssign &VA, CCValAssign &NextVA,
1392 SmallVectorImpl<SDValue> &MemOpChains,
1393 ISD::ArgFlagsTy Flags) const {
1395 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1396 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1397 unsigned id = Subtarget->isLittle() ? 0 : 1;
1398 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1400 if (NextVA.isRegLoc())
1401 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1403 assert(NextVA.isMemLoc());
1404 if (!StackPtr.getNode())
1405 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1407 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1413 /// LowerCall - Lowering a call into a callseq_start <-
1414 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1417 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1418 SmallVectorImpl<SDValue> &InVals) const {
1419 SelectionDAG &DAG = CLI.DAG;
1421 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1422 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1423 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1424 SDValue Chain = CLI.Chain;
1425 SDValue Callee = CLI.Callee;
1426 bool &isTailCall = CLI.IsTailCall;
1427 CallingConv::ID CallConv = CLI.CallConv;
1428 bool doesNotRet = CLI.DoesNotReturn;
1429 bool isVarArg = CLI.IsVarArg;
1431 MachineFunction &MF = DAG.getMachineFunction();
1432 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1433 bool isThisReturn = false;
1434 bool isSibCall = false;
1436 // Disable tail calls if they're not supported.
1437 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1441 // Check if it's really possible to do a tail call.
1442 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1443 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1444 Outs, OutVals, Ins, DAG);
1445 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1446 report_fatal_error("failed to perform tail call elimination on a call "
1447 "site marked musttail");
1448 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1449 // detected sibcalls.
1456 // Analyze operands of the call, assigning locations to each operand.
1457 SmallVector<CCValAssign, 16> ArgLocs;
1458 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1459 *DAG.getContext(), Call);
1460 CCInfo.AnalyzeCallOperands(Outs,
1461 CCAssignFnForNode(CallConv, /* Return*/ false,
1464 // Get a count of how many bytes are to be pushed on the stack.
1465 unsigned NumBytes = CCInfo.getNextStackOffset();
1467 // For tail calls, memory operands are available in our caller's stack.
1471 // Adjust the stack pointer for the new arguments...
1472 // These operations are automatically eliminated by the prolog/epilog pass
1474 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1477 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1479 RegsToPassVector RegsToPass;
1480 SmallVector<SDValue, 8> MemOpChains;
1482 // Walk the register/memloc assignments, inserting copies/loads. In the case
1483 // of tail call optimization, arguments are handled later.
1484 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1486 ++i, ++realArgIdx) {
1487 CCValAssign &VA = ArgLocs[i];
1488 SDValue Arg = OutVals[realArgIdx];
1489 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1490 bool isByVal = Flags.isByVal();
1492 // Promote the value if needed.
1493 switch (VA.getLocInfo()) {
1494 default: llvm_unreachable("Unknown loc info!");
1495 case CCValAssign::Full: break;
1496 case CCValAssign::SExt:
1497 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1499 case CCValAssign::ZExt:
1500 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1502 case CCValAssign::AExt:
1503 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1505 case CCValAssign::BCvt:
1506 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1510 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1511 if (VA.needsCustom()) {
1512 if (VA.getLocVT() == MVT::v2f64) {
1513 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1514 DAG.getConstant(0, MVT::i32));
1515 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1516 DAG.getConstant(1, MVT::i32));
1518 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1519 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1521 VA = ArgLocs[++i]; // skip ahead to next loc
1522 if (VA.isRegLoc()) {
1523 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1524 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1526 assert(VA.isMemLoc());
1528 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1529 dl, DAG, VA, Flags));
1532 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1533 StackPtr, MemOpChains, Flags);
1535 } else if (VA.isRegLoc()) {
1536 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1537 assert(VA.getLocVT() == MVT::i32 &&
1538 "unexpected calling convention register assignment");
1539 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1540 "unexpected use of 'returned'");
1541 isThisReturn = true;
1543 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1544 } else if (isByVal) {
1545 assert(VA.isMemLoc());
1546 unsigned offset = 0;
1548 // True if this byval aggregate will be split between registers
1550 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1551 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1553 if (CurByValIdx < ByValArgsCount) {
1555 unsigned RegBegin, RegEnd;
1556 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1558 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1560 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1561 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1562 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1563 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1564 MachinePointerInfo(),
1565 false, false, false,
1566 DAG.InferPtrAlignment(AddArg));
1567 MemOpChains.push_back(Load.getValue(1));
1568 RegsToPass.push_back(std::make_pair(j, Load));
1571 // If parameter size outsides register area, "offset" value
1572 // helps us to calculate stack slot for remained part properly.
1573 offset = RegEnd - RegBegin;
1575 CCInfo.nextInRegsParam();
1578 if (Flags.getByValSize() > 4*offset) {
1579 unsigned LocMemOffset = VA.getLocMemOffset();
1580 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1581 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1583 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1584 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1585 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1587 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1589 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1590 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1591 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1594 } else if (!isSibCall) {
1595 assert(VA.isMemLoc());
1597 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1598 dl, DAG, VA, Flags));
1602 if (!MemOpChains.empty())
1603 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1605 // Build a sequence of copy-to-reg nodes chained together with token chain
1606 // and flag operands which copy the outgoing args into the appropriate regs.
1608 // Tail call byval lowering might overwrite argument registers so in case of
1609 // tail call optimization the copies to registers are lowered later.
1611 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1612 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1613 RegsToPass[i].second, InFlag);
1614 InFlag = Chain.getValue(1);
1617 // For tail calls lower the arguments to the 'real' stack slot.
1619 // Force all the incoming stack arguments to be loaded from the stack
1620 // before any new outgoing arguments are stored to the stack, because the
1621 // outgoing stack slots may alias the incoming argument stack slots, and
1622 // the alias isn't otherwise explicit. This is slightly more conservative
1623 // than necessary, because it means that each store effectively depends
1624 // on every argument instead of just those arguments it would clobber.
1626 // Do not flag preceding copytoreg stuff together with the following stuff.
1628 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1629 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1630 RegsToPass[i].second, InFlag);
1631 InFlag = Chain.getValue(1);
1636 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1637 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1638 // node so that legalize doesn't hack it.
1639 bool isDirect = false;
1640 bool isARMFunc = false;
1641 bool isLocalARMFunc = false;
1642 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1644 if (EnableARMLongCalls) {
1645 assert((Subtarget->isTargetWindows() ||
1646 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1647 "long-calls with non-static relocation model!");
1648 // Handle a global address or an external symbol. If it's not one of
1649 // those, the target's already in a register, so we don't need to do
1651 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1652 const GlobalValue *GV = G->getGlobal();
1653 // Create a constant pool entry for the callee address
1654 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1655 ARMConstantPoolValue *CPV =
1656 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1658 // Get the address of the callee into a register
1659 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1660 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1661 Callee = DAG.getLoad(getPointerTy(), dl,
1662 DAG.getEntryNode(), CPAddr,
1663 MachinePointerInfo::getConstantPool(),
1664 false, false, false, 0);
1665 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1666 const char *Sym = S->getSymbol();
1668 // Create a constant pool entry for the callee address
1669 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1670 ARMConstantPoolValue *CPV =
1671 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1672 ARMPCLabelIndex, 0);
1673 // Get the address of the callee into a register
1674 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1675 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1676 Callee = DAG.getLoad(getPointerTy(), dl,
1677 DAG.getEntryNode(), CPAddr,
1678 MachinePointerInfo::getConstantPool(),
1679 false, false, false, 0);
1681 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1682 const GlobalValue *GV = G->getGlobal();
1684 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1685 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1686 getTargetMachine().getRelocationModel() != Reloc::Static;
1687 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1688 // ARM call to a local ARM function is predicable.
1689 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1690 // tBX takes a register source operand.
1691 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1692 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1693 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1694 DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1695 0, ARMII::MO_NONLAZY));
1696 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1697 MachinePointerInfo::getGOT(), false, false, true, 0);
1698 } else if (Subtarget->isTargetCOFF()) {
1699 assert(Subtarget->isTargetWindows() &&
1700 "Windows is the only supported COFF target");
1701 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1702 ? ARMII::MO_DLLIMPORT
1703 : ARMII::MO_NO_FLAG;
1704 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1706 if (GV->hasDLLImportStorageClass())
1707 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1708 DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1709 Callee), MachinePointerInfo::getGOT(),
1710 false, false, false, 0);
1712 // On ELF targets for PIC code, direct calls should go through the PLT
1713 unsigned OpFlags = 0;
1714 if (Subtarget->isTargetELF() &&
1715 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1716 OpFlags = ARMII::MO_PLT;
1717 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1719 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1721 bool isStub = Subtarget->isTargetMachO() &&
1722 getTargetMachine().getRelocationModel() != Reloc::Static;
1723 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1724 // tBX takes a register source operand.
1725 const char *Sym = S->getSymbol();
1726 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1727 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1728 ARMConstantPoolValue *CPV =
1729 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1730 ARMPCLabelIndex, 4);
1731 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1732 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1733 Callee = DAG.getLoad(getPointerTy(), dl,
1734 DAG.getEntryNode(), CPAddr,
1735 MachinePointerInfo::getConstantPool(),
1736 false, false, false, 0);
1737 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1738 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1739 getPointerTy(), Callee, PICLabel);
1741 unsigned OpFlags = 0;
1742 // On ELF targets for PIC code, direct calls should go through the PLT
1743 if (Subtarget->isTargetELF() &&
1744 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1745 OpFlags = ARMII::MO_PLT;
1746 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1750 // FIXME: handle tail calls differently.
1752 bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1753 AttributeSet::FunctionIndex, Attribute::MinSize);
1754 if (Subtarget->isThumb()) {
1755 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1756 CallOpc = ARMISD::CALL_NOLINK;
1758 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1760 if (!isDirect && !Subtarget->hasV5TOps())
1761 CallOpc = ARMISD::CALL_NOLINK;
1762 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1763 // Emit regular call when code size is the priority
1765 // "mov lr, pc; b _foo" to avoid confusing the RSP
1766 CallOpc = ARMISD::CALL_NOLINK;
1768 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1771 std::vector<SDValue> Ops;
1772 Ops.push_back(Chain);
1773 Ops.push_back(Callee);
1775 // Add argument registers to the end of the list so that they are known live
1777 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1778 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1779 RegsToPass[i].second.getValueType()));
1781 // Add a register mask operand representing the call-preserved registers.
1783 const uint32_t *Mask;
1784 const TargetRegisterInfo *TRI =
1785 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1786 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1788 // For 'this' returns, use the R0-preserving mask if applicable
1789 Mask = ARI->getThisReturnPreservedMask(CallConv);
1791 // Set isThisReturn to false if the calling convention is not one that
1792 // allows 'returned' to be modeled in this way, so LowerCallResult does
1793 // not try to pass 'this' straight through
1794 isThisReturn = false;
1795 Mask = ARI->getCallPreservedMask(CallConv);
1798 Mask = ARI->getCallPreservedMask(CallConv);
1800 assert(Mask && "Missing call preserved mask for calling convention");
1801 Ops.push_back(DAG.getRegisterMask(Mask));
1804 if (InFlag.getNode())
1805 Ops.push_back(InFlag);
1807 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1809 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1811 // Returns a chain and a flag for retval copy to use.
1812 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1813 InFlag = Chain.getValue(1);
1815 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1816 DAG.getIntPtrConstant(0, true), InFlag, dl);
1818 InFlag = Chain.getValue(1);
1820 // Handle result values, copying them out of physregs into vregs that we
1822 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1823 InVals, isThisReturn,
1824 isThisReturn ? OutVals[0] : SDValue());
1827 /// HandleByVal - Every parameter *after* a byval parameter is passed
1828 /// on the stack. Remember the next parameter register to allocate,
1829 /// and then confiscate the rest of the parameter registers to insure
1832 ARMTargetLowering::HandleByVal(
1833 CCState *State, unsigned &size, unsigned Align) const {
1834 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1835 assert((State->getCallOrPrologue() == Prologue ||
1836 State->getCallOrPrologue() == Call) &&
1837 "unhandled ParmContext");
1839 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1840 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1841 unsigned AlignInRegs = Align / 4;
1842 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1843 for (unsigned i = 0; i < Waste; ++i)
1844 reg = State->AllocateReg(GPRArgRegs, 4);
1847 unsigned excess = 4 * (ARM::R4 - reg);
1849 // Special case when NSAA != SP and parameter size greater than size of
1850 // all remained GPR regs. In that case we can't split parameter, we must
1851 // send it to stack. We also must set NCRN to R4, so waste all
1852 // remained registers.
1853 const unsigned NSAAOffset = State->getNextStackOffset();
1854 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1855 while (State->AllocateReg(GPRArgRegs, 4))
1860 // First register for byval parameter is the first register that wasn't
1861 // allocated before this method call, so it would be "reg".
1862 // If parameter is small enough to be saved in range [reg, r4), then
1863 // the end (first after last) register would be reg + param-size-in-regs,
1864 // else parameter would be splitted between registers and stack,
1865 // end register would be r4 in this case.
1866 unsigned ByValRegBegin = reg;
1867 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1868 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1869 // Note, first register is allocated in the beginning of function already,
1870 // allocate remained amount of registers we need.
1871 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1872 State->AllocateReg(GPRArgRegs, 4);
1873 // A byval parameter that is split between registers and memory needs its
1874 // size truncated here.
1875 // In the case where the entire structure fits in registers, we set the
1876 // size in memory to zero.
1885 /// MatchingStackOffset - Return true if the given stack call argument is
1886 /// already available in the same position (relatively) of the caller's
1887 /// incoming argument stack.
1889 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1890 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1891 const TargetInstrInfo *TII) {
1892 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1894 if (Arg.getOpcode() == ISD::CopyFromReg) {
1895 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1896 if (!TargetRegisterInfo::isVirtualRegister(VR))
1898 MachineInstr *Def = MRI->getVRegDef(VR);
1901 if (!Flags.isByVal()) {
1902 if (!TII->isLoadFromStackSlot(Def, FI))
1907 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1908 if (Flags.isByVal())
1909 // ByVal argument is passed in as a pointer but it's now being
1910 // dereferenced. e.g.
1911 // define @foo(%struct.X* %A) {
1912 // tail call @bar(%struct.X* byval %A)
1915 SDValue Ptr = Ld->getBasePtr();
1916 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1919 FI = FINode->getIndex();
1923 assert(FI != INT_MAX);
1924 if (!MFI->isFixedObjectIndex(FI))
1926 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1929 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1930 /// for tail call optimization. Targets which want to do tail call
1931 /// optimization should implement this function.
1933 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1934 CallingConv::ID CalleeCC,
1936 bool isCalleeStructRet,
1937 bool isCallerStructRet,
1938 const SmallVectorImpl<ISD::OutputArg> &Outs,
1939 const SmallVectorImpl<SDValue> &OutVals,
1940 const SmallVectorImpl<ISD::InputArg> &Ins,
1941 SelectionDAG& DAG) const {
1942 const Function *CallerF = DAG.getMachineFunction().getFunction();
1943 CallingConv::ID CallerCC = CallerF->getCallingConv();
1944 bool CCMatch = CallerCC == CalleeCC;
1946 // Look for obvious safe cases to perform tail call optimization that do not
1947 // require ABI changes. This is what gcc calls sibcall.
1949 // Do not sibcall optimize vararg calls unless the call site is not passing
1951 if (isVarArg && !Outs.empty())
1954 // Exception-handling functions need a special set of instructions to indicate
1955 // a return to the hardware. Tail-calling another function would probably
1957 if (CallerF->hasFnAttribute("interrupt"))
1960 // Also avoid sibcall optimization if either caller or callee uses struct
1961 // return semantics.
1962 if (isCalleeStructRet || isCallerStructRet)
1965 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1966 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1967 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1968 // support in the assembler and linker to be used. This would need to be
1969 // fixed to fully support tail calls in Thumb1.
1971 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1972 // LR. This means if we need to reload LR, it takes an extra instructions,
1973 // which outweighs the value of the tail call; but here we don't know yet
1974 // whether LR is going to be used. Probably the right approach is to
1975 // generate the tail call here and turn it back into CALL/RET in
1976 // emitEpilogue if LR is used.
1978 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1979 // but we need to make sure there are enough registers; the only valid
1980 // registers are the 4 used for parameters. We don't currently do this
1982 if (Subtarget->isThumb1Only())
1985 // If the calling conventions do not match, then we'd better make sure the
1986 // results are returned in the same way as what the caller expects.
1988 SmallVector<CCValAssign, 16> RVLocs1;
1989 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
1990 *DAG.getContext(), Call);
1991 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1993 SmallVector<CCValAssign, 16> RVLocs2;
1994 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
1995 *DAG.getContext(), Call);
1996 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1998 if (RVLocs1.size() != RVLocs2.size())
2000 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2001 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2003 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2005 if (RVLocs1[i].isRegLoc()) {
2006 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2009 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2015 // If Caller's vararg or byval argument has been split between registers and
2016 // stack, do not perform tail call, since part of the argument is in caller's
2018 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2019 getInfo<ARMFunctionInfo>();
2020 if (AFI_Caller->getArgRegsSaveSize())
2023 // If the callee takes no arguments then go on to check the results of the
2025 if (!Outs.empty()) {
2026 // Check if stack adjustment is needed. For now, do not do this if any
2027 // argument is passed on the stack.
2028 SmallVector<CCValAssign, 16> ArgLocs;
2029 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2030 *DAG.getContext(), Call);
2031 CCInfo.AnalyzeCallOperands(Outs,
2032 CCAssignFnForNode(CalleeCC, false, isVarArg));
2033 if (CCInfo.getNextStackOffset()) {
2034 MachineFunction &MF = DAG.getMachineFunction();
2036 // Check if the arguments are already laid out in the right way as
2037 // the caller's fixed stack objects.
2038 MachineFrameInfo *MFI = MF.getFrameInfo();
2039 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2040 const TargetInstrInfo *TII =
2041 getTargetMachine().getSubtargetImpl()->getInstrInfo();
2042 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2044 ++i, ++realArgIdx) {
2045 CCValAssign &VA = ArgLocs[i];
2046 EVT RegVT = VA.getLocVT();
2047 SDValue Arg = OutVals[realArgIdx];
2048 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2049 if (VA.getLocInfo() == CCValAssign::Indirect)
2051 if (VA.needsCustom()) {
2052 // f64 and vector types are split into multiple registers or
2053 // register/stack-slot combinations. The types will not match
2054 // the registers; give up on memory f64 refs until we figure
2055 // out what to do about this.
2058 if (!ArgLocs[++i].isRegLoc())
2060 if (RegVT == MVT::v2f64) {
2061 if (!ArgLocs[++i].isRegLoc())
2063 if (!ArgLocs[++i].isRegLoc())
2066 } else if (!VA.isRegLoc()) {
2067 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2079 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2080 MachineFunction &MF, bool isVarArg,
2081 const SmallVectorImpl<ISD::OutputArg> &Outs,
2082 LLVMContext &Context) const {
2083 SmallVector<CCValAssign, 16> RVLocs;
2084 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2085 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2089 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2090 SDLoc DL, SelectionDAG &DAG) {
2091 const MachineFunction &MF = DAG.getMachineFunction();
2092 const Function *F = MF.getFunction();
2094 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2096 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2097 // version of the "preferred return address". These offsets affect the return
2098 // instruction if this is a return from PL1 without hypervisor extensions.
2099 // IRQ/FIQ: +4 "subs pc, lr, #4"
2100 // SWI: 0 "subs pc, lr, #0"
2101 // ABORT: +4 "subs pc, lr, #4"
2102 // UNDEF: +4/+2 "subs pc, lr, #0"
2103 // UNDEF varies depending on where the exception came from ARM or Thumb
2104 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2107 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2110 else if (IntKind == "SWI" || IntKind == "UNDEF")
2113 report_fatal_error("Unsupported interrupt attribute. If present, value "
2114 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2116 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2118 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2122 ARMTargetLowering::LowerReturn(SDValue Chain,
2123 CallingConv::ID CallConv, bool isVarArg,
2124 const SmallVectorImpl<ISD::OutputArg> &Outs,
2125 const SmallVectorImpl<SDValue> &OutVals,
2126 SDLoc dl, SelectionDAG &DAG) const {
2128 // CCValAssign - represent the assignment of the return value to a location.
2129 SmallVector<CCValAssign, 16> RVLocs;
2131 // CCState - Info about the registers and stack slots.
2132 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2133 *DAG.getContext(), Call);
2135 // Analyze outgoing return values.
2136 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2140 SmallVector<SDValue, 4> RetOps;
2141 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2142 bool isLittleEndian = Subtarget->isLittle();
2144 MachineFunction &MF = DAG.getMachineFunction();
2145 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2146 AFI->setReturnRegsCount(RVLocs.size());
2148 // Copy the result values into the output registers.
2149 for (unsigned i = 0, realRVLocIdx = 0;
2151 ++i, ++realRVLocIdx) {
2152 CCValAssign &VA = RVLocs[i];
2153 assert(VA.isRegLoc() && "Can only return in registers!");
2155 SDValue Arg = OutVals[realRVLocIdx];
2157 switch (VA.getLocInfo()) {
2158 default: llvm_unreachable("Unknown loc info!");
2159 case CCValAssign::Full: break;
2160 case CCValAssign::BCvt:
2161 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2165 if (VA.needsCustom()) {
2166 if (VA.getLocVT() == MVT::v2f64) {
2167 // Extract the first half and return it in two registers.
2168 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2169 DAG.getConstant(0, MVT::i32));
2170 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2171 DAG.getVTList(MVT::i32, MVT::i32), Half);
2173 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2174 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2176 Flag = Chain.getValue(1);
2177 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2178 VA = RVLocs[++i]; // skip ahead to next loc
2179 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2180 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2182 Flag = Chain.getValue(1);
2183 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2184 VA = RVLocs[++i]; // skip ahead to next loc
2186 // Extract the 2nd half and fall through to handle it as an f64 value.
2187 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2188 DAG.getConstant(1, MVT::i32));
2190 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2192 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2193 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2194 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2195 fmrrd.getValue(isLittleEndian ? 0 : 1),
2197 Flag = Chain.getValue(1);
2198 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2199 VA = RVLocs[++i]; // skip ahead to next loc
2200 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2201 fmrrd.getValue(isLittleEndian ? 1 : 0),
2204 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2206 // Guarantee that all emitted copies are
2207 // stuck together, avoiding something bad.
2208 Flag = Chain.getValue(1);
2209 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2212 // Update chain and glue.
2215 RetOps.push_back(Flag);
2217 // CPUs which aren't M-class use a special sequence to return from
2218 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2219 // though we use "subs pc, lr, #N").
2221 // M-class CPUs actually use a normal return sequence with a special
2222 // (hardware-provided) value in LR, so the normal code path works.
2223 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2224 !Subtarget->isMClass()) {
2225 if (Subtarget->isThumb1Only())
2226 report_fatal_error("interrupt attribute is not supported in Thumb1");
2227 return LowerInterruptReturn(RetOps, dl, DAG);
2230 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2233 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2234 if (N->getNumValues() != 1)
2236 if (!N->hasNUsesOfValue(1, 0))
2239 SDValue TCChain = Chain;
2240 SDNode *Copy = *N->use_begin();
2241 if (Copy->getOpcode() == ISD::CopyToReg) {
2242 // If the copy has a glue operand, we conservatively assume it isn't safe to
2243 // perform a tail call.
2244 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2246 TCChain = Copy->getOperand(0);
2247 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2248 SDNode *VMov = Copy;
2249 // f64 returned in a pair of GPRs.
2250 SmallPtrSet<SDNode*, 2> Copies;
2251 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2253 if (UI->getOpcode() != ISD::CopyToReg)
2257 if (Copies.size() > 2)
2260 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2262 SDValue UseChain = UI->getOperand(0);
2263 if (Copies.count(UseChain.getNode()))
2270 } else if (Copy->getOpcode() == ISD::BITCAST) {
2271 // f32 returned in a single GPR.
2272 if (!Copy->hasOneUse())
2274 Copy = *Copy->use_begin();
2275 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2277 TCChain = Copy->getOperand(0);
2282 bool HasRet = false;
2283 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2285 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2286 UI->getOpcode() != ARMISD::INTRET_FLAG)
2298 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2299 if (!Subtarget->supportsTailCall())
2302 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2305 return !Subtarget->isThumb1Only();
2308 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2309 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2310 // one of the above mentioned nodes. It has to be wrapped because otherwise
2311 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2312 // be used to form addressing mode. These wrapped nodes will be selected
2314 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2315 EVT PtrVT = Op.getValueType();
2316 // FIXME there is no actual debug info here
2318 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2320 if (CP->isMachineConstantPoolEntry())
2321 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2322 CP->getAlignment());
2324 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2325 CP->getAlignment());
2326 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2329 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2330 return MachineJumpTableInfo::EK_Inline;
2333 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2334 SelectionDAG &DAG) const {
2335 MachineFunction &MF = DAG.getMachineFunction();
2336 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2337 unsigned ARMPCLabelIndex = 0;
2339 EVT PtrVT = getPointerTy();
2340 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2341 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2343 if (RelocM == Reloc::Static) {
2344 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2346 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2347 ARMPCLabelIndex = AFI->createPICLabelUId();
2348 ARMConstantPoolValue *CPV =
2349 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2350 ARMCP::CPBlockAddress, PCAdj);
2351 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2353 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2354 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2355 MachinePointerInfo::getConstantPool(),
2356 false, false, false, 0);
2357 if (RelocM == Reloc::Static)
2359 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2360 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2363 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2365 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2366 SelectionDAG &DAG) const {
2368 EVT PtrVT = getPointerTy();
2369 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2370 MachineFunction &MF = DAG.getMachineFunction();
2371 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2372 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2373 ARMConstantPoolValue *CPV =
2374 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2375 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2376 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2377 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2378 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2379 MachinePointerInfo::getConstantPool(),
2380 false, false, false, 0);
2381 SDValue Chain = Argument.getValue(1);
2383 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2384 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2386 // call __tls_get_addr.
2389 Entry.Node = Argument;
2390 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2391 Args.push_back(Entry);
2393 // FIXME: is there useful debug info available here?
2394 TargetLowering::CallLoweringInfo CLI(DAG);
2395 CLI.setDebugLoc(dl).setChain(Chain)
2396 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2397 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2400 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2401 return CallResult.first;
2404 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2405 // "local exec" model.
2407 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2409 TLSModel::Model model) const {
2410 const GlobalValue *GV = GA->getGlobal();
2413 SDValue Chain = DAG.getEntryNode();
2414 EVT PtrVT = getPointerTy();
2415 // Get the Thread Pointer
2416 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2418 if (model == TLSModel::InitialExec) {
2419 MachineFunction &MF = DAG.getMachineFunction();
2420 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2421 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2422 // Initial exec model.
2423 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2424 ARMConstantPoolValue *CPV =
2425 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2426 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2428 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2429 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2430 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2431 MachinePointerInfo::getConstantPool(),
2432 false, false, false, 0);
2433 Chain = Offset.getValue(1);
2435 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2436 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2438 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2439 MachinePointerInfo::getConstantPool(),
2440 false, false, false, 0);
2443 assert(model == TLSModel::LocalExec);
2444 ARMConstantPoolValue *CPV =
2445 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2446 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2447 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2448 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2449 MachinePointerInfo::getConstantPool(),
2450 false, false, false, 0);
2453 // The address of the thread local variable is the add of the thread
2454 // pointer with the offset of the variable.
2455 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2459 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2460 // TODO: implement the "local dynamic" model
2461 assert(Subtarget->isTargetELF() &&
2462 "TLS not implemented for non-ELF targets");
2463 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2465 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2468 case TLSModel::GeneralDynamic:
2469 case TLSModel::LocalDynamic:
2470 return LowerToTLSGeneralDynamicModel(GA, DAG);
2471 case TLSModel::InitialExec:
2472 case TLSModel::LocalExec:
2473 return LowerToTLSExecModels(GA, DAG, model);
2475 llvm_unreachable("bogus TLS model");
2478 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2479 SelectionDAG &DAG) const {
2480 EVT PtrVT = getPointerTy();
2482 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2483 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2484 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2485 ARMConstantPoolValue *CPV =
2486 ARMConstantPoolConstant::Create(GV,
2487 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2488 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2489 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2490 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2492 MachinePointerInfo::getConstantPool(),
2493 false, false, false, 0);
2494 SDValue Chain = Result.getValue(1);
2495 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2496 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2498 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2499 MachinePointerInfo::getGOT(),
2500 false, false, false, 0);
2504 // If we have T2 ops, we can materialize the address directly via movt/movw
2505 // pair. This is always cheaper.
2506 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2508 // FIXME: Once remat is capable of dealing with instructions with register
2509 // operands, expand this into two nodes.
2510 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2511 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2513 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2514 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2515 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2516 MachinePointerInfo::getConstantPool(),
2517 false, false, false, 0);
2521 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2522 SelectionDAG &DAG) const {
2523 EVT PtrVT = getPointerTy();
2525 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2526 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2528 if (Subtarget->useMovt(DAG.getMachineFunction()))
2531 // FIXME: Once remat is capable of dealing with instructions with register
2532 // operands, expand this into multiple nodes
2534 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2536 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2537 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2539 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2540 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2541 MachinePointerInfo::getGOT(), false, false, false, 0);
2545 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2546 SelectionDAG &DAG) const {
2547 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2548 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2549 "Windows on ARM expects to use movw/movt");
2551 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2552 const ARMII::TOF TargetFlags =
2553 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2554 EVT PtrVT = getPointerTy();
2560 // FIXME: Once remat is capable of dealing with instructions with register
2561 // operands, expand this into two nodes.
2562 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2563 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2565 if (GV->hasDLLImportStorageClass())
2566 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2567 MachinePointerInfo::getGOT(), false, false, false, 0);
2571 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2572 SelectionDAG &DAG) const {
2573 assert(Subtarget->isTargetELF() &&
2574 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2575 MachineFunction &MF = DAG.getMachineFunction();
2576 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2577 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2578 EVT PtrVT = getPointerTy();
2580 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2581 ARMConstantPoolValue *CPV =
2582 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2583 ARMPCLabelIndex, PCAdj);
2584 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2585 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2586 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2587 MachinePointerInfo::getConstantPool(),
2588 false, false, false, 0);
2589 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2590 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2594 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2596 SDValue Val = DAG.getConstant(0, MVT::i32);
2597 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2598 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2599 Op.getOperand(1), Val);
2603 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2605 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2606 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2610 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2611 const ARMSubtarget *Subtarget) const {
2612 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2615 default: return SDValue(); // Don't custom lower most intrinsics.
2616 case Intrinsic::arm_rbit: {
2617 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
2618 "RBIT intrinsic must have i32 type!");
2619 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(0));
2621 case Intrinsic::arm_thread_pointer: {
2622 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2623 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2625 case Intrinsic::eh_sjlj_lsda: {
2626 MachineFunction &MF = DAG.getMachineFunction();
2627 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2628 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2629 EVT PtrVT = getPointerTy();
2630 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2632 unsigned PCAdj = (RelocM != Reloc::PIC_)
2633 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2634 ARMConstantPoolValue *CPV =
2635 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2636 ARMCP::CPLSDA, PCAdj);
2637 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2638 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2640 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2641 MachinePointerInfo::getConstantPool(),
2642 false, false, false, 0);
2644 if (RelocM == Reloc::PIC_) {
2645 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2646 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2650 case Intrinsic::arm_neon_vmulls:
2651 case Intrinsic::arm_neon_vmullu: {
2652 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2653 ? ARMISD::VMULLs : ARMISD::VMULLu;
2654 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2655 Op.getOperand(1), Op.getOperand(2));
2660 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2661 const ARMSubtarget *Subtarget) {
2662 // FIXME: handle "fence singlethread" more efficiently.
2664 if (!Subtarget->hasDataBarrier()) {
2665 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2666 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2668 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2669 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2670 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2671 DAG.getConstant(0, MVT::i32));
2674 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2675 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2676 unsigned Domain = ARM_MB::ISH;
2677 if (Subtarget->isMClass()) {
2678 // Only a full system barrier exists in the M-class architectures.
2679 Domain = ARM_MB::SY;
2680 } else if (Subtarget->isSwift() && Ord == Release) {
2681 // Swift happens to implement ISHST barriers in a way that's compatible with
2682 // Release semantics but weaker than ISH so we'd be fools not to use
2683 // it. Beware: other processors probably don't!
2684 Domain = ARM_MB::ISHST;
2687 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2688 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2689 DAG.getConstant(Domain, MVT::i32));
2692 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2693 const ARMSubtarget *Subtarget) {
2694 // ARM pre v5TE and Thumb1 does not have preload instructions.
2695 if (!(Subtarget->isThumb2() ||
2696 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2697 // Just preserve the chain.
2698 return Op.getOperand(0);
2701 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2703 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2704 // ARMv7 with MP extension has PLDW.
2705 return Op.getOperand(0);
2707 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2708 if (Subtarget->isThumb()) {
2710 isRead = ~isRead & 1;
2711 isData = ~isData & 1;
2714 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2715 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2716 DAG.getConstant(isData, MVT::i32));
2719 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2720 MachineFunction &MF = DAG.getMachineFunction();
2721 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2723 // vastart just stores the address of the VarArgsFrameIndex slot into the
2724 // memory location argument.
2726 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2727 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2728 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2729 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2730 MachinePointerInfo(SV), false, false, 0);
2734 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2735 SDValue &Root, SelectionDAG &DAG,
2737 MachineFunction &MF = DAG.getMachineFunction();
2738 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2740 const TargetRegisterClass *RC;
2741 if (AFI->isThumb1OnlyFunction())
2742 RC = &ARM::tGPRRegClass;
2744 RC = &ARM::GPRRegClass;
2746 // Transform the arguments stored in physical registers into virtual ones.
2747 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2748 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2751 if (NextVA.isMemLoc()) {
2752 MachineFrameInfo *MFI = MF.getFrameInfo();
2753 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2755 // Create load node to retrieve arguments from the stack.
2756 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2757 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2758 MachinePointerInfo::getFixedStack(FI),
2759 false, false, false, 0);
2761 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2762 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2764 if (!Subtarget->isLittle())
2765 std::swap (ArgValue, ArgValue2);
2766 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2770 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2771 unsigned InRegsParamRecordIdx,
2773 unsigned &ArgRegsSize,
2774 unsigned &ArgRegsSaveSize)
2777 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2778 unsigned RBegin, REnd;
2779 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2780 NumGPRs = REnd - RBegin;
2782 unsigned int firstUnalloced;
2783 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2784 sizeof(GPRArgRegs) /
2785 sizeof(GPRArgRegs[0]));
2786 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2789 unsigned Align = MF.getTarget()
2791 ->getFrameLowering()
2792 ->getStackAlignment();
2793 ArgRegsSize = NumGPRs * 4;
2795 // If parameter is split between stack and GPRs...
2796 if (NumGPRs && Align > 4 &&
2797 (ArgRegsSize < ArgSize ||
2798 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2799 // Add padding for part of param recovered from GPRs. For example,
2800 // if Align == 8, its last byte must be at address K*8 - 1.
2801 // We need to do it, since remained (stack) part of parameter has
2802 // stack alignment, and we need to "attach" "GPRs head" without gaps
2805 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2806 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2808 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2810 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2811 ArgRegsSaveSize = ArgRegsSize + Padding;
2813 // We don't need to extend regs save size for byval parameters if they
2814 // are passed via GPRs only.
2815 ArgRegsSaveSize = ArgRegsSize;
2818 // The remaining GPRs hold either the beginning of variable-argument
2819 // data, or the beginning of an aggregate passed by value (usually
2820 // byval). Either way, we allocate stack slots adjacent to the data
2821 // provided by our caller, and store the unallocated registers there.
2822 // If this is a variadic function, the va_list pointer will begin with
2823 // these values; otherwise, this reassembles a (byval) structure that
2824 // was split between registers and memory.
2825 // Return: The frame index registers were stored into.
2827 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2828 SDLoc dl, SDValue &Chain,
2829 const Value *OrigArg,
2830 unsigned InRegsParamRecordIdx,
2831 unsigned OffsetFromOrigArg,
2835 unsigned ByValStoreOffset,
2836 unsigned TotalArgRegsSaveSize) const {
2838 // Currently, two use-cases possible:
2839 // Case #1. Non-var-args function, and we meet first byval parameter.
2840 // Setup first unallocated register as first byval register;
2841 // eat all remained registers
2842 // (these two actions are performed by HandleByVal method).
2843 // Then, here, we initialize stack frame with
2844 // "store-reg" instructions.
2845 // Case #2. Var-args function, that doesn't contain byval parameters.
2846 // The same: eat all remained unallocated registers,
2847 // initialize stack frame.
2849 MachineFunction &MF = DAG.getMachineFunction();
2850 MachineFrameInfo *MFI = MF.getFrameInfo();
2851 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2852 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2853 unsigned RBegin, REnd;
2854 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2855 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2856 firstRegToSaveIndex = RBegin - ARM::R0;
2857 lastRegToSaveIndex = REnd - ARM::R0;
2859 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2860 (GPRArgRegs, array_lengthof(GPRArgRegs));
2861 lastRegToSaveIndex = 4;
2864 unsigned ArgRegsSize, ArgRegsSaveSize;
2865 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2866 ArgRegsSize, ArgRegsSaveSize);
2868 // Store any by-val regs to their spots on the stack so that they may be
2869 // loaded by deferencing the result of formal parameter pointer or va_next.
2870 // Note: once stack area for byval/varargs registers
2871 // was initialized, it can't be initialized again.
2872 if (ArgRegsSaveSize) {
2873 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2876 assert(AFI->getStoredByValParamsPadding() == 0 &&
2877 "The only parameter may be padded.");
2878 AFI->setStoredByValParamsPadding(Padding);
2881 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2884 (int64_t)TotalArgRegsSaveSize,
2886 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2888 MFI->CreateFixedObject(Padding,
2889 ArgOffset + ByValStoreOffset -
2890 (int64_t)ArgRegsSaveSize,
2894 SmallVector<SDValue, 4> MemOps;
2895 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2896 ++firstRegToSaveIndex, ++i) {
2897 const TargetRegisterClass *RC;
2898 if (AFI->isThumb1OnlyFunction())
2899 RC = &ARM::tGPRRegClass;
2901 RC = &ARM::GPRRegClass;
2903 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2904 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2906 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2907 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2909 MemOps.push_back(Store);
2910 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2911 DAG.getConstant(4, getPointerTy()));
2914 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2916 if (!MemOps.empty())
2917 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2921 // We cannot allocate a zero-byte object for the first variadic argument,
2922 // so just make up a size.
2925 // This will point to the next argument passed via stack.
2926 return MFI->CreateFixedObject(
2927 ArgSize, ArgOffset, !ForceMutable);
2931 // Setup stack frame, the va_list pointer will start from.
2933 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2934 SDLoc dl, SDValue &Chain,
2936 unsigned TotalArgRegsSaveSize,
2937 bool ForceMutable) const {
2938 MachineFunction &MF = DAG.getMachineFunction();
2939 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2941 // Try to store any remaining integer argument regs
2942 // to their spots on the stack so that they may be loaded by deferencing
2943 // the result of va_next.
2944 // If there is no regs to be stored, just point address after last
2945 // argument passed via stack.
2947 StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2948 CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2949 0, TotalArgRegsSaveSize);
2951 AFI->setVarArgsFrameIndex(FrameIndex);
2955 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2956 CallingConv::ID CallConv, bool isVarArg,
2957 const SmallVectorImpl<ISD::InputArg>
2959 SDLoc dl, SelectionDAG &DAG,
2960 SmallVectorImpl<SDValue> &InVals)
2962 MachineFunction &MF = DAG.getMachineFunction();
2963 MachineFrameInfo *MFI = MF.getFrameInfo();
2965 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2967 // Assign locations to all of the incoming arguments.
2968 SmallVector<CCValAssign, 16> ArgLocs;
2969 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2970 *DAG.getContext(), Prologue);
2971 CCInfo.AnalyzeFormalArguments(Ins,
2972 CCAssignFnForNode(CallConv, /* Return*/ false,
2975 SmallVector<SDValue, 16> ArgValues;
2976 int lastInsIndex = -1;
2978 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2979 unsigned CurArgIdx = 0;
2981 // Initially ArgRegsSaveSize is zero.
2982 // Then we increase this value each time we meet byval parameter.
2983 // We also increase this value in case of varargs function.
2984 AFI->setArgRegsSaveSize(0);
2986 unsigned ByValStoreOffset = 0;
2987 unsigned TotalArgRegsSaveSize = 0;
2988 unsigned ArgRegsSaveSizeMaxAlign = 4;
2990 // Calculate the amount of stack space that we need to allocate to store
2991 // byval and variadic arguments that are passed in registers.
2992 // We need to know this before we allocate the first byval or variadic
2993 // argument, as they will be allocated a stack slot below the CFA (Canonical
2994 // Frame Address, the stack pointer at entry to the function).
2995 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2996 CCValAssign &VA = ArgLocs[i];
2997 if (VA.isMemLoc()) {
2998 int index = VA.getValNo();
2999 if (index != lastInsIndex) {
3000 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3001 if (Flags.isByVal()) {
3002 unsigned ExtraArgRegsSize;
3003 unsigned ExtraArgRegsSaveSize;
3004 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
3005 Flags.getByValSize(),
3006 ExtraArgRegsSize, ExtraArgRegsSaveSize);
3008 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3009 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3010 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3011 CCInfo.nextInRegsParam();
3013 lastInsIndex = index;
3017 CCInfo.rewindByValRegsInfo();
3020 unsigned ExtraArgRegsSize;
3021 unsigned ExtraArgRegsSaveSize;
3022 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3023 ExtraArgRegsSize, ExtraArgRegsSaveSize);
3024 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3026 // If the arg regs save area contains N-byte aligned values, the
3027 // bottom of it must be at least N-byte aligned.
3028 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3029 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3031 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3032 CCValAssign &VA = ArgLocs[i];
3033 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3034 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3035 // Arguments stored in registers.
3036 if (VA.isRegLoc()) {
3037 EVT RegVT = VA.getLocVT();
3039 if (VA.needsCustom()) {
3040 // f64 and vector types are split up into multiple registers or
3041 // combinations of registers and stack slots.
3042 if (VA.getLocVT() == MVT::v2f64) {
3043 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3045 VA = ArgLocs[++i]; // skip ahead to next loc
3047 if (VA.isMemLoc()) {
3048 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3049 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3050 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3051 MachinePointerInfo::getFixedStack(FI),
3052 false, false, false, 0);
3054 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3057 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3058 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3059 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3060 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3061 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3063 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3066 const TargetRegisterClass *RC;
3068 if (RegVT == MVT::f32)
3069 RC = &ARM::SPRRegClass;
3070 else if (RegVT == MVT::f64)
3071 RC = &ARM::DPRRegClass;
3072 else if (RegVT == MVT::v2f64)
3073 RC = &ARM::QPRRegClass;
3074 else if (RegVT == MVT::i32)
3075 RC = AFI->isThumb1OnlyFunction() ?
3076 (const TargetRegisterClass*)&ARM::tGPRRegClass :
3077 (const TargetRegisterClass*)&ARM::GPRRegClass;
3079 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3081 // Transform the arguments in physical registers into virtual ones.
3082 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3083 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3086 // If this is an 8 or 16-bit value, it is really passed promoted
3087 // to 32 bits. Insert an assert[sz]ext to capture this, then
3088 // truncate to the right size.
3089 switch (VA.getLocInfo()) {
3090 default: llvm_unreachable("Unknown loc info!");
3091 case CCValAssign::Full: break;
3092 case CCValAssign::BCvt:
3093 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3095 case CCValAssign::SExt:
3096 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3097 DAG.getValueType(VA.getValVT()));
3098 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3100 case CCValAssign::ZExt:
3101 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3102 DAG.getValueType(VA.getValVT()));
3103 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3107 InVals.push_back(ArgValue);
3109 } else { // VA.isRegLoc()
3112 assert(VA.isMemLoc());
3113 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3115 int index = ArgLocs[i].getValNo();
3117 // Some Ins[] entries become multiple ArgLoc[] entries.
3118 // Process them only once.
3119 if (index != lastInsIndex)
3121 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3122 // FIXME: For now, all byval parameter objects are marked mutable.
3123 // This can be changed with more analysis.
3124 // In case of tail call optimization mark all arguments mutable.
3125 // Since they could be overwritten by lowering of arguments in case of
3127 if (Flags.isByVal()) {
3128 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3130 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3131 int FrameIndex = StoreByValRegs(
3132 CCInfo, DAG, dl, Chain, CurOrigArg,
3134 Ins[VA.getValNo()].PartOffset,
3135 VA.getLocMemOffset(),
3136 Flags.getByValSize(),
3137 true /*force mutable frames*/,
3139 TotalArgRegsSaveSize);
3140 ByValStoreOffset += Flags.getByValSize();
3141 ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3142 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3143 CCInfo.nextInRegsParam();
3145 unsigned FIOffset = VA.getLocMemOffset();
3146 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3149 // Create load nodes to retrieve arguments from the stack.
3150 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3151 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3152 MachinePointerInfo::getFixedStack(FI),
3153 false, false, false, 0));
3155 lastInsIndex = index;
3162 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3163 CCInfo.getNextStackOffset(),
3164 TotalArgRegsSaveSize);
3166 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3171 /// isFloatingPointZero - Return true if this is +0.0.
3172 static bool isFloatingPointZero(SDValue Op) {
3173 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3174 return CFP->getValueAPF().isPosZero();
3175 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3176 // Maybe this has already been legalized into the constant pool?
3177 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3178 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3179 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3180 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3181 return CFP->getValueAPF().isPosZero();
3187 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3188 /// the given operands.
3190 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3191 SDValue &ARMcc, SelectionDAG &DAG,
3193 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3194 unsigned C = RHSC->getZExtValue();
3195 if (!isLegalICmpImmediate(C)) {
3196 // Constant does not fit, try adjusting it by one?
3201 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3202 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3203 RHS = DAG.getConstant(C-1, MVT::i32);
3208 if (C != 0 && isLegalICmpImmediate(C-1)) {
3209 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3210 RHS = DAG.getConstant(C-1, MVT::i32);
3215 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3216 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3217 RHS = DAG.getConstant(C+1, MVT::i32);
3222 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3223 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3224 RHS = DAG.getConstant(C+1, MVT::i32);
3231 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3232 ARMISD::NodeType CompareType;
3235 CompareType = ARMISD::CMP;
3240 CompareType = ARMISD::CMPZ;
3243 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3244 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3247 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3249 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3252 if (!isFloatingPointZero(RHS))
3253 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3255 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3256 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3259 /// duplicateCmp - Glue values can have only one use, so this function
3260 /// duplicates a comparison node.
3262 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3263 unsigned Opc = Cmp.getOpcode();
3265 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3266 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3268 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3269 Cmp = Cmp.getOperand(0);
3270 Opc = Cmp.getOpcode();
3271 if (Opc == ARMISD::CMPFP)
3272 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3274 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3275 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3277 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3280 std::pair<SDValue, SDValue>
3281 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3282 SDValue &ARMcc) const {
3283 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3285 SDValue Value, OverflowCmp;
3286 SDValue LHS = Op.getOperand(0);
3287 SDValue RHS = Op.getOperand(1);
3290 // FIXME: We are currently always generating CMPs because we don't support
3291 // generating CMN through the backend. This is not as good as the natural
3292 // CMP case because it causes a register dependency and cannot be folded
3295 switch (Op.getOpcode()) {
3297 llvm_unreachable("Unknown overflow instruction!");
3299 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3300 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3301 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3304 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3305 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3306 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3309 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3310 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3311 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3314 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3315 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3316 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3320 return std::make_pair(Value, OverflowCmp);
3325 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3326 // Let legalize expand this if it isn't a legal type yet.
3327 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3330 SDValue Value, OverflowCmp;
3332 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3333 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3334 // We use 0 and 1 as false and true values.
3335 SDValue TVal = DAG.getConstant(1, MVT::i32);
3336 SDValue FVal = DAG.getConstant(0, MVT::i32);
3337 EVT VT = Op.getValueType();
3339 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3340 ARMcc, CCR, OverflowCmp);
3342 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3343 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3347 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3348 SDValue Cond = Op.getOperand(0);
3349 SDValue SelectTrue = Op.getOperand(1);
3350 SDValue SelectFalse = Op.getOperand(2);
3352 unsigned Opc = Cond.getOpcode();
3354 if (Cond.getResNo() == 1 &&
3355 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3356 Opc == ISD::USUBO)) {
3357 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3360 SDValue Value, OverflowCmp;
3362 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3363 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3364 EVT VT = Op.getValueType();
3366 return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3367 ARMcc, CCR, OverflowCmp);
3373 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3374 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3376 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3377 const ConstantSDNode *CMOVTrue =
3378 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3379 const ConstantSDNode *CMOVFalse =
3380 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3382 if (CMOVTrue && CMOVFalse) {
3383 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3384 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3388 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3390 False = SelectFalse;
3391 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3396 if (True.getNode() && False.getNode()) {
3397 EVT VT = Op.getValueType();
3398 SDValue ARMcc = Cond.getOperand(2);
3399 SDValue CCR = Cond.getOperand(3);
3400 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3401 assert(True.getValueType() == VT);
3402 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3407 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3408 // undefined bits before doing a full-word comparison with zero.
3409 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3410 DAG.getConstant(1, Cond.getValueType()));
3412 return DAG.getSelectCC(dl, Cond,
3413 DAG.getConstant(0, Cond.getValueType()),
3414 SelectTrue, SelectFalse, ISD::SETNE);
3417 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3418 if (CC == ISD::SETNE)
3420 return ISD::getSetCCInverse(CC, true);
3423 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3424 bool &swpCmpOps, bool &swpVselOps) {
3425 // Start by selecting the GE condition code for opcodes that return true for
3427 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3429 CondCode = ARMCC::GE;
3431 // and GT for opcodes that return false for 'equality'.
3432 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3434 CondCode = ARMCC::GT;
3436 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3437 // to swap the compare operands.
3438 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3442 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3443 // If we have an unordered opcode, we need to swap the operands to the VSEL
3444 // instruction (effectively negating the condition).
3446 // This also has the effect of swapping which one of 'less' or 'greater'
3447 // returns true, so we also swap the compare operands. It also switches
3448 // whether we return true for 'equality', so we compensate by picking the
3449 // opposite condition code to our original choice.
3450 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3451 CC == ISD::SETUGT) {
3452 swpCmpOps = !swpCmpOps;
3453 swpVselOps = !swpVselOps;
3454 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3457 // 'ordered' is 'anything but unordered', so use the VS condition code and
3458 // swap the VSEL operands.
3459 if (CC == ISD::SETO) {
3460 CondCode = ARMCC::VS;
3464 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3465 // code and swap the VSEL operands.
3466 if (CC == ISD::SETUNE) {
3467 CondCode = ARMCC::EQ;
3472 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3473 EVT VT = Op.getValueType();
3474 SDValue LHS = Op.getOperand(0);
3475 SDValue RHS = Op.getOperand(1);
3476 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3477 SDValue TrueVal = Op.getOperand(2);
3478 SDValue FalseVal = Op.getOperand(3);
3481 if (LHS.getValueType() == MVT::i32) {
3482 // Try to generate VSEL on ARMv8.
3483 // The VSEL instruction can't use all the usual ARM condition
3484 // codes: it only has two bits to select the condition code, so it's
3485 // constrained to use only GE, GT, VS and EQ.
3487 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3488 // swap the operands of the previous compare instruction (effectively
3489 // inverting the compare condition, swapping 'less' and 'greater') and
3490 // sometimes need to swap the operands to the VSEL (which inverts the
3491 // condition in the sense of firing whenever the previous condition didn't)
3492 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3493 TrueVal.getValueType() == MVT::f64)) {
3494 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3495 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3496 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3497 CC = getInverseCCForVSEL(CC);
3498 std::swap(TrueVal, FalseVal);
3503 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3504 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3505 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3509 ARMCC::CondCodes CondCode, CondCode2;
3510 FPCCToARMCC(CC, CondCode, CondCode2);
3512 // Try to generate VSEL on ARMv8.
3513 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3514 TrueVal.getValueType() == MVT::f64)) {
3515 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3516 // same operands, as follows:
3517 // c = fcmp [ogt, olt, ugt, ult] a, b
3519 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3520 // handled differently than the original code sequence.
3521 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3523 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3524 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3525 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3526 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 = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3547 if (CondCode2 != ARMCC::AL) {
3548 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3549 // FIXME: Needs another CMP because flag can have but one use.
3550 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3551 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3552 Result, TrueVal, ARMcc2, CCR, Cmp2);
3557 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3558 /// to morph to an integer compare sequence.
3559 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3560 const ARMSubtarget *Subtarget) {
3561 SDNode *N = Op.getNode();
3562 if (!N->hasOneUse())
3563 // Otherwise it requires moving the value from fp to integer registers.
3565 if (!N->getNumValues())
3567 EVT VT = Op.getValueType();
3568 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3569 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3570 // vmrs are very slow, e.g. cortex-a8.
3573 if (isFloatingPointZero(Op)) {
3577 return ISD::isNormalLoad(N);
3580 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3581 if (isFloatingPointZero(Op))
3582 return DAG.getConstant(0, MVT::i32);
3584 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3585 return DAG.getLoad(MVT::i32, SDLoc(Op),
3586 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3587 Ld->isVolatile(), Ld->isNonTemporal(),
3588 Ld->isInvariant(), Ld->getAlignment());
3590 llvm_unreachable("Unknown VFP cmp argument!");
3593 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3594 SDValue &RetVal1, SDValue &RetVal2) {
3595 if (isFloatingPointZero(Op)) {
3596 RetVal1 = DAG.getConstant(0, MVT::i32);
3597 RetVal2 = DAG.getConstant(0, MVT::i32);
3601 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3602 SDValue Ptr = Ld->getBasePtr();
3603 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3604 Ld->getChain(), Ptr,
3605 Ld->getPointerInfo(),
3606 Ld->isVolatile(), Ld->isNonTemporal(),
3607 Ld->isInvariant(), Ld->getAlignment());
3609 EVT PtrType = Ptr.getValueType();
3610 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3611 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3612 PtrType, Ptr, DAG.getConstant(4, PtrType));
3613 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3614 Ld->getChain(), NewPtr,
3615 Ld->getPointerInfo().getWithOffset(4),
3616 Ld->isVolatile(), Ld->isNonTemporal(),
3617 Ld->isInvariant(), NewAlign);
3621 llvm_unreachable("Unknown VFP cmp argument!");
3624 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3625 /// f32 and even f64 comparisons to integer ones.
3627 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3628 SDValue Chain = Op.getOperand(0);
3629 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3630 SDValue LHS = Op.getOperand(2);
3631 SDValue RHS = Op.getOperand(3);
3632 SDValue Dest = Op.getOperand(4);
3635 bool LHSSeenZero = false;
3636 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3637 bool RHSSeenZero = false;
3638 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3639 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3640 // If unsafe fp math optimization is enabled and there are no other uses of
3641 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3642 // to an integer comparison.
3643 if (CC == ISD::SETOEQ)
3645 else if (CC == ISD::SETUNE)
3648 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3650 if (LHS.getValueType() == MVT::f32) {
3651 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3652 bitcastf32Toi32(LHS, DAG), Mask);
3653 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3654 bitcastf32Toi32(RHS, DAG), Mask);
3655 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3656 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3657 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3658 Chain, Dest, ARMcc, CCR, Cmp);
3663 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3664 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3665 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3666 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3667 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3668 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3669 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3670 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3671 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3677 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3678 SDValue Chain = Op.getOperand(0);
3679 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3680 SDValue LHS = Op.getOperand(2);
3681 SDValue RHS = Op.getOperand(3);
3682 SDValue Dest = Op.getOperand(4);
3685 if (LHS.getValueType() == MVT::i32) {
3687 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3688 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3689 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3690 Chain, Dest, ARMcc, CCR, Cmp);
3693 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3695 if (getTargetMachine().Options.UnsafeFPMath &&
3696 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3697 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3698 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3699 if (Result.getNode())
3703 ARMCC::CondCodes CondCode, CondCode2;
3704 FPCCToARMCC(CC, CondCode, CondCode2);
3706 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3707 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3708 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3709 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3710 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3711 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3712 if (CondCode2 != ARMCC::AL) {
3713 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3714 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3715 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3720 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3721 SDValue Chain = Op.getOperand(0);
3722 SDValue Table = Op.getOperand(1);
3723 SDValue Index = Op.getOperand(2);
3726 EVT PTy = getPointerTy();
3727 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3728 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3729 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3730 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3731 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3732 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3733 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3734 if (Subtarget->isThumb2()) {
3735 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3736 // which does another jump to the destination. This also makes it easier
3737 // to translate it to TBB / TBH later.
3738 // FIXME: This might not work if the function is extremely large.
3739 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3740 Addr, Op.getOperand(2), JTI, UId);
3742 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3743 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3744 MachinePointerInfo::getJumpTable(),
3745 false, false, false, 0);
3746 Chain = Addr.getValue(1);
3747 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3748 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3750 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3751 MachinePointerInfo::getJumpTable(),
3752 false, false, false, 0);
3753 Chain = Addr.getValue(1);
3754 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3758 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3759 EVT VT = Op.getValueType();
3762 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3763 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3765 return DAG.UnrollVectorOp(Op.getNode());
3768 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3769 "Invalid type for custom lowering!");
3770 if (VT != MVT::v4i16)
3771 return DAG.UnrollVectorOp(Op.getNode());
3773 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3774 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3777 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3778 EVT VT = Op.getValueType();
3780 return LowerVectorFP_TO_INT(Op, DAG);
3785 switch (Op.getOpcode()) {
3786 default: llvm_unreachable("Invalid opcode!");
3787 case ISD::FP_TO_SINT:
3788 Opc = ARMISD::FTOSI;
3790 case ISD::FP_TO_UINT:
3791 Opc = ARMISD::FTOUI;
3794 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3795 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3798 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3799 EVT VT = Op.getValueType();
3802 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3803 if (VT.getVectorElementType() == MVT::f32)
3805 return DAG.UnrollVectorOp(Op.getNode());
3808 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3809 "Invalid type for custom lowering!");
3810 if (VT != MVT::v4f32)
3811 return DAG.UnrollVectorOp(Op.getNode());
3815 switch (Op.getOpcode()) {
3816 default: llvm_unreachable("Invalid opcode!");
3817 case ISD::SINT_TO_FP:
3818 CastOpc = ISD::SIGN_EXTEND;
3819 Opc = ISD::SINT_TO_FP;
3821 case ISD::UINT_TO_FP:
3822 CastOpc = ISD::ZERO_EXTEND;
3823 Opc = ISD::UINT_TO_FP;
3827 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3828 return DAG.getNode(Opc, dl, VT, Op);
3831 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3832 EVT VT = Op.getValueType();
3834 return LowerVectorINT_TO_FP(Op, DAG);
3839 switch (Op.getOpcode()) {
3840 default: llvm_unreachable("Invalid opcode!");
3841 case ISD::SINT_TO_FP:
3842 Opc = ARMISD::SITOF;
3844 case ISD::UINT_TO_FP:
3845 Opc = ARMISD::UITOF;
3849 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3850 return DAG.getNode(Opc, dl, VT, Op);
3853 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3854 // Implement fcopysign with a fabs and a conditional fneg.
3855 SDValue Tmp0 = Op.getOperand(0);
3856 SDValue Tmp1 = Op.getOperand(1);
3858 EVT VT = Op.getValueType();
3859 EVT SrcVT = Tmp1.getValueType();
3860 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3861 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3862 bool UseNEON = !InGPR && Subtarget->hasNEON();
3865 // Use VBSL to copy the sign bit.
3866 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3867 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3868 DAG.getTargetConstant(EncodedVal, MVT::i32));
3869 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3871 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3872 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3873 DAG.getConstant(32, MVT::i32));
3874 else /*if (VT == MVT::f32)*/
3875 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3876 if (SrcVT == MVT::f32) {
3877 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3879 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3880 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3881 DAG.getConstant(32, MVT::i32));
3882 } else if (VT == MVT::f32)
3883 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3884 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3885 DAG.getConstant(32, MVT::i32));
3886 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3887 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3889 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3891 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3892 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3893 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3895 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3896 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3897 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3898 if (VT == MVT::f32) {
3899 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3900 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3901 DAG.getConstant(0, MVT::i32));
3903 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3909 // Bitcast operand 1 to i32.
3910 if (SrcVT == MVT::f64)
3911 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3913 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3915 // Or in the signbit with integer operations.
3916 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3917 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3918 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3919 if (VT == MVT::f32) {
3920 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3921 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3922 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3923 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3926 // f64: Or the high part with signbit and then combine two parts.
3927 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3929 SDValue Lo = Tmp0.getValue(0);
3930 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3931 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3932 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3935 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3936 MachineFunction &MF = DAG.getMachineFunction();
3937 MachineFrameInfo *MFI = MF.getFrameInfo();
3938 MFI->setReturnAddressIsTaken(true);
3940 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3943 EVT VT = Op.getValueType();
3945 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3947 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3948 SDValue Offset = DAG.getConstant(4, MVT::i32);
3949 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3950 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3951 MachinePointerInfo(), false, false, false, 0);
3954 // Return LR, which contains the return address. Mark it an implicit live-in.
3955 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3956 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3959 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3960 const ARMBaseRegisterInfo &ARI =
3961 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3962 MachineFunction &MF = DAG.getMachineFunction();
3963 MachineFrameInfo *MFI = MF.getFrameInfo();
3964 MFI->setFrameAddressIsTaken(true);
3966 EVT VT = Op.getValueType();
3967 SDLoc dl(Op); // FIXME probably not meaningful
3968 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3969 unsigned FrameReg = ARI.getFrameRegister(MF);
3970 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3972 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3973 MachinePointerInfo(),
3974 false, false, false, 0);
3978 // FIXME? Maybe this could be a TableGen attribute on some registers and
3979 // this table could be generated automatically from RegInfo.
3980 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3982 unsigned Reg = StringSwitch<unsigned>(RegName)
3983 .Case("sp", ARM::SP)
3987 report_fatal_error("Invalid register name global variable");
3990 /// ExpandBITCAST - If the target supports VFP, this function is called to
3991 /// expand a bit convert where either the source or destination type is i64 to
3992 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3993 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3994 /// vectors), since the legalizer won't know what to do with that.
3995 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3996 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3998 SDValue Op = N->getOperand(0);
4000 // This function is only supposed to be called for i64 types, either as the
4001 // source or destination of the bit convert.
4002 EVT SrcVT = Op.getValueType();
4003 EVT DstVT = N->getValueType(0);
4004 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4005 "ExpandBITCAST called for non-i64 type");
4007 // Turn i64->f64 into VMOVDRR.
4008 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4009 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4010 DAG.getConstant(0, MVT::i32));
4011 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4012 DAG.getConstant(1, MVT::i32));
4013 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4014 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4017 // Turn f64->i64 into VMOVRRD.
4018 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4020 if (TLI.isBigEndian() && SrcVT.isVector() &&
4021 SrcVT.getVectorNumElements() > 1)
4022 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4023 DAG.getVTList(MVT::i32, MVT::i32),
4024 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4026 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4027 DAG.getVTList(MVT::i32, MVT::i32), Op);
4028 // Merge the pieces into a single i64 value.
4029 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4035 /// getZeroVector - Returns a vector of specified type with all zero elements.
4036 /// Zero vectors are used to represent vector negation and in those cases
4037 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4038 /// not support i64 elements, so sometimes the zero vectors will need to be
4039 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4041 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4042 assert(VT.isVector() && "Expected a vector type");
4043 // The canonical modified immediate encoding of a zero vector is....0!
4044 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4045 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4046 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4047 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4050 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4051 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4052 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4053 SelectionDAG &DAG) const {
4054 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4055 EVT VT = Op.getValueType();
4056 unsigned VTBits = VT.getSizeInBits();
4058 SDValue ShOpLo = Op.getOperand(0);
4059 SDValue ShOpHi = Op.getOperand(1);
4060 SDValue ShAmt = Op.getOperand(2);
4062 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4064 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4066 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4067 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4068 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4069 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4070 DAG.getConstant(VTBits, MVT::i32));
4071 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4072 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4073 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4075 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4076 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4078 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4079 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4082 SDValue Ops[2] = { Lo, Hi };
4083 return DAG.getMergeValues(Ops, dl);
4086 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4087 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4088 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4089 SelectionDAG &DAG) const {
4090 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4091 EVT VT = Op.getValueType();
4092 unsigned VTBits = VT.getSizeInBits();
4094 SDValue ShOpLo = Op.getOperand(0);
4095 SDValue ShOpHi = Op.getOperand(1);
4096 SDValue ShAmt = Op.getOperand(2);
4099 assert(Op.getOpcode() == ISD::SHL_PARTS);
4100 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4101 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4102 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4103 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4104 DAG.getConstant(VTBits, MVT::i32));
4105 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4106 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4108 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4109 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4110 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4112 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4113 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4116 SDValue Ops[2] = { Lo, Hi };
4117 return DAG.getMergeValues(Ops, dl);
4120 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4121 SelectionDAG &DAG) const {
4122 // The rounding mode is in bits 23:22 of the FPSCR.
4123 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4124 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4125 // so that the shift + and get folded into a bitfield extract.
4127 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4128 DAG.getConstant(Intrinsic::arm_get_fpscr,
4130 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4131 DAG.getConstant(1U << 22, MVT::i32));
4132 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4133 DAG.getConstant(22, MVT::i32));
4134 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4135 DAG.getConstant(3, MVT::i32));
4138 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4139 const ARMSubtarget *ST) {
4140 EVT VT = N->getValueType(0);
4143 if (!ST->hasV6T2Ops())
4146 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4147 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4150 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4151 /// for each 16-bit element from operand, repeated. The basic idea is to
4152 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4154 /// Trace for v4i16:
4155 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4156 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4157 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4158 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4159 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4160 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4161 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4162 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4163 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4164 EVT VT = N->getValueType(0);
4167 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4168 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4169 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4170 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4171 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4172 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4175 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4176 /// bit-count for each 16-bit element from the operand. We need slightly
4177 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4178 /// 64/128-bit registers.
4180 /// Trace for v4i16:
4181 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4182 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4183 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4184 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4185 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4186 EVT VT = N->getValueType(0);
4189 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4190 if (VT.is64BitVector()) {
4191 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4192 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4193 DAG.getIntPtrConstant(0));
4195 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4196 BitCounts, DAG.getIntPtrConstant(0));
4197 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4201 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4202 /// bit-count for each 32-bit element from the operand. The idea here is
4203 /// to split the vector into 16-bit elements, leverage the 16-bit count
4204 /// routine, and then combine the results.
4206 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4207 /// input = [v0 v1 ] (vi: 32-bit elements)
4208 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4209 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4210 /// vrev: N0 = [k1 k0 k3 k2 ]
4212 /// N1 =+[k1 k0 k3 k2 ]
4214 /// N2 =+[k1 k3 k0 k2 ]
4216 /// Extended =+[k1 k3 k0 k2 ]
4218 /// Extracted=+[k1 k3 ]
4220 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4221 EVT VT = N->getValueType(0);
4224 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4226 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4227 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4228 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4229 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4230 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4232 if (VT.is64BitVector()) {
4233 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4234 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4235 DAG.getIntPtrConstant(0));
4237 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4238 DAG.getIntPtrConstant(0));
4239 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4243 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4244 const ARMSubtarget *ST) {
4245 EVT VT = N->getValueType(0);
4247 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4248 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4249 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4250 "Unexpected type for custom ctpop lowering");
4252 if (VT.getVectorElementType() == MVT::i32)
4253 return lowerCTPOP32BitElements(N, DAG);
4255 return lowerCTPOP16BitElements(N, DAG);
4258 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4259 const ARMSubtarget *ST) {
4260 EVT VT = N->getValueType(0);
4266 // Lower vector shifts on NEON to use VSHL.
4267 assert(ST->hasNEON() && "unexpected vector shift");
4269 // Left shifts translate directly to the vshiftu intrinsic.
4270 if (N->getOpcode() == ISD::SHL)
4271 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4272 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4273 N->getOperand(0), N->getOperand(1));
4275 assert((N->getOpcode() == ISD::SRA ||
4276 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4278 // NEON uses the same intrinsics for both left and right shifts. For
4279 // right shifts, the shift amounts are negative, so negate the vector of
4281 EVT ShiftVT = N->getOperand(1).getValueType();
4282 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4283 getZeroVector(ShiftVT, DAG, dl),
4285 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4286 Intrinsic::arm_neon_vshifts :
4287 Intrinsic::arm_neon_vshiftu);
4288 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4289 DAG.getConstant(vshiftInt, MVT::i32),
4290 N->getOperand(0), NegatedCount);
4293 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4294 const ARMSubtarget *ST) {
4295 EVT VT = N->getValueType(0);
4298 // We can get here for a node like i32 = ISD::SHL i32, i64
4302 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4303 "Unknown shift to lower!");
4305 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4306 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4307 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4310 // If we are in thumb mode, we don't have RRX.
4311 if (ST->isThumb1Only()) return SDValue();
4313 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4314 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4315 DAG.getConstant(0, MVT::i32));
4316 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4317 DAG.getConstant(1, MVT::i32));
4319 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4320 // captures the result into a carry flag.
4321 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4322 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4324 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4325 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4327 // Merge the pieces into a single i64 value.
4328 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4331 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4332 SDValue TmpOp0, TmpOp1;
4333 bool Invert = false;
4337 SDValue Op0 = Op.getOperand(0);
4338 SDValue Op1 = Op.getOperand(1);
4339 SDValue CC = Op.getOperand(2);
4340 EVT VT = Op.getValueType();
4341 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4344 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4345 switch (SetCCOpcode) {
4346 default: llvm_unreachable("Illegal FP comparison");
4348 case ISD::SETNE: Invert = true; // Fallthrough
4350 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4352 case ISD::SETLT: Swap = true; // Fallthrough
4354 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4356 case ISD::SETLE: Swap = true; // Fallthrough
4358 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4359 case ISD::SETUGE: Swap = true; // Fallthrough
4360 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4361 case ISD::SETUGT: Swap = true; // Fallthrough
4362 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4363 case ISD::SETUEQ: Invert = true; // Fallthrough
4365 // Expand this to (OLT | OGT).
4369 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4370 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4372 case ISD::SETUO: Invert = true; // Fallthrough
4374 // Expand this to (OLT | OGE).
4378 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4379 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4383 // Integer comparisons.
4384 switch (SetCCOpcode) {
4385 default: llvm_unreachable("Illegal integer comparison");
4386 case ISD::SETNE: Invert = true;
4387 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4388 case ISD::SETLT: Swap = true;
4389 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4390 case ISD::SETLE: Swap = true;
4391 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4392 case ISD::SETULT: Swap = true;
4393 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4394 case ISD::SETULE: Swap = true;
4395 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4398 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4399 if (Opc == ARMISD::VCEQ) {
4402 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4404 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4407 // Ignore bitconvert.
4408 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4409 AndOp = AndOp.getOperand(0);
4411 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4413 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4414 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4421 std::swap(Op0, Op1);
4423 // If one of the operands is a constant vector zero, attempt to fold the
4424 // comparison to a specialized compare-against-zero form.
4426 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4428 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4429 if (Opc == ARMISD::VCGE)
4430 Opc = ARMISD::VCLEZ;
4431 else if (Opc == ARMISD::VCGT)
4432 Opc = ARMISD::VCLTZ;
4437 if (SingleOp.getNode()) {
4440 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4442 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4444 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4446 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4448 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4450 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4453 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4457 Result = DAG.getNOT(dl, Result, VT);
4462 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4463 /// valid vector constant for a NEON instruction with a "modified immediate"
4464 /// operand (e.g., VMOV). If so, return the encoded value.
4465 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4466 unsigned SplatBitSize, SelectionDAG &DAG,
4467 EVT &VT, bool is128Bits, NEONModImmType type) {
4468 unsigned OpCmode, Imm;
4470 // SplatBitSize is set to the smallest size that splats the vector, so a
4471 // zero vector will always have SplatBitSize == 8. However, NEON modified
4472 // immediate instructions others than VMOV do not support the 8-bit encoding
4473 // of a zero vector, and the default encoding of zero is supposed to be the
4478 switch (SplatBitSize) {
4480 if (type != VMOVModImm)
4482 // Any 1-byte value is OK. Op=0, Cmode=1110.
4483 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4486 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4490 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4491 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4492 if ((SplatBits & ~0xff) == 0) {
4493 // Value = 0x00nn: Op=x, Cmode=100x.
4498 if ((SplatBits & ~0xff00) == 0) {
4499 // Value = 0xnn00: Op=x, Cmode=101x.
4501 Imm = SplatBits >> 8;
4507 // NEON's 32-bit VMOV supports splat values where:
4508 // * only one byte is nonzero, or
4509 // * the least significant byte is 0xff and the second byte is nonzero, or
4510 // * the least significant 2 bytes are 0xff and the third is nonzero.
4511 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4512 if ((SplatBits & ~0xff) == 0) {
4513 // Value = 0x000000nn: Op=x, Cmode=000x.
4518 if ((SplatBits & ~0xff00) == 0) {
4519 // Value = 0x0000nn00: Op=x, Cmode=001x.
4521 Imm = SplatBits >> 8;
4524 if ((SplatBits & ~0xff0000) == 0) {
4525 // Value = 0x00nn0000: Op=x, Cmode=010x.
4527 Imm = SplatBits >> 16;
4530 if ((SplatBits & ~0xff000000) == 0) {
4531 // Value = 0xnn000000: Op=x, Cmode=011x.
4533 Imm = SplatBits >> 24;
4537 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4538 if (type == OtherModImm) return SDValue();
4540 if ((SplatBits & ~0xffff) == 0 &&
4541 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4542 // Value = 0x0000nnff: Op=x, Cmode=1100.
4544 Imm = SplatBits >> 8;
4548 if ((SplatBits & ~0xffffff) == 0 &&
4549 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4550 // Value = 0x00nnffff: Op=x, Cmode=1101.
4552 Imm = SplatBits >> 16;
4556 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4557 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4558 // VMOV.I32. A (very) minor optimization would be to replicate the value
4559 // and fall through here to test for a valid 64-bit splat. But, then the
4560 // caller would also need to check and handle the change in size.
4564 if (type != VMOVModImm)
4566 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4567 uint64_t BitMask = 0xff;
4569 unsigned ImmMask = 1;
4571 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4572 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4575 } else if ((SplatBits & BitMask) != 0) {
4582 if (DAG.getTargetLoweringInfo().isBigEndian())
4583 // swap higher and lower 32 bit word
4584 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4586 // Op=1, Cmode=1110.
4588 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4593 llvm_unreachable("unexpected size for isNEONModifiedImm");
4596 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4597 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4600 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4601 const ARMSubtarget *ST) const {
4605 bool IsDouble = Op.getValueType() == MVT::f64;
4606 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4608 // Try splatting with a VMOV.f32...
4609 APFloat FPVal = CFP->getValueAPF();
4610 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4613 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4614 // We have code in place to select a valid ConstantFP already, no need to
4619 // It's a float and we are trying to use NEON operations where
4620 // possible. Lower it to a splat followed by an extract.
4622 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4623 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4625 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4626 DAG.getConstant(0, MVT::i32));
4629 // The rest of our options are NEON only, make sure that's allowed before
4631 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4635 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4637 // It wouldn't really be worth bothering for doubles except for one very
4638 // important value, which does happen to match: 0.0. So make sure we don't do
4640 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4643 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4644 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4646 if (NewVal != SDValue()) {
4648 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4651 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4653 // It's a float: cast and extract a vector element.
4654 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4656 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4657 DAG.getConstant(0, MVT::i32));
4660 // Finally, try a VMVN.i32
4661 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4663 if (NewVal != SDValue()) {
4665 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4668 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4670 // It's a float: cast and extract a vector element.
4671 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4673 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4674 DAG.getConstant(0, MVT::i32));
4680 // check if an VEXT instruction can handle the shuffle mask when the
4681 // vector sources of the shuffle are the same.
4682 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4683 unsigned NumElts = VT.getVectorNumElements();
4685 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4691 // If this is a VEXT shuffle, the immediate value is the index of the first
4692 // element. The other shuffle indices must be the successive elements after
4694 unsigned ExpectedElt = Imm;
4695 for (unsigned i = 1; i < NumElts; ++i) {
4696 // Increment the expected index. If it wraps around, just follow it
4697 // back to index zero and keep going.
4699 if (ExpectedElt == NumElts)
4702 if (M[i] < 0) continue; // ignore UNDEF indices
4703 if (ExpectedElt != static_cast<unsigned>(M[i]))
4711 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4712 bool &ReverseVEXT, unsigned &Imm) {
4713 unsigned NumElts = VT.getVectorNumElements();
4714 ReverseVEXT = false;
4716 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4722 // If this is a VEXT shuffle, the immediate value is the index of the first
4723 // element. The other shuffle indices must be the successive elements after
4725 unsigned ExpectedElt = Imm;
4726 for (unsigned i = 1; i < NumElts; ++i) {
4727 // Increment the expected index. If it wraps around, it may still be
4728 // a VEXT but the source vectors must be swapped.
4730 if (ExpectedElt == NumElts * 2) {
4735 if (M[i] < 0) continue; // ignore UNDEF indices
4736 if (ExpectedElt != static_cast<unsigned>(M[i]))
4740 // Adjust the index value if the source operands will be swapped.
4747 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4748 /// instruction with the specified blocksize. (The order of the elements
4749 /// within each block of the vector is reversed.)
4750 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4751 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4752 "Only possible block sizes for VREV are: 16, 32, 64");
4754 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4758 unsigned NumElts = VT.getVectorNumElements();
4759 unsigned BlockElts = M[0] + 1;
4760 // If the first shuffle index is UNDEF, be optimistic.
4762 BlockElts = BlockSize / EltSz;
4764 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4767 for (unsigned i = 0; i < NumElts; ++i) {
4768 if (M[i] < 0) continue; // ignore UNDEF indices
4769 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4776 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4777 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4778 // range, then 0 is placed into the resulting vector. So pretty much any mask
4779 // of 8 elements can work here.
4780 return VT == MVT::v8i8 && M.size() == 8;
4783 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4784 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4788 unsigned NumElts = VT.getVectorNumElements();
4789 WhichResult = (M[0] == 0 ? 0 : 1);
4790 for (unsigned i = 0; i < NumElts; i += 2) {
4791 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4792 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4798 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4799 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4800 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4801 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4802 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4806 unsigned NumElts = VT.getVectorNumElements();
4807 WhichResult = (M[0] == 0 ? 0 : 1);
4808 for (unsigned i = 0; i < NumElts; i += 2) {
4809 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4810 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4816 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4817 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4821 unsigned NumElts = VT.getVectorNumElements();
4822 WhichResult = (M[0] == 0 ? 0 : 1);
4823 for (unsigned i = 0; i != NumElts; ++i) {
4824 if (M[i] < 0) continue; // ignore UNDEF indices
4825 if ((unsigned) M[i] != 2 * i + WhichResult)
4829 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4830 if (VT.is64BitVector() && EltSz == 32)
4836 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4837 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4838 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4839 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4840 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4844 unsigned Half = VT.getVectorNumElements() / 2;
4845 WhichResult = (M[0] == 0 ? 0 : 1);
4846 for (unsigned j = 0; j != 2; ++j) {
4847 unsigned Idx = WhichResult;
4848 for (unsigned i = 0; i != Half; ++i) {
4849 int MIdx = M[i + j * Half];
4850 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4856 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4857 if (VT.is64BitVector() && EltSz == 32)
4863 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4864 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4868 unsigned NumElts = VT.getVectorNumElements();
4869 WhichResult = (M[0] == 0 ? 0 : 1);
4870 unsigned Idx = WhichResult * NumElts / 2;
4871 for (unsigned i = 0; i != NumElts; i += 2) {
4872 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4873 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4878 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4879 if (VT.is64BitVector() && EltSz == 32)
4885 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4886 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4887 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4888 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4889 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4893 unsigned NumElts = VT.getVectorNumElements();
4894 WhichResult = (M[0] == 0 ? 0 : 1);
4895 unsigned Idx = WhichResult * NumElts / 2;
4896 for (unsigned i = 0; i != NumElts; i += 2) {
4897 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4898 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4903 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4904 if (VT.is64BitVector() && EltSz == 32)
4910 /// \return true if this is a reverse operation on an vector.
4911 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4912 unsigned NumElts = VT.getVectorNumElements();
4913 // Make sure the mask has the right size.
4914 if (NumElts != M.size())
4917 // Look for <15, ..., 3, -1, 1, 0>.
4918 for (unsigned i = 0; i != NumElts; ++i)
4919 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4925 // If N is an integer constant that can be moved into a register in one
4926 // instruction, return an SDValue of such a constant (will become a MOV
4927 // instruction). Otherwise return null.
4928 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4929 const ARMSubtarget *ST, SDLoc dl) {
4931 if (!isa<ConstantSDNode>(N))
4933 Val = cast<ConstantSDNode>(N)->getZExtValue();
4935 if (ST->isThumb1Only()) {
4936 if (Val <= 255 || ~Val <= 255)
4937 return DAG.getConstant(Val, MVT::i32);
4939 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4940 return DAG.getConstant(Val, MVT::i32);
4945 // If this is a case we can't handle, return null and let the default
4946 // expansion code take care of it.
4947 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4948 const ARMSubtarget *ST) const {
4949 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4951 EVT VT = Op.getValueType();
4953 APInt SplatBits, SplatUndef;
4954 unsigned SplatBitSize;
4956 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4957 if (SplatBitSize <= 64) {
4958 // Check if an immediate VMOV works.
4960 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4961 SplatUndef.getZExtValue(), SplatBitSize,
4962 DAG, VmovVT, VT.is128BitVector(),
4964 if (Val.getNode()) {
4965 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4966 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4969 // Try an immediate VMVN.
4970 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4971 Val = isNEONModifiedImm(NegatedImm,
4972 SplatUndef.getZExtValue(), SplatBitSize,
4973 DAG, VmovVT, VT.is128BitVector(),
4975 if (Val.getNode()) {
4976 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4977 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4980 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4981 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4982 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4984 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4985 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4991 // Scan through the operands to see if only one value is used.
4993 // As an optimisation, even if more than one value is used it may be more
4994 // profitable to splat with one value then change some lanes.
4996 // Heuristically we decide to do this if the vector has a "dominant" value,
4997 // defined as splatted to more than half of the lanes.
4998 unsigned NumElts = VT.getVectorNumElements();
4999 bool isOnlyLowElement = true;
5000 bool usesOnlyOneValue = true;
5001 bool hasDominantValue = false;
5002 bool isConstant = true;
5004 // Map of the number of times a particular SDValue appears in the
5006 DenseMap<SDValue, unsigned> ValueCounts;
5008 for (unsigned i = 0; i < NumElts; ++i) {
5009 SDValue V = Op.getOperand(i);
5010 if (V.getOpcode() == ISD::UNDEF)
5013 isOnlyLowElement = false;
5014 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5017 ValueCounts.insert(std::make_pair(V, 0));
5018 unsigned &Count = ValueCounts[V];
5020 // Is this value dominant? (takes up more than half of the lanes)
5021 if (++Count > (NumElts / 2)) {
5022 hasDominantValue = true;
5026 if (ValueCounts.size() != 1)
5027 usesOnlyOneValue = false;
5028 if (!Value.getNode() && ValueCounts.size() > 0)
5029 Value = ValueCounts.begin()->first;
5031 if (ValueCounts.size() == 0)
5032 return DAG.getUNDEF(VT);
5034 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5035 // Keep going if we are hitting this case.
5036 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5037 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5039 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5041 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5042 // i32 and try again.
5043 if (hasDominantValue && EltSize <= 32) {
5047 // If we are VDUPing a value that comes directly from a vector, that will
5048 // cause an unnecessary move to and from a GPR, where instead we could
5049 // just use VDUPLANE. We can only do this if the lane being extracted
5050 // is at a constant index, as the VDUP from lane instructions only have
5051 // constant-index forms.
5052 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5053 isa<ConstantSDNode>(Value->getOperand(1))) {
5054 // We need to create a new undef vector to use for the VDUPLANE if the
5055 // size of the vector from which we get the value is different than the
5056 // size of the vector that we need to create. We will insert the element
5057 // such that the register coalescer will remove unnecessary copies.
5058 if (VT != Value->getOperand(0).getValueType()) {
5059 ConstantSDNode *constIndex;
5060 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5061 assert(constIndex && "The index is not a constant!");
5062 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5063 VT.getVectorNumElements();
5064 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5065 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5066 Value, DAG.getConstant(index, MVT::i32)),
5067 DAG.getConstant(index, MVT::i32));
5069 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5070 Value->getOperand(0), Value->getOperand(1));
5072 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5074 if (!usesOnlyOneValue) {
5075 // The dominant value was splatted as 'N', but we now have to insert
5076 // all differing elements.
5077 for (unsigned I = 0; I < NumElts; ++I) {
5078 if (Op.getOperand(I) == Value)
5080 SmallVector<SDValue, 3> Ops;
5082 Ops.push_back(Op.getOperand(I));
5083 Ops.push_back(DAG.getConstant(I, MVT::i32));
5084 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5089 if (VT.getVectorElementType().isFloatingPoint()) {
5090 SmallVector<SDValue, 8> Ops;
5091 for (unsigned i = 0; i < NumElts; ++i)
5092 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5094 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5095 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5096 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5098 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5100 if (usesOnlyOneValue) {
5101 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5102 if (isConstant && Val.getNode())
5103 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5107 // If all elements are constants and the case above didn't get hit, fall back
5108 // to the default expansion, which will generate a load from the constant
5113 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5115 SDValue shuffle = ReconstructShuffle(Op, DAG);
5116 if (shuffle != SDValue())
5120 // Vectors with 32- or 64-bit elements can be built by directly assigning
5121 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5122 // will be legalized.
5123 if (EltSize >= 32) {
5124 // Do the expansion with floating-point types, since that is what the VFP
5125 // registers are defined to use, and since i64 is not legal.
5126 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5127 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5128 SmallVector<SDValue, 8> Ops;
5129 for (unsigned i = 0; i < NumElts; ++i)
5130 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5131 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5132 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5135 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5136 // know the default expansion would otherwise fall back on something even
5137 // worse. For a vector with one or two non-undef values, that's
5138 // scalar_to_vector for the elements followed by a shuffle (provided the
5139 // shuffle is valid for the target) and materialization element by element
5140 // on the stack followed by a load for everything else.
5141 if (!isConstant && !usesOnlyOneValue) {
5142 SDValue Vec = DAG.getUNDEF(VT);
5143 for (unsigned i = 0 ; i < NumElts; ++i) {
5144 SDValue V = Op.getOperand(i);
5145 if (V.getOpcode() == ISD::UNDEF)
5147 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5148 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5156 // Gather data to see if the operation can be modelled as a
5157 // shuffle in combination with VEXTs.
5158 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5159 SelectionDAG &DAG) const {
5161 EVT VT = Op.getValueType();
5162 unsigned NumElts = VT.getVectorNumElements();
5164 SmallVector<SDValue, 2> SourceVecs;
5165 SmallVector<unsigned, 2> MinElts;
5166 SmallVector<unsigned, 2> MaxElts;
5168 for (unsigned i = 0; i < NumElts; ++i) {
5169 SDValue V = Op.getOperand(i);
5170 if (V.getOpcode() == ISD::UNDEF)
5172 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5173 // A shuffle can only come from building a vector from various
5174 // elements of other vectors.
5176 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5177 VT.getVectorElementType()) {
5178 // This code doesn't know how to handle shuffles where the vector
5179 // element types do not match (this happens because type legalization
5180 // promotes the return type of EXTRACT_VECTOR_ELT).
5181 // FIXME: It might be appropriate to extend this code to handle
5182 // mismatched types.
5186 // Record this extraction against the appropriate vector if possible...
5187 SDValue SourceVec = V.getOperand(0);
5188 // If the element number isn't a constant, we can't effectively
5189 // analyze what's going on.
5190 if (!isa<ConstantSDNode>(V.getOperand(1)))
5192 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5193 bool FoundSource = false;
5194 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5195 if (SourceVecs[j] == SourceVec) {
5196 if (MinElts[j] > EltNo)
5198 if (MaxElts[j] < EltNo)
5205 // Or record a new source if not...
5207 SourceVecs.push_back(SourceVec);
5208 MinElts.push_back(EltNo);
5209 MaxElts.push_back(EltNo);
5213 // Currently only do something sane when at most two source vectors
5215 if (SourceVecs.size() > 2)
5218 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5219 int VEXTOffsets[2] = {0, 0};
5221 // This loop extracts the usage patterns of the source vectors
5222 // and prepares appropriate SDValues for a shuffle if possible.
5223 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5224 if (SourceVecs[i].getValueType() == VT) {
5225 // No VEXT necessary
5226 ShuffleSrcs[i] = SourceVecs[i];
5229 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5230 // It probably isn't worth padding out a smaller vector just to
5231 // break it down again in a shuffle.
5235 // Since only 64-bit and 128-bit vectors are legal on ARM and
5236 // we've eliminated the other cases...
5237 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5238 "unexpected vector sizes in ReconstructShuffle");
5240 if (MaxElts[i] - MinElts[i] >= NumElts) {
5241 // Span too large for a VEXT to cope
5245 if (MinElts[i] >= NumElts) {
5246 // The extraction can just take the second half
5247 VEXTOffsets[i] = NumElts;
5248 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5250 DAG.getIntPtrConstant(NumElts));
5251 } else if (MaxElts[i] < NumElts) {
5252 // The extraction can just take the first half
5254 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5256 DAG.getIntPtrConstant(0));
5258 // An actual VEXT is needed
5259 VEXTOffsets[i] = MinElts[i];
5260 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5262 DAG.getIntPtrConstant(0));
5263 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5265 DAG.getIntPtrConstant(NumElts));
5266 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5267 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5271 SmallVector<int, 8> Mask;
5273 for (unsigned i = 0; i < NumElts; ++i) {
5274 SDValue Entry = Op.getOperand(i);
5275 if (Entry.getOpcode() == ISD::UNDEF) {
5280 SDValue ExtractVec = Entry.getOperand(0);
5281 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5282 .getOperand(1))->getSExtValue();
5283 if (ExtractVec == SourceVecs[0]) {
5284 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5286 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5290 // Final check before we try to produce nonsense...
5291 if (isShuffleMaskLegal(Mask, VT))
5292 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5298 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5299 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5300 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5301 /// are assumed to be legal.
5303 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5305 if (VT.getVectorNumElements() == 4 &&
5306 (VT.is128BitVector() || VT.is64BitVector())) {
5307 unsigned PFIndexes[4];
5308 for (unsigned i = 0; i != 4; ++i) {
5312 PFIndexes[i] = M[i];
5315 // Compute the index in the perfect shuffle table.
5316 unsigned PFTableIndex =
5317 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5318 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5319 unsigned Cost = (PFEntry >> 30);
5326 unsigned Imm, WhichResult;
5328 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5329 return (EltSize >= 32 ||
5330 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5331 isVREVMask(M, VT, 64) ||
5332 isVREVMask(M, VT, 32) ||
5333 isVREVMask(M, VT, 16) ||
5334 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5335 isVTBLMask(M, VT) ||
5336 isVTRNMask(M, VT, WhichResult) ||
5337 isVUZPMask(M, VT, WhichResult) ||
5338 isVZIPMask(M, VT, WhichResult) ||
5339 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5340 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5341 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5342 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5345 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5346 /// the specified operations to build the shuffle.
5347 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5348 SDValue RHS, SelectionDAG &DAG,
5350 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5351 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5352 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5355 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5364 OP_VUZPL, // VUZP, left result
5365 OP_VUZPR, // VUZP, right result
5366 OP_VZIPL, // VZIP, left result
5367 OP_VZIPR, // VZIP, right result
5368 OP_VTRNL, // VTRN, left result
5369 OP_VTRNR // VTRN, right result
5372 if (OpNum == OP_COPY) {
5373 if (LHSID == (1*9+2)*9+3) return LHS;
5374 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5378 SDValue OpLHS, OpRHS;
5379 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5380 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5381 EVT VT = OpLHS.getValueType();
5384 default: llvm_unreachable("Unknown shuffle opcode!");
5386 // VREV divides the vector in half and swaps within the half.
5387 if (VT.getVectorElementType() == MVT::i32 ||
5388 VT.getVectorElementType() == MVT::f32)
5389 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5390 // vrev <4 x i16> -> VREV32
5391 if (VT.getVectorElementType() == MVT::i16)
5392 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5393 // vrev <4 x i8> -> VREV16
5394 assert(VT.getVectorElementType() == MVT::i8);
5395 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5400 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5401 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5405 return DAG.getNode(ARMISD::VEXT, dl, VT,
5407 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5410 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5411 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5414 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5415 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5418 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5419 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5423 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5424 ArrayRef<int> ShuffleMask,
5425 SelectionDAG &DAG) {
5426 // Check to see if we can use the VTBL instruction.
5427 SDValue V1 = Op.getOperand(0);
5428 SDValue V2 = Op.getOperand(1);
5431 SmallVector<SDValue, 8> VTBLMask;
5432 for (ArrayRef<int>::iterator
5433 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5434 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5436 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5437 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5438 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5440 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5441 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5444 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5445 SelectionDAG &DAG) {
5447 SDValue OpLHS = Op.getOperand(0);
5448 EVT VT = OpLHS.getValueType();
5450 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5451 "Expect an v8i16/v16i8 type");
5452 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5453 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5454 // extract the first 8 bytes into the top double word and the last 8 bytes
5455 // into the bottom double word. The v8i16 case is similar.
5456 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5457 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5458 DAG.getConstant(ExtractNum, MVT::i32));
5461 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5462 SDValue V1 = Op.getOperand(0);
5463 SDValue V2 = Op.getOperand(1);
5465 EVT VT = Op.getValueType();
5466 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5468 // Convert shuffles that are directly supported on NEON to target-specific
5469 // DAG nodes, instead of keeping them as shuffles and matching them again
5470 // during code selection. This is more efficient and avoids the possibility
5471 // of inconsistencies between legalization and selection.
5472 // FIXME: floating-point vectors should be canonicalized to integer vectors
5473 // of the same time so that they get CSEd properly.
5474 ArrayRef<int> ShuffleMask = SVN->getMask();
5476 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5477 if (EltSize <= 32) {
5478 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5479 int Lane = SVN->getSplatIndex();
5480 // If this is undef splat, generate it via "just" vdup, if possible.
5481 if (Lane == -1) Lane = 0;
5483 // Test if V1 is a SCALAR_TO_VECTOR.
5484 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5485 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5487 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5488 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5490 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5491 !isa<ConstantSDNode>(V1.getOperand(0))) {
5492 bool IsScalarToVector = true;
5493 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5494 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5495 IsScalarToVector = false;
5498 if (IsScalarToVector)
5499 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5501 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5502 DAG.getConstant(Lane, MVT::i32));
5507 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5510 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5511 DAG.getConstant(Imm, MVT::i32));
5514 if (isVREVMask(ShuffleMask, VT, 64))
5515 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5516 if (isVREVMask(ShuffleMask, VT, 32))
5517 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5518 if (isVREVMask(ShuffleMask, VT, 16))
5519 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5521 if (V2->getOpcode() == ISD::UNDEF &&
5522 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5523 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5524 DAG.getConstant(Imm, MVT::i32));
5527 // Check for Neon shuffles that modify both input vectors in place.
5528 // If both results are used, i.e., if there are two shuffles with the same
5529 // source operands and with masks corresponding to both results of one of
5530 // these operations, DAG memoization will ensure that a single node is
5531 // used for both shuffles.
5532 unsigned WhichResult;
5533 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5534 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5535 V1, V2).getValue(WhichResult);
5536 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5537 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5538 V1, V2).getValue(WhichResult);
5539 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5540 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5541 V1, V2).getValue(WhichResult);
5543 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5544 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5545 V1, V1).getValue(WhichResult);
5546 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5547 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5548 V1, V1).getValue(WhichResult);
5549 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5550 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5551 V1, V1).getValue(WhichResult);
5554 // If the shuffle is not directly supported and it has 4 elements, use
5555 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5556 unsigned NumElts = VT.getVectorNumElements();
5558 unsigned PFIndexes[4];
5559 for (unsigned i = 0; i != 4; ++i) {
5560 if (ShuffleMask[i] < 0)
5563 PFIndexes[i] = ShuffleMask[i];
5566 // Compute the index in the perfect shuffle table.
5567 unsigned PFTableIndex =
5568 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5569 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5570 unsigned Cost = (PFEntry >> 30);
5573 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5576 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5577 if (EltSize >= 32) {
5578 // Do the expansion with floating-point types, since that is what the VFP
5579 // registers are defined to use, and since i64 is not legal.
5580 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5581 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5582 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5583 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5584 SmallVector<SDValue, 8> Ops;
5585 for (unsigned i = 0; i < NumElts; ++i) {
5586 if (ShuffleMask[i] < 0)
5587 Ops.push_back(DAG.getUNDEF(EltVT));
5589 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5590 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5591 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5594 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5595 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5598 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5599 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5601 if (VT == MVT::v8i8) {
5602 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5603 if (NewOp.getNode())
5610 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5611 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5612 SDValue Lane = Op.getOperand(2);
5613 if (!isa<ConstantSDNode>(Lane))
5619 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5620 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5621 SDValue Lane = Op.getOperand(1);
5622 if (!isa<ConstantSDNode>(Lane))
5625 SDValue Vec = Op.getOperand(0);
5626 if (Op.getValueType() == MVT::i32 &&
5627 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5629 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5635 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5636 // The only time a CONCAT_VECTORS operation can have legal types is when
5637 // two 64-bit vectors are concatenated to a 128-bit vector.
5638 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5639 "unexpected CONCAT_VECTORS");
5641 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5642 SDValue Op0 = Op.getOperand(0);
5643 SDValue Op1 = Op.getOperand(1);
5644 if (Op0.getOpcode() != ISD::UNDEF)
5645 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5646 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5647 DAG.getIntPtrConstant(0));
5648 if (Op1.getOpcode() != ISD::UNDEF)
5649 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5650 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5651 DAG.getIntPtrConstant(1));
5652 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5655 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5656 /// element has been zero/sign-extended, depending on the isSigned parameter,
5657 /// from an integer type half its size.
5658 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5660 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5661 EVT VT = N->getValueType(0);
5662 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5663 SDNode *BVN = N->getOperand(0).getNode();
5664 if (BVN->getValueType(0) != MVT::v4i32 ||
5665 BVN->getOpcode() != ISD::BUILD_VECTOR)
5667 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5668 unsigned HiElt = 1 - LoElt;
5669 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5670 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5671 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5672 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5673 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5676 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5677 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5680 if (Hi0->isNullValue() && Hi1->isNullValue())
5686 if (N->getOpcode() != ISD::BUILD_VECTOR)
5689 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5690 SDNode *Elt = N->getOperand(i).getNode();
5691 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5692 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5693 unsigned HalfSize = EltSize / 2;
5695 if (!isIntN(HalfSize, C->getSExtValue()))
5698 if (!isUIntN(HalfSize, C->getZExtValue()))
5709 /// isSignExtended - Check if a node is a vector value that is sign-extended
5710 /// or a constant BUILD_VECTOR with sign-extended elements.
5711 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5712 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5714 if (isExtendedBUILD_VECTOR(N, DAG, true))
5719 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5720 /// or a constant BUILD_VECTOR with zero-extended elements.
5721 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5722 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5724 if (isExtendedBUILD_VECTOR(N, DAG, false))
5729 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5730 if (OrigVT.getSizeInBits() >= 64)
5733 assert(OrigVT.isSimple() && "Expecting a simple value type");
5735 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5736 switch (OrigSimpleTy) {
5737 default: llvm_unreachable("Unexpected Vector Type");
5746 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5747 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5748 /// We insert the required extension here to get the vector to fill a D register.
5749 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5752 unsigned ExtOpcode) {
5753 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5754 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5755 // 64-bits we need to insert a new extension so that it will be 64-bits.
5756 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5757 if (OrigTy.getSizeInBits() >= 64)
5760 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5761 EVT NewVT = getExtensionTo64Bits(OrigTy);
5763 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5766 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5767 /// does not do any sign/zero extension. If the original vector is less
5768 /// than 64 bits, an appropriate extension will be added after the load to
5769 /// reach a total size of 64 bits. We have to add the extension separately
5770 /// because ARM does not have a sign/zero extending load for vectors.
5771 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5772 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5774 // The load already has the right type.
5775 if (ExtendedTy == LD->getMemoryVT())
5776 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5777 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5778 LD->isNonTemporal(), LD->isInvariant(),
5779 LD->getAlignment());
5781 // We need to create a zextload/sextload. We cannot just create a load
5782 // followed by a zext/zext node because LowerMUL is also run during normal
5783 // operation legalization where we can't create illegal types.
5784 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5785 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5786 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5787 LD->isNonTemporal(), LD->getAlignment());
5790 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5791 /// extending load, or BUILD_VECTOR with extended elements, return the
5792 /// unextended value. The unextended vector should be 64 bits so that it can
5793 /// be used as an operand to a VMULL instruction. If the original vector size
5794 /// before extension is less than 64 bits we add a an extension to resize
5795 /// the vector to 64 bits.
5796 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5797 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5798 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5799 N->getOperand(0)->getValueType(0),
5803 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5804 return SkipLoadExtensionForVMULL(LD, DAG);
5806 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5807 // have been legalized as a BITCAST from v4i32.
5808 if (N->getOpcode() == ISD::BITCAST) {
5809 SDNode *BVN = N->getOperand(0).getNode();
5810 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5811 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5812 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5813 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5814 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5816 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5817 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5818 EVT VT = N->getValueType(0);
5819 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5820 unsigned NumElts = VT.getVectorNumElements();
5821 MVT TruncVT = MVT::getIntegerVT(EltSize);
5822 SmallVector<SDValue, 8> Ops;
5823 for (unsigned i = 0; i != NumElts; ++i) {
5824 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5825 const APInt &CInt = C->getAPIntValue();
5826 // Element types smaller than 32 bits are not legal, so use i32 elements.
5827 // The values are implicitly truncated so sext vs. zext doesn't matter.
5828 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5830 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5831 MVT::getVectorVT(TruncVT, NumElts), Ops);
5834 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5835 unsigned Opcode = N->getOpcode();
5836 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5837 SDNode *N0 = N->getOperand(0).getNode();
5838 SDNode *N1 = N->getOperand(1).getNode();
5839 return N0->hasOneUse() && N1->hasOneUse() &&
5840 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5845 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5846 unsigned Opcode = N->getOpcode();
5847 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5848 SDNode *N0 = N->getOperand(0).getNode();
5849 SDNode *N1 = N->getOperand(1).getNode();
5850 return N0->hasOneUse() && N1->hasOneUse() &&
5851 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5856 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5857 // Multiplications are only custom-lowered for 128-bit vectors so that
5858 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5859 EVT VT = Op.getValueType();
5860 assert(VT.is128BitVector() && VT.isInteger() &&
5861 "unexpected type for custom-lowering ISD::MUL");
5862 SDNode *N0 = Op.getOperand(0).getNode();
5863 SDNode *N1 = Op.getOperand(1).getNode();
5864 unsigned NewOpc = 0;
5866 bool isN0SExt = isSignExtended(N0, DAG);
5867 bool isN1SExt = isSignExtended(N1, DAG);
5868 if (isN0SExt && isN1SExt)
5869 NewOpc = ARMISD::VMULLs;
5871 bool isN0ZExt = isZeroExtended(N0, DAG);
5872 bool isN1ZExt = isZeroExtended(N1, DAG);
5873 if (isN0ZExt && isN1ZExt)
5874 NewOpc = ARMISD::VMULLu;
5875 else if (isN1SExt || isN1ZExt) {
5876 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5877 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5878 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5879 NewOpc = ARMISD::VMULLs;
5881 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5882 NewOpc = ARMISD::VMULLu;
5884 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5886 NewOpc = ARMISD::VMULLu;
5892 if (VT == MVT::v2i64)
5893 // Fall through to expand this. It is not legal.
5896 // Other vector multiplications are legal.
5901 // Legalize to a VMULL instruction.
5904 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5906 Op0 = SkipExtensionForVMULL(N0, DAG);
5907 assert(Op0.getValueType().is64BitVector() &&
5908 Op1.getValueType().is64BitVector() &&
5909 "unexpected types for extended operands to VMULL");
5910 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5913 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5914 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5921 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5922 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5923 EVT Op1VT = Op1.getValueType();
5924 return DAG.getNode(N0->getOpcode(), DL, VT,
5925 DAG.getNode(NewOpc, DL, VT,
5926 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5927 DAG.getNode(NewOpc, DL, VT,
5928 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5932 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5934 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5935 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5936 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5937 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5938 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5939 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5940 // Get reciprocal estimate.
5941 // float4 recip = vrecpeq_f32(yf);
5942 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5943 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5944 // Because char has a smaller range than uchar, we can actually get away
5945 // without any newton steps. This requires that we use a weird bias
5946 // of 0xb000, however (again, this has been exhaustively tested).
5947 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5948 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5949 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5950 Y = DAG.getConstant(0xb000, MVT::i32);
5951 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5952 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5953 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5954 // Convert back to short.
5955 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5956 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5961 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5963 // Convert to float.
5964 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5965 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5966 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5967 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5968 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5969 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5971 // Use reciprocal estimate and one refinement step.
5972 // float4 recip = vrecpeq_f32(yf);
5973 // recip *= vrecpsq_f32(yf, recip);
5974 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5975 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5976 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5977 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5979 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5980 // Because short has a smaller range than ushort, we can actually get away
5981 // with only a single newton step. This requires that we use a weird bias
5982 // of 89, however (again, this has been exhaustively tested).
5983 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5984 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5985 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5986 N1 = DAG.getConstant(0x89, MVT::i32);
5987 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5988 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5989 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5990 // Convert back to integer and return.
5991 // return vmovn_s32(vcvt_s32_f32(result));
5992 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5993 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5997 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5998 EVT VT = Op.getValueType();
5999 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6000 "unexpected type for custom-lowering ISD::SDIV");
6003 SDValue N0 = Op.getOperand(0);
6004 SDValue N1 = Op.getOperand(1);
6007 if (VT == MVT::v8i8) {
6008 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6009 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6011 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6012 DAG.getIntPtrConstant(4));
6013 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6014 DAG.getIntPtrConstant(4));
6015 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6016 DAG.getIntPtrConstant(0));
6017 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6018 DAG.getIntPtrConstant(0));
6020 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6021 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6023 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6024 N0 = LowerCONCAT_VECTORS(N0, DAG);
6026 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6029 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6032 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6033 EVT VT = Op.getValueType();
6034 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6035 "unexpected type for custom-lowering ISD::UDIV");
6038 SDValue N0 = Op.getOperand(0);
6039 SDValue N1 = Op.getOperand(1);
6042 if (VT == MVT::v8i8) {
6043 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6044 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6046 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6047 DAG.getIntPtrConstant(4));
6048 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6049 DAG.getIntPtrConstant(4));
6050 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6051 DAG.getIntPtrConstant(0));
6052 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6053 DAG.getIntPtrConstant(0));
6055 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6056 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6058 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6059 N0 = LowerCONCAT_VECTORS(N0, DAG);
6061 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6062 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6067 // v4i16 sdiv ... Convert to float.
6068 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6069 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6070 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6071 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6072 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6073 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6075 // Use reciprocal estimate and two refinement steps.
6076 // float4 recip = vrecpeq_f32(yf);
6077 // recip *= vrecpsq_f32(yf, recip);
6078 // recip *= vrecpsq_f32(yf, recip);
6079 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6080 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6081 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6082 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6084 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6085 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6086 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6088 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6089 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6090 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6091 // and that it will never cause us to return an answer too large).
6092 // float4 result = as_float4(as_int4(xf*recip) + 2);
6093 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6094 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6095 N1 = DAG.getConstant(2, MVT::i32);
6096 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6097 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6098 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6099 // Convert back to integer and return.
6100 // return vmovn_u32(vcvt_s32_f32(result));
6101 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6102 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6106 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6107 EVT VT = Op.getNode()->getValueType(0);
6108 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6111 bool ExtraOp = false;
6112 switch (Op.getOpcode()) {
6113 default: llvm_unreachable("Invalid code");
6114 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6115 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6116 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6117 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6121 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6123 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6124 Op.getOperand(1), Op.getOperand(2));
6127 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6128 assert(Subtarget->isTargetDarwin());
6130 // For iOS, we want to call an alternative entry point: __sincos_stret,
6131 // return values are passed via sret.
6133 SDValue Arg = Op.getOperand(0);
6134 EVT ArgVT = Arg.getValueType();
6135 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6137 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6138 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6140 // Pair of floats / doubles used to pass the result.
6141 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6143 // Create stack object for sret.
6144 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6145 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6146 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6147 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6153 Entry.Ty = RetTy->getPointerTo();
6154 Entry.isSExt = false;
6155 Entry.isZExt = false;
6156 Entry.isSRet = true;
6157 Args.push_back(Entry);
6161 Entry.isSExt = false;
6162 Entry.isZExt = false;
6163 Args.push_back(Entry);
6165 const char *LibcallName = (ArgVT == MVT::f64)
6166 ? "__sincos_stret" : "__sincosf_stret";
6167 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6169 TargetLowering::CallLoweringInfo CLI(DAG);
6170 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6171 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6173 .setDiscardResult();
6175 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6177 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6178 MachinePointerInfo(), false, false, false, 0);
6180 // Address of cos field.
6181 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6182 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6183 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6184 MachinePointerInfo(), false, false, false, 0);
6186 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6187 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6188 LoadSin.getValue(0), LoadCos.getValue(0));
6191 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6192 // Monotonic load/store is legal for all targets
6193 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6196 // Acquire/Release load/store is not legal for targets without a
6197 // dmb or equivalent available.
6201 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6202 SmallVectorImpl<SDValue> &Results,
6204 const ARMSubtarget *Subtarget) {
6206 SDValue Cycles32, OutChain;
6208 if (Subtarget->hasPerfMon()) {
6209 // Under Power Management extensions, the cycle-count is:
6210 // mrc p15, #0, <Rt>, c9, c13, #0
6211 SDValue Ops[] = { N->getOperand(0), // Chain
6212 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6213 DAG.getConstant(15, MVT::i32),
6214 DAG.getConstant(0, MVT::i32),
6215 DAG.getConstant(9, MVT::i32),
6216 DAG.getConstant(13, MVT::i32),
6217 DAG.getConstant(0, MVT::i32)
6220 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6221 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6222 OutChain = Cycles32.getValue(1);
6224 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6225 // there are older ARM CPUs that have implementation-specific ways of
6226 // obtaining this information (FIXME!).
6227 Cycles32 = DAG.getConstant(0, MVT::i32);
6228 OutChain = DAG.getEntryNode();
6232 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6233 Cycles32, DAG.getConstant(0, MVT::i32));
6234 Results.push_back(Cycles64);
6235 Results.push_back(OutChain);
6238 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6239 switch (Op.getOpcode()) {
6240 default: llvm_unreachable("Don't know how to custom lower this!");
6241 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6242 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6243 case ISD::GlobalAddress:
6244 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6245 default: llvm_unreachable("unknown object format");
6247 return LowerGlobalAddressWindows(Op, DAG);
6249 return LowerGlobalAddressELF(Op, DAG);
6251 return LowerGlobalAddressDarwin(Op, DAG);
6253 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6254 case ISD::SELECT: return LowerSELECT(Op, DAG);
6255 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6256 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6257 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6258 case ISD::VASTART: return LowerVASTART(Op, DAG);
6259 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6260 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6261 case ISD::SINT_TO_FP:
6262 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6263 case ISD::FP_TO_SINT:
6264 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6265 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6266 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6267 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6268 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6269 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6270 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6271 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6273 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6276 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6277 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6278 case ISD::SRL_PARTS:
6279 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6280 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6281 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6282 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6283 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6284 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6285 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6286 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6287 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6288 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6289 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6290 case ISD::MUL: return LowerMUL(Op, DAG);
6291 case ISD::SDIV: return LowerSDIV(Op, DAG);
6292 case ISD::UDIV: return LowerUDIV(Op, DAG);
6296 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6301 return LowerXALUO(Op, DAG);
6302 case ISD::ATOMIC_LOAD:
6303 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6304 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6306 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6307 case ISD::DYNAMIC_STACKALLOC:
6308 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6309 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6310 llvm_unreachable("Don't know how to custom lower this!");
6314 /// ReplaceNodeResults - Replace the results of node with an illegal result
6315 /// type with new values built out of custom code.
6316 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6317 SmallVectorImpl<SDValue>&Results,
6318 SelectionDAG &DAG) const {
6320 switch (N->getOpcode()) {
6322 llvm_unreachable("Don't know how to custom expand this!");
6324 Res = ExpandBITCAST(N, DAG);
6328 Res = Expand64BitShift(N, DAG, Subtarget);
6330 case ISD::READCYCLECOUNTER:
6331 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6335 Results.push_back(Res);
6338 //===----------------------------------------------------------------------===//
6339 // ARM Scheduler Hooks
6340 //===----------------------------------------------------------------------===//
6342 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6343 /// registers the function context.
6344 void ARMTargetLowering::
6345 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6346 MachineBasicBlock *DispatchBB, int FI) const {
6347 const TargetInstrInfo *TII =
6348 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6349 DebugLoc dl = MI->getDebugLoc();
6350 MachineFunction *MF = MBB->getParent();
6351 MachineRegisterInfo *MRI = &MF->getRegInfo();
6352 MachineConstantPool *MCP = MF->getConstantPool();
6353 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6354 const Function *F = MF->getFunction();
6356 bool isThumb = Subtarget->isThumb();
6357 bool isThumb2 = Subtarget->isThumb2();
6359 unsigned PCLabelId = AFI->createPICLabelUId();
6360 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6361 ARMConstantPoolValue *CPV =
6362 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6363 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6365 const TargetRegisterClass *TRC = isThumb ?
6366 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6367 (const TargetRegisterClass*)&ARM::GPRRegClass;
6369 // Grab constant pool and fixed stack memory operands.
6370 MachineMemOperand *CPMMO =
6371 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6372 MachineMemOperand::MOLoad, 4, 4);
6374 MachineMemOperand *FIMMOSt =
6375 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6376 MachineMemOperand::MOStore, 4, 4);
6378 // Load the address of the dispatch MBB into the jump buffer.
6380 // Incoming value: jbuf
6381 // ldr.n r5, LCPI1_1
6384 // str r5, [$jbuf, #+4] ; &jbuf[1]
6385 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6386 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6387 .addConstantPoolIndex(CPI)
6388 .addMemOperand(CPMMO));
6389 // Set the low bit because of thumb mode.
6390 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6392 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6393 .addReg(NewVReg1, RegState::Kill)
6395 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6396 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6397 .addReg(NewVReg2, RegState::Kill)
6399 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6400 .addReg(NewVReg3, RegState::Kill)
6402 .addImm(36) // &jbuf[1] :: pc
6403 .addMemOperand(FIMMOSt));
6404 } else if (isThumb) {
6405 // Incoming value: jbuf
6406 // ldr.n r1, LCPI1_4
6410 // add r2, $jbuf, #+4 ; &jbuf[1]
6412 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6413 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6414 .addConstantPoolIndex(CPI)
6415 .addMemOperand(CPMMO));
6416 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6417 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6418 .addReg(NewVReg1, RegState::Kill)
6420 // Set the low bit because of thumb mode.
6421 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6422 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6423 .addReg(ARM::CPSR, RegState::Define)
6425 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6426 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6427 .addReg(ARM::CPSR, RegState::Define)
6428 .addReg(NewVReg2, RegState::Kill)
6429 .addReg(NewVReg3, RegState::Kill));
6430 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6431 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6433 .addImm(36)); // &jbuf[1] :: pc
6434 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6435 .addReg(NewVReg4, RegState::Kill)
6436 .addReg(NewVReg5, RegState::Kill)
6438 .addMemOperand(FIMMOSt));
6440 // Incoming value: jbuf
6443 // str r1, [$jbuf, #+4] ; &jbuf[1]
6444 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6445 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6446 .addConstantPoolIndex(CPI)
6448 .addMemOperand(CPMMO));
6449 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6450 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6451 .addReg(NewVReg1, RegState::Kill)
6452 .addImm(PCLabelId));
6453 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6454 .addReg(NewVReg2, RegState::Kill)
6456 .addImm(36) // &jbuf[1] :: pc
6457 .addMemOperand(FIMMOSt));
6461 MachineBasicBlock *ARMTargetLowering::
6462 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6463 const TargetInstrInfo *TII =
6464 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6465 DebugLoc dl = MI->getDebugLoc();
6466 MachineFunction *MF = MBB->getParent();
6467 MachineRegisterInfo *MRI = &MF->getRegInfo();
6468 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6469 MachineFrameInfo *MFI = MF->getFrameInfo();
6470 int FI = MFI->getFunctionContextIndex();
6472 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6473 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6474 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6476 // Get a mapping of the call site numbers to all of the landing pads they're
6478 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6479 unsigned MaxCSNum = 0;
6480 MachineModuleInfo &MMI = MF->getMMI();
6481 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6483 if (!BB->isLandingPad()) continue;
6485 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6487 for (MachineBasicBlock::iterator
6488 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6489 if (!II->isEHLabel()) continue;
6491 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6492 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6494 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6495 for (SmallVectorImpl<unsigned>::iterator
6496 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6497 CSI != CSE; ++CSI) {
6498 CallSiteNumToLPad[*CSI].push_back(BB);
6499 MaxCSNum = std::max(MaxCSNum, *CSI);
6505 // Get an ordered list of the machine basic blocks for the jump table.
6506 std::vector<MachineBasicBlock*> LPadList;
6507 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6508 LPadList.reserve(CallSiteNumToLPad.size());
6509 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6510 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6511 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6512 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6513 LPadList.push_back(*II);
6514 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6518 assert(!LPadList.empty() &&
6519 "No landing pad destinations for the dispatch jump table!");
6521 // Create the jump table and associated information.
6522 MachineJumpTableInfo *JTI =
6523 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6524 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6525 unsigned UId = AFI->createJumpTableUId();
6526 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6528 // Create the MBBs for the dispatch code.
6530 // Shove the dispatch's address into the return slot in the function context.
6531 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6532 DispatchBB->setIsLandingPad();
6534 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6535 unsigned trap_opcode;
6536 if (Subtarget->isThumb())
6537 trap_opcode = ARM::tTRAP;
6539 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6541 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6542 DispatchBB->addSuccessor(TrapBB);
6544 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6545 DispatchBB->addSuccessor(DispContBB);
6548 MF->insert(MF->end(), DispatchBB);
6549 MF->insert(MF->end(), DispContBB);
6550 MF->insert(MF->end(), TrapBB);
6552 // Insert code into the entry block that creates and registers the function
6554 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6556 MachineMemOperand *FIMMOLd =
6557 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6558 MachineMemOperand::MOLoad |
6559 MachineMemOperand::MOVolatile, 4, 4);
6561 MachineInstrBuilder MIB;
6562 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6564 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6565 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6567 // Add a register mask with no preserved registers. This results in all
6568 // registers being marked as clobbered.
6569 MIB.addRegMask(RI.getNoPreservedMask());
6571 unsigned NumLPads = LPadList.size();
6572 if (Subtarget->isThumb2()) {
6573 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6574 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6577 .addMemOperand(FIMMOLd));
6579 if (NumLPads < 256) {
6580 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6582 .addImm(LPadList.size()));
6584 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6585 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6586 .addImm(NumLPads & 0xFFFF));
6588 unsigned VReg2 = VReg1;
6589 if ((NumLPads & 0xFFFF0000) != 0) {
6590 VReg2 = MRI->createVirtualRegister(TRC);
6591 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6593 .addImm(NumLPads >> 16));
6596 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6601 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6606 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6607 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6608 .addJumpTableIndex(MJTI)
6611 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6614 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6615 .addReg(NewVReg3, RegState::Kill)
6617 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6619 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6620 .addReg(NewVReg4, RegState::Kill)
6622 .addJumpTableIndex(MJTI)
6624 } else if (Subtarget->isThumb()) {
6625 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6626 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6629 .addMemOperand(FIMMOLd));
6631 if (NumLPads < 256) {
6632 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6636 MachineConstantPool *ConstantPool = MF->getConstantPool();
6637 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6638 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6640 // MachineConstantPool wants an explicit alignment.
6641 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6643 Align = getDataLayout()->getTypeAllocSize(C->getType());
6644 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6646 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6647 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6648 .addReg(VReg1, RegState::Define)
6649 .addConstantPoolIndex(Idx));
6650 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6655 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6660 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6661 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6662 .addReg(ARM::CPSR, RegState::Define)
6666 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6667 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6668 .addJumpTableIndex(MJTI)
6671 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6672 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6673 .addReg(ARM::CPSR, RegState::Define)
6674 .addReg(NewVReg2, RegState::Kill)
6677 MachineMemOperand *JTMMOLd =
6678 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6679 MachineMemOperand::MOLoad, 4, 4);
6681 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6682 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6683 .addReg(NewVReg4, RegState::Kill)
6685 .addMemOperand(JTMMOLd));
6687 unsigned NewVReg6 = NewVReg5;
6688 if (RelocM == Reloc::PIC_) {
6689 NewVReg6 = MRI->createVirtualRegister(TRC);
6690 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6691 .addReg(ARM::CPSR, RegState::Define)
6692 .addReg(NewVReg5, RegState::Kill)
6696 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6697 .addReg(NewVReg6, RegState::Kill)
6698 .addJumpTableIndex(MJTI)
6701 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6702 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6705 .addMemOperand(FIMMOLd));
6707 if (NumLPads < 256) {
6708 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6711 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6712 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6713 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6714 .addImm(NumLPads & 0xFFFF));
6716 unsigned VReg2 = VReg1;
6717 if ((NumLPads & 0xFFFF0000) != 0) {
6718 VReg2 = MRI->createVirtualRegister(TRC);
6719 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6721 .addImm(NumLPads >> 16));
6724 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6728 MachineConstantPool *ConstantPool = MF->getConstantPool();
6729 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6730 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6732 // MachineConstantPool wants an explicit alignment.
6733 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6735 Align = getDataLayout()->getTypeAllocSize(C->getType());
6736 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6738 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6739 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6740 .addReg(VReg1, RegState::Define)
6741 .addConstantPoolIndex(Idx)
6743 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6745 .addReg(VReg1, RegState::Kill));
6748 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6753 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6755 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6757 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6758 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6759 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6760 .addJumpTableIndex(MJTI)
6763 MachineMemOperand *JTMMOLd =
6764 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6765 MachineMemOperand::MOLoad, 4, 4);
6766 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6768 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6769 .addReg(NewVReg3, RegState::Kill)
6772 .addMemOperand(JTMMOLd));
6774 if (RelocM == Reloc::PIC_) {
6775 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6776 .addReg(NewVReg5, RegState::Kill)
6778 .addJumpTableIndex(MJTI)
6781 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6782 .addReg(NewVReg5, RegState::Kill)
6783 .addJumpTableIndex(MJTI)
6788 // Add the jump table entries as successors to the MBB.
6789 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6790 for (std::vector<MachineBasicBlock*>::iterator
6791 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6792 MachineBasicBlock *CurMBB = *I;
6793 if (SeenMBBs.insert(CurMBB))
6794 DispContBB->addSuccessor(CurMBB);
6797 // N.B. the order the invoke BBs are processed in doesn't matter here.
6798 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6799 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6800 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6801 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6802 MachineBasicBlock *BB = *I;
6804 // Remove the landing pad successor from the invoke block and replace it
6805 // with the new dispatch block.
6806 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6808 while (!Successors.empty()) {
6809 MachineBasicBlock *SMBB = Successors.pop_back_val();
6810 if (SMBB->isLandingPad()) {
6811 BB->removeSuccessor(SMBB);
6812 MBBLPads.push_back(SMBB);
6816 BB->addSuccessor(DispatchBB);
6818 // Find the invoke call and mark all of the callee-saved registers as
6819 // 'implicit defined' so that they're spilled. This prevents code from
6820 // moving instructions to before the EH block, where they will never be
6822 for (MachineBasicBlock::reverse_iterator
6823 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6824 if (!II->isCall()) continue;
6826 DenseMap<unsigned, bool> DefRegs;
6827 for (MachineInstr::mop_iterator
6828 OI = II->operands_begin(), OE = II->operands_end();
6830 if (!OI->isReg()) continue;
6831 DefRegs[OI->getReg()] = true;
6834 MachineInstrBuilder MIB(*MF, &*II);
6836 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6837 unsigned Reg = SavedRegs[i];
6838 if (Subtarget->isThumb2() &&
6839 !ARM::tGPRRegClass.contains(Reg) &&
6840 !ARM::hGPRRegClass.contains(Reg))
6842 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6844 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6847 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6854 // Mark all former landing pads as non-landing pads. The dispatch is the only
6856 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6857 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6858 (*I)->setIsLandingPad(false);
6860 // The instruction is gone now.
6861 MI->eraseFromParent();
6867 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6868 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6869 E = MBB->succ_end(); I != E; ++I)
6872 llvm_unreachable("Expecting a BB with two successors!");
6875 /// Return the load opcode for a given load size. If load size >= 8,
6876 /// neon opcode will be returned.
6877 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6879 return LdSize == 16 ? ARM::VLD1q32wb_fixed
6880 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6882 return LdSize == 4 ? ARM::tLDRi
6883 : LdSize == 2 ? ARM::tLDRHi
6884 : LdSize == 1 ? ARM::tLDRBi : 0;
6886 return LdSize == 4 ? ARM::t2LDR_POST
6887 : LdSize == 2 ? ARM::t2LDRH_POST
6888 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6889 return LdSize == 4 ? ARM::LDR_POST_IMM
6890 : LdSize == 2 ? ARM::LDRH_POST
6891 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6894 /// Return the store opcode for a given store size. If store size >= 8,
6895 /// neon opcode will be returned.
6896 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6898 return StSize == 16 ? ARM::VST1q32wb_fixed
6899 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6901 return StSize == 4 ? ARM::tSTRi
6902 : StSize == 2 ? ARM::tSTRHi
6903 : StSize == 1 ? ARM::tSTRBi : 0;
6905 return StSize == 4 ? ARM::t2STR_POST
6906 : StSize == 2 ? ARM::t2STRH_POST
6907 : StSize == 1 ? ARM::t2STRB_POST : 0;
6908 return StSize == 4 ? ARM::STR_POST_IMM
6909 : StSize == 2 ? ARM::STRH_POST
6910 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6913 /// Emit a post-increment load operation with given size. The instructions
6914 /// will be added to BB at Pos.
6915 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6916 const TargetInstrInfo *TII, DebugLoc dl,
6917 unsigned LdSize, unsigned Data, unsigned AddrIn,
6918 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6919 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6920 assert(LdOpc != 0 && "Should have a load opcode");
6922 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6923 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6925 } else if (IsThumb1) {
6926 // load + update AddrIn
6927 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6928 .addReg(AddrIn).addImm(0));
6929 MachineInstrBuilder MIB =
6930 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6931 MIB = AddDefaultT1CC(MIB);
6932 MIB.addReg(AddrIn).addImm(LdSize);
6933 AddDefaultPred(MIB);
6934 } else if (IsThumb2) {
6935 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6936 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6939 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6940 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6941 .addReg(0).addImm(LdSize));
6945 /// Emit a post-increment store operation with given size. The instructions
6946 /// will be added to BB at Pos.
6947 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6948 const TargetInstrInfo *TII, DebugLoc dl,
6949 unsigned StSize, unsigned Data, unsigned AddrIn,
6950 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6951 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6952 assert(StOpc != 0 && "Should have a store opcode");
6954 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6955 .addReg(AddrIn).addImm(0).addReg(Data));
6956 } else if (IsThumb1) {
6957 // store + update AddrIn
6958 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6959 .addReg(AddrIn).addImm(0));
6960 MachineInstrBuilder MIB =
6961 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6962 MIB = AddDefaultT1CC(MIB);
6963 MIB.addReg(AddrIn).addImm(StSize);
6964 AddDefaultPred(MIB);
6965 } else if (IsThumb2) {
6966 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6967 .addReg(Data).addReg(AddrIn).addImm(StSize));
6969 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6970 .addReg(Data).addReg(AddrIn).addReg(0)
6976 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6977 MachineBasicBlock *BB) const {
6978 // This pseudo instruction has 3 operands: dst, src, size
6979 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6980 // Otherwise, we will generate unrolled scalar copies.
6981 const TargetInstrInfo *TII =
6982 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6983 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6984 MachineFunction::iterator It = BB;
6987 unsigned dest = MI->getOperand(0).getReg();
6988 unsigned src = MI->getOperand(1).getReg();
6989 unsigned SizeVal = MI->getOperand(2).getImm();
6990 unsigned Align = MI->getOperand(3).getImm();
6991 DebugLoc dl = MI->getDebugLoc();
6993 MachineFunction *MF = BB->getParent();
6994 MachineRegisterInfo &MRI = MF->getRegInfo();
6995 unsigned UnitSize = 0;
6996 const TargetRegisterClass *TRC = nullptr;
6997 const TargetRegisterClass *VecTRC = nullptr;
6999 bool IsThumb1 = Subtarget->isThumb1Only();
7000 bool IsThumb2 = Subtarget->isThumb2();
7004 } else if (Align & 2) {
7007 // Check whether we can use NEON instructions.
7008 if (!MF->getFunction()->getAttributes().
7009 hasAttribute(AttributeSet::FunctionIndex,
7010 Attribute::NoImplicitFloat) &&
7011 Subtarget->hasNEON()) {
7012 if ((Align % 16 == 0) && SizeVal >= 16)
7014 else if ((Align % 8 == 0) && SizeVal >= 8)
7017 // Can't use NEON instructions.
7022 // Select the correct opcode and register class for unit size load/store
7023 bool IsNeon = UnitSize >= 8;
7024 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7025 : (const TargetRegisterClass *)&ARM::GPRRegClass;
7027 VecTRC = UnitSize == 16
7028 ? (const TargetRegisterClass *)&ARM::DPairRegClass
7030 ? (const TargetRegisterClass *)&ARM::DPRRegClass
7033 unsigned BytesLeft = SizeVal % UnitSize;
7034 unsigned LoopSize = SizeVal - BytesLeft;
7036 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7037 // Use LDR and STR to copy.
7038 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7039 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7040 unsigned srcIn = src;
7041 unsigned destIn = dest;
7042 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7043 unsigned srcOut = MRI.createVirtualRegister(TRC);
7044 unsigned destOut = MRI.createVirtualRegister(TRC);
7045 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7046 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7047 IsThumb1, IsThumb2);
7048 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7049 IsThumb1, IsThumb2);
7054 // Handle the leftover bytes with LDRB and STRB.
7055 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7056 // [destOut] = STRB_POST(scratch, destIn, 1)
7057 for (unsigned i = 0; i < BytesLeft; i++) {
7058 unsigned srcOut = MRI.createVirtualRegister(TRC);
7059 unsigned destOut = MRI.createVirtualRegister(TRC);
7060 unsigned scratch = MRI.createVirtualRegister(TRC);
7061 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7062 IsThumb1, IsThumb2);
7063 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7064 IsThumb1, IsThumb2);
7068 MI->eraseFromParent(); // The instruction is gone now.
7072 // Expand the pseudo op to a loop.
7075 // movw varEnd, # --> with thumb2
7077 // ldrcp varEnd, idx --> without thumb2
7078 // fallthrough --> loopMBB
7080 // PHI varPhi, varEnd, varLoop
7081 // PHI srcPhi, src, srcLoop
7082 // PHI destPhi, dst, destLoop
7083 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7084 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7085 // subs varLoop, varPhi, #UnitSize
7087 // fallthrough --> exitMBB
7089 // epilogue to handle left-over bytes
7090 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7091 // [destOut] = STRB_POST(scratch, destLoop, 1)
7092 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7093 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7094 MF->insert(It, loopMBB);
7095 MF->insert(It, exitMBB);
7097 // Transfer the remainder of BB and its successor edges to exitMBB.
7098 exitMBB->splice(exitMBB->begin(), BB,
7099 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7100 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7102 // Load an immediate to varEnd.
7103 unsigned varEnd = MRI.createVirtualRegister(TRC);
7105 unsigned Vtmp = varEnd;
7106 if ((LoopSize & 0xFFFF0000) != 0)
7107 Vtmp = MRI.createVirtualRegister(TRC);
7108 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7109 .addImm(LoopSize & 0xFFFF));
7111 if ((LoopSize & 0xFFFF0000) != 0)
7112 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7113 .addReg(Vtmp).addImm(LoopSize >> 16));
7115 MachineConstantPool *ConstantPool = MF->getConstantPool();
7116 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7117 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7119 // MachineConstantPool wants an explicit alignment.
7120 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7122 Align = getDataLayout()->getTypeAllocSize(C->getType());
7123 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7126 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7127 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7129 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7130 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7132 BB->addSuccessor(loopMBB);
7134 // Generate the loop body:
7135 // varPhi = PHI(varLoop, varEnd)
7136 // srcPhi = PHI(srcLoop, src)
7137 // destPhi = PHI(destLoop, dst)
7138 MachineBasicBlock *entryBB = BB;
7140 unsigned varLoop = MRI.createVirtualRegister(TRC);
7141 unsigned varPhi = MRI.createVirtualRegister(TRC);
7142 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7143 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7144 unsigned destLoop = MRI.createVirtualRegister(TRC);
7145 unsigned destPhi = MRI.createVirtualRegister(TRC);
7147 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7148 .addReg(varLoop).addMBB(loopMBB)
7149 .addReg(varEnd).addMBB(entryBB);
7150 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7151 .addReg(srcLoop).addMBB(loopMBB)
7152 .addReg(src).addMBB(entryBB);
7153 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7154 .addReg(destLoop).addMBB(loopMBB)
7155 .addReg(dest).addMBB(entryBB);
7157 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7158 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7159 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7160 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7161 IsThumb1, IsThumb2);
7162 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7163 IsThumb1, IsThumb2);
7165 // Decrement loop variable by UnitSize.
7167 MachineInstrBuilder MIB =
7168 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7169 MIB = AddDefaultT1CC(MIB);
7170 MIB.addReg(varPhi).addImm(UnitSize);
7171 AddDefaultPred(MIB);
7173 MachineInstrBuilder MIB =
7174 BuildMI(*BB, BB->end(), dl,
7175 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7176 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7177 MIB->getOperand(5).setReg(ARM::CPSR);
7178 MIB->getOperand(5).setIsDef(true);
7180 BuildMI(*BB, BB->end(), dl,
7181 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7182 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7184 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7185 BB->addSuccessor(loopMBB);
7186 BB->addSuccessor(exitMBB);
7188 // Add epilogue to handle BytesLeft.
7190 MachineInstr *StartOfExit = exitMBB->begin();
7192 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7193 // [destOut] = STRB_POST(scratch, destLoop, 1)
7194 unsigned srcIn = srcLoop;
7195 unsigned destIn = destLoop;
7196 for (unsigned i = 0; i < BytesLeft; i++) {
7197 unsigned srcOut = MRI.createVirtualRegister(TRC);
7198 unsigned destOut = MRI.createVirtualRegister(TRC);
7199 unsigned scratch = MRI.createVirtualRegister(TRC);
7200 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7201 IsThumb1, IsThumb2);
7202 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7203 IsThumb1, IsThumb2);
7208 MI->eraseFromParent(); // The instruction is gone now.
7213 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7214 MachineBasicBlock *MBB) const {
7215 const TargetMachine &TM = getTargetMachine();
7216 const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
7217 DebugLoc DL = MI->getDebugLoc();
7219 assert(Subtarget->isTargetWindows() &&
7220 "__chkstk is only supported on Windows");
7221 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7223 // __chkstk takes the number of words to allocate on the stack in R4, and
7224 // returns the stack adjustment in number of bytes in R4. This will not
7225 // clober any other registers (other than the obvious lr).
7227 // Although, technically, IP should be considered a register which may be
7228 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7229 // thumb-2 environment, so there is no interworking required. As a result, we
7230 // do not expect a veneer to be emitted by the linker, clobbering IP.
7232 // Each module receives its own copy of __chkstk, so no import thunk is
7233 // required, again, ensuring that IP is not clobbered.
7235 // Finally, although some linkers may theoretically provide a trampoline for
7236 // out of range calls (which is quite common due to a 32M range limitation of
7237 // branches for Thumb), we can generate the long-call version via
7238 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7241 switch (TM.getCodeModel()) {
7242 case CodeModel::Small:
7243 case CodeModel::Medium:
7244 case CodeModel::Default:
7245 case CodeModel::Kernel:
7246 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7247 .addImm((unsigned)ARMCC::AL).addReg(0)
7248 .addExternalSymbol("__chkstk")
7249 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7250 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7251 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7253 case CodeModel::Large:
7254 case CodeModel::JITDefault: {
7255 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7256 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7258 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7259 .addExternalSymbol("__chkstk");
7260 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7261 .addImm((unsigned)ARMCC::AL).addReg(0)
7262 .addReg(Reg, RegState::Kill)
7263 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7264 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7265 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7270 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7272 .addReg(ARM::SP).addReg(ARM::R4)));
7274 MI->eraseFromParent();
7279 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7280 MachineBasicBlock *BB) const {
7281 const TargetInstrInfo *TII =
7282 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7283 DebugLoc dl = MI->getDebugLoc();
7284 bool isThumb2 = Subtarget->isThumb2();
7285 switch (MI->getOpcode()) {
7288 llvm_unreachable("Unexpected instr type to insert");
7290 // The Thumb2 pre-indexed stores have the same MI operands, they just
7291 // define them differently in the .td files from the isel patterns, so
7292 // they need pseudos.
7293 case ARM::t2STR_preidx:
7294 MI->setDesc(TII->get(ARM::t2STR_PRE));
7296 case ARM::t2STRB_preidx:
7297 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7299 case ARM::t2STRH_preidx:
7300 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7303 case ARM::STRi_preidx:
7304 case ARM::STRBi_preidx: {
7305 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7306 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7307 // Decode the offset.
7308 unsigned Offset = MI->getOperand(4).getImm();
7309 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7310 Offset = ARM_AM::getAM2Offset(Offset);
7314 MachineMemOperand *MMO = *MI->memoperands_begin();
7315 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7316 .addOperand(MI->getOperand(0)) // Rn_wb
7317 .addOperand(MI->getOperand(1)) // Rt
7318 .addOperand(MI->getOperand(2)) // Rn
7319 .addImm(Offset) // offset (skip GPR==zero_reg)
7320 .addOperand(MI->getOperand(5)) // pred
7321 .addOperand(MI->getOperand(6))
7322 .addMemOperand(MMO);
7323 MI->eraseFromParent();
7326 case ARM::STRr_preidx:
7327 case ARM::STRBr_preidx:
7328 case ARM::STRH_preidx: {
7330 switch (MI->getOpcode()) {
7331 default: llvm_unreachable("unexpected opcode!");
7332 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7333 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7334 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7336 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7337 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7338 MIB.addOperand(MI->getOperand(i));
7339 MI->eraseFromParent();
7343 case ARM::tMOVCCr_pseudo: {
7344 // To "insert" a SELECT_CC instruction, we actually have to insert the
7345 // diamond control-flow pattern. The incoming instruction knows the
7346 // destination vreg to set, the condition code register to branch on, the
7347 // true/false values to select between, and a branch opcode to use.
7348 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7349 MachineFunction::iterator It = BB;
7355 // cmpTY ccX, r1, r2
7357 // fallthrough --> copy0MBB
7358 MachineBasicBlock *thisMBB = BB;
7359 MachineFunction *F = BB->getParent();
7360 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7361 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7362 F->insert(It, copy0MBB);
7363 F->insert(It, sinkMBB);
7365 // Transfer the remainder of BB and its successor edges to sinkMBB.
7366 sinkMBB->splice(sinkMBB->begin(), BB,
7367 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7368 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7370 BB->addSuccessor(copy0MBB);
7371 BB->addSuccessor(sinkMBB);
7373 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7374 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7377 // %FalseValue = ...
7378 // # fallthrough to sinkMBB
7381 // Update machine-CFG edges
7382 BB->addSuccessor(sinkMBB);
7385 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7388 BuildMI(*BB, BB->begin(), dl,
7389 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7390 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7391 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7393 MI->eraseFromParent(); // The pseudo instruction is gone now.
7398 case ARM::BCCZi64: {
7399 // If there is an unconditional branch to the other successor, remove it.
7400 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7402 // Compare both parts that make up the double comparison separately for
7404 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7406 unsigned LHS1 = MI->getOperand(1).getReg();
7407 unsigned LHS2 = MI->getOperand(2).getReg();
7409 AddDefaultPred(BuildMI(BB, dl,
7410 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7411 .addReg(LHS1).addImm(0));
7412 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7413 .addReg(LHS2).addImm(0)
7414 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7416 unsigned RHS1 = MI->getOperand(3).getReg();
7417 unsigned RHS2 = MI->getOperand(4).getReg();
7418 AddDefaultPred(BuildMI(BB, dl,
7419 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7420 .addReg(LHS1).addReg(RHS1));
7421 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7422 .addReg(LHS2).addReg(RHS2)
7423 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7426 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7427 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7428 if (MI->getOperand(0).getImm() == ARMCC::NE)
7429 std::swap(destMBB, exitMBB);
7431 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7432 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7434 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7436 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7438 MI->eraseFromParent(); // The pseudo instruction is gone now.
7442 case ARM::Int_eh_sjlj_setjmp:
7443 case ARM::Int_eh_sjlj_setjmp_nofp:
7444 case ARM::tInt_eh_sjlj_setjmp:
7445 case ARM::t2Int_eh_sjlj_setjmp:
7446 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7447 EmitSjLjDispatchBlock(MI, BB);
7452 // To insert an ABS instruction, we have to insert the
7453 // diamond control-flow pattern. The incoming instruction knows the
7454 // source vreg to test against 0, the destination vreg to set,
7455 // the condition code register to branch on, the
7456 // true/false values to select between, and a branch opcode to use.
7461 // BCC (branch to SinkBB if V0 >= 0)
7462 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7463 // SinkBB: V1 = PHI(V2, V3)
7464 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7465 MachineFunction::iterator BBI = BB;
7467 MachineFunction *Fn = BB->getParent();
7468 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7469 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7470 Fn->insert(BBI, RSBBB);
7471 Fn->insert(BBI, SinkBB);
7473 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7474 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7475 bool isThumb2 = Subtarget->isThumb2();
7476 MachineRegisterInfo &MRI = Fn->getRegInfo();
7477 // In Thumb mode S must not be specified if source register is the SP or
7478 // PC and if destination register is the SP, so restrict register class
7479 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7480 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7481 (const TargetRegisterClass*)&ARM::GPRRegClass);
7483 // Transfer the remainder of BB and its successor edges to sinkMBB.
7484 SinkBB->splice(SinkBB->begin(), BB,
7485 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7486 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7488 BB->addSuccessor(RSBBB);
7489 BB->addSuccessor(SinkBB);
7491 // fall through to SinkMBB
7492 RSBBB->addSuccessor(SinkBB);
7494 // insert a cmp at the end of BB
7495 AddDefaultPred(BuildMI(BB, dl,
7496 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7497 .addReg(ABSSrcReg).addImm(0));
7499 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7501 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7502 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7504 // insert rsbri in RSBBB
7505 // Note: BCC and rsbri will be converted into predicated rsbmi
7506 // by if-conversion pass
7507 BuildMI(*RSBBB, RSBBB->begin(), dl,
7508 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7509 .addReg(ABSSrcReg, RegState::Kill)
7510 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7512 // insert PHI in SinkBB,
7513 // reuse ABSDstReg to not change uses of ABS instruction
7514 BuildMI(*SinkBB, SinkBB->begin(), dl,
7515 TII->get(ARM::PHI), ABSDstReg)
7516 .addReg(NewRsbDstReg).addMBB(RSBBB)
7517 .addReg(ABSSrcReg).addMBB(BB);
7519 // remove ABS instruction
7520 MI->eraseFromParent();
7522 // return last added BB
7525 case ARM::COPY_STRUCT_BYVAL_I32:
7527 return EmitStructByval(MI, BB);
7528 case ARM::WIN__CHKSTK:
7529 return EmitLowered__chkstk(MI, BB);
7533 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7534 SDNode *Node) const {
7535 if (!MI->hasPostISelHook()) {
7536 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7537 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7541 const MCInstrDesc *MCID = &MI->getDesc();
7542 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7543 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7544 // operand is still set to noreg. If needed, set the optional operand's
7545 // register to CPSR, and remove the redundant implicit def.
7547 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7549 // Rename pseudo opcodes.
7550 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7552 const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
7553 getTargetMachine().getSubtargetImpl()->getInstrInfo());
7554 MCID = &TII->get(NewOpc);
7556 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7557 "converted opcode should be the same except for cc_out");
7561 // Add the optional cc_out operand
7562 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7564 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7566 // Any ARM instruction that sets the 's' bit should specify an optional
7567 // "cc_out" operand in the last operand position.
7568 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7569 assert(!NewOpc && "Optional cc_out operand required");
7572 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7573 // since we already have an optional CPSR def.
7574 bool definesCPSR = false;
7575 bool deadCPSR = false;
7576 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7578 const MachineOperand &MO = MI->getOperand(i);
7579 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7583 MI->RemoveOperand(i);
7588 assert(!NewOpc && "Optional cc_out operand required");
7591 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7593 assert(!MI->getOperand(ccOutIdx).getReg() &&
7594 "expect uninitialized optional cc_out operand");
7598 // If this instruction was defined with an optional CPSR def and its dag node
7599 // had a live implicit CPSR def, then activate the optional CPSR def.
7600 MachineOperand &MO = MI->getOperand(ccOutIdx);
7601 MO.setReg(ARM::CPSR);
7605 //===----------------------------------------------------------------------===//
7606 // ARM Optimization Hooks
7607 //===----------------------------------------------------------------------===//
7609 // Helper function that checks if N is a null or all ones constant.
7610 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7611 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7614 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7617 // Return true if N is conditionally 0 or all ones.
7618 // Detects these expressions where cc is an i1 value:
7620 // (select cc 0, y) [AllOnes=0]
7621 // (select cc y, 0) [AllOnes=0]
7622 // (zext cc) [AllOnes=0]
7623 // (sext cc) [AllOnes=0/1]
7624 // (select cc -1, y) [AllOnes=1]
7625 // (select cc y, -1) [AllOnes=1]
7627 // Invert is set when N is the null/all ones constant when CC is false.
7628 // OtherOp is set to the alternative value of N.
7629 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7630 SDValue &CC, bool &Invert,
7632 SelectionDAG &DAG) {
7633 switch (N->getOpcode()) {
7634 default: return false;
7636 CC = N->getOperand(0);
7637 SDValue N1 = N->getOperand(1);
7638 SDValue N2 = N->getOperand(2);
7639 if (isZeroOrAllOnes(N1, AllOnes)) {
7644 if (isZeroOrAllOnes(N2, AllOnes)) {
7651 case ISD::ZERO_EXTEND:
7652 // (zext cc) can never be the all ones value.
7656 case ISD::SIGN_EXTEND: {
7657 EVT VT = N->getValueType(0);
7658 CC = N->getOperand(0);
7659 if (CC.getValueType() != MVT::i1)
7663 // When looking for an AllOnes constant, N is an sext, and the 'other'
7665 OtherOp = DAG.getConstant(0, VT);
7666 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7667 // When looking for a 0 constant, N can be zext or sext.
7668 OtherOp = DAG.getConstant(1, VT);
7670 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7676 // Combine a constant select operand into its use:
7678 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7679 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7680 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7681 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7682 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7684 // The transform is rejected if the select doesn't have a constant operand that
7685 // is null, or all ones when AllOnes is set.
7687 // Also recognize sext/zext from i1:
7689 // (add (zext cc), x) -> (select cc (add x, 1), x)
7690 // (add (sext cc), x) -> (select cc (add x, -1), x)
7692 // These transformations eventually create predicated instructions.
7694 // @param N The node to transform.
7695 // @param Slct The N operand that is a select.
7696 // @param OtherOp The other N operand (x above).
7697 // @param DCI Context.
7698 // @param AllOnes Require the select constant to be all ones instead of null.
7699 // @returns The new node, or SDValue() on failure.
7701 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7702 TargetLowering::DAGCombinerInfo &DCI,
7703 bool AllOnes = false) {
7704 SelectionDAG &DAG = DCI.DAG;
7705 EVT VT = N->getValueType(0);
7706 SDValue NonConstantVal;
7709 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7710 NonConstantVal, DAG))
7713 // Slct is now know to be the desired identity constant when CC is true.
7714 SDValue TrueVal = OtherOp;
7715 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7716 OtherOp, NonConstantVal);
7717 // Unless SwapSelectOps says CC should be false.
7719 std::swap(TrueVal, FalseVal);
7721 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7722 CCOp, TrueVal, FalseVal);
7725 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7727 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7728 TargetLowering::DAGCombinerInfo &DCI) {
7729 SDValue N0 = N->getOperand(0);
7730 SDValue N1 = N->getOperand(1);
7731 if (N0.getNode()->hasOneUse()) {
7732 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7733 if (Result.getNode())
7736 if (N1.getNode()->hasOneUse()) {
7737 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7738 if (Result.getNode())
7744 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7745 // (only after legalization).
7746 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7747 TargetLowering::DAGCombinerInfo &DCI,
7748 const ARMSubtarget *Subtarget) {
7750 // Only perform optimization if after legalize, and if NEON is available. We
7751 // also expected both operands to be BUILD_VECTORs.
7752 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7753 || N0.getOpcode() != ISD::BUILD_VECTOR
7754 || N1.getOpcode() != ISD::BUILD_VECTOR)
7757 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7758 EVT VT = N->getValueType(0);
7759 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7762 // Check that the vector operands are of the right form.
7763 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7764 // operands, where N is the size of the formed vector.
7765 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7766 // index such that we have a pair wise add pattern.
7768 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7769 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7771 SDValue Vec = N0->getOperand(0)->getOperand(0);
7772 SDNode *V = Vec.getNode();
7773 unsigned nextIndex = 0;
7775 // For each operands to the ADD which are BUILD_VECTORs,
7776 // check to see if each of their operands are an EXTRACT_VECTOR with
7777 // the same vector and appropriate index.
7778 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7779 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7780 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7782 SDValue ExtVec0 = N0->getOperand(i);
7783 SDValue ExtVec1 = N1->getOperand(i);
7785 // First operand is the vector, verify its the same.
7786 if (V != ExtVec0->getOperand(0).getNode() ||
7787 V != ExtVec1->getOperand(0).getNode())
7790 // Second is the constant, verify its correct.
7791 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7792 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7794 // For the constant, we want to see all the even or all the odd.
7795 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7796 || C1->getZExtValue() != nextIndex+1)
7805 // Create VPADDL node.
7806 SelectionDAG &DAG = DCI.DAG;
7807 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7809 // Build operand list.
7810 SmallVector<SDValue, 8> Ops;
7811 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7812 TLI.getPointerTy()));
7814 // Input is the vector.
7817 // Get widened type and narrowed type.
7819 unsigned numElem = VT.getVectorNumElements();
7821 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7822 switch (inputLaneType.getSimpleVT().SimpleTy) {
7823 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7824 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7825 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7827 llvm_unreachable("Invalid vector element type for padd optimization.");
7830 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7831 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7832 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7835 static SDValue findMUL_LOHI(SDValue V) {
7836 if (V->getOpcode() == ISD::UMUL_LOHI ||
7837 V->getOpcode() == ISD::SMUL_LOHI)
7842 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7843 TargetLowering::DAGCombinerInfo &DCI,
7844 const ARMSubtarget *Subtarget) {
7846 if (Subtarget->isThumb1Only()) return SDValue();
7848 // Only perform the checks after legalize when the pattern is available.
7849 if (DCI.isBeforeLegalize()) return SDValue();
7851 // Look for multiply add opportunities.
7852 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7853 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7854 // a glue link from the first add to the second add.
7855 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7856 // a S/UMLAL instruction.
7859 // \ / \ [no multiline comment]
7865 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7866 SDValue AddcOp0 = AddcNode->getOperand(0);
7867 SDValue AddcOp1 = AddcNode->getOperand(1);
7869 // Check if the two operands are from the same mul_lohi node.
7870 if (AddcOp0.getNode() == AddcOp1.getNode())
7873 assert(AddcNode->getNumValues() == 2 &&
7874 AddcNode->getValueType(0) == MVT::i32 &&
7875 "Expect ADDC with two result values. First: i32");
7877 // Check that we have a glued ADDC node.
7878 if (AddcNode->getValueType(1) != MVT::Glue)
7881 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7882 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7883 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7884 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7885 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7888 // Look for the glued ADDE.
7889 SDNode* AddeNode = AddcNode->getGluedUser();
7893 // Make sure it is really an ADDE.
7894 if (AddeNode->getOpcode() != ISD::ADDE)
7897 assert(AddeNode->getNumOperands() == 3 &&
7898 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7899 "ADDE node has the wrong inputs");
7901 // Check for the triangle shape.
7902 SDValue AddeOp0 = AddeNode->getOperand(0);
7903 SDValue AddeOp1 = AddeNode->getOperand(1);
7905 // Make sure that the ADDE operands are not coming from the same node.
7906 if (AddeOp0.getNode() == AddeOp1.getNode())
7909 // Find the MUL_LOHI node walking up ADDE's operands.
7910 bool IsLeftOperandMUL = false;
7911 SDValue MULOp = findMUL_LOHI(AddeOp0);
7912 if (MULOp == SDValue())
7913 MULOp = findMUL_LOHI(AddeOp1);
7915 IsLeftOperandMUL = true;
7916 if (MULOp == SDValue())
7919 // Figure out the right opcode.
7920 unsigned Opc = MULOp->getOpcode();
7921 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7923 // Figure out the high and low input values to the MLAL node.
7924 SDValue* HiMul = &MULOp;
7925 SDValue* HiAdd = nullptr;
7926 SDValue* LoMul = nullptr;
7927 SDValue* LowAdd = nullptr;
7929 if (IsLeftOperandMUL)
7935 if (AddcOp0->getOpcode() == Opc) {
7939 if (AddcOp1->getOpcode() == Opc) {
7947 if (LoMul->getNode() != HiMul->getNode())
7950 // Create the merged node.
7951 SelectionDAG &DAG = DCI.DAG;
7953 // Build operand list.
7954 SmallVector<SDValue, 8> Ops;
7955 Ops.push_back(LoMul->getOperand(0));
7956 Ops.push_back(LoMul->getOperand(1));
7957 Ops.push_back(*LowAdd);
7958 Ops.push_back(*HiAdd);
7960 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
7961 DAG.getVTList(MVT::i32, MVT::i32), Ops);
7963 // Replace the ADDs' nodes uses by the MLA node's values.
7964 SDValue HiMLALResult(MLALNode.getNode(), 1);
7965 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7967 SDValue LoMLALResult(MLALNode.getNode(), 0);
7968 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7970 // Return original node to notify the driver to stop replacing.
7971 SDValue resNode(AddcNode, 0);
7975 /// PerformADDCCombine - Target-specific dag combine transform from
7976 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7977 static SDValue PerformADDCCombine(SDNode *N,
7978 TargetLowering::DAGCombinerInfo &DCI,
7979 const ARMSubtarget *Subtarget) {
7981 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7985 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7986 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7987 /// called with the default operands, and if that fails, with commuted
7989 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7990 TargetLowering::DAGCombinerInfo &DCI,
7991 const ARMSubtarget *Subtarget){
7993 // Attempt to create vpaddl for this add.
7994 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7995 if (Result.getNode())
7998 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7999 if (N0.getNode()->hasOneUse()) {
8000 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8001 if (Result.getNode()) return Result;
8006 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8008 static SDValue PerformADDCombine(SDNode *N,
8009 TargetLowering::DAGCombinerInfo &DCI,
8010 const ARMSubtarget *Subtarget) {
8011 SDValue N0 = N->getOperand(0);
8012 SDValue N1 = N->getOperand(1);
8014 // First try with the default operand order.
8015 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8016 if (Result.getNode())
8019 // If that didn't work, try again with the operands commuted.
8020 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8023 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8025 static SDValue PerformSUBCombine(SDNode *N,
8026 TargetLowering::DAGCombinerInfo &DCI) {
8027 SDValue N0 = N->getOperand(0);
8028 SDValue N1 = N->getOperand(1);
8030 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8031 if (N1.getNode()->hasOneUse()) {
8032 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8033 if (Result.getNode()) return Result;
8039 /// PerformVMULCombine
8040 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8041 /// special multiplier accumulator forwarding.
8047 // However, for (A + B) * (A + B),
8054 static SDValue PerformVMULCombine(SDNode *N,
8055 TargetLowering::DAGCombinerInfo &DCI,
8056 const ARMSubtarget *Subtarget) {
8057 if (!Subtarget->hasVMLxForwarding())
8060 SelectionDAG &DAG = DCI.DAG;
8061 SDValue N0 = N->getOperand(0);
8062 SDValue N1 = N->getOperand(1);
8063 unsigned Opcode = N0.getOpcode();
8064 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8065 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8066 Opcode = N1.getOpcode();
8067 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8068 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8076 EVT VT = N->getValueType(0);
8078 SDValue N00 = N0->getOperand(0);
8079 SDValue N01 = N0->getOperand(1);
8080 return DAG.getNode(Opcode, DL, VT,
8081 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8082 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8085 static SDValue PerformMULCombine(SDNode *N,
8086 TargetLowering::DAGCombinerInfo &DCI,
8087 const ARMSubtarget *Subtarget) {
8088 SelectionDAG &DAG = DCI.DAG;
8090 if (Subtarget->isThumb1Only())
8093 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8096 EVT VT = N->getValueType(0);
8097 if (VT.is64BitVector() || VT.is128BitVector())
8098 return PerformVMULCombine(N, DCI, Subtarget);
8102 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8106 int64_t MulAmt = C->getSExtValue();
8107 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8109 ShiftAmt = ShiftAmt & (32 - 1);
8110 SDValue V = N->getOperand(0);
8114 MulAmt >>= ShiftAmt;
8117 if (isPowerOf2_32(MulAmt - 1)) {
8118 // (mul x, 2^N + 1) => (add (shl x, N), x)
8119 Res = DAG.getNode(ISD::ADD, DL, VT,
8121 DAG.getNode(ISD::SHL, DL, VT,
8123 DAG.getConstant(Log2_32(MulAmt - 1),
8125 } else if (isPowerOf2_32(MulAmt + 1)) {
8126 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8127 Res = DAG.getNode(ISD::SUB, DL, VT,
8128 DAG.getNode(ISD::SHL, DL, VT,
8130 DAG.getConstant(Log2_32(MulAmt + 1),
8136 uint64_t MulAmtAbs = -MulAmt;
8137 if (isPowerOf2_32(MulAmtAbs + 1)) {
8138 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8139 Res = DAG.getNode(ISD::SUB, DL, VT,
8141 DAG.getNode(ISD::SHL, DL, VT,
8143 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8145 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8146 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8147 Res = DAG.getNode(ISD::ADD, DL, VT,
8149 DAG.getNode(ISD::SHL, DL, VT,
8151 DAG.getConstant(Log2_32(MulAmtAbs-1),
8153 Res = DAG.getNode(ISD::SUB, DL, VT,
8154 DAG.getConstant(0, MVT::i32),Res);
8161 Res = DAG.getNode(ISD::SHL, DL, VT,
8162 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8164 // Do not add new nodes to DAG combiner worklist.
8165 DCI.CombineTo(N, Res, false);
8169 static SDValue PerformANDCombine(SDNode *N,
8170 TargetLowering::DAGCombinerInfo &DCI,
8171 const ARMSubtarget *Subtarget) {
8173 // Attempt to use immediate-form VBIC
8174 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8176 EVT VT = N->getValueType(0);
8177 SelectionDAG &DAG = DCI.DAG;
8179 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8182 APInt SplatBits, SplatUndef;
8183 unsigned SplatBitSize;
8186 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8187 if (SplatBitSize <= 64) {
8189 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8190 SplatUndef.getZExtValue(), SplatBitSize,
8191 DAG, VbicVT, VT.is128BitVector(),
8193 if (Val.getNode()) {
8195 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8196 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8197 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8202 if (!Subtarget->isThumb1Only()) {
8203 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8204 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8205 if (Result.getNode())
8212 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8213 static SDValue PerformORCombine(SDNode *N,
8214 TargetLowering::DAGCombinerInfo &DCI,
8215 const ARMSubtarget *Subtarget) {
8216 // Attempt to use immediate-form VORR
8217 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8219 EVT VT = N->getValueType(0);
8220 SelectionDAG &DAG = DCI.DAG;
8222 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8225 APInt SplatBits, SplatUndef;
8226 unsigned SplatBitSize;
8228 if (BVN && Subtarget->hasNEON() &&
8229 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8230 if (SplatBitSize <= 64) {
8232 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8233 SplatUndef.getZExtValue(), SplatBitSize,
8234 DAG, VorrVT, VT.is128BitVector(),
8236 if (Val.getNode()) {
8238 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8239 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8240 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8245 if (!Subtarget->isThumb1Only()) {
8246 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8247 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8248 if (Result.getNode())
8252 // The code below optimizes (or (and X, Y), Z).
8253 // The AND operand needs to have a single user to make these optimizations
8255 SDValue N0 = N->getOperand(0);
8256 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8258 SDValue N1 = N->getOperand(1);
8260 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8261 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8262 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8264 unsigned SplatBitSize;
8267 APInt SplatBits0, SplatBits1;
8268 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8269 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8270 // Ensure that the second operand of both ands are constants
8271 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8272 HasAnyUndefs) && !HasAnyUndefs) {
8273 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8274 HasAnyUndefs) && !HasAnyUndefs) {
8275 // Ensure that the bit width of the constants are the same and that
8276 // the splat arguments are logical inverses as per the pattern we
8277 // are trying to simplify.
8278 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8279 SplatBits0 == ~SplatBits1) {
8280 // Canonicalize the vector type to make instruction selection
8282 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8283 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8287 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8293 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8296 // BFI is only available on V6T2+
8297 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8301 // 1) or (and A, mask), val => ARMbfi A, val, mask
8302 // iff (val & mask) == val
8304 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8305 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8306 // && mask == ~mask2
8307 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8308 // && ~mask == mask2
8309 // (i.e., copy a bitfield value into another bitfield of the same width)
8314 SDValue N00 = N0.getOperand(0);
8316 // The value and the mask need to be constants so we can verify this is
8317 // actually a bitfield set. If the mask is 0xffff, we can do better
8318 // via a movt instruction, so don't use BFI in that case.
8319 SDValue MaskOp = N0.getOperand(1);
8320 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8323 unsigned Mask = MaskC->getZExtValue();
8327 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8328 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8330 unsigned Val = N1C->getZExtValue();
8331 if ((Val & ~Mask) != Val)
8334 if (ARM::isBitFieldInvertedMask(Mask)) {
8335 Val >>= countTrailingZeros(~Mask);
8337 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8338 DAG.getConstant(Val, MVT::i32),
8339 DAG.getConstant(Mask, MVT::i32));
8341 // Do not add new nodes to DAG combiner worklist.
8342 DCI.CombineTo(N, Res, false);
8345 } else if (N1.getOpcode() == ISD::AND) {
8346 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8347 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8350 unsigned Mask2 = N11C->getZExtValue();
8352 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8354 if (ARM::isBitFieldInvertedMask(Mask) &&
8356 // The pack halfword instruction works better for masks that fit it,
8357 // so use that when it's available.
8358 if (Subtarget->hasT2ExtractPack() &&
8359 (Mask == 0xffff || Mask == 0xffff0000))
8362 unsigned amt = countTrailingZeros(Mask2);
8363 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8364 DAG.getConstant(amt, MVT::i32));
8365 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8366 DAG.getConstant(Mask, MVT::i32));
8367 // Do not add new nodes to DAG combiner worklist.
8368 DCI.CombineTo(N, Res, false);
8370 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8372 // The pack halfword instruction works better for masks that fit it,
8373 // so use that when it's available.
8374 if (Subtarget->hasT2ExtractPack() &&
8375 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8378 unsigned lsb = countTrailingZeros(Mask);
8379 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8380 DAG.getConstant(lsb, MVT::i32));
8381 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8382 DAG.getConstant(Mask2, MVT::i32));
8383 // Do not add new nodes to DAG combiner worklist.
8384 DCI.CombineTo(N, Res, false);
8389 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8390 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8391 ARM::isBitFieldInvertedMask(~Mask)) {
8392 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8393 // where lsb(mask) == #shamt and masked bits of B are known zero.
8394 SDValue ShAmt = N00.getOperand(1);
8395 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8396 unsigned LSB = countTrailingZeros(Mask);
8400 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8401 DAG.getConstant(~Mask, MVT::i32));
8403 // Do not add new nodes to DAG combiner worklist.
8404 DCI.CombineTo(N, Res, false);
8410 static SDValue PerformXORCombine(SDNode *N,
8411 TargetLowering::DAGCombinerInfo &DCI,
8412 const ARMSubtarget *Subtarget) {
8413 EVT VT = N->getValueType(0);
8414 SelectionDAG &DAG = DCI.DAG;
8416 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8419 if (!Subtarget->isThumb1Only()) {
8420 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8421 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8422 if (Result.getNode())
8429 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8430 /// the bits being cleared by the AND are not demanded by the BFI.
8431 static SDValue PerformBFICombine(SDNode *N,
8432 TargetLowering::DAGCombinerInfo &DCI) {
8433 SDValue N1 = N->getOperand(1);
8434 if (N1.getOpcode() == ISD::AND) {
8435 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8438 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8439 unsigned LSB = countTrailingZeros(~InvMask);
8440 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8441 unsigned Mask = (1 << 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 // vmovrrd(vmovdrr x, y) -> x,y
8456 SDValue InDouble = N->getOperand(0);
8457 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8458 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8460 // vmovrrd(load f64) -> (load i32), (load i32)
8461 SDNode *InNode = InDouble.getNode();
8462 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8463 InNode->getValueType(0) == MVT::f64 &&
8464 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8465 !cast<LoadSDNode>(InNode)->isVolatile()) {
8466 // TODO: Should this be done for non-FrameIndex operands?
8467 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8469 SelectionDAG &DAG = DCI.DAG;
8471 SDValue BasePtr = LD->getBasePtr();
8472 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8473 LD->getPointerInfo(), LD->isVolatile(),
8474 LD->isNonTemporal(), LD->isInvariant(),
8475 LD->getAlignment());
8477 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8478 DAG.getConstant(4, MVT::i32));
8479 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8480 LD->getPointerInfo(), LD->isVolatile(),
8481 LD->isNonTemporal(), LD->isInvariant(),
8482 std::min(4U, LD->getAlignment() / 2));
8484 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8485 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8486 std::swap (NewLD1, NewLD2);
8487 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8494 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8495 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8496 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8497 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8498 SDValue Op0 = N->getOperand(0);
8499 SDValue Op1 = N->getOperand(1);
8500 if (Op0.getOpcode() == ISD::BITCAST)
8501 Op0 = Op0.getOperand(0);
8502 if (Op1.getOpcode() == ISD::BITCAST)
8503 Op1 = Op1.getOperand(0);
8504 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8505 Op0.getNode() == Op1.getNode() &&
8506 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8507 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8508 N->getValueType(0), Op0.getOperand(0));
8512 /// PerformSTORECombine - Target-specific dag combine xforms for
8514 static SDValue PerformSTORECombine(SDNode *N,
8515 TargetLowering::DAGCombinerInfo &DCI) {
8516 StoreSDNode *St = cast<StoreSDNode>(N);
8517 if (St->isVolatile())
8520 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8521 // pack all of the elements in one place. Next, store to memory in fewer
8523 SDValue StVal = St->getValue();
8524 EVT VT = StVal.getValueType();
8525 if (St->isTruncatingStore() && VT.isVector()) {
8526 SelectionDAG &DAG = DCI.DAG;
8527 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8528 EVT StVT = St->getMemoryVT();
8529 unsigned NumElems = VT.getVectorNumElements();
8530 assert(StVT != VT && "Cannot truncate to the same type");
8531 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8532 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8534 // From, To sizes and ElemCount must be pow of two
8535 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8537 // We are going to use the original vector elt for storing.
8538 // Accumulated smaller vector elements must be a multiple of the store size.
8539 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8541 unsigned SizeRatio = FromEltSz / ToEltSz;
8542 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8544 // Create a type on which we perform the shuffle.
8545 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8546 NumElems*SizeRatio);
8547 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8550 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8551 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8552 for (unsigned i = 0; i < NumElems; ++i)
8553 ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8555 // Can't shuffle using an illegal type.
8556 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8558 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8559 DAG.getUNDEF(WideVec.getValueType()),
8561 // At this point all of the data is stored at the bottom of the
8562 // register. We now need to save it to mem.
8564 // Find the largest store unit
8565 MVT StoreType = MVT::i8;
8566 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8567 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8568 MVT Tp = (MVT::SimpleValueType)tp;
8569 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8572 // Didn't find a legal store type.
8573 if (!TLI.isTypeLegal(StoreType))
8576 // Bitcast the original vector into a vector of store-size units
8577 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8578 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8579 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8580 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8581 SmallVector<SDValue, 8> Chains;
8582 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8583 TLI.getPointerTy());
8584 SDValue BasePtr = St->getBasePtr();
8586 // Perform one or more big stores into memory.
8587 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8588 for (unsigned I = 0; I < E; I++) {
8589 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8590 StoreType, ShuffWide,
8591 DAG.getIntPtrConstant(I));
8592 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8593 St->getPointerInfo(), St->isVolatile(),
8594 St->isNonTemporal(), St->getAlignment());
8595 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8597 Chains.push_back(Ch);
8599 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8602 if (!ISD::isNormalStore(St))
8605 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8606 // ARM stores of arguments in the same cache line.
8607 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8608 StVal.getNode()->hasOneUse()) {
8609 SelectionDAG &DAG = DCI.DAG;
8610 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8612 SDValue BasePtr = St->getBasePtr();
8613 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8614 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8615 BasePtr, St->getPointerInfo(), St->isVolatile(),
8616 St->isNonTemporal(), St->getAlignment());
8618 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8619 DAG.getConstant(4, MVT::i32));
8620 return DAG.getStore(NewST1.getValue(0), DL,
8621 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8622 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8623 St->isNonTemporal(),
8624 std::min(4U, St->getAlignment() / 2));
8627 if (StVal.getValueType() != MVT::i64 ||
8628 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8631 // Bitcast an i64 store extracted from a vector to f64.
8632 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8633 SelectionDAG &DAG = DCI.DAG;
8635 SDValue IntVec = StVal.getOperand(0);
8636 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8637 IntVec.getValueType().getVectorNumElements());
8638 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8639 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8640 Vec, StVal.getOperand(1));
8642 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8643 // Make the DAGCombiner fold the bitcasts.
8644 DCI.AddToWorklist(Vec.getNode());
8645 DCI.AddToWorklist(ExtElt.getNode());
8646 DCI.AddToWorklist(V.getNode());
8647 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8648 St->getPointerInfo(), St->isVolatile(),
8649 St->isNonTemporal(), St->getAlignment(),
8653 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8654 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8655 /// i64 vector to have f64 elements, since the value can then be loaded
8656 /// directly into a VFP register.
8657 static bool hasNormalLoadOperand(SDNode *N) {
8658 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8659 for (unsigned i = 0; i < NumElts; ++i) {
8660 SDNode *Elt = N->getOperand(i).getNode();
8661 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8667 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8668 /// ISD::BUILD_VECTOR.
8669 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8670 TargetLowering::DAGCombinerInfo &DCI){
8671 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8672 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8673 // into a pair of GPRs, which is fine when the value is used as a scalar,
8674 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8675 SelectionDAG &DAG = DCI.DAG;
8676 if (N->getNumOperands() == 2) {
8677 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8682 // Load i64 elements as f64 values so that type legalization does not split
8683 // them up into i32 values.
8684 EVT VT = N->getValueType(0);
8685 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8688 SmallVector<SDValue, 8> Ops;
8689 unsigned NumElts = VT.getVectorNumElements();
8690 for (unsigned i = 0; i < NumElts; ++i) {
8691 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8693 // Make the DAGCombiner fold the bitcast.
8694 DCI.AddToWorklist(V.getNode());
8696 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8697 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8698 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8701 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8703 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8704 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8705 // At that time, we may have inserted bitcasts from integer to float.
8706 // If these bitcasts have survived DAGCombine, change the lowering of this
8707 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8708 // force to use floating point types.
8710 // Make sure we can change the type of the vector.
8711 // This is possible iff:
8712 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8713 // 1.1. Vector is used only once.
8714 // 1.2. Use is a bit convert to an integer type.
8715 // 2. The size of its operands are 32-bits (64-bits are not legal).
8716 EVT VT = N->getValueType(0);
8717 EVT EltVT = VT.getVectorElementType();
8719 // Check 1.1. and 2.
8720 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8723 // By construction, the input type must be float.
8724 assert(EltVT == MVT::f32 && "Unexpected type!");
8727 SDNode *Use = *N->use_begin();
8728 if (Use->getOpcode() != ISD::BITCAST ||
8729 Use->getValueType(0).isFloatingPoint())
8732 // Check profitability.
8733 // Model is, if more than half of the relevant operands are bitcast from
8734 // i32, turn the build_vector into a sequence of insert_vector_elt.
8735 // Relevant operands are everything that is not statically
8736 // (i.e., at compile time) bitcasted.
8737 unsigned NumOfBitCastedElts = 0;
8738 unsigned NumElts = VT.getVectorNumElements();
8739 unsigned NumOfRelevantElts = NumElts;
8740 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8741 SDValue Elt = N->getOperand(Idx);
8742 if (Elt->getOpcode() == ISD::BITCAST) {
8743 // Assume only bit cast to i32 will go away.
8744 if (Elt->getOperand(0).getValueType() == MVT::i32)
8745 ++NumOfBitCastedElts;
8746 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8747 // Constants are statically casted, thus do not count them as
8748 // relevant operands.
8749 --NumOfRelevantElts;
8752 // Check if more than half of the elements require a non-free bitcast.
8753 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8756 SelectionDAG &DAG = DCI.DAG;
8757 // Create the new vector type.
8758 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8759 // Check if the type is legal.
8760 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8761 if (!TLI.isTypeLegal(VecVT))
8765 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8766 // => BITCAST INSERT_VECTOR_ELT
8767 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8769 SDValue Vec = DAG.getUNDEF(VecVT);
8771 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8772 SDValue V = N->getOperand(Idx);
8773 if (V.getOpcode() == ISD::UNDEF)
8775 if (V.getOpcode() == ISD::BITCAST &&
8776 V->getOperand(0).getValueType() == MVT::i32)
8777 // Fold obvious case.
8778 V = V.getOperand(0);
8780 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8781 // Make the DAGCombiner fold the bitcasts.
8782 DCI.AddToWorklist(V.getNode());
8784 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8785 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8787 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8788 // Make the DAGCombiner fold the bitcasts.
8789 DCI.AddToWorklist(Vec.getNode());
8793 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8794 /// ISD::INSERT_VECTOR_ELT.
8795 static SDValue PerformInsertEltCombine(SDNode *N,
8796 TargetLowering::DAGCombinerInfo &DCI) {
8797 // Bitcast an i64 load inserted into a vector to f64.
8798 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8799 EVT VT = N->getValueType(0);
8800 SDNode *Elt = N->getOperand(1).getNode();
8801 if (VT.getVectorElementType() != MVT::i64 ||
8802 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8805 SelectionDAG &DAG = DCI.DAG;
8807 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8808 VT.getVectorNumElements());
8809 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8810 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8811 // Make the DAGCombiner fold the bitcasts.
8812 DCI.AddToWorklist(Vec.getNode());
8813 DCI.AddToWorklist(V.getNode());
8814 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8815 Vec, V, N->getOperand(2));
8816 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8819 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8820 /// ISD::VECTOR_SHUFFLE.
8821 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8822 // The LLVM shufflevector instruction does not require the shuffle mask
8823 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8824 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8825 // operands do not match the mask length, they are extended by concatenating
8826 // them with undef vectors. That is probably the right thing for other
8827 // targets, but for NEON it is better to concatenate two double-register
8828 // size vector operands into a single quad-register size vector. Do that
8829 // transformation here:
8830 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8831 // shuffle(concat(v1, v2), undef)
8832 SDValue Op0 = N->getOperand(0);
8833 SDValue Op1 = N->getOperand(1);
8834 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8835 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8836 Op0.getNumOperands() != 2 ||
8837 Op1.getNumOperands() != 2)
8839 SDValue Concat0Op1 = Op0.getOperand(1);
8840 SDValue Concat1Op1 = Op1.getOperand(1);
8841 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8842 Concat1Op1.getOpcode() != ISD::UNDEF)
8844 // Skip the transformation if any of the types are illegal.
8845 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8846 EVT VT = N->getValueType(0);
8847 if (!TLI.isTypeLegal(VT) ||
8848 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8849 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8852 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8853 Op0.getOperand(0), Op1.getOperand(0));
8854 // Translate the shuffle mask.
8855 SmallVector<int, 16> NewMask;
8856 unsigned NumElts = VT.getVectorNumElements();
8857 unsigned HalfElts = NumElts/2;
8858 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8859 for (unsigned n = 0; n < NumElts; ++n) {
8860 int MaskElt = SVN->getMaskElt(n);
8862 if (MaskElt < (int)HalfElts)
8864 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8865 NewElt = HalfElts + MaskElt - NumElts;
8866 NewMask.push_back(NewElt);
8868 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8869 DAG.getUNDEF(VT), NewMask.data());
8872 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8873 /// NEON load/store intrinsics to merge base address updates.
8874 static SDValue CombineBaseUpdate(SDNode *N,
8875 TargetLowering::DAGCombinerInfo &DCI) {
8876 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8879 SelectionDAG &DAG = DCI.DAG;
8880 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8881 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8882 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8883 SDValue Addr = N->getOperand(AddrOpIdx);
8885 // Search for a use of the address operand that is an increment.
8886 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8887 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8889 if (User->getOpcode() != ISD::ADD ||
8890 UI.getUse().getResNo() != Addr.getResNo())
8893 // Check that the add is independent of the load/store. Otherwise, folding
8894 // it would create a cycle.
8895 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8898 // Find the new opcode for the updating load/store.
8900 bool isLaneOp = false;
8901 unsigned NewOpc = 0;
8902 unsigned NumVecs = 0;
8904 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8906 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8907 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8909 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8911 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8913 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8915 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8916 NumVecs = 2; isLaneOp = true; break;
8917 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8918 NumVecs = 3; isLaneOp = true; break;
8919 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8920 NumVecs = 4; isLaneOp = true; break;
8921 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8922 NumVecs = 1; isLoad = false; break;
8923 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8924 NumVecs = 2; isLoad = false; break;
8925 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8926 NumVecs = 3; isLoad = false; break;
8927 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8928 NumVecs = 4; isLoad = false; break;
8929 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8930 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8931 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8932 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8933 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8934 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8938 switch (N->getOpcode()) {
8939 default: llvm_unreachable("unexpected opcode for Neon base update");
8940 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8941 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8942 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8946 // Find the size of memory referenced by the load/store.
8949 VecTy = N->getValueType(0);
8951 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8952 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8954 NumBytes /= VecTy.getVectorNumElements();
8956 // If the increment is a constant, it must match the memory ref size.
8957 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8958 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8959 uint64_t IncVal = CInc->getZExtValue();
8960 if (IncVal != NumBytes)
8962 } else if (NumBytes >= 3 * 16) {
8963 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8964 // separate instructions that make it harder to use a non-constant update.
8968 // Create the new updating load/store node.
8970 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8972 for (n = 0; n < NumResultVecs; ++n)
8974 Tys[n++] = MVT::i32;
8975 Tys[n] = MVT::Other;
8976 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8977 SmallVector<SDValue, 8> Ops;
8978 Ops.push_back(N->getOperand(0)); // incoming chain
8979 Ops.push_back(N->getOperand(AddrOpIdx));
8981 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8982 Ops.push_back(N->getOperand(i));
8984 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8985 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8986 Ops, MemInt->getMemoryVT(),
8987 MemInt->getMemOperand());
8990 std::vector<SDValue> NewResults;
8991 for (unsigned i = 0; i < NumResultVecs; ++i) {
8992 NewResults.push_back(SDValue(UpdN.getNode(), i));
8994 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8995 DCI.CombineTo(N, NewResults);
8996 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9003 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9004 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9005 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9007 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9008 SelectionDAG &DAG = DCI.DAG;
9009 EVT VT = N->getValueType(0);
9010 // vldN-dup instructions only support 64-bit vectors for N > 1.
9011 if (!VT.is64BitVector())
9014 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9015 SDNode *VLD = N->getOperand(0).getNode();
9016 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9018 unsigned NumVecs = 0;
9019 unsigned NewOpc = 0;
9020 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9021 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9023 NewOpc = ARMISD::VLD2DUP;
9024 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9026 NewOpc = ARMISD::VLD3DUP;
9027 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9029 NewOpc = ARMISD::VLD4DUP;
9034 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9035 // numbers match the load.
9036 unsigned VLDLaneNo =
9037 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9038 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9040 // Ignore uses of the chain result.
9041 if (UI.getUse().getResNo() == NumVecs)
9044 if (User->getOpcode() != ARMISD::VDUPLANE ||
9045 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9049 // Create the vldN-dup node.
9052 for (n = 0; n < NumVecs; ++n)
9054 Tys[n] = MVT::Other;
9055 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
9056 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9057 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9058 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9059 Ops, VLDMemInt->getMemoryVT(),
9060 VLDMemInt->getMemOperand());
9063 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9065 unsigned ResNo = UI.getUse().getResNo();
9066 // Ignore uses of the chain result.
9067 if (ResNo == NumVecs)
9070 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9073 // Now the vldN-lane intrinsic is dead except for its chain result.
9074 // Update uses of the chain.
9075 std::vector<SDValue> VLDDupResults;
9076 for (unsigned n = 0; n < NumVecs; ++n)
9077 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9078 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9079 DCI.CombineTo(VLD, VLDDupResults);
9084 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9085 /// ARMISD::VDUPLANE.
9086 static SDValue PerformVDUPLANECombine(SDNode *N,
9087 TargetLowering::DAGCombinerInfo &DCI) {
9088 SDValue Op = N->getOperand(0);
9090 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9091 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9092 if (CombineVLDDUP(N, DCI))
9093 return SDValue(N, 0);
9095 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9096 // redundant. Ignore bit_converts for now; element sizes are checked below.
9097 while (Op.getOpcode() == ISD::BITCAST)
9098 Op = Op.getOperand(0);
9099 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9102 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9103 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9104 // The canonical VMOV for a zero vector uses a 32-bit element size.
9105 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9107 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9109 EVT VT = N->getValueType(0);
9110 if (EltSize > VT.getVectorElementType().getSizeInBits())
9113 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9116 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9117 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9118 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9122 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9124 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9129 APFloat APF = C->getValueAPF();
9130 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9131 != APFloat::opOK || !isExact)
9134 c0 = (I == 0) ? cN : c0;
9135 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9142 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9143 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9144 /// when the VMUL has a constant operand that is a power of 2.
9146 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9147 /// vmul.f32 d16, d17, d16
9148 /// vcvt.s32.f32 d16, d16
9150 /// vcvt.s32.f32 d16, d16, #3
9151 static SDValue PerformVCVTCombine(SDNode *N,
9152 TargetLowering::DAGCombinerInfo &DCI,
9153 const ARMSubtarget *Subtarget) {
9154 SelectionDAG &DAG = DCI.DAG;
9155 SDValue Op = N->getOperand(0);
9157 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9158 Op.getOpcode() != ISD::FMUL)
9162 SDValue N0 = Op->getOperand(0);
9163 SDValue ConstVec = Op->getOperand(1);
9164 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9166 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9167 !isConstVecPow2(ConstVec, isSigned, C))
9170 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9171 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9172 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9173 // These instructions only exist converting from f32 to i32. We can handle
9174 // smaller integers by generating an extra truncate, but larger ones would
9179 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9180 Intrinsic::arm_neon_vcvtfp2fxu;
9181 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9182 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9183 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9184 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9185 DAG.getConstant(Log2_64(C), MVT::i32));
9187 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9188 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9193 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9194 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9195 /// when the VDIV has a constant operand that is a power of 2.
9197 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9198 /// vcvt.f32.s32 d16, d16
9199 /// vdiv.f32 d16, d17, d16
9201 /// vcvt.f32.s32 d16, d16, #3
9202 static SDValue PerformVDIVCombine(SDNode *N,
9203 TargetLowering::DAGCombinerInfo &DCI,
9204 const ARMSubtarget *Subtarget) {
9205 SelectionDAG &DAG = DCI.DAG;
9206 SDValue Op = N->getOperand(0);
9207 unsigned OpOpcode = Op.getNode()->getOpcode();
9209 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9210 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9214 SDValue ConstVec = N->getOperand(1);
9215 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9217 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9218 !isConstVecPow2(ConstVec, isSigned, C))
9221 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9222 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9223 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9224 // These instructions only exist converting from i32 to f32. We can handle
9225 // smaller integers by generating an extra extend, but larger ones would
9230 SDValue ConvInput = Op.getOperand(0);
9231 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9232 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9233 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9234 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9237 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9238 Intrinsic::arm_neon_vcvtfxu2fp;
9239 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9241 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9242 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9245 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9246 /// operand of a vector shift operation, where all the elements of the
9247 /// build_vector must have the same constant integer value.
9248 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9249 // Ignore bit_converts.
9250 while (Op.getOpcode() == ISD::BITCAST)
9251 Op = Op.getOperand(0);
9252 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9253 APInt SplatBits, SplatUndef;
9254 unsigned SplatBitSize;
9256 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9257 HasAnyUndefs, ElementBits) ||
9258 SplatBitSize > ElementBits)
9260 Cnt = SplatBits.getSExtValue();
9264 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9265 /// operand of a vector shift left operation. That value must be in the range:
9266 /// 0 <= Value < ElementBits for a left shift; or
9267 /// 0 <= Value <= ElementBits for a long left shift.
9268 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9269 assert(VT.isVector() && "vector shift count is not a vector type");
9270 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9271 if (! getVShiftImm(Op, ElementBits, Cnt))
9273 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9276 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9277 /// operand of a vector shift right operation. For a shift opcode, the value
9278 /// is positive, but for an intrinsic the value count must be negative. The
9279 /// absolute value must be in the range:
9280 /// 1 <= |Value| <= ElementBits for a right shift; or
9281 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9282 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9284 assert(VT.isVector() && "vector shift count is not a vector type");
9285 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9286 if (! getVShiftImm(Op, ElementBits, Cnt))
9290 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9293 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9294 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9295 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9298 // Don't do anything for most intrinsics.
9301 // Vector shifts: check for immediate versions and lower them.
9302 // Note: This is done during DAG combining instead of DAG legalizing because
9303 // the build_vectors for 64-bit vector element shift counts are generally
9304 // not legal, and it is hard to see their values after they get legalized to
9305 // loads from a constant pool.
9306 case Intrinsic::arm_neon_vshifts:
9307 case Intrinsic::arm_neon_vshiftu:
9308 case Intrinsic::arm_neon_vrshifts:
9309 case Intrinsic::arm_neon_vrshiftu:
9310 case Intrinsic::arm_neon_vrshiftn:
9311 case Intrinsic::arm_neon_vqshifts:
9312 case Intrinsic::arm_neon_vqshiftu:
9313 case Intrinsic::arm_neon_vqshiftsu:
9314 case Intrinsic::arm_neon_vqshiftns:
9315 case Intrinsic::arm_neon_vqshiftnu:
9316 case Intrinsic::arm_neon_vqshiftnsu:
9317 case Intrinsic::arm_neon_vqrshiftns:
9318 case Intrinsic::arm_neon_vqrshiftnu:
9319 case Intrinsic::arm_neon_vqrshiftnsu: {
9320 EVT VT = N->getOperand(1).getValueType();
9322 unsigned VShiftOpc = 0;
9325 case Intrinsic::arm_neon_vshifts:
9326 case Intrinsic::arm_neon_vshiftu:
9327 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9328 VShiftOpc = ARMISD::VSHL;
9331 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9332 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9333 ARMISD::VSHRs : ARMISD::VSHRu);
9338 case Intrinsic::arm_neon_vrshifts:
9339 case Intrinsic::arm_neon_vrshiftu:
9340 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9344 case Intrinsic::arm_neon_vqshifts:
9345 case Intrinsic::arm_neon_vqshiftu:
9346 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9350 case Intrinsic::arm_neon_vqshiftsu:
9351 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9353 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9355 case Intrinsic::arm_neon_vrshiftn:
9356 case Intrinsic::arm_neon_vqshiftns:
9357 case Intrinsic::arm_neon_vqshiftnu:
9358 case Intrinsic::arm_neon_vqshiftnsu:
9359 case Intrinsic::arm_neon_vqrshiftns:
9360 case Intrinsic::arm_neon_vqrshiftnu:
9361 case Intrinsic::arm_neon_vqrshiftnsu:
9362 // Narrowing shifts require an immediate right shift.
9363 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9365 llvm_unreachable("invalid shift count for narrowing vector shift "
9369 llvm_unreachable("unhandled vector shift");
9373 case Intrinsic::arm_neon_vshifts:
9374 case Intrinsic::arm_neon_vshiftu:
9375 // Opcode already set above.
9377 case Intrinsic::arm_neon_vrshifts:
9378 VShiftOpc = ARMISD::VRSHRs; break;
9379 case Intrinsic::arm_neon_vrshiftu:
9380 VShiftOpc = ARMISD::VRSHRu; break;
9381 case Intrinsic::arm_neon_vrshiftn:
9382 VShiftOpc = ARMISD::VRSHRN; break;
9383 case Intrinsic::arm_neon_vqshifts:
9384 VShiftOpc = ARMISD::VQSHLs; break;
9385 case Intrinsic::arm_neon_vqshiftu:
9386 VShiftOpc = ARMISD::VQSHLu; break;
9387 case Intrinsic::arm_neon_vqshiftsu:
9388 VShiftOpc = ARMISD::VQSHLsu; break;
9389 case Intrinsic::arm_neon_vqshiftns:
9390 VShiftOpc = ARMISD::VQSHRNs; break;
9391 case Intrinsic::arm_neon_vqshiftnu:
9392 VShiftOpc = ARMISD::VQSHRNu; break;
9393 case Intrinsic::arm_neon_vqshiftnsu:
9394 VShiftOpc = ARMISD::VQSHRNsu; break;
9395 case Intrinsic::arm_neon_vqrshiftns:
9396 VShiftOpc = ARMISD::VQRSHRNs; break;
9397 case Intrinsic::arm_neon_vqrshiftnu:
9398 VShiftOpc = ARMISD::VQRSHRNu; break;
9399 case Intrinsic::arm_neon_vqrshiftnsu:
9400 VShiftOpc = ARMISD::VQRSHRNsu; break;
9403 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9404 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9407 case Intrinsic::arm_neon_vshiftins: {
9408 EVT VT = N->getOperand(1).getValueType();
9410 unsigned VShiftOpc = 0;
9412 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9413 VShiftOpc = ARMISD::VSLI;
9414 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9415 VShiftOpc = ARMISD::VSRI;
9417 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9420 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9421 N->getOperand(1), N->getOperand(2),
9422 DAG.getConstant(Cnt, MVT::i32));
9425 case Intrinsic::arm_neon_vqrshifts:
9426 case Intrinsic::arm_neon_vqrshiftu:
9427 // No immediate versions of these to check for.
9434 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9435 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9436 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9437 /// vector element shift counts are generally not legal, and it is hard to see
9438 /// their values after they get legalized to loads from a constant pool.
9439 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9440 const ARMSubtarget *ST) {
9441 EVT VT = N->getValueType(0);
9442 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9443 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9444 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9445 SDValue N1 = N->getOperand(1);
9446 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9447 SDValue N0 = N->getOperand(0);
9448 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9449 DAG.MaskedValueIsZero(N0.getOperand(0),
9450 APInt::getHighBitsSet(32, 16)))
9451 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9455 // Nothing to be done for scalar shifts.
9456 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9457 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9460 assert(ST->hasNEON() && "unexpected vector shift");
9463 switch (N->getOpcode()) {
9464 default: llvm_unreachable("unexpected shift opcode");
9467 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9468 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9469 DAG.getConstant(Cnt, MVT::i32));
9474 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9475 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9476 ARMISD::VSHRs : ARMISD::VSHRu);
9477 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9478 DAG.getConstant(Cnt, MVT::i32));
9484 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9485 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9486 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9487 const ARMSubtarget *ST) {
9488 SDValue N0 = N->getOperand(0);
9490 // Check for sign- and zero-extensions of vector extract operations of 8-
9491 // and 16-bit vector elements. NEON supports these directly. They are
9492 // handled during DAG combining because type legalization will promote them
9493 // to 32-bit types and it is messy to recognize the operations after that.
9494 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9495 SDValue Vec = N0.getOperand(0);
9496 SDValue Lane = N0.getOperand(1);
9497 EVT VT = N->getValueType(0);
9498 EVT EltVT = N0.getValueType();
9499 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9501 if (VT == MVT::i32 &&
9502 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9503 TLI.isTypeLegal(Vec.getValueType()) &&
9504 isa<ConstantSDNode>(Lane)) {
9507 switch (N->getOpcode()) {
9508 default: llvm_unreachable("unexpected opcode");
9509 case ISD::SIGN_EXTEND:
9510 Opc = ARMISD::VGETLANEs;
9512 case ISD::ZERO_EXTEND:
9513 case ISD::ANY_EXTEND:
9514 Opc = ARMISD::VGETLANEu;
9517 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9524 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9525 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9526 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9527 const ARMSubtarget *ST) {
9528 // If the target supports NEON, try to use vmax/vmin instructions for f32
9529 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9530 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9531 // a NaN; only do the transformation when it matches that behavior.
9533 // For now only do this when using NEON for FP operations; if using VFP, it
9534 // is not obvious that the benefit outweighs the cost of switching to the
9536 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9537 N->getValueType(0) != MVT::f32)
9540 SDValue CondLHS = N->getOperand(0);
9541 SDValue CondRHS = N->getOperand(1);
9542 SDValue LHS = N->getOperand(2);
9543 SDValue RHS = N->getOperand(3);
9544 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9546 unsigned Opcode = 0;
9548 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9549 IsReversed = false; // x CC y ? x : y
9550 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9551 IsReversed = true ; // x CC y ? y : x
9565 // If LHS is NaN, an ordered comparison will be false and the result will
9566 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9567 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9568 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9569 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9571 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9572 // will return -0, so vmin can only be used for unsafe math or if one of
9573 // the operands is known to be nonzero.
9574 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9575 !DAG.getTarget().Options.UnsafeFPMath &&
9576 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9578 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9587 // If LHS is NaN, an ordered comparison will be false and the result will
9588 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9589 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9590 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9591 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9593 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9594 // will return +0, so vmax can only be used for unsafe math or if one of
9595 // the operands is known to be nonzero.
9596 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9597 !DAG.getTarget().Options.UnsafeFPMath &&
9598 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9600 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9606 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9609 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9611 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9612 SDValue Cmp = N->getOperand(4);
9613 if (Cmp.getOpcode() != ARMISD::CMPZ)
9614 // Only looking at EQ and NE cases.
9617 EVT VT = N->getValueType(0);
9619 SDValue LHS = Cmp.getOperand(0);
9620 SDValue RHS = Cmp.getOperand(1);
9621 SDValue FalseVal = N->getOperand(0);
9622 SDValue TrueVal = N->getOperand(1);
9623 SDValue ARMcc = N->getOperand(2);
9624 ARMCC::CondCodes CC =
9625 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9643 /// FIXME: Turn this into a target neutral optimization?
9645 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9646 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9647 N->getOperand(3), Cmp);
9648 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9650 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9651 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9652 N->getOperand(3), NewCmp);
9655 if (Res.getNode()) {
9656 APInt KnownZero, KnownOne;
9657 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9658 // Capture demanded bits information that would be otherwise lost.
9659 if (KnownZero == 0xfffffffe)
9660 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9661 DAG.getValueType(MVT::i1));
9662 else if (KnownZero == 0xffffff00)
9663 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9664 DAG.getValueType(MVT::i8));
9665 else if (KnownZero == 0xffff0000)
9666 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9667 DAG.getValueType(MVT::i16));
9673 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9674 DAGCombinerInfo &DCI) const {
9675 switch (N->getOpcode()) {
9677 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9678 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9679 case ISD::SUB: return PerformSUBCombine(N, DCI);
9680 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9681 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9682 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9683 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9684 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9685 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9686 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9687 case ISD::STORE: return PerformSTORECombine(N, DCI);
9688 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9689 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9690 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9691 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9692 case ISD::FP_TO_SINT:
9693 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9694 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9695 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9698 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9699 case ISD::SIGN_EXTEND:
9700 case ISD::ZERO_EXTEND:
9701 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9702 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9703 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9704 case ARMISD::VLD2DUP:
9705 case ARMISD::VLD3DUP:
9706 case ARMISD::VLD4DUP:
9707 return CombineBaseUpdate(N, DCI);
9708 case ARMISD::BUILD_VECTOR:
9709 return PerformARMBUILD_VECTORCombine(N, DCI);
9710 case ISD::INTRINSIC_VOID:
9711 case ISD::INTRINSIC_W_CHAIN:
9712 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9713 case Intrinsic::arm_neon_vld1:
9714 case Intrinsic::arm_neon_vld2:
9715 case Intrinsic::arm_neon_vld3:
9716 case Intrinsic::arm_neon_vld4:
9717 case Intrinsic::arm_neon_vld2lane:
9718 case Intrinsic::arm_neon_vld3lane:
9719 case Intrinsic::arm_neon_vld4lane:
9720 case Intrinsic::arm_neon_vst1:
9721 case Intrinsic::arm_neon_vst2:
9722 case Intrinsic::arm_neon_vst3:
9723 case Intrinsic::arm_neon_vst4:
9724 case Intrinsic::arm_neon_vst2lane:
9725 case Intrinsic::arm_neon_vst3lane:
9726 case Intrinsic::arm_neon_vst4lane:
9727 return CombineBaseUpdate(N, DCI);
9735 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9737 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9740 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9744 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9745 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9747 switch (VT.getSimpleVT().SimpleTy) {
9753 // Unaligned access can use (for example) LRDB, LRDH, LDR
9754 if (AllowsUnaligned) {
9756 *Fast = Subtarget->hasV7Ops();
9763 // For any little-endian targets with neon, we can support unaligned ld/st
9764 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9765 // A big-endian target may also explicitly support unaligned accesses
9766 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9776 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9777 unsigned AlignCheck) {
9778 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9779 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9782 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9783 unsigned DstAlign, unsigned SrcAlign,
9784 bool IsMemset, bool ZeroMemset,
9786 MachineFunction &MF) const {
9787 const Function *F = MF.getFunction();
9789 // See if we can use NEON instructions for this...
9790 if ((!IsMemset || ZeroMemset) &&
9791 Subtarget->hasNEON() &&
9792 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9793 Attribute::NoImplicitFloat)) {
9796 (memOpAlign(SrcAlign, DstAlign, 16) ||
9797 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9799 } else if (Size >= 8 &&
9800 (memOpAlign(SrcAlign, DstAlign, 8) ||
9801 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9807 // Lowering to i32/i16 if the size permits.
9813 // Let the target-independent logic figure it out.
9817 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9818 if (Val.getOpcode() != ISD::LOAD)
9821 EVT VT1 = Val.getValueType();
9822 if (!VT1.isSimple() || !VT1.isInteger() ||
9823 !VT2.isSimple() || !VT2.isInteger())
9826 switch (VT1.getSimpleVT().SimpleTy) {
9831 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9838 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9839 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9842 if (!isTypeLegal(EVT::getEVT(Ty1)))
9845 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9847 // Assuming the caller doesn't have a zeroext or signext return parameter,
9848 // truncation all the way down to i1 is valid.
9853 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9858 switch (VT.getSimpleVT().SimpleTy) {
9859 default: return false;
9874 if ((V & (Scale - 1)) != 0)
9877 return V == (V & ((1LL << 5) - 1));
9880 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9881 const ARMSubtarget *Subtarget) {
9888 switch (VT.getSimpleVT().SimpleTy) {
9889 default: return false;
9894 // + imm12 or - imm8
9896 return V == (V & ((1LL << 8) - 1));
9897 return V == (V & ((1LL << 12) - 1));
9900 // Same as ARM mode. FIXME: NEON?
9901 if (!Subtarget->hasVFP2())
9906 return V == (V & ((1LL << 8) - 1));
9910 /// isLegalAddressImmediate - Return true if the integer value can be used
9911 /// as the offset of the target addressing mode for load / store of the
9913 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9914 const ARMSubtarget *Subtarget) {
9921 if (Subtarget->isThumb1Only())
9922 return isLegalT1AddressImmediate(V, VT);
9923 else if (Subtarget->isThumb2())
9924 return isLegalT2AddressImmediate(V, VT, Subtarget);
9929 switch (VT.getSimpleVT().SimpleTy) {
9930 default: return false;
9935 return V == (V & ((1LL << 12) - 1));
9938 return V == (V & ((1LL << 8) - 1));
9941 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9946 return V == (V & ((1LL << 8) - 1));
9950 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9952 int Scale = AM.Scale;
9956 switch (VT.getSimpleVT().SimpleTy) {
9957 default: return false;
9966 return Scale == 2 || Scale == 4 || Scale == 8;
9969 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9973 // Note, we allow "void" uses (basically, uses that aren't loads or
9974 // stores), because arm allows folding a scale into many arithmetic
9975 // operations. This should be made more precise and revisited later.
9977 // Allow r << imm, but the imm has to be a multiple of two.
9978 if (Scale & 1) return false;
9979 return isPowerOf2_32(Scale);
9983 /// isLegalAddressingMode - Return true if the addressing mode represented
9984 /// by AM is legal for this target, for a load/store of the specified type.
9985 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9987 EVT VT = getValueType(Ty, true);
9988 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9991 // Can never fold addr of global into load/store.
9996 case 0: // no scale reg, must be "r+i" or "r", or "i".
9999 if (Subtarget->isThumb1Only())
10003 // ARM doesn't support any R+R*scale+imm addr modes.
10007 if (!VT.isSimple())
10010 if (Subtarget->isThumb2())
10011 return isLegalT2ScaledAddressingMode(AM, VT);
10013 int Scale = AM.Scale;
10014 switch (VT.getSimpleVT().SimpleTy) {
10015 default: return false;
10019 if (Scale < 0) Scale = -Scale;
10023 return isPowerOf2_32(Scale & ~1);
10027 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10032 // Note, we allow "void" uses (basically, uses that aren't loads or
10033 // stores), because arm allows folding a scale into many arithmetic
10034 // operations. This should be made more precise and revisited later.
10036 // Allow r << imm, but the imm has to be a multiple of two.
10037 if (Scale & 1) return false;
10038 return isPowerOf2_32(Scale);
10044 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10045 /// icmp immediate, that is the target has icmp instructions which can compare
10046 /// a register against the immediate without having to materialize the
10047 /// immediate into a register.
10048 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10049 // Thumb2 and ARM modes can use cmn for negative immediates.
10050 if (!Subtarget->isThumb())
10051 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10052 if (Subtarget->isThumb2())
10053 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10054 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10055 return Imm >= 0 && Imm <= 255;
10058 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10059 /// *or sub* immediate, that is the target has add or sub instructions which can
10060 /// add a register with the immediate without having to materialize the
10061 /// immediate into a register.
10062 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10063 // Same encoding for add/sub, just flip the sign.
10064 int64_t AbsImm = llvm::abs64(Imm);
10065 if (!Subtarget->isThumb())
10066 return ARM_AM::getSOImmVal(AbsImm) != -1;
10067 if (Subtarget->isThumb2())
10068 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10069 // Thumb1 only has 8-bit unsigned immediate.
10070 return AbsImm >= 0 && AbsImm <= 255;
10073 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10074 bool isSEXTLoad, SDValue &Base,
10075 SDValue &Offset, bool &isInc,
10076 SelectionDAG &DAG) {
10077 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10080 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10081 // AddressingMode 3
10082 Base = Ptr->getOperand(0);
10083 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10084 int RHSC = (int)RHS->getZExtValue();
10085 if (RHSC < 0 && RHSC > -256) {
10086 assert(Ptr->getOpcode() == ISD::ADD);
10088 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10092 isInc = (Ptr->getOpcode() == ISD::ADD);
10093 Offset = Ptr->getOperand(1);
10095 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10096 // AddressingMode 2
10097 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10098 int RHSC = (int)RHS->getZExtValue();
10099 if (RHSC < 0 && RHSC > -0x1000) {
10100 assert(Ptr->getOpcode() == ISD::ADD);
10102 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10103 Base = Ptr->getOperand(0);
10108 if (Ptr->getOpcode() == ISD::ADD) {
10110 ARM_AM::ShiftOpc ShOpcVal=
10111 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10112 if (ShOpcVal != ARM_AM::no_shift) {
10113 Base = Ptr->getOperand(1);
10114 Offset = Ptr->getOperand(0);
10116 Base = Ptr->getOperand(0);
10117 Offset = Ptr->getOperand(1);
10122 isInc = (Ptr->getOpcode() == ISD::ADD);
10123 Base = Ptr->getOperand(0);
10124 Offset = Ptr->getOperand(1);
10128 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10132 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10133 bool isSEXTLoad, SDValue &Base,
10134 SDValue &Offset, bool &isInc,
10135 SelectionDAG &DAG) {
10136 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10139 Base = Ptr->getOperand(0);
10140 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10141 int RHSC = (int)RHS->getZExtValue();
10142 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10143 assert(Ptr->getOpcode() == ISD::ADD);
10145 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10147 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10148 isInc = Ptr->getOpcode() == ISD::ADD;
10149 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10157 /// getPreIndexedAddressParts - returns true by value, base pointer and
10158 /// offset pointer and addressing mode by reference if the node's address
10159 /// can be legally represented as pre-indexed load / store address.
10161 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10163 ISD::MemIndexedMode &AM,
10164 SelectionDAG &DAG) const {
10165 if (Subtarget->isThumb1Only())
10170 bool isSEXTLoad = false;
10171 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10172 Ptr = LD->getBasePtr();
10173 VT = LD->getMemoryVT();
10174 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10175 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10176 Ptr = ST->getBasePtr();
10177 VT = ST->getMemoryVT();
10182 bool isLegal = false;
10183 if (Subtarget->isThumb2())
10184 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10185 Offset, isInc, DAG);
10187 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10188 Offset, isInc, DAG);
10192 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10196 /// getPostIndexedAddressParts - returns true by value, base pointer and
10197 /// offset pointer and addressing mode by reference if this node can be
10198 /// combined with a load / store to form a post-indexed load / store.
10199 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10202 ISD::MemIndexedMode &AM,
10203 SelectionDAG &DAG) const {
10204 if (Subtarget->isThumb1Only())
10209 bool isSEXTLoad = false;
10210 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10211 VT = LD->getMemoryVT();
10212 Ptr = LD->getBasePtr();
10213 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10214 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10215 VT = ST->getMemoryVT();
10216 Ptr = ST->getBasePtr();
10221 bool isLegal = false;
10222 if (Subtarget->isThumb2())
10223 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10226 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10232 // Swap base ptr and offset to catch more post-index load / store when
10233 // it's legal. In Thumb2 mode, offset must be an immediate.
10234 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10235 !Subtarget->isThumb2())
10236 std::swap(Base, Offset);
10238 // Post-indexed load / store update the base pointer.
10243 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10247 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10250 const SelectionDAG &DAG,
10251 unsigned Depth) const {
10252 unsigned BitWidth = KnownOne.getBitWidth();
10253 KnownZero = KnownOne = APInt(BitWidth, 0);
10254 switch (Op.getOpcode()) {
10260 // These nodes' second result is a boolean
10261 if (Op.getResNo() == 0)
10263 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10265 case ARMISD::CMOV: {
10266 // Bits are known zero/one if known on the LHS and RHS.
10267 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10268 if (KnownZero == 0 && KnownOne == 0) return;
10270 APInt KnownZeroRHS, KnownOneRHS;
10271 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10272 KnownZero &= KnownZeroRHS;
10273 KnownOne &= KnownOneRHS;
10276 case ISD::INTRINSIC_W_CHAIN: {
10277 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10278 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10281 case Intrinsic::arm_ldaex:
10282 case Intrinsic::arm_ldrex: {
10283 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10284 unsigned MemBits = VT.getScalarType().getSizeInBits();
10285 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10293 //===----------------------------------------------------------------------===//
10294 // ARM Inline Assembly Support
10295 //===----------------------------------------------------------------------===//
10297 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10298 // Looking for "rev" which is V6+.
10299 if (!Subtarget->hasV6Ops())
10302 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10303 std::string AsmStr = IA->getAsmString();
10304 SmallVector<StringRef, 4> AsmPieces;
10305 SplitString(AsmStr, AsmPieces, ";\n");
10307 switch (AsmPieces.size()) {
10308 default: return false;
10310 AsmStr = AsmPieces[0];
10312 SplitString(AsmStr, AsmPieces, " \t,");
10315 if (AsmPieces.size() == 3 &&
10316 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10317 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10318 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10319 if (Ty && Ty->getBitWidth() == 32)
10320 return IntrinsicLowering::LowerToByteSwap(CI);
10328 /// getConstraintType - Given a constraint letter, return the type of
10329 /// constraint it is for this target.
10330 ARMTargetLowering::ConstraintType
10331 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10332 if (Constraint.size() == 1) {
10333 switch (Constraint[0]) {
10335 case 'l': return C_RegisterClass;
10336 case 'w': return C_RegisterClass;
10337 case 'h': return C_RegisterClass;
10338 case 'x': return C_RegisterClass;
10339 case 't': return C_RegisterClass;
10340 case 'j': return C_Other; // Constant for movw.
10341 // An address with a single base register. Due to the way we
10342 // currently handle addresses it is the same as an 'r' memory constraint.
10343 case 'Q': return C_Memory;
10345 } else if (Constraint.size() == 2) {
10346 switch (Constraint[0]) {
10348 // All 'U+' constraints are addresses.
10349 case 'U': return C_Memory;
10352 return TargetLowering::getConstraintType(Constraint);
10355 /// Examine constraint type and operand type and determine a weight value.
10356 /// This object must already have been set up with the operand type
10357 /// and the current alternative constraint selected.
10358 TargetLowering::ConstraintWeight
10359 ARMTargetLowering::getSingleConstraintMatchWeight(
10360 AsmOperandInfo &info, const char *constraint) const {
10361 ConstraintWeight weight = CW_Invalid;
10362 Value *CallOperandVal = info.CallOperandVal;
10363 // If we don't have a value, we can't do a match,
10364 // but allow it at the lowest weight.
10365 if (!CallOperandVal)
10367 Type *type = CallOperandVal->getType();
10368 // Look at the constraint type.
10369 switch (*constraint) {
10371 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10374 if (type->isIntegerTy()) {
10375 if (Subtarget->isThumb())
10376 weight = CW_SpecificReg;
10378 weight = CW_Register;
10382 if (type->isFloatingPointTy())
10383 weight = CW_Register;
10389 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10391 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10393 if (Constraint.size() == 1) {
10394 // GCC ARM Constraint Letters
10395 switch (Constraint[0]) {
10396 case 'l': // Low regs or general regs.
10397 if (Subtarget->isThumb())
10398 return RCPair(0U, &ARM::tGPRRegClass);
10399 return RCPair(0U, &ARM::GPRRegClass);
10400 case 'h': // High regs or no regs.
10401 if (Subtarget->isThumb())
10402 return RCPair(0U, &ARM::hGPRRegClass);
10405 return RCPair(0U, &ARM::GPRRegClass);
10407 if (VT == MVT::Other)
10409 if (VT == MVT::f32)
10410 return RCPair(0U, &ARM::SPRRegClass);
10411 if (VT.getSizeInBits() == 64)
10412 return RCPair(0U, &ARM::DPRRegClass);
10413 if (VT.getSizeInBits() == 128)
10414 return RCPair(0U, &ARM::QPRRegClass);
10417 if (VT == MVT::Other)
10419 if (VT == MVT::f32)
10420 return RCPair(0U, &ARM::SPR_8RegClass);
10421 if (VT.getSizeInBits() == 64)
10422 return RCPair(0U, &ARM::DPR_8RegClass);
10423 if (VT.getSizeInBits() == 128)
10424 return RCPair(0U, &ARM::QPR_8RegClass);
10427 if (VT == MVT::f32)
10428 return RCPair(0U, &ARM::SPRRegClass);
10432 if (StringRef("{cc}").equals_lower(Constraint))
10433 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10435 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10438 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10439 /// vector. If it is invalid, don't add anything to Ops.
10440 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10441 std::string &Constraint,
10442 std::vector<SDValue>&Ops,
10443 SelectionDAG &DAG) const {
10446 // Currently only support length 1 constraints.
10447 if (Constraint.length() != 1) return;
10449 char ConstraintLetter = Constraint[0];
10450 switch (ConstraintLetter) {
10453 case 'I': case 'J': case 'K': case 'L':
10454 case 'M': case 'N': case 'O':
10455 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10459 int64_t CVal64 = C->getSExtValue();
10460 int CVal = (int) CVal64;
10461 // None of these constraints allow values larger than 32 bits. Check
10462 // that the value fits in an int.
10463 if (CVal != CVal64)
10466 switch (ConstraintLetter) {
10468 // Constant suitable for movw, must be between 0 and
10470 if (Subtarget->hasV6T2Ops())
10471 if (CVal >= 0 && CVal <= 65535)
10475 if (Subtarget->isThumb1Only()) {
10476 // This must be a constant between 0 and 255, for ADD
10478 if (CVal >= 0 && CVal <= 255)
10480 } else if (Subtarget->isThumb2()) {
10481 // A constant that can be used as an immediate value in a
10482 // data-processing instruction.
10483 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10486 // A constant that can be used as an immediate value in a
10487 // data-processing instruction.
10488 if (ARM_AM::getSOImmVal(CVal) != -1)
10494 if (Subtarget->isThumb()) { // FIXME thumb2
10495 // This must be a constant between -255 and -1, for negated ADD
10496 // immediates. This can be used in GCC with an "n" modifier that
10497 // prints the negated value, for use with SUB instructions. It is
10498 // not useful otherwise but is implemented for compatibility.
10499 if (CVal >= -255 && CVal <= -1)
10502 // This must be a constant between -4095 and 4095. It is not clear
10503 // what this constraint is intended for. Implemented for
10504 // compatibility with GCC.
10505 if (CVal >= -4095 && CVal <= 4095)
10511 if (Subtarget->isThumb1Only()) {
10512 // A 32-bit value where only one byte has a nonzero value. Exclude
10513 // zero to match GCC. This constraint is used by GCC internally for
10514 // constants that can be loaded with a move/shift combination.
10515 // It is not useful otherwise but is implemented for compatibility.
10516 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10518 } else if (Subtarget->isThumb2()) {
10519 // A constant whose bitwise inverse can be used as an immediate
10520 // value in a data-processing instruction. This can be used in GCC
10521 // with a "B" modifier that prints the inverted value, for use with
10522 // BIC and MVN instructions. It is not useful otherwise but is
10523 // implemented for compatibility.
10524 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10527 // A constant whose bitwise inverse can be used as an immediate
10528 // value in a data-processing instruction. This can be used in GCC
10529 // with a "B" modifier that prints the inverted value, for use with
10530 // BIC and MVN instructions. It is not useful otherwise but is
10531 // implemented for compatibility.
10532 if (ARM_AM::getSOImmVal(~CVal) != -1)
10538 if (Subtarget->isThumb1Only()) {
10539 // This must be a constant between -7 and 7,
10540 // for 3-operand ADD/SUB immediate instructions.
10541 if (CVal >= -7 && CVal < 7)
10543 } else if (Subtarget->isThumb2()) {
10544 // A constant whose negation can be used as an immediate value in a
10545 // data-processing instruction. This can be used in GCC with an "n"
10546 // modifier that prints the negated value, for use with SUB
10547 // instructions. It is not useful otherwise but is implemented for
10549 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10552 // A constant whose negation can be used as an immediate value in a
10553 // data-processing instruction. This can be used in GCC with an "n"
10554 // modifier that prints the negated value, for use with SUB
10555 // instructions. It is not useful otherwise but is implemented for
10557 if (ARM_AM::getSOImmVal(-CVal) != -1)
10563 if (Subtarget->isThumb()) { // FIXME thumb2
10564 // This must be a multiple of 4 between 0 and 1020, for
10565 // ADD sp + immediate.
10566 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10569 // A power of two or a constant between 0 and 32. This is used in
10570 // GCC for the shift amount on shifted register operands, but it is
10571 // useful in general for any shift amounts.
10572 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10578 if (Subtarget->isThumb()) { // FIXME thumb2
10579 // This must be a constant between 0 and 31, for shift amounts.
10580 if (CVal >= 0 && CVal <= 31)
10586 if (Subtarget->isThumb()) { // FIXME thumb2
10587 // This must be a multiple of 4 between -508 and 508, for
10588 // ADD/SUB sp = sp + immediate.
10589 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10594 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10598 if (Result.getNode()) {
10599 Ops.push_back(Result);
10602 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10605 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10606 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10607 unsigned Opcode = Op->getOpcode();
10608 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10609 "Invalid opcode for Div/Rem lowering");
10610 bool isSigned = (Opcode == ISD::SDIVREM);
10611 EVT VT = Op->getValueType(0);
10612 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10615 switch (VT.getSimpleVT().SimpleTy) {
10616 default: llvm_unreachable("Unexpected request for libcall!");
10617 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10618 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10619 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10620 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10623 SDValue InChain = DAG.getEntryNode();
10625 TargetLowering::ArgListTy Args;
10626 TargetLowering::ArgListEntry Entry;
10627 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10628 EVT ArgVT = Op->getOperand(i).getValueType();
10629 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10630 Entry.Node = Op->getOperand(i);
10632 Entry.isSExt = isSigned;
10633 Entry.isZExt = !isSigned;
10634 Args.push_back(Entry);
10637 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10640 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10643 TargetLowering::CallLoweringInfo CLI(DAG);
10644 CLI.setDebugLoc(dl).setChain(InChain)
10645 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10646 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10648 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10649 return CallInfo.first;
10653 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10654 assert(Subtarget->isTargetWindows() && "unsupported target platform");
10658 SDValue Chain = Op.getOperand(0);
10659 SDValue Size = Op.getOperand(1);
10661 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10662 DAG.getConstant(2, MVT::i32));
10665 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10666 Flag = Chain.getValue(1);
10668 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10669 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10671 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10672 Chain = NewSP.getValue(1);
10674 SDValue Ops[2] = { NewSP, Chain };
10675 return DAG.getMergeValues(Ops, DL);
10679 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10680 // The ARM target isn't yet aware of offsets.
10684 bool ARM::isBitFieldInvertedMask(unsigned v) {
10685 if (v == 0xffffffff)
10688 // there can be 1's on either or both "outsides", all the "inside"
10689 // bits must be 0's
10690 unsigned TO = CountTrailingOnes_32(v);
10691 unsigned LO = CountLeadingOnes_32(v);
10692 v = (v >> TO) << TO;
10693 v = (v << LO) >> LO;
10697 /// isFPImmLegal - Returns true if the target can instruction select the
10698 /// specified FP immediate natively. If false, the legalizer will
10699 /// materialize the FP immediate as a load from a constant pool.
10700 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10701 if (!Subtarget->hasVFP3())
10703 if (VT == MVT::f32)
10704 return ARM_AM::getFP32Imm(Imm) != -1;
10705 if (VT == MVT::f64)
10706 return ARM_AM::getFP64Imm(Imm) != -1;
10710 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10711 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10712 /// specified in the intrinsic calls.
10713 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10715 unsigned Intrinsic) const {
10716 switch (Intrinsic) {
10717 case Intrinsic::arm_neon_vld1:
10718 case Intrinsic::arm_neon_vld2:
10719 case Intrinsic::arm_neon_vld3:
10720 case Intrinsic::arm_neon_vld4:
10721 case Intrinsic::arm_neon_vld2lane:
10722 case Intrinsic::arm_neon_vld3lane:
10723 case Intrinsic::arm_neon_vld4lane: {
10724 Info.opc = ISD::INTRINSIC_W_CHAIN;
10725 // Conservatively set memVT to the entire set of vectors loaded.
10726 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10727 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10728 Info.ptrVal = I.getArgOperand(0);
10730 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10731 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10732 Info.vol = false; // volatile loads with NEON intrinsics not supported
10733 Info.readMem = true;
10734 Info.writeMem = false;
10737 case Intrinsic::arm_neon_vst1:
10738 case Intrinsic::arm_neon_vst2:
10739 case Intrinsic::arm_neon_vst3:
10740 case Intrinsic::arm_neon_vst4:
10741 case Intrinsic::arm_neon_vst2lane:
10742 case Intrinsic::arm_neon_vst3lane:
10743 case Intrinsic::arm_neon_vst4lane: {
10744 Info.opc = ISD::INTRINSIC_VOID;
10745 // Conservatively set memVT to the entire set of vectors stored.
10746 unsigned NumElts = 0;
10747 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10748 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10749 if (!ArgTy->isVectorTy())
10751 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10753 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10754 Info.ptrVal = I.getArgOperand(0);
10756 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10757 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10758 Info.vol = false; // volatile stores with NEON intrinsics not supported
10759 Info.readMem = false;
10760 Info.writeMem = true;
10763 case Intrinsic::arm_ldaex:
10764 case Intrinsic::arm_ldrex: {
10765 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10766 Info.opc = ISD::INTRINSIC_W_CHAIN;
10767 Info.memVT = MVT::getVT(PtrTy->getElementType());
10768 Info.ptrVal = I.getArgOperand(0);
10770 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10772 Info.readMem = true;
10773 Info.writeMem = false;
10776 case Intrinsic::arm_stlex:
10777 case Intrinsic::arm_strex: {
10778 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10779 Info.opc = ISD::INTRINSIC_W_CHAIN;
10780 Info.memVT = MVT::getVT(PtrTy->getElementType());
10781 Info.ptrVal = I.getArgOperand(1);
10783 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10785 Info.readMem = false;
10786 Info.writeMem = true;
10789 case Intrinsic::arm_stlexd:
10790 case Intrinsic::arm_strexd: {
10791 Info.opc = ISD::INTRINSIC_W_CHAIN;
10792 Info.memVT = MVT::i64;
10793 Info.ptrVal = I.getArgOperand(2);
10797 Info.readMem = false;
10798 Info.writeMem = true;
10801 case Intrinsic::arm_ldaexd:
10802 case Intrinsic::arm_ldrexd: {
10803 Info.opc = ISD::INTRINSIC_W_CHAIN;
10804 Info.memVT = MVT::i64;
10805 Info.ptrVal = I.getArgOperand(0);
10809 Info.readMem = true;
10810 Info.writeMem = false;
10820 /// \brief Returns true if it is beneficial to convert a load of a constant
10821 /// to just the constant itself.
10822 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10824 assert(Ty->isIntegerTy());
10826 unsigned Bits = Ty->getPrimitiveSizeInBits();
10827 if (Bits == 0 || Bits > 32)
10832 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10833 // Loads and stores less than 64-bits are already atomic; ones above that
10834 // are doomed anyway, so defer to the default libcall and blame the OS when
10835 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
10836 // anything for those.
10837 bool IsMClass = Subtarget->isMClass();
10838 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
10839 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10840 return Size == 64 && !IsMClass;
10841 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
10842 return LI->getType()->getPrimitiveSizeInBits() == 64 && !IsMClass;
10845 // For the real atomic operations, we have ldrex/strex up to 32 bits,
10846 // and up to 64 bits on the non-M profiles
10847 unsigned AtomicLimit = IsMClass ? 32 : 64;
10848 return Inst->getType()->getPrimitiveSizeInBits() <= AtomicLimit;
10851 // This has so far only been implemented for MachO.
10852 bool ARMTargetLowering::useLoadStackGuardNode() const {
10853 return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO;
10856 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10857 AtomicOrdering Ord) const {
10858 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10859 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10861 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10863 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10864 // intrinsic must return {i32, i32} and we have to recombine them into a
10865 // single i64 here.
10866 if (ValTy->getPrimitiveSizeInBits() == 64) {
10867 Intrinsic::ID Int =
10868 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10869 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10871 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10872 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10874 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10875 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10876 if (!Subtarget->isLittle())
10877 std::swap (Lo, Hi);
10878 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10879 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10880 return Builder.CreateOr(
10881 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10884 Type *Tys[] = { Addr->getType() };
10885 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10886 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10888 return Builder.CreateTruncOrBitCast(
10889 Builder.CreateCall(Ldrex, Addr),
10890 cast<PointerType>(Addr->getType())->getElementType());
10893 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10895 AtomicOrdering Ord) const {
10896 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10898 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10900 // Since the intrinsics must have legal type, the i64 intrinsics take two
10901 // parameters: "i32, i32". We must marshal Val into the appropriate form
10902 // before the call.
10903 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10904 Intrinsic::ID Int =
10905 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10906 Function *Strex = Intrinsic::getDeclaration(M, Int);
10907 Type *Int32Ty = Type::getInt32Ty(M->getContext());
10909 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10910 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10911 if (!Subtarget->isLittle())
10912 std::swap (Lo, Hi);
10913 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10914 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10917 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10918 Type *Tys[] = { Addr->getType() };
10919 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10921 return Builder.CreateCall2(
10922 Strex, Builder.CreateZExtOrBitCast(
10923 Val, Strex->getFunctionType()->getParamType(0)),
10935 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10936 uint64_t &Members) {
10937 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10938 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10939 uint64_t SubMembers = 0;
10940 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10942 Members += SubMembers;
10944 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10945 uint64_t SubMembers = 0;
10946 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10948 Members += SubMembers * AT->getNumElements();
10949 } else if (Ty->isFloatTy()) {
10950 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10954 } else if (Ty->isDoubleTy()) {
10955 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10959 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10966 return VT->getBitWidth() == 64;
10968 return VT->getBitWidth() == 128;
10970 switch (VT->getBitWidth()) {
10983 return (Members > 0 && Members <= 4);
10986 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10987 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10988 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10989 if (getEffectiveCallingConv(CallConv, isVarArg) !=
10990 CallingConv::ARM_AAPCS_VFP)
10993 HABaseType Base = HA_UNKNOWN;
10994 uint64_t Members = 0;
10995 bool result = isHomogeneousAggregate(Ty, Base, Members);
10996 DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump());