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/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalValue.h"
40 #include "llvm/IR/IRBuilder.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
54 #define DEBUG_TYPE "arm-isel"
56 STATISTIC(NumTailCalls, "Number of tail calls");
57 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
58 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
61 EnableARMLongCalls("arm-long-calls", cl::Hidden,
62 cl::desc("Generate calls via indirect call instructions"),
66 ARMInterworking("arm-interworking", cl::Hidden,
67 cl::desc("Enable / disable ARM interworking (for debugging only)"),
71 class ARMCCState : public CCState {
73 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
74 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
76 : CCState(CC, isVarArg, MF, locs, C) {
77 assert(((PC == Call) || (PC == Prologue)) &&
78 "ARMCCState users must specify whether their context is call"
79 "or prologue generation.");
85 // The APCS parameter registers.
86 static const MCPhysReg GPRArgRegs[] = {
87 ARM::R0, ARM::R1, ARM::R2, ARM::R3
90 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
91 MVT PromotedBitwiseVT) {
92 if (VT != PromotedLdStVT) {
93 setOperationAction(ISD::LOAD, VT, Promote);
94 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
96 setOperationAction(ISD::STORE, VT, Promote);
97 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
100 MVT ElemTy = VT.getVectorElementType();
101 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
102 setOperationAction(ISD::SETCC, VT, Custom);
103 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
104 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
105 if (ElemTy == MVT::i32) {
106 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
107 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
108 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
109 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
111 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
112 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
113 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
114 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
116 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
117 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
118 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
119 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
120 setOperationAction(ISD::SELECT, VT, Expand);
121 setOperationAction(ISD::SELECT_CC, VT, Expand);
122 setOperationAction(ISD::VSELECT, VT, Expand);
123 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
124 if (VT.isInteger()) {
125 setOperationAction(ISD::SHL, VT, Custom);
126 setOperationAction(ISD::SRA, VT, Custom);
127 setOperationAction(ISD::SRL, VT, Custom);
130 // Promote all bit-wise operations.
131 if (VT.isInteger() && VT != PromotedBitwiseVT) {
132 setOperationAction(ISD::AND, VT, Promote);
133 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
134 setOperationAction(ISD::OR, VT, Promote);
135 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
136 setOperationAction(ISD::XOR, VT, Promote);
137 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
140 // Neon does not support vector divide/remainder operations.
141 setOperationAction(ISD::SDIV, VT, Expand);
142 setOperationAction(ISD::UDIV, VT, Expand);
143 setOperationAction(ISD::FDIV, VT, Expand);
144 setOperationAction(ISD::SREM, VT, Expand);
145 setOperationAction(ISD::UREM, VT, Expand);
146 setOperationAction(ISD::FREM, VT, Expand);
149 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
150 addRegisterClass(VT, &ARM::DPRRegClass);
151 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
154 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
155 addRegisterClass(VT, &ARM::DPairRegClass);
156 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
159 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
160 if (TT.isOSBinFormatMachO())
161 return new TargetLoweringObjectFileMachO();
162 if (TT.isOSWindows())
163 return new TargetLoweringObjectFileCOFF();
164 return new ARMElfTargetObjectFile();
167 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
168 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
169 Subtarget = &TM.getSubtarget<ARMSubtarget>();
170 RegInfo = TM.getSubtargetImpl()->getRegisterInfo();
171 Itins = TM.getSubtargetImpl()->getInstrItineraryData();
173 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
175 if (Subtarget->isTargetMachO()) {
176 // Uses VFP for Thumb libfuncs if available.
177 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
178 Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
179 // Single-precision floating-point arithmetic.
180 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
181 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
182 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
183 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
185 // Double-precision floating-point arithmetic.
186 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
187 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
188 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
189 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
191 // Single-precision comparisons.
192 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
193 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
194 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
195 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
196 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
197 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
198 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
199 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
201 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
202 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
203 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
204 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
208 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
210 // Double-precision comparisons.
211 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
212 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
213 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
214 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
215 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
216 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
217 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
218 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
220 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
221 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
222 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
223 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
227 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
229 // Floating-point to integer conversions.
230 // i64 conversions are done via library routines even when generating VFP
231 // instructions, so use the same ones.
232 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
233 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
234 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
235 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
237 // Conversions between floating types.
238 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
239 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
241 // Integer to floating-point conversions.
242 // i64 conversions are done via library routines even when generating VFP
243 // instructions, so use the same ones.
244 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
245 // e.g., __floatunsidf vs. __floatunssidfvfp.
246 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
247 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
248 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
249 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
253 // These libcalls are not available in 32-bit.
254 setLibcallName(RTLIB::SHL_I128, nullptr);
255 setLibcallName(RTLIB::SRL_I128, nullptr);
256 setLibcallName(RTLIB::SRA_I128, nullptr);
258 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
259 !Subtarget->isTargetWindows()) {
260 static const struct {
261 const RTLIB::Libcall Op;
262 const char * const Name;
263 const CallingConv::ID CC;
264 const ISD::CondCode Cond;
266 // Double-precision floating-point arithmetic helper functions
267 // RTABI chapter 4.1.2, Table 2
268 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
269 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
271 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
273 // Double-precision floating-point comparison helper functions
274 // RTABI chapter 4.1.2, Table 3
275 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
276 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
277 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
278 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
279 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
280 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
281 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
282 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
284 // Single-precision floating-point arithmetic helper functions
285 // RTABI chapter 4.1.2, Table 4
286 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
287 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
289 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
291 // Single-precision floating-point comparison helper functions
292 // RTABI chapter 4.1.2, Table 5
293 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
294 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
295 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
296 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
297 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
298 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
299 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
300 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
302 // Floating-point to integer conversions.
303 // RTABI chapter 4.1.2, Table 6
304 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313 // Conversions between floating types.
314 // RTABI chapter 4.1.2, Table 7
315 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319 // Integer to floating-point conversions.
320 // RTABI chapter 4.1.2, Table 8
321 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330 // Long long helper functions
331 // RTABI chapter 4.2, Table 9
332 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337 // Integer division functions
338 // RTABI chapter 4.3.1
339 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
349 // RTABI chapter 4.3.4
350 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
355 for (const auto &LC : LibraryCalls) {
356 setLibcallName(LC.Op, LC.Name);
357 setLibcallCallingConv(LC.Op, LC.CC);
358 if (LC.Cond != ISD::SETCC_INVALID)
359 setCmpLibcallCC(LC.Op, LC.Cond);
363 if (Subtarget->isTargetWindows()) {
364 static const struct {
365 const RTLIB::Libcall Op;
366 const char * const Name;
367 const CallingConv::ID CC;
369 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
370 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
371 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
372 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
373 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
374 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
375 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
376 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
379 for (const auto &LC : LibraryCalls) {
380 setLibcallName(LC.Op, LC.Name);
381 setLibcallCallingConv(LC.Op, LC.CC);
385 // Use divmod compiler-rt calls for iOS 5.0 and later.
386 if (Subtarget->getTargetTriple().isiOS() &&
387 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
388 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
389 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
392 // The half <-> float conversion functions are always soft-float, but are
393 // needed for some targets which use a hard-float calling convention by
395 if (Subtarget->isAAPCS_ABI()) {
396 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
397 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
398 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
400 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
401 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
402 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
405 if (Subtarget->isThumb1Only())
406 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
408 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
409 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
410 !Subtarget->isThumb1Only()) {
411 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
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);
594 if (Subtarget->isFPOnlySP()) {
595 // When targetting a floating-point unit with only single-precision
596 // operations, f64 is legal for the few double-precision instructions which
597 // are present However, no double-precision operations other than moves,
598 // loads and stores are provided by the hardware.
599 setOperationAction(ISD::FADD, MVT::f64, Expand);
600 setOperationAction(ISD::FSUB, MVT::f64, Expand);
601 setOperationAction(ISD::FMUL, MVT::f64, Expand);
602 setOperationAction(ISD::FMA, MVT::f64, Expand);
603 setOperationAction(ISD::FDIV, MVT::f64, Expand);
604 setOperationAction(ISD::FREM, MVT::f64, Expand);
605 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
606 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
607 setOperationAction(ISD::FNEG, MVT::f64, Expand);
608 setOperationAction(ISD::FABS, MVT::f64, Expand);
609 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
610 setOperationAction(ISD::FSIN, MVT::f64, Expand);
611 setOperationAction(ISD::FCOS, MVT::f64, Expand);
612 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
613 setOperationAction(ISD::FPOW, MVT::f64, Expand);
614 setOperationAction(ISD::FLOG, MVT::f64, Expand);
615 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
616 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
617 setOperationAction(ISD::FEXP, MVT::f64, Expand);
618 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
619 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
620 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
621 setOperationAction(ISD::FRINT, MVT::f64, Expand);
622 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
623 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
624 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
625 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
628 computeRegisterProperties();
630 // ARM does not have floating-point extending loads.
631 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
632 setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
634 // ... or truncating stores
635 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
636 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
637 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
639 // ARM does not have i1 sign extending load.
640 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
642 // ARM supports all 4 flavors of integer indexed load / store.
643 if (!Subtarget->isThumb1Only()) {
644 for (unsigned im = (unsigned)ISD::PRE_INC;
645 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
646 setIndexedLoadAction(im, MVT::i1, Legal);
647 setIndexedLoadAction(im, MVT::i8, Legal);
648 setIndexedLoadAction(im, MVT::i16, Legal);
649 setIndexedLoadAction(im, MVT::i32, Legal);
650 setIndexedStoreAction(im, MVT::i1, Legal);
651 setIndexedStoreAction(im, MVT::i8, Legal);
652 setIndexedStoreAction(im, MVT::i16, Legal);
653 setIndexedStoreAction(im, MVT::i32, Legal);
657 setOperationAction(ISD::SADDO, MVT::i32, Custom);
658 setOperationAction(ISD::UADDO, MVT::i32, Custom);
659 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
660 setOperationAction(ISD::USUBO, MVT::i32, Custom);
662 // i64 operation support.
663 setOperationAction(ISD::MUL, MVT::i64, Expand);
664 setOperationAction(ISD::MULHU, MVT::i32, Expand);
665 if (Subtarget->isThumb1Only()) {
666 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
667 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
669 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
670 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
671 setOperationAction(ISD::MULHS, MVT::i32, Expand);
673 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
674 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
675 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
676 setOperationAction(ISD::SRL, MVT::i64, Custom);
677 setOperationAction(ISD::SRA, MVT::i64, Custom);
679 if (!Subtarget->isThumb1Only()) {
680 // FIXME: We should do this for Thumb1 as well.
681 setOperationAction(ISD::ADDC, MVT::i32, Custom);
682 setOperationAction(ISD::ADDE, MVT::i32, Custom);
683 setOperationAction(ISD::SUBC, MVT::i32, Custom);
684 setOperationAction(ISD::SUBE, MVT::i32, Custom);
687 // ARM does not have ROTL.
688 setOperationAction(ISD::ROTL, MVT::i32, Expand);
689 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
690 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
691 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
692 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
694 // These just redirect to CTTZ and CTLZ on ARM.
695 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
696 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
698 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
700 // Only ARMv6 has BSWAP.
701 if (!Subtarget->hasV6Ops())
702 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
704 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
705 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
706 // These are expanded into libcalls if the cpu doesn't have HW divider.
707 setOperationAction(ISD::SDIV, MVT::i32, Expand);
708 setOperationAction(ISD::UDIV, MVT::i32, Expand);
711 // FIXME: Also set divmod for SREM on EABI
712 setOperationAction(ISD::SREM, MVT::i32, Expand);
713 setOperationAction(ISD::UREM, MVT::i32, Expand);
714 // Register based DivRem for AEABI (RTABI 4.2)
715 if (Subtarget->isTargetAEABI()) {
716 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
717 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
718 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
719 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
720 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
721 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
722 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
723 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
725 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
726 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
727 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
728 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
729 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
730 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
731 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
732 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
734 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
735 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
737 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
738 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
741 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
742 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
743 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
744 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
745 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
747 setOperationAction(ISD::TRAP, MVT::Other, Legal);
749 // Use the default implementation.
750 setOperationAction(ISD::VASTART, MVT::Other, Custom);
751 setOperationAction(ISD::VAARG, MVT::Other, Expand);
752 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
753 setOperationAction(ISD::VAEND, MVT::Other, Expand);
754 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
755 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
757 if (!Subtarget->isTargetMachO()) {
758 // Non-MachO platforms may return values in these registers via the
759 // personality function.
760 setExceptionPointerRegister(ARM::R0);
761 setExceptionSelectorRegister(ARM::R1);
764 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
765 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
767 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
769 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
770 // the default expansion. If we are targeting a single threaded system,
771 // then set them all for expand so we can lower them later into their
773 if (TM.Options.ThreadModel == ThreadModel::Single)
774 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
775 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
776 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
777 // to ldrex/strex loops already.
778 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
780 // On v8, we have particularly efficient implementations of atomic fences
781 // if they can be combined with nearby atomic loads and stores.
782 if (!Subtarget->hasV8Ops()) {
783 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
784 setInsertFencesForAtomic(true);
787 // If there's anything we can use as a barrier, go through custom lowering
789 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
790 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
792 // Set them all for expansion, which will force libcalls.
793 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
794 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
795 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
796 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
797 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
798 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
799 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
800 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
801 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
802 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
803 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
804 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
805 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
806 // Unordered/Monotonic case.
807 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
808 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
811 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
813 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
814 if (!Subtarget->hasV6Ops()) {
815 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
816 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
818 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
820 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
821 !Subtarget->isThumb1Only()) {
822 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
823 // iff target supports vfp2.
824 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
825 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
828 // We want to custom lower some of our intrinsics.
829 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
830 if (Subtarget->isTargetDarwin()) {
831 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
832 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
833 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
836 setOperationAction(ISD::SETCC, MVT::i32, Expand);
837 setOperationAction(ISD::SETCC, MVT::f32, Expand);
838 setOperationAction(ISD::SETCC, MVT::f64, Expand);
839 setOperationAction(ISD::SELECT, MVT::i32, Custom);
840 setOperationAction(ISD::SELECT, MVT::f32, Custom);
841 setOperationAction(ISD::SELECT, MVT::f64, Custom);
842 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
843 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
844 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
846 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
847 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
848 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
849 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
850 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
852 // We don't support sin/cos/fmod/copysign/pow
853 setOperationAction(ISD::FSIN, MVT::f64, Expand);
854 setOperationAction(ISD::FSIN, MVT::f32, Expand);
855 setOperationAction(ISD::FCOS, MVT::f32, Expand);
856 setOperationAction(ISD::FCOS, MVT::f64, Expand);
857 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
858 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
859 setOperationAction(ISD::FREM, MVT::f64, Expand);
860 setOperationAction(ISD::FREM, MVT::f32, Expand);
861 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
862 !Subtarget->isThumb1Only()) {
863 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
864 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
866 setOperationAction(ISD::FPOW, MVT::f64, Expand);
867 setOperationAction(ISD::FPOW, MVT::f32, Expand);
869 if (!Subtarget->hasVFP4()) {
870 setOperationAction(ISD::FMA, MVT::f64, Expand);
871 setOperationAction(ISD::FMA, MVT::f32, Expand);
874 // Various VFP goodness
875 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
876 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
877 if (Subtarget->hasVFP2()) {
878 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
879 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
880 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
881 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
884 // v8 adds f64 <-> f16 conversion. Before that it should be expanded.
885 if (!Subtarget->hasV8Ops()) {
886 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
887 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
890 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
891 if (!Subtarget->hasFP16()) {
892 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
893 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
897 // Combine sin / cos into one node or libcall if possible.
898 if (Subtarget->hasSinCos()) {
899 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
900 setLibcallName(RTLIB::SINCOS_F64, "sincos");
901 if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
902 // For iOS, we don't want to the normal expansion of a libcall to
903 // sincos. We want to issue a libcall to __sincos_stret.
904 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
905 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
909 // ARMv8 implements a lot of rounding-like FP operations.
910 if (Subtarget->hasV8Ops()) {
911 static MVT RoundingTypes[] = {MVT::f32, MVT::f64};
912 for (const auto Ty : RoundingTypes) {
913 setOperationAction(ISD::FFLOOR, Ty, Legal);
914 setOperationAction(ISD::FCEIL, Ty, Legal);
915 setOperationAction(ISD::FROUND, Ty, Legal);
916 setOperationAction(ISD::FTRUNC, Ty, Legal);
917 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
918 setOperationAction(ISD::FRINT, Ty, Legal);
921 // We have target-specific dag combine patterns for the following nodes:
922 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
923 setTargetDAGCombine(ISD::ADD);
924 setTargetDAGCombine(ISD::SUB);
925 setTargetDAGCombine(ISD::MUL);
926 setTargetDAGCombine(ISD::AND);
927 setTargetDAGCombine(ISD::OR);
928 setTargetDAGCombine(ISD::XOR);
930 if (Subtarget->hasV6Ops())
931 setTargetDAGCombine(ISD::SRL);
933 setStackPointerRegisterToSaveRestore(ARM::SP);
935 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
936 !Subtarget->hasVFP2())
937 setSchedulingPreference(Sched::RegPressure);
939 setSchedulingPreference(Sched::Hybrid);
941 //// temporary - rewrite interface to use type
942 MaxStoresPerMemset = 8;
943 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
944 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
945 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
946 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
947 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
949 // On ARM arguments smaller than 4 bytes are extended, so all arguments
950 // are at least 4 bytes aligned.
951 setMinStackArgumentAlignment(4);
953 // Prefer likely predicted branches to selects on out-of-order cores.
954 PredictableSelectIsExpensive = Subtarget->isLikeA9();
956 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
959 // FIXME: It might make sense to define the representative register class as the
960 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
961 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
962 // SPR's representative would be DPR_VFP2. This should work well if register
963 // pressure tracking were modified such that a register use would increment the
964 // pressure of the register class's representative and all of it's super
965 // classes' representatives transitively. We have not implemented this because
966 // of the difficulty prior to coalescing of modeling operand register classes
967 // due to the common occurrence of cross class copies and subregister insertions
969 std::pair<const TargetRegisterClass*, uint8_t>
970 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
971 const TargetRegisterClass *RRC = nullptr;
973 switch (VT.SimpleTy) {
975 return TargetLowering::findRepresentativeClass(VT);
976 // Use DPR as representative register class for all floating point
977 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
978 // the cost is 1 for both f32 and f64.
979 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
980 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
981 RRC = &ARM::DPRRegClass;
982 // When NEON is used for SP, only half of the register file is available
983 // because operations that define both SP and DP results will be constrained
984 // to the VFP2 class (D0-D15). We currently model this constraint prior to
985 // coalescing by double-counting the SP regs. See the FIXME above.
986 if (Subtarget->useNEONForSinglePrecisionFP())
989 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
990 case MVT::v4f32: case MVT::v2f64:
991 RRC = &ARM::DPRRegClass;
995 RRC = &ARM::DPRRegClass;
999 RRC = &ARM::DPRRegClass;
1003 return std::make_pair(RRC, Cost);
1006 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1008 default: return nullptr;
1009 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1010 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1011 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1012 case ARMISD::CALL: return "ARMISD::CALL";
1013 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1014 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1015 case ARMISD::tCALL: return "ARMISD::tCALL";
1016 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1017 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1018 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1019 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1020 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1021 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1022 case ARMISD::CMP: return "ARMISD::CMP";
1023 case ARMISD::CMN: return "ARMISD::CMN";
1024 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1025 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1026 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1027 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1028 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1030 case ARMISD::CMOV: return "ARMISD::CMOV";
1032 case ARMISD::RBIT: return "ARMISD::RBIT";
1034 case ARMISD::FTOSI: return "ARMISD::FTOSI";
1035 case ARMISD::FTOUI: return "ARMISD::FTOUI";
1036 case ARMISD::SITOF: return "ARMISD::SITOF";
1037 case ARMISD::UITOF: return "ARMISD::UITOF";
1039 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1040 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1041 case ARMISD::RRX: return "ARMISD::RRX";
1043 case ARMISD::ADDC: return "ARMISD::ADDC";
1044 case ARMISD::ADDE: return "ARMISD::ADDE";
1045 case ARMISD::SUBC: return "ARMISD::SUBC";
1046 case ARMISD::SUBE: return "ARMISD::SUBE";
1048 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1049 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1051 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1052 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1054 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1056 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1058 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1060 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1062 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1064 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1066 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1067 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1068 case ARMISD::VCGE: return "ARMISD::VCGE";
1069 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1070 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1071 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1072 case ARMISD::VCGT: return "ARMISD::VCGT";
1073 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1074 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1075 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1076 case ARMISD::VTST: return "ARMISD::VTST";
1078 case ARMISD::VSHL: return "ARMISD::VSHL";
1079 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1080 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1081 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1082 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1083 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1084 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1085 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1086 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1087 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1088 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1089 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1090 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1091 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1092 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1093 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1094 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1095 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1096 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1097 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1098 case ARMISD::VDUP: return "ARMISD::VDUP";
1099 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1100 case ARMISD::VEXT: return "ARMISD::VEXT";
1101 case ARMISD::VREV64: return "ARMISD::VREV64";
1102 case ARMISD::VREV32: return "ARMISD::VREV32";
1103 case ARMISD::VREV16: return "ARMISD::VREV16";
1104 case ARMISD::VZIP: return "ARMISD::VZIP";
1105 case ARMISD::VUZP: return "ARMISD::VUZP";
1106 case ARMISD::VTRN: return "ARMISD::VTRN";
1107 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1108 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1109 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1110 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1111 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1112 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1113 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1114 case ARMISD::FMAX: return "ARMISD::FMAX";
1115 case ARMISD::FMIN: return "ARMISD::FMIN";
1116 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1117 case ARMISD::VMINNM: return "ARMISD::VMIN";
1118 case ARMISD::BFI: return "ARMISD::BFI";
1119 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1120 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1121 case ARMISD::VBSL: return "ARMISD::VBSL";
1122 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1123 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1124 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1125 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1126 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1127 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1128 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1129 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1130 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1131 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1132 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1133 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1134 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1135 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1136 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1137 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1138 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1139 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1140 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1141 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1145 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1146 if (!VT.isVector()) return getPointerTy();
1147 return VT.changeVectorElementTypeToInteger();
1150 /// getRegClassFor - Return the register class that should be used for the
1151 /// specified value type.
1152 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1153 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1154 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1155 // load / store 4 to 8 consecutive D registers.
1156 if (Subtarget->hasNEON()) {
1157 if (VT == MVT::v4i64)
1158 return &ARM::QQPRRegClass;
1159 if (VT == MVT::v8i64)
1160 return &ARM::QQQQPRRegClass;
1162 return TargetLowering::getRegClassFor(VT);
1165 // Create a fast isel object.
1167 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1168 const TargetLibraryInfo *libInfo) const {
1169 return ARM::createFastISel(funcInfo, libInfo);
1172 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1173 /// be used for loads / stores from the global.
1174 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1175 return (Subtarget->isThumb1Only() ? 127 : 4095);
1178 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1179 unsigned NumVals = N->getNumValues();
1181 return Sched::RegPressure;
1183 for (unsigned i = 0; i != NumVals; ++i) {
1184 EVT VT = N->getValueType(i);
1185 if (VT == MVT::Glue || VT == MVT::Other)
1187 if (VT.isFloatingPoint() || VT.isVector())
1191 if (!N->isMachineOpcode())
1192 return Sched::RegPressure;
1194 // Load are scheduled for latency even if there instruction itinerary
1195 // is not available.
1196 const TargetInstrInfo *TII =
1197 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1198 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1200 if (MCID.getNumDefs() == 0)
1201 return Sched::RegPressure;
1202 if (!Itins->isEmpty() &&
1203 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1206 return Sched::RegPressure;
1209 //===----------------------------------------------------------------------===//
1211 //===----------------------------------------------------------------------===//
1213 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1214 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1216 default: llvm_unreachable("Unknown condition code!");
1217 case ISD::SETNE: return ARMCC::NE;
1218 case ISD::SETEQ: return ARMCC::EQ;
1219 case ISD::SETGT: return ARMCC::GT;
1220 case ISD::SETGE: return ARMCC::GE;
1221 case ISD::SETLT: return ARMCC::LT;
1222 case ISD::SETLE: return ARMCC::LE;
1223 case ISD::SETUGT: return ARMCC::HI;
1224 case ISD::SETUGE: return ARMCC::HS;
1225 case ISD::SETULT: return ARMCC::LO;
1226 case ISD::SETULE: return ARMCC::LS;
1230 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1231 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1232 ARMCC::CondCodes &CondCode2) {
1233 CondCode2 = ARMCC::AL;
1235 default: llvm_unreachable("Unknown FP condition!");
1237 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1239 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1241 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1242 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1243 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1244 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1245 case ISD::SETO: CondCode = ARMCC::VC; break;
1246 case ISD::SETUO: CondCode = ARMCC::VS; break;
1247 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1248 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1249 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1251 case ISD::SETULT: CondCode = ARMCC::LT; break;
1253 case ISD::SETULE: CondCode = ARMCC::LE; break;
1255 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1259 //===----------------------------------------------------------------------===//
1260 // Calling Convention Implementation
1261 //===----------------------------------------------------------------------===//
1263 #include "ARMGenCallingConv.inc"
1265 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1266 /// account presence of floating point hardware and calling convention
1267 /// limitations, such as support for variadic functions.
1269 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1270 bool isVarArg) const {
1273 llvm_unreachable("Unsupported calling convention");
1274 case CallingConv::ARM_AAPCS:
1275 case CallingConv::ARM_APCS:
1276 case CallingConv::GHC:
1278 case CallingConv::ARM_AAPCS_VFP:
1279 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1280 case CallingConv::C:
1281 if (!Subtarget->isAAPCS_ABI())
1282 return CallingConv::ARM_APCS;
1283 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1284 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1286 return CallingConv::ARM_AAPCS_VFP;
1288 return CallingConv::ARM_AAPCS;
1289 case CallingConv::Fast:
1290 if (!Subtarget->isAAPCS_ABI()) {
1291 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1292 return CallingConv::Fast;
1293 return CallingConv::ARM_APCS;
1294 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1295 return CallingConv::ARM_AAPCS_VFP;
1297 return CallingConv::ARM_AAPCS;
1301 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1302 /// CallingConvention.
1303 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1305 bool isVarArg) const {
1306 switch (getEffectiveCallingConv(CC, isVarArg)) {
1308 llvm_unreachable("Unsupported calling convention");
1309 case CallingConv::ARM_APCS:
1310 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1311 case CallingConv::ARM_AAPCS:
1312 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1313 case CallingConv::ARM_AAPCS_VFP:
1314 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1315 case CallingConv::Fast:
1316 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1317 case CallingConv::GHC:
1318 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1322 /// LowerCallResult - Lower the result values of a call into the
1323 /// appropriate copies out of appropriate physical registers.
1325 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1326 CallingConv::ID CallConv, bool isVarArg,
1327 const SmallVectorImpl<ISD::InputArg> &Ins,
1328 SDLoc dl, SelectionDAG &DAG,
1329 SmallVectorImpl<SDValue> &InVals,
1330 bool isThisReturn, SDValue ThisVal) const {
1332 // Assign locations to each value returned by this call.
1333 SmallVector<CCValAssign, 16> RVLocs;
1334 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1335 *DAG.getContext(), Call);
1336 CCInfo.AnalyzeCallResult(Ins,
1337 CCAssignFnForNode(CallConv, /* Return*/ true,
1340 // Copy all of the result registers out of their specified physreg.
1341 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1342 CCValAssign VA = RVLocs[i];
1344 // Pass 'this' value directly from the argument to return value, to avoid
1345 // reg unit interference
1346 if (i == 0 && isThisReturn) {
1347 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1348 "unexpected return calling convention register assignment");
1349 InVals.push_back(ThisVal);
1354 if (VA.needsCustom()) {
1355 // Handle f64 or half of a v2f64.
1356 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1358 Chain = Lo.getValue(1);
1359 InFlag = Lo.getValue(2);
1360 VA = RVLocs[++i]; // skip ahead to next loc
1361 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1363 Chain = Hi.getValue(1);
1364 InFlag = Hi.getValue(2);
1365 if (!Subtarget->isLittle())
1367 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1369 if (VA.getLocVT() == MVT::v2f64) {
1370 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1371 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1372 DAG.getConstant(0, MVT::i32));
1374 VA = RVLocs[++i]; // skip ahead to next loc
1375 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1376 Chain = Lo.getValue(1);
1377 InFlag = Lo.getValue(2);
1378 VA = RVLocs[++i]; // skip ahead to next loc
1379 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1380 Chain = Hi.getValue(1);
1381 InFlag = Hi.getValue(2);
1382 if (!Subtarget->isLittle())
1384 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1385 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1386 DAG.getConstant(1, MVT::i32));
1389 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1391 Chain = Val.getValue(1);
1392 InFlag = Val.getValue(2);
1395 switch (VA.getLocInfo()) {
1396 default: llvm_unreachable("Unknown loc info!");
1397 case CCValAssign::Full: break;
1398 case CCValAssign::BCvt:
1399 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1403 InVals.push_back(Val);
1409 /// LowerMemOpCallTo - Store the argument to the stack.
1411 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1412 SDValue StackPtr, SDValue Arg,
1413 SDLoc dl, SelectionDAG &DAG,
1414 const CCValAssign &VA,
1415 ISD::ArgFlagsTy Flags) const {
1416 unsigned LocMemOffset = VA.getLocMemOffset();
1417 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1418 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1419 return DAG.getStore(Chain, dl, Arg, PtrOff,
1420 MachinePointerInfo::getStack(LocMemOffset),
1424 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1425 SDValue Chain, SDValue &Arg,
1426 RegsToPassVector &RegsToPass,
1427 CCValAssign &VA, CCValAssign &NextVA,
1429 SmallVectorImpl<SDValue> &MemOpChains,
1430 ISD::ArgFlagsTy Flags) const {
1432 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1433 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1434 unsigned id = Subtarget->isLittle() ? 0 : 1;
1435 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1437 if (NextVA.isRegLoc())
1438 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1440 assert(NextVA.isMemLoc());
1441 if (!StackPtr.getNode())
1442 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1444 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1450 /// LowerCall - Lowering a call into a callseq_start <-
1451 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1454 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1455 SmallVectorImpl<SDValue> &InVals) const {
1456 SelectionDAG &DAG = CLI.DAG;
1458 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1459 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1460 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1461 SDValue Chain = CLI.Chain;
1462 SDValue Callee = CLI.Callee;
1463 bool &isTailCall = CLI.IsTailCall;
1464 CallingConv::ID CallConv = CLI.CallConv;
1465 bool doesNotRet = CLI.DoesNotReturn;
1466 bool isVarArg = CLI.IsVarArg;
1468 MachineFunction &MF = DAG.getMachineFunction();
1469 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1470 bool isThisReturn = false;
1471 bool isSibCall = false;
1473 // Disable tail calls if they're not supported.
1474 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1478 // Check if it's really possible to do a tail call.
1479 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1480 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1481 Outs, OutVals, Ins, DAG);
1482 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1483 report_fatal_error("failed to perform tail call elimination on a call "
1484 "site marked musttail");
1485 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1486 // detected sibcalls.
1493 // Analyze operands of the call, assigning locations to each operand.
1494 SmallVector<CCValAssign, 16> ArgLocs;
1495 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1496 *DAG.getContext(), Call);
1497 CCInfo.AnalyzeCallOperands(Outs,
1498 CCAssignFnForNode(CallConv, /* Return*/ false,
1501 // Get a count of how many bytes are to be pushed on the stack.
1502 unsigned NumBytes = CCInfo.getNextStackOffset();
1504 // For tail calls, memory operands are available in our caller's stack.
1508 // Adjust the stack pointer for the new arguments...
1509 // These operations are automatically eliminated by the prolog/epilog pass
1511 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1514 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1516 RegsToPassVector RegsToPass;
1517 SmallVector<SDValue, 8> MemOpChains;
1519 // Walk the register/memloc assignments, inserting copies/loads. In the case
1520 // of tail call optimization, arguments are handled later.
1521 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1523 ++i, ++realArgIdx) {
1524 CCValAssign &VA = ArgLocs[i];
1525 SDValue Arg = OutVals[realArgIdx];
1526 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1527 bool isByVal = Flags.isByVal();
1529 // Promote the value if needed.
1530 switch (VA.getLocInfo()) {
1531 default: llvm_unreachable("Unknown loc info!");
1532 case CCValAssign::Full: break;
1533 case CCValAssign::SExt:
1534 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1536 case CCValAssign::ZExt:
1537 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1539 case CCValAssign::AExt:
1540 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1542 case CCValAssign::BCvt:
1543 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1547 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1548 if (VA.needsCustom()) {
1549 if (VA.getLocVT() == MVT::v2f64) {
1550 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1551 DAG.getConstant(0, MVT::i32));
1552 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1553 DAG.getConstant(1, MVT::i32));
1555 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1556 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1558 VA = ArgLocs[++i]; // skip ahead to next loc
1559 if (VA.isRegLoc()) {
1560 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1561 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1563 assert(VA.isMemLoc());
1565 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1566 dl, DAG, VA, Flags));
1569 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1570 StackPtr, MemOpChains, Flags);
1572 } else if (VA.isRegLoc()) {
1573 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1574 assert(VA.getLocVT() == MVT::i32 &&
1575 "unexpected calling convention register assignment");
1576 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1577 "unexpected use of 'returned'");
1578 isThisReturn = true;
1580 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1581 } else if (isByVal) {
1582 assert(VA.isMemLoc());
1583 unsigned offset = 0;
1585 // True if this byval aggregate will be split between registers
1587 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1588 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1590 if (CurByValIdx < ByValArgsCount) {
1592 unsigned RegBegin, RegEnd;
1593 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1595 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1597 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1598 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1599 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1600 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1601 MachinePointerInfo(),
1602 false, false, false,
1603 DAG.InferPtrAlignment(AddArg));
1604 MemOpChains.push_back(Load.getValue(1));
1605 RegsToPass.push_back(std::make_pair(j, Load));
1608 // If parameter size outsides register area, "offset" value
1609 // helps us to calculate stack slot for remained part properly.
1610 offset = RegEnd - RegBegin;
1612 CCInfo.nextInRegsParam();
1615 if (Flags.getByValSize() > 4*offset) {
1616 unsigned LocMemOffset = VA.getLocMemOffset();
1617 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1618 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1620 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1621 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1622 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1624 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1626 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1627 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1628 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1631 } else if (!isSibCall) {
1632 assert(VA.isMemLoc());
1634 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1635 dl, DAG, VA, Flags));
1639 if (!MemOpChains.empty())
1640 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1642 // Build a sequence of copy-to-reg nodes chained together with token chain
1643 // and flag operands which copy the outgoing args into the appropriate regs.
1645 // Tail call byval lowering might overwrite argument registers so in case of
1646 // tail call optimization the copies to registers are lowered later.
1648 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1649 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1650 RegsToPass[i].second, InFlag);
1651 InFlag = Chain.getValue(1);
1654 // For tail calls lower the arguments to the 'real' stack slot.
1656 // Force all the incoming stack arguments to be loaded from the stack
1657 // before any new outgoing arguments are stored to the stack, because the
1658 // outgoing stack slots may alias the incoming argument stack slots, and
1659 // the alias isn't otherwise explicit. This is slightly more conservative
1660 // than necessary, because it means that each store effectively depends
1661 // on every argument instead of just those arguments it would clobber.
1663 // Do not flag preceding copytoreg stuff together with the following stuff.
1665 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1666 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1667 RegsToPass[i].second, InFlag);
1668 InFlag = Chain.getValue(1);
1673 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1674 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1675 // node so that legalize doesn't hack it.
1676 bool isDirect = false;
1677 bool isARMFunc = false;
1678 bool isLocalARMFunc = false;
1679 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1681 if (EnableARMLongCalls) {
1682 assert((Subtarget->isTargetWindows() ||
1683 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1684 "long-calls with non-static relocation model!");
1685 // Handle a global address or an external symbol. If it's not one of
1686 // those, the target's already in a register, so we don't need to do
1688 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1689 const GlobalValue *GV = G->getGlobal();
1690 // Create a constant pool entry for the callee address
1691 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1692 ARMConstantPoolValue *CPV =
1693 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1695 // Get the address of the callee into a register
1696 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1697 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1698 Callee = DAG.getLoad(getPointerTy(), dl,
1699 DAG.getEntryNode(), CPAddr,
1700 MachinePointerInfo::getConstantPool(),
1701 false, false, false, 0);
1702 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1703 const char *Sym = S->getSymbol();
1705 // Create a constant pool entry for the callee address
1706 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1707 ARMConstantPoolValue *CPV =
1708 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1709 ARMPCLabelIndex, 0);
1710 // Get the address of the callee into a register
1711 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1712 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1713 Callee = DAG.getLoad(getPointerTy(), dl,
1714 DAG.getEntryNode(), CPAddr,
1715 MachinePointerInfo::getConstantPool(),
1716 false, false, false, 0);
1718 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1719 const GlobalValue *GV = G->getGlobal();
1721 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1722 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1723 getTargetMachine().getRelocationModel() != Reloc::Static;
1724 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1725 // ARM call to a local ARM function is predicable.
1726 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1727 // tBX takes a register source operand.
1728 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1729 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1730 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1731 DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1732 0, ARMII::MO_NONLAZY));
1733 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1734 MachinePointerInfo::getGOT(), false, false, true, 0);
1735 } else if (Subtarget->isTargetCOFF()) {
1736 assert(Subtarget->isTargetWindows() &&
1737 "Windows is the only supported COFF target");
1738 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1739 ? ARMII::MO_DLLIMPORT
1740 : ARMII::MO_NO_FLAG;
1741 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1743 if (GV->hasDLLImportStorageClass())
1744 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1745 DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1746 Callee), MachinePointerInfo::getGOT(),
1747 false, false, false, 0);
1749 // On ELF targets for PIC code, direct calls should go through the PLT
1750 unsigned OpFlags = 0;
1751 if (Subtarget->isTargetELF() &&
1752 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1753 OpFlags = ARMII::MO_PLT;
1754 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1756 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1758 bool isStub = Subtarget->isTargetMachO() &&
1759 getTargetMachine().getRelocationModel() != Reloc::Static;
1760 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1761 // tBX takes a register source operand.
1762 const char *Sym = S->getSymbol();
1763 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1764 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1765 ARMConstantPoolValue *CPV =
1766 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1767 ARMPCLabelIndex, 4);
1768 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1769 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1770 Callee = DAG.getLoad(getPointerTy(), dl,
1771 DAG.getEntryNode(), CPAddr,
1772 MachinePointerInfo::getConstantPool(),
1773 false, false, false, 0);
1774 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1775 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1776 getPointerTy(), Callee, PICLabel);
1778 unsigned OpFlags = 0;
1779 // On ELF targets for PIC code, direct calls should go through the PLT
1780 if (Subtarget->isTargetELF() &&
1781 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1782 OpFlags = ARMII::MO_PLT;
1783 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1787 // FIXME: handle tail calls differently.
1789 bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1790 AttributeSet::FunctionIndex, Attribute::MinSize);
1791 if (Subtarget->isThumb()) {
1792 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1793 CallOpc = ARMISD::CALL_NOLINK;
1795 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1797 if (!isDirect && !Subtarget->hasV5TOps())
1798 CallOpc = ARMISD::CALL_NOLINK;
1799 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1800 // Emit regular call when code size is the priority
1802 // "mov lr, pc; b _foo" to avoid confusing the RSP
1803 CallOpc = ARMISD::CALL_NOLINK;
1805 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1808 std::vector<SDValue> Ops;
1809 Ops.push_back(Chain);
1810 Ops.push_back(Callee);
1812 // Add argument registers to the end of the list so that they are known live
1814 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1815 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1816 RegsToPass[i].second.getValueType()));
1818 // Add a register mask operand representing the call-preserved registers.
1820 const uint32_t *Mask;
1821 const TargetRegisterInfo *TRI =
1822 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1823 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1825 // For 'this' returns, use the R0-preserving mask if applicable
1826 Mask = ARI->getThisReturnPreservedMask(CallConv);
1828 // Set isThisReturn to false if the calling convention is not one that
1829 // allows 'returned' to be modeled in this way, so LowerCallResult does
1830 // not try to pass 'this' straight through
1831 isThisReturn = false;
1832 Mask = ARI->getCallPreservedMask(CallConv);
1835 Mask = ARI->getCallPreservedMask(CallConv);
1837 assert(Mask && "Missing call preserved mask for calling convention");
1838 Ops.push_back(DAG.getRegisterMask(Mask));
1841 if (InFlag.getNode())
1842 Ops.push_back(InFlag);
1844 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1846 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1848 // Returns a chain and a flag for retval copy to use.
1849 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1850 InFlag = Chain.getValue(1);
1852 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1853 DAG.getIntPtrConstant(0, true), InFlag, dl);
1855 InFlag = Chain.getValue(1);
1857 // Handle result values, copying them out of physregs into vregs that we
1859 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1860 InVals, isThisReturn,
1861 isThisReturn ? OutVals[0] : SDValue());
1864 /// HandleByVal - Every parameter *after* a byval parameter is passed
1865 /// on the stack. Remember the next parameter register to allocate,
1866 /// and then confiscate the rest of the parameter registers to insure
1869 ARMTargetLowering::HandleByVal(
1870 CCState *State, unsigned &size, unsigned Align) const {
1871 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1872 assert((State->getCallOrPrologue() == Prologue ||
1873 State->getCallOrPrologue() == Call) &&
1874 "unhandled ParmContext");
1876 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1877 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1878 unsigned AlignInRegs = Align / 4;
1879 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1880 for (unsigned i = 0; i < Waste; ++i)
1881 reg = State->AllocateReg(GPRArgRegs, 4);
1884 unsigned excess = 4 * (ARM::R4 - reg);
1886 // Special case when NSAA != SP and parameter size greater than size of
1887 // all remained GPR regs. In that case we can't split parameter, we must
1888 // send it to stack. We also must set NCRN to R4, so waste all
1889 // remained registers.
1890 const unsigned NSAAOffset = State->getNextStackOffset();
1891 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1892 while (State->AllocateReg(GPRArgRegs, 4))
1897 // First register for byval parameter is the first register that wasn't
1898 // allocated before this method call, so it would be "reg".
1899 // If parameter is small enough to be saved in range [reg, r4), then
1900 // the end (first after last) register would be reg + param-size-in-regs,
1901 // else parameter would be splitted between registers and stack,
1902 // end register would be r4 in this case.
1903 unsigned ByValRegBegin = reg;
1904 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1905 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1906 // Note, first register is allocated in the beginning of function already,
1907 // allocate remained amount of registers we need.
1908 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1909 State->AllocateReg(GPRArgRegs, 4);
1910 // A byval parameter that is split between registers and memory needs its
1911 // size truncated here.
1912 // In the case where the entire structure fits in registers, we set the
1913 // size in memory to zero.
1922 /// MatchingStackOffset - Return true if the given stack call argument is
1923 /// already available in the same position (relatively) of the caller's
1924 /// incoming argument stack.
1926 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1927 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1928 const TargetInstrInfo *TII) {
1929 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1931 if (Arg.getOpcode() == ISD::CopyFromReg) {
1932 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1933 if (!TargetRegisterInfo::isVirtualRegister(VR))
1935 MachineInstr *Def = MRI->getVRegDef(VR);
1938 if (!Flags.isByVal()) {
1939 if (!TII->isLoadFromStackSlot(Def, FI))
1944 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1945 if (Flags.isByVal())
1946 // ByVal argument is passed in as a pointer but it's now being
1947 // dereferenced. e.g.
1948 // define @foo(%struct.X* %A) {
1949 // tail call @bar(%struct.X* byval %A)
1952 SDValue Ptr = Ld->getBasePtr();
1953 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1956 FI = FINode->getIndex();
1960 assert(FI != INT_MAX);
1961 if (!MFI->isFixedObjectIndex(FI))
1963 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1966 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1967 /// for tail call optimization. Targets which want to do tail call
1968 /// optimization should implement this function.
1970 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1971 CallingConv::ID CalleeCC,
1973 bool isCalleeStructRet,
1974 bool isCallerStructRet,
1975 const SmallVectorImpl<ISD::OutputArg> &Outs,
1976 const SmallVectorImpl<SDValue> &OutVals,
1977 const SmallVectorImpl<ISD::InputArg> &Ins,
1978 SelectionDAG& DAG) const {
1979 const Function *CallerF = DAG.getMachineFunction().getFunction();
1980 CallingConv::ID CallerCC = CallerF->getCallingConv();
1981 bool CCMatch = CallerCC == CalleeCC;
1983 // Look for obvious safe cases to perform tail call optimization that do not
1984 // require ABI changes. This is what gcc calls sibcall.
1986 // Do not sibcall optimize vararg calls unless the call site is not passing
1988 if (isVarArg && !Outs.empty())
1991 // Exception-handling functions need a special set of instructions to indicate
1992 // a return to the hardware. Tail-calling another function would probably
1994 if (CallerF->hasFnAttribute("interrupt"))
1997 // Also avoid sibcall optimization if either caller or callee uses struct
1998 // return semantics.
1999 if (isCalleeStructRet || isCallerStructRet)
2002 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
2003 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2004 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2005 // support in the assembler and linker to be used. This would need to be
2006 // fixed to fully support tail calls in Thumb1.
2008 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2009 // LR. This means if we need to reload LR, it takes an extra instructions,
2010 // which outweighs the value of the tail call; but here we don't know yet
2011 // whether LR is going to be used. Probably the right approach is to
2012 // generate the tail call here and turn it back into CALL/RET in
2013 // emitEpilogue if LR is used.
2015 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2016 // but we need to make sure there are enough registers; the only valid
2017 // registers are the 4 used for parameters. We don't currently do this
2019 if (Subtarget->isThumb1Only())
2022 // Externally-defined functions with weak linkage should not be
2023 // tail-called on ARM when the OS does not support dynamic
2024 // pre-emption of symbols, as the AAELF spec requires normal calls
2025 // to undefined weak functions to be replaced with a NOP or jump to the
2026 // next instruction. The behaviour of branch instructions in this
2027 // situation (as used for tail calls) is implementation-defined, so we
2028 // cannot rely on the linker replacing the tail call with a return.
2029 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2030 const GlobalValue *GV = G->getGlobal();
2031 if (GV->hasExternalWeakLinkage())
2035 // If the calling conventions do not match, then we'd better make sure the
2036 // results are returned in the same way as what the caller expects.
2038 SmallVector<CCValAssign, 16> RVLocs1;
2039 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2040 *DAG.getContext(), Call);
2041 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2043 SmallVector<CCValAssign, 16> RVLocs2;
2044 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2045 *DAG.getContext(), Call);
2046 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2048 if (RVLocs1.size() != RVLocs2.size())
2050 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2051 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2053 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2055 if (RVLocs1[i].isRegLoc()) {
2056 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2059 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2065 // If Caller's vararg or byval argument has been split between registers and
2066 // stack, do not perform tail call, since part of the argument is in caller's
2068 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2069 getInfo<ARMFunctionInfo>();
2070 if (AFI_Caller->getArgRegsSaveSize())
2073 // If the callee takes no arguments then go on to check the results of the
2075 if (!Outs.empty()) {
2076 // Check if stack adjustment is needed. For now, do not do this if any
2077 // argument is passed on the stack.
2078 SmallVector<CCValAssign, 16> ArgLocs;
2079 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2080 *DAG.getContext(), Call);
2081 CCInfo.AnalyzeCallOperands(Outs,
2082 CCAssignFnForNode(CalleeCC, false, isVarArg));
2083 if (CCInfo.getNextStackOffset()) {
2084 MachineFunction &MF = DAG.getMachineFunction();
2086 // Check if the arguments are already laid out in the right way as
2087 // the caller's fixed stack objects.
2088 MachineFrameInfo *MFI = MF.getFrameInfo();
2089 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2090 const TargetInstrInfo *TII =
2091 getTargetMachine().getSubtargetImpl()->getInstrInfo();
2092 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2094 ++i, ++realArgIdx) {
2095 CCValAssign &VA = ArgLocs[i];
2096 EVT RegVT = VA.getLocVT();
2097 SDValue Arg = OutVals[realArgIdx];
2098 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2099 if (VA.getLocInfo() == CCValAssign::Indirect)
2101 if (VA.needsCustom()) {
2102 // f64 and vector types are split into multiple registers or
2103 // register/stack-slot combinations. The types will not match
2104 // the registers; give up on memory f64 refs until we figure
2105 // out what to do about this.
2108 if (!ArgLocs[++i].isRegLoc())
2110 if (RegVT == MVT::v2f64) {
2111 if (!ArgLocs[++i].isRegLoc())
2113 if (!ArgLocs[++i].isRegLoc())
2116 } else if (!VA.isRegLoc()) {
2117 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2129 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2130 MachineFunction &MF, bool isVarArg,
2131 const SmallVectorImpl<ISD::OutputArg> &Outs,
2132 LLVMContext &Context) const {
2133 SmallVector<CCValAssign, 16> RVLocs;
2134 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2135 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2139 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2140 SDLoc DL, SelectionDAG &DAG) {
2141 const MachineFunction &MF = DAG.getMachineFunction();
2142 const Function *F = MF.getFunction();
2144 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2146 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2147 // version of the "preferred return address". These offsets affect the return
2148 // instruction if this is a return from PL1 without hypervisor extensions.
2149 // IRQ/FIQ: +4 "subs pc, lr, #4"
2150 // SWI: 0 "subs pc, lr, #0"
2151 // ABORT: +4 "subs pc, lr, #4"
2152 // UNDEF: +4/+2 "subs pc, lr, #0"
2153 // UNDEF varies depending on where the exception came from ARM or Thumb
2154 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2157 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2160 else if (IntKind == "SWI" || IntKind == "UNDEF")
2163 report_fatal_error("Unsupported interrupt attribute. If present, value "
2164 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2166 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2168 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2172 ARMTargetLowering::LowerReturn(SDValue Chain,
2173 CallingConv::ID CallConv, bool isVarArg,
2174 const SmallVectorImpl<ISD::OutputArg> &Outs,
2175 const SmallVectorImpl<SDValue> &OutVals,
2176 SDLoc dl, SelectionDAG &DAG) const {
2178 // CCValAssign - represent the assignment of the return value to a location.
2179 SmallVector<CCValAssign, 16> RVLocs;
2181 // CCState - Info about the registers and stack slots.
2182 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2183 *DAG.getContext(), Call);
2185 // Analyze outgoing return values.
2186 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2190 SmallVector<SDValue, 4> RetOps;
2191 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2192 bool isLittleEndian = Subtarget->isLittle();
2194 MachineFunction &MF = DAG.getMachineFunction();
2195 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2196 AFI->setReturnRegsCount(RVLocs.size());
2198 // Copy the result values into the output registers.
2199 for (unsigned i = 0, realRVLocIdx = 0;
2201 ++i, ++realRVLocIdx) {
2202 CCValAssign &VA = RVLocs[i];
2203 assert(VA.isRegLoc() && "Can only return in registers!");
2205 SDValue Arg = OutVals[realRVLocIdx];
2207 switch (VA.getLocInfo()) {
2208 default: llvm_unreachable("Unknown loc info!");
2209 case CCValAssign::Full: break;
2210 case CCValAssign::BCvt:
2211 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2215 if (VA.needsCustom()) {
2216 if (VA.getLocVT() == MVT::v2f64) {
2217 // Extract the first half and return it in two registers.
2218 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2219 DAG.getConstant(0, MVT::i32));
2220 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2221 DAG.getVTList(MVT::i32, MVT::i32), Half);
2223 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2224 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2226 Flag = Chain.getValue(1);
2227 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2228 VA = RVLocs[++i]; // skip ahead to next loc
2229 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2230 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2232 Flag = Chain.getValue(1);
2233 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2234 VA = RVLocs[++i]; // skip ahead to next loc
2236 // Extract the 2nd half and fall through to handle it as an f64 value.
2237 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2238 DAG.getConstant(1, MVT::i32));
2240 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2242 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2243 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2244 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2245 fmrrd.getValue(isLittleEndian ? 0 : 1),
2247 Flag = Chain.getValue(1);
2248 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2249 VA = RVLocs[++i]; // skip ahead to next loc
2250 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2251 fmrrd.getValue(isLittleEndian ? 1 : 0),
2254 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2256 // Guarantee that all emitted copies are
2257 // stuck together, avoiding something bad.
2258 Flag = Chain.getValue(1);
2259 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2262 // Update chain and glue.
2265 RetOps.push_back(Flag);
2267 // CPUs which aren't M-class use a special sequence to return from
2268 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2269 // though we use "subs pc, lr, #N").
2271 // M-class CPUs actually use a normal return sequence with a special
2272 // (hardware-provided) value in LR, so the normal code path works.
2273 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2274 !Subtarget->isMClass()) {
2275 if (Subtarget->isThumb1Only())
2276 report_fatal_error("interrupt attribute is not supported in Thumb1");
2277 return LowerInterruptReturn(RetOps, dl, DAG);
2280 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2283 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2284 if (N->getNumValues() != 1)
2286 if (!N->hasNUsesOfValue(1, 0))
2289 SDValue TCChain = Chain;
2290 SDNode *Copy = *N->use_begin();
2291 if (Copy->getOpcode() == ISD::CopyToReg) {
2292 // If the copy has a glue operand, we conservatively assume it isn't safe to
2293 // perform a tail call.
2294 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2296 TCChain = Copy->getOperand(0);
2297 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2298 SDNode *VMov = Copy;
2299 // f64 returned in a pair of GPRs.
2300 SmallPtrSet<SDNode*, 2> Copies;
2301 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2303 if (UI->getOpcode() != ISD::CopyToReg)
2307 if (Copies.size() > 2)
2310 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2312 SDValue UseChain = UI->getOperand(0);
2313 if (Copies.count(UseChain.getNode()))
2320 } else if (Copy->getOpcode() == ISD::BITCAST) {
2321 // f32 returned in a single GPR.
2322 if (!Copy->hasOneUse())
2324 Copy = *Copy->use_begin();
2325 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2327 TCChain = Copy->getOperand(0);
2332 bool HasRet = false;
2333 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2335 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2336 UI->getOpcode() != ARMISD::INTRET_FLAG)
2348 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2349 if (!Subtarget->supportsTailCall())
2352 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2355 return !Subtarget->isThumb1Only();
2358 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2359 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2360 // one of the above mentioned nodes. It has to be wrapped because otherwise
2361 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2362 // be used to form addressing mode. These wrapped nodes will be selected
2364 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2365 EVT PtrVT = Op.getValueType();
2366 // FIXME there is no actual debug info here
2368 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2370 if (CP->isMachineConstantPoolEntry())
2371 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2372 CP->getAlignment());
2374 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2375 CP->getAlignment());
2376 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2379 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2380 return MachineJumpTableInfo::EK_Inline;
2383 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2384 SelectionDAG &DAG) const {
2385 MachineFunction &MF = DAG.getMachineFunction();
2386 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2387 unsigned ARMPCLabelIndex = 0;
2389 EVT PtrVT = getPointerTy();
2390 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2391 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2393 if (RelocM == Reloc::Static) {
2394 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2396 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2397 ARMPCLabelIndex = AFI->createPICLabelUId();
2398 ARMConstantPoolValue *CPV =
2399 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2400 ARMCP::CPBlockAddress, PCAdj);
2401 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2403 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2404 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2405 MachinePointerInfo::getConstantPool(),
2406 false, false, false, 0);
2407 if (RelocM == Reloc::Static)
2409 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2410 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2413 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2415 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2416 SelectionDAG &DAG) const {
2418 EVT PtrVT = getPointerTy();
2419 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2420 MachineFunction &MF = DAG.getMachineFunction();
2421 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2422 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2423 ARMConstantPoolValue *CPV =
2424 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2425 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2426 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2427 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2428 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2429 MachinePointerInfo::getConstantPool(),
2430 false, false, false, 0);
2431 SDValue Chain = Argument.getValue(1);
2433 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2434 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2436 // call __tls_get_addr.
2439 Entry.Node = Argument;
2440 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2441 Args.push_back(Entry);
2443 // FIXME: is there useful debug info available here?
2444 TargetLowering::CallLoweringInfo CLI(DAG);
2445 CLI.setDebugLoc(dl).setChain(Chain)
2446 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2447 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2450 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2451 return CallResult.first;
2454 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2455 // "local exec" model.
2457 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2459 TLSModel::Model model) const {
2460 const GlobalValue *GV = GA->getGlobal();
2463 SDValue Chain = DAG.getEntryNode();
2464 EVT PtrVT = getPointerTy();
2465 // Get the Thread Pointer
2466 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2468 if (model == TLSModel::InitialExec) {
2469 MachineFunction &MF = DAG.getMachineFunction();
2470 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2471 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2472 // Initial exec model.
2473 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2474 ARMConstantPoolValue *CPV =
2475 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2476 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2478 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2479 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2480 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2481 MachinePointerInfo::getConstantPool(),
2482 false, false, false, 0);
2483 Chain = Offset.getValue(1);
2485 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2486 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2488 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2489 MachinePointerInfo::getConstantPool(),
2490 false, false, false, 0);
2493 assert(model == TLSModel::LocalExec);
2494 ARMConstantPoolValue *CPV =
2495 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2496 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2497 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2498 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2499 MachinePointerInfo::getConstantPool(),
2500 false, false, false, 0);
2503 // The address of the thread local variable is the add of the thread
2504 // pointer with the offset of the variable.
2505 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2509 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2510 // TODO: implement the "local dynamic" model
2511 assert(Subtarget->isTargetELF() &&
2512 "TLS not implemented for non-ELF targets");
2513 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2515 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2518 case TLSModel::GeneralDynamic:
2519 case TLSModel::LocalDynamic:
2520 return LowerToTLSGeneralDynamicModel(GA, DAG);
2521 case TLSModel::InitialExec:
2522 case TLSModel::LocalExec:
2523 return LowerToTLSExecModels(GA, DAG, model);
2525 llvm_unreachable("bogus TLS model");
2528 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2529 SelectionDAG &DAG) const {
2530 EVT PtrVT = getPointerTy();
2532 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2533 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2534 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2535 ARMConstantPoolValue *CPV =
2536 ARMConstantPoolConstant::Create(GV,
2537 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2538 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2539 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2540 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2542 MachinePointerInfo::getConstantPool(),
2543 false, false, false, 0);
2544 SDValue Chain = Result.getValue(1);
2545 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2546 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2548 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2549 MachinePointerInfo::getGOT(),
2550 false, false, false, 0);
2554 // If we have T2 ops, we can materialize the address directly via movt/movw
2555 // pair. This is always cheaper.
2556 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2558 // FIXME: Once remat is capable of dealing with instructions with register
2559 // operands, expand this into two nodes.
2560 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2561 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2563 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2564 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2565 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2566 MachinePointerInfo::getConstantPool(),
2567 false, false, false, 0);
2571 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2572 SelectionDAG &DAG) const {
2573 EVT PtrVT = getPointerTy();
2575 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2576 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2578 if (Subtarget->useMovt(DAG.getMachineFunction()))
2581 // FIXME: Once remat is capable of dealing with instructions with register
2582 // operands, expand this into multiple nodes
2584 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2586 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2587 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2589 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2590 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2591 MachinePointerInfo::getGOT(), false, false, false, 0);
2595 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2596 SelectionDAG &DAG) const {
2597 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2598 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2599 "Windows on ARM expects to use movw/movt");
2601 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2602 const ARMII::TOF TargetFlags =
2603 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2604 EVT PtrVT = getPointerTy();
2610 // FIXME: Once remat is capable of dealing with instructions with register
2611 // operands, expand this into two nodes.
2612 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2613 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2615 if (GV->hasDLLImportStorageClass())
2616 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2617 MachinePointerInfo::getGOT(), false, false, false, 0);
2621 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2622 SelectionDAG &DAG) const {
2623 assert(Subtarget->isTargetELF() &&
2624 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2625 MachineFunction &MF = DAG.getMachineFunction();
2626 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2627 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2628 EVT PtrVT = getPointerTy();
2630 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2631 ARMConstantPoolValue *CPV =
2632 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2633 ARMPCLabelIndex, PCAdj);
2634 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2635 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2636 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2637 MachinePointerInfo::getConstantPool(),
2638 false, false, false, 0);
2639 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2640 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2644 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2646 SDValue Val = DAG.getConstant(0, MVT::i32);
2647 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2648 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2649 Op.getOperand(1), Val);
2653 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2655 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2656 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2660 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2661 const ARMSubtarget *Subtarget) const {
2662 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2665 default: return SDValue(); // Don't custom lower most intrinsics.
2666 case Intrinsic::arm_rbit: {
2667 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2668 "RBIT intrinsic must have i32 type!");
2669 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2671 case Intrinsic::arm_thread_pointer: {
2672 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2673 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2675 case Intrinsic::eh_sjlj_lsda: {
2676 MachineFunction &MF = DAG.getMachineFunction();
2677 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2678 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2679 EVT PtrVT = getPointerTy();
2680 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2682 unsigned PCAdj = (RelocM != Reloc::PIC_)
2683 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2684 ARMConstantPoolValue *CPV =
2685 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2686 ARMCP::CPLSDA, PCAdj);
2687 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2688 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2690 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2691 MachinePointerInfo::getConstantPool(),
2692 false, false, false, 0);
2694 if (RelocM == Reloc::PIC_) {
2695 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2696 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2700 case Intrinsic::arm_neon_vmulls:
2701 case Intrinsic::arm_neon_vmullu: {
2702 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2703 ? ARMISD::VMULLs : ARMISD::VMULLu;
2704 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2705 Op.getOperand(1), Op.getOperand(2));
2710 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2711 const ARMSubtarget *Subtarget) {
2712 // FIXME: handle "fence singlethread" more efficiently.
2714 if (!Subtarget->hasDataBarrier()) {
2715 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2716 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2718 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2719 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2720 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2721 DAG.getConstant(0, MVT::i32));
2724 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2725 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2726 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2727 if (Subtarget->isMClass()) {
2728 // Only a full system barrier exists in the M-class architectures.
2729 Domain = ARM_MB::SY;
2730 } else if (Subtarget->isSwift() && Ord == Release) {
2731 // Swift happens to implement ISHST barriers in a way that's compatible with
2732 // Release semantics but weaker than ISH so we'd be fools not to use
2733 // it. Beware: other processors probably don't!
2734 Domain = ARM_MB::ISHST;
2737 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2738 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2739 DAG.getConstant(Domain, MVT::i32));
2742 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2743 const ARMSubtarget *Subtarget) {
2744 // ARM pre v5TE and Thumb1 does not have preload instructions.
2745 if (!(Subtarget->isThumb2() ||
2746 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2747 // Just preserve the chain.
2748 return Op.getOperand(0);
2751 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2753 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2754 // ARMv7 with MP extension has PLDW.
2755 return Op.getOperand(0);
2757 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2758 if (Subtarget->isThumb()) {
2760 isRead = ~isRead & 1;
2761 isData = ~isData & 1;
2764 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2765 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2766 DAG.getConstant(isData, MVT::i32));
2769 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2770 MachineFunction &MF = DAG.getMachineFunction();
2771 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2773 // vastart just stores the address of the VarArgsFrameIndex slot into the
2774 // memory location argument.
2776 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2777 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2778 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2779 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2780 MachinePointerInfo(SV), false, false, 0);
2784 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2785 SDValue &Root, SelectionDAG &DAG,
2787 MachineFunction &MF = DAG.getMachineFunction();
2788 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2790 const TargetRegisterClass *RC;
2791 if (AFI->isThumb1OnlyFunction())
2792 RC = &ARM::tGPRRegClass;
2794 RC = &ARM::GPRRegClass;
2796 // Transform the arguments stored in physical registers into virtual ones.
2797 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2798 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2801 if (NextVA.isMemLoc()) {
2802 MachineFrameInfo *MFI = MF.getFrameInfo();
2803 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2805 // Create load node to retrieve arguments from the stack.
2806 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2807 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2808 MachinePointerInfo::getFixedStack(FI),
2809 false, false, false, 0);
2811 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2812 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2814 if (!Subtarget->isLittle())
2815 std::swap (ArgValue, ArgValue2);
2816 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2820 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2821 unsigned InRegsParamRecordIdx,
2823 unsigned &ArgRegsSize,
2824 unsigned &ArgRegsSaveSize)
2827 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2828 unsigned RBegin, REnd;
2829 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2830 NumGPRs = REnd - RBegin;
2832 unsigned int firstUnalloced;
2833 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2834 sizeof(GPRArgRegs) /
2835 sizeof(GPRArgRegs[0]));
2836 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2839 unsigned Align = MF.getTarget()
2841 ->getFrameLowering()
2842 ->getStackAlignment();
2843 ArgRegsSize = NumGPRs * 4;
2845 // If parameter is split between stack and GPRs...
2846 if (NumGPRs && Align > 4 &&
2847 (ArgRegsSize < ArgSize ||
2848 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2849 // Add padding for part of param recovered from GPRs. For example,
2850 // if Align == 8, its last byte must be at address K*8 - 1.
2851 // We need to do it, since remained (stack) part of parameter has
2852 // stack alignment, and we need to "attach" "GPRs head" without gaps
2855 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2856 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2858 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2860 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2861 ArgRegsSaveSize = ArgRegsSize + Padding;
2863 // We don't need to extend regs save size for byval parameters if they
2864 // are passed via GPRs only.
2865 ArgRegsSaveSize = ArgRegsSize;
2868 // The remaining GPRs hold either the beginning of variable-argument
2869 // data, or the beginning of an aggregate passed by value (usually
2870 // byval). Either way, we allocate stack slots adjacent to the data
2871 // provided by our caller, and store the unallocated registers there.
2872 // If this is a variadic function, the va_list pointer will begin with
2873 // these values; otherwise, this reassembles a (byval) structure that
2874 // was split between registers and memory.
2875 // Return: The frame index registers were stored into.
2877 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2878 SDLoc dl, SDValue &Chain,
2879 const Value *OrigArg,
2880 unsigned InRegsParamRecordIdx,
2881 unsigned OffsetFromOrigArg,
2885 unsigned ByValStoreOffset,
2886 unsigned TotalArgRegsSaveSize) const {
2888 // Currently, two use-cases possible:
2889 // Case #1. Non-var-args function, and we meet first byval parameter.
2890 // Setup first unallocated register as first byval register;
2891 // eat all remained registers
2892 // (these two actions are performed by HandleByVal method).
2893 // Then, here, we initialize stack frame with
2894 // "store-reg" instructions.
2895 // Case #2. Var-args function, that doesn't contain byval parameters.
2896 // The same: eat all remained unallocated registers,
2897 // initialize stack frame.
2899 MachineFunction &MF = DAG.getMachineFunction();
2900 MachineFrameInfo *MFI = MF.getFrameInfo();
2901 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2902 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2903 unsigned RBegin, REnd;
2904 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2905 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2906 firstRegToSaveIndex = RBegin - ARM::R0;
2907 lastRegToSaveIndex = REnd - ARM::R0;
2909 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2910 (GPRArgRegs, array_lengthof(GPRArgRegs));
2911 lastRegToSaveIndex = 4;
2914 unsigned ArgRegsSize, ArgRegsSaveSize;
2915 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2916 ArgRegsSize, ArgRegsSaveSize);
2918 // Store any by-val regs to their spots on the stack so that they may be
2919 // loaded by deferencing the result of formal parameter pointer or va_next.
2920 // Note: once stack area for byval/varargs registers
2921 // was initialized, it can't be initialized again.
2922 if (ArgRegsSaveSize) {
2923 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2926 assert(AFI->getStoredByValParamsPadding() == 0 &&
2927 "The only parameter may be padded.");
2928 AFI->setStoredByValParamsPadding(Padding);
2931 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2934 (int64_t)TotalArgRegsSaveSize,
2936 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2938 MFI->CreateFixedObject(Padding,
2939 ArgOffset + ByValStoreOffset -
2940 (int64_t)ArgRegsSaveSize,
2944 SmallVector<SDValue, 4> MemOps;
2945 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2946 ++firstRegToSaveIndex, ++i) {
2947 const TargetRegisterClass *RC;
2948 if (AFI->isThumb1OnlyFunction())
2949 RC = &ARM::tGPRRegClass;
2951 RC = &ARM::GPRRegClass;
2953 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2954 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2956 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2957 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2959 MemOps.push_back(Store);
2960 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2961 DAG.getConstant(4, getPointerTy()));
2964 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2966 if (!MemOps.empty())
2967 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2971 // We cannot allocate a zero-byte object for the first variadic argument,
2972 // so just make up a size.
2975 // This will point to the next argument passed via stack.
2976 return MFI->CreateFixedObject(
2977 ArgSize, ArgOffset, !ForceMutable);
2981 // Setup stack frame, the va_list pointer will start from.
2983 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2984 SDLoc dl, SDValue &Chain,
2986 unsigned TotalArgRegsSaveSize,
2987 bool ForceMutable) const {
2988 MachineFunction &MF = DAG.getMachineFunction();
2989 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2991 // Try to store any remaining integer argument regs
2992 // to their spots on the stack so that they may be loaded by deferencing
2993 // the result of va_next.
2994 // If there is no regs to be stored, just point address after last
2995 // argument passed via stack.
2997 StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2998 CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2999 0, TotalArgRegsSaveSize);
3001 AFI->setVarArgsFrameIndex(FrameIndex);
3005 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3006 CallingConv::ID CallConv, bool isVarArg,
3007 const SmallVectorImpl<ISD::InputArg>
3009 SDLoc dl, SelectionDAG &DAG,
3010 SmallVectorImpl<SDValue> &InVals)
3012 MachineFunction &MF = DAG.getMachineFunction();
3013 MachineFrameInfo *MFI = MF.getFrameInfo();
3015 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3017 // Assign locations to all of the incoming arguments.
3018 SmallVector<CCValAssign, 16> ArgLocs;
3019 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3020 *DAG.getContext(), Prologue);
3021 CCInfo.AnalyzeFormalArguments(Ins,
3022 CCAssignFnForNode(CallConv, /* Return*/ false,
3025 SmallVector<SDValue, 16> ArgValues;
3026 int lastInsIndex = -1;
3028 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3029 unsigned CurArgIdx = 0;
3031 // Initially ArgRegsSaveSize is zero.
3032 // Then we increase this value each time we meet byval parameter.
3033 // We also increase this value in case of varargs function.
3034 AFI->setArgRegsSaveSize(0);
3036 unsigned ByValStoreOffset = 0;
3037 unsigned TotalArgRegsSaveSize = 0;
3038 unsigned ArgRegsSaveSizeMaxAlign = 4;
3040 // Calculate the amount of stack space that we need to allocate to store
3041 // byval and variadic arguments that are passed in registers.
3042 // We need to know this before we allocate the first byval or variadic
3043 // argument, as they will be allocated a stack slot below the CFA (Canonical
3044 // Frame Address, the stack pointer at entry to the function).
3045 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3046 CCValAssign &VA = ArgLocs[i];
3047 if (VA.isMemLoc()) {
3048 int index = VA.getValNo();
3049 if (index != lastInsIndex) {
3050 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3051 if (Flags.isByVal()) {
3052 unsigned ExtraArgRegsSize;
3053 unsigned ExtraArgRegsSaveSize;
3054 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
3055 Flags.getByValSize(),
3056 ExtraArgRegsSize, ExtraArgRegsSaveSize);
3058 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3059 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3060 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3061 CCInfo.nextInRegsParam();
3063 lastInsIndex = index;
3067 CCInfo.rewindByValRegsInfo();
3069 if (isVarArg && MFI->hasVAStart()) {
3070 unsigned ExtraArgRegsSize;
3071 unsigned ExtraArgRegsSaveSize;
3072 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3073 ExtraArgRegsSize, ExtraArgRegsSaveSize);
3074 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3076 // If the arg regs save area contains N-byte aligned values, the
3077 // bottom of it must be at least N-byte aligned.
3078 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3079 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3081 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3082 CCValAssign &VA = ArgLocs[i];
3083 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3084 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3085 // Arguments stored in registers.
3086 if (VA.isRegLoc()) {
3087 EVT RegVT = VA.getLocVT();
3089 if (VA.needsCustom()) {
3090 // f64 and vector types are split up into multiple registers or
3091 // combinations of registers and stack slots.
3092 if (VA.getLocVT() == MVT::v2f64) {
3093 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3095 VA = ArgLocs[++i]; // skip ahead to next loc
3097 if (VA.isMemLoc()) {
3098 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3099 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3100 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3101 MachinePointerInfo::getFixedStack(FI),
3102 false, false, false, 0);
3104 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3107 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3108 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3109 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3110 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3111 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3113 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3116 const TargetRegisterClass *RC;
3118 if (RegVT == MVT::f32)
3119 RC = &ARM::SPRRegClass;
3120 else if (RegVT == MVT::f64)
3121 RC = &ARM::DPRRegClass;
3122 else if (RegVT == MVT::v2f64)
3123 RC = &ARM::QPRRegClass;
3124 else if (RegVT == MVT::i32)
3125 RC = AFI->isThumb1OnlyFunction() ?
3126 (const TargetRegisterClass*)&ARM::tGPRRegClass :
3127 (const TargetRegisterClass*)&ARM::GPRRegClass;
3129 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3131 // Transform the arguments in physical registers into virtual ones.
3132 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3133 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3136 // If this is an 8 or 16-bit value, it is really passed promoted
3137 // to 32 bits. Insert an assert[sz]ext to capture this, then
3138 // truncate to the right size.
3139 switch (VA.getLocInfo()) {
3140 default: llvm_unreachable("Unknown loc info!");
3141 case CCValAssign::Full: break;
3142 case CCValAssign::BCvt:
3143 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3145 case CCValAssign::SExt:
3146 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3147 DAG.getValueType(VA.getValVT()));
3148 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3150 case CCValAssign::ZExt:
3151 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3152 DAG.getValueType(VA.getValVT()));
3153 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3157 InVals.push_back(ArgValue);
3159 } else { // VA.isRegLoc()
3162 assert(VA.isMemLoc());
3163 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3165 int index = ArgLocs[i].getValNo();
3167 // Some Ins[] entries become multiple ArgLoc[] entries.
3168 // Process them only once.
3169 if (index != lastInsIndex)
3171 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3172 // FIXME: For now, all byval parameter objects are marked mutable.
3173 // This can be changed with more analysis.
3174 // In case of tail call optimization mark all arguments mutable.
3175 // Since they could be overwritten by lowering of arguments in case of
3177 if (Flags.isByVal()) {
3178 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3180 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3181 int FrameIndex = StoreByValRegs(
3182 CCInfo, DAG, dl, Chain, CurOrigArg,
3184 Ins[VA.getValNo()].PartOffset,
3185 VA.getLocMemOffset(),
3186 Flags.getByValSize(),
3187 true /*force mutable frames*/,
3189 TotalArgRegsSaveSize);
3190 ByValStoreOffset += Flags.getByValSize();
3191 ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3192 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3193 CCInfo.nextInRegsParam();
3195 unsigned FIOffset = VA.getLocMemOffset();
3196 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3199 // Create load nodes to retrieve arguments from the stack.
3200 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3201 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3202 MachinePointerInfo::getFixedStack(FI),
3203 false, false, false, 0));
3205 lastInsIndex = index;
3211 if (isVarArg && MFI->hasVAStart())
3212 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3213 CCInfo.getNextStackOffset(),
3214 TotalArgRegsSaveSize);
3216 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3221 /// isFloatingPointZero - Return true if this is +0.0.
3222 static bool isFloatingPointZero(SDValue Op) {
3223 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3224 return CFP->getValueAPF().isPosZero();
3225 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3226 // Maybe this has already been legalized into the constant pool?
3227 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3228 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3229 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3230 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3231 return CFP->getValueAPF().isPosZero();
3237 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3238 /// the given operands.
3240 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3241 SDValue &ARMcc, SelectionDAG &DAG,
3243 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3244 unsigned C = RHSC->getZExtValue();
3245 if (!isLegalICmpImmediate(C)) {
3246 // Constant does not fit, try adjusting it by one?
3251 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3252 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3253 RHS = DAG.getConstant(C-1, MVT::i32);
3258 if (C != 0 && isLegalICmpImmediate(C-1)) {
3259 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3260 RHS = DAG.getConstant(C-1, MVT::i32);
3265 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3266 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3267 RHS = DAG.getConstant(C+1, MVT::i32);
3272 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3273 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3274 RHS = DAG.getConstant(C+1, MVT::i32);
3281 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3282 ARMISD::NodeType CompareType;
3285 CompareType = ARMISD::CMP;
3290 CompareType = ARMISD::CMPZ;
3293 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3294 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3297 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3299 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3301 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3303 if (!isFloatingPointZero(RHS))
3304 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3306 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3307 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3310 /// duplicateCmp - Glue values can have only one use, so this function
3311 /// duplicates a comparison node.
3313 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3314 unsigned Opc = Cmp.getOpcode();
3316 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3317 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3319 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3320 Cmp = Cmp.getOperand(0);
3321 Opc = Cmp.getOpcode();
3322 if (Opc == ARMISD::CMPFP)
3323 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3325 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3326 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3328 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3331 std::pair<SDValue, SDValue>
3332 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3333 SDValue &ARMcc) const {
3334 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3336 SDValue Value, OverflowCmp;
3337 SDValue LHS = Op.getOperand(0);
3338 SDValue RHS = Op.getOperand(1);
3341 // FIXME: We are currently always generating CMPs because we don't support
3342 // generating CMN through the backend. This is not as good as the natural
3343 // CMP case because it causes a register dependency and cannot be folded
3346 switch (Op.getOpcode()) {
3348 llvm_unreachable("Unknown overflow instruction!");
3350 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3351 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3352 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3355 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3356 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3357 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3360 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3361 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3362 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3365 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3366 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3367 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3371 return std::make_pair(Value, OverflowCmp);
3376 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3377 // Let legalize expand this if it isn't a legal type yet.
3378 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3381 SDValue Value, OverflowCmp;
3383 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3384 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3385 // We use 0 and 1 as false and true values.
3386 SDValue TVal = DAG.getConstant(1, MVT::i32);
3387 SDValue FVal = DAG.getConstant(0, MVT::i32);
3388 EVT VT = Op.getValueType();
3390 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3391 ARMcc, CCR, OverflowCmp);
3393 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3394 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3398 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3399 SDValue Cond = Op.getOperand(0);
3400 SDValue SelectTrue = Op.getOperand(1);
3401 SDValue SelectFalse = Op.getOperand(2);
3403 unsigned Opc = Cond.getOpcode();
3405 if (Cond.getResNo() == 1 &&
3406 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3407 Opc == ISD::USUBO)) {
3408 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3411 SDValue Value, OverflowCmp;
3413 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3414 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3415 EVT VT = Op.getValueType();
3417 return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3423 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3424 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3426 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3427 const ConstantSDNode *CMOVTrue =
3428 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3429 const ConstantSDNode *CMOVFalse =
3430 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3432 if (CMOVTrue && CMOVFalse) {
3433 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3434 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3438 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3440 False = SelectFalse;
3441 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3446 if (True.getNode() && False.getNode()) {
3447 EVT VT = Op.getValueType();
3448 SDValue ARMcc = Cond.getOperand(2);
3449 SDValue CCR = Cond.getOperand(3);
3450 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3451 assert(True.getValueType() == VT);
3452 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3457 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3458 // undefined bits before doing a full-word comparison with zero.
3459 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3460 DAG.getConstant(1, Cond.getValueType()));
3462 return DAG.getSelectCC(dl, Cond,
3463 DAG.getConstant(0, Cond.getValueType()),
3464 SelectTrue, SelectFalse, ISD::SETNE);
3467 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3468 if (CC == ISD::SETNE)
3470 return ISD::getSetCCInverse(CC, true);
3473 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3474 bool &swpCmpOps, bool &swpVselOps) {
3475 // Start by selecting the GE condition code for opcodes that return true for
3477 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3479 CondCode = ARMCC::GE;
3481 // and GT for opcodes that return false for 'equality'.
3482 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3484 CondCode = ARMCC::GT;
3486 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3487 // to swap the compare operands.
3488 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3492 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3493 // If we have an unordered opcode, we need to swap the operands to the VSEL
3494 // instruction (effectively negating the condition).
3496 // This also has the effect of swapping which one of 'less' or 'greater'
3497 // returns true, so we also swap the compare operands. It also switches
3498 // whether we return true for 'equality', so we compensate by picking the
3499 // opposite condition code to our original choice.
3500 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3501 CC == ISD::SETUGT) {
3502 swpCmpOps = !swpCmpOps;
3503 swpVselOps = !swpVselOps;
3504 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3507 // 'ordered' is 'anything but unordered', so use the VS condition code and
3508 // swap the VSEL operands.
3509 if (CC == ISD::SETO) {
3510 CondCode = ARMCC::VS;
3514 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3515 // code and swap the VSEL operands.
3516 if (CC == ISD::SETUNE) {
3517 CondCode = ARMCC::EQ;
3522 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3523 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3524 SDValue Cmp, SelectionDAG &DAG) const {
3525 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3526 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3527 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3528 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3529 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3531 SDValue TrueLow = TrueVal.getValue(0);
3532 SDValue TrueHigh = TrueVal.getValue(1);
3533 SDValue FalseLow = FalseVal.getValue(0);
3534 SDValue FalseHigh = FalseVal.getValue(1);
3536 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3538 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3539 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3541 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3543 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3548 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3549 EVT VT = Op.getValueType();
3550 SDValue LHS = Op.getOperand(0);
3551 SDValue RHS = Op.getOperand(1);
3552 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3553 SDValue TrueVal = Op.getOperand(2);
3554 SDValue FalseVal = Op.getOperand(3);
3557 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3558 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3561 // If softenSetCCOperands only returned one value, we should compare it to
3563 if (!RHS.getNode()) {
3564 RHS = DAG.getConstant(0, LHS.getValueType());
3569 if (LHS.getValueType() == MVT::i32) {
3570 // Try to generate VSEL on ARMv8.
3571 // The VSEL instruction can't use all the usual ARM condition
3572 // codes: it only has two bits to select the condition code, so it's
3573 // constrained to use only GE, GT, VS and EQ.
3575 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3576 // swap the operands of the previous compare instruction (effectively
3577 // inverting the compare condition, swapping 'less' and 'greater') and
3578 // sometimes need to swap the operands to the VSEL (which inverts the
3579 // condition in the sense of firing whenever the previous condition didn't)
3580 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3581 TrueVal.getValueType() == MVT::f64)) {
3582 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3583 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3584 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3585 CC = getInverseCCForVSEL(CC);
3586 std::swap(TrueVal, FalseVal);
3591 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3592 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3593 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3596 ARMCC::CondCodes CondCode, CondCode2;
3597 FPCCToARMCC(CC, CondCode, CondCode2);
3599 // Try to generate VSEL on ARMv8.
3600 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3601 TrueVal.getValueType() == MVT::f64)) {
3602 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3603 // same operands, as follows:
3604 // c = fcmp [ogt, olt, ugt, ult] a, b
3606 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3607 // handled differently than the original code sequence.
3608 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3610 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3611 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3612 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3613 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3616 bool swpCmpOps = false;
3617 bool swpVselOps = false;
3618 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3620 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3621 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3623 std::swap(LHS, RHS);
3625 std::swap(TrueVal, FalseVal);
3629 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3630 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3631 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3632 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3633 if (CondCode2 != ARMCC::AL) {
3634 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3635 // FIXME: Needs another CMP because flag can have but one use.
3636 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3637 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3642 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3643 /// to morph to an integer compare sequence.
3644 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3645 const ARMSubtarget *Subtarget) {
3646 SDNode *N = Op.getNode();
3647 if (!N->hasOneUse())
3648 // Otherwise it requires moving the value from fp to integer registers.
3650 if (!N->getNumValues())
3652 EVT VT = Op.getValueType();
3653 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3654 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3655 // vmrs are very slow, e.g. cortex-a8.
3658 if (isFloatingPointZero(Op)) {
3662 return ISD::isNormalLoad(N);
3665 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3666 if (isFloatingPointZero(Op))
3667 return DAG.getConstant(0, MVT::i32);
3669 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3670 return DAG.getLoad(MVT::i32, SDLoc(Op),
3671 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3672 Ld->isVolatile(), Ld->isNonTemporal(),
3673 Ld->isInvariant(), Ld->getAlignment());
3675 llvm_unreachable("Unknown VFP cmp argument!");
3678 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3679 SDValue &RetVal1, SDValue &RetVal2) {
3680 if (isFloatingPointZero(Op)) {
3681 RetVal1 = DAG.getConstant(0, MVT::i32);
3682 RetVal2 = DAG.getConstant(0, MVT::i32);
3686 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3687 SDValue Ptr = Ld->getBasePtr();
3688 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3689 Ld->getChain(), Ptr,
3690 Ld->getPointerInfo(),
3691 Ld->isVolatile(), Ld->isNonTemporal(),
3692 Ld->isInvariant(), Ld->getAlignment());
3694 EVT PtrType = Ptr.getValueType();
3695 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3696 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3697 PtrType, Ptr, DAG.getConstant(4, PtrType));
3698 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3699 Ld->getChain(), NewPtr,
3700 Ld->getPointerInfo().getWithOffset(4),
3701 Ld->isVolatile(), Ld->isNonTemporal(),
3702 Ld->isInvariant(), NewAlign);
3706 llvm_unreachable("Unknown VFP cmp argument!");
3709 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3710 /// f32 and even f64 comparisons to integer ones.
3712 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3713 SDValue Chain = Op.getOperand(0);
3714 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3715 SDValue LHS = Op.getOperand(2);
3716 SDValue RHS = Op.getOperand(3);
3717 SDValue Dest = Op.getOperand(4);
3720 bool LHSSeenZero = false;
3721 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3722 bool RHSSeenZero = false;
3723 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3724 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3725 // If unsafe fp math optimization is enabled and there are no other uses of
3726 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3727 // to an integer comparison.
3728 if (CC == ISD::SETOEQ)
3730 else if (CC == ISD::SETUNE)
3733 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3735 if (LHS.getValueType() == MVT::f32) {
3736 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3737 bitcastf32Toi32(LHS, DAG), Mask);
3738 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3739 bitcastf32Toi32(RHS, DAG), Mask);
3740 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3741 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3742 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3743 Chain, Dest, ARMcc, CCR, Cmp);
3748 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3749 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3750 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3751 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3752 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3753 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3754 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3755 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3756 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3762 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3763 SDValue Chain = Op.getOperand(0);
3764 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3765 SDValue LHS = Op.getOperand(2);
3766 SDValue RHS = Op.getOperand(3);
3767 SDValue Dest = Op.getOperand(4);
3770 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3771 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3774 // If softenSetCCOperands only returned one value, we should compare it to
3776 if (!RHS.getNode()) {
3777 RHS = DAG.getConstant(0, LHS.getValueType());
3782 if (LHS.getValueType() == MVT::i32) {
3784 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3785 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3786 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3787 Chain, Dest, ARMcc, CCR, Cmp);
3790 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3792 if (getTargetMachine().Options.UnsafeFPMath &&
3793 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3794 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3795 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3796 if (Result.getNode())
3800 ARMCC::CondCodes CondCode, CondCode2;
3801 FPCCToARMCC(CC, CondCode, CondCode2);
3803 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3804 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3805 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3806 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3807 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3808 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3809 if (CondCode2 != ARMCC::AL) {
3810 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3811 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3812 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3817 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3818 SDValue Chain = Op.getOperand(0);
3819 SDValue Table = Op.getOperand(1);
3820 SDValue Index = Op.getOperand(2);
3823 EVT PTy = getPointerTy();
3824 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3825 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3826 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3827 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3828 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3829 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3830 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3831 if (Subtarget->isThumb2()) {
3832 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3833 // which does another jump to the destination. This also makes it easier
3834 // to translate it to TBB / TBH later.
3835 // FIXME: This might not work if the function is extremely large.
3836 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3837 Addr, Op.getOperand(2), JTI, UId);
3839 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3840 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3841 MachinePointerInfo::getJumpTable(),
3842 false, false, false, 0);
3843 Chain = Addr.getValue(1);
3844 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3845 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3847 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3848 MachinePointerInfo::getJumpTable(),
3849 false, false, false, 0);
3850 Chain = Addr.getValue(1);
3851 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3855 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3856 EVT VT = Op.getValueType();
3859 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3860 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3862 return DAG.UnrollVectorOp(Op.getNode());
3865 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3866 "Invalid type for custom lowering!");
3867 if (VT != MVT::v4i16)
3868 return DAG.UnrollVectorOp(Op.getNode());
3870 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3871 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3874 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3875 EVT VT = Op.getValueType();
3877 return LowerVectorFP_TO_INT(Op, DAG);
3879 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3881 if (Op.getOpcode() == ISD::FP_TO_SINT)
3882 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3885 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3887 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3888 /*isSigned*/ false, SDLoc(Op)).first;
3894 switch (Op.getOpcode()) {
3895 default: llvm_unreachable("Invalid opcode!");
3896 case ISD::FP_TO_SINT:
3897 Opc = ARMISD::FTOSI;
3899 case ISD::FP_TO_UINT:
3900 Opc = ARMISD::FTOUI;
3903 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3904 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3907 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3908 EVT VT = Op.getValueType();
3911 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3912 if (VT.getVectorElementType() == MVT::f32)
3914 return DAG.UnrollVectorOp(Op.getNode());
3917 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3918 "Invalid type for custom lowering!");
3919 if (VT != MVT::v4f32)
3920 return DAG.UnrollVectorOp(Op.getNode());
3924 switch (Op.getOpcode()) {
3925 default: llvm_unreachable("Invalid opcode!");
3926 case ISD::SINT_TO_FP:
3927 CastOpc = ISD::SIGN_EXTEND;
3928 Opc = ISD::SINT_TO_FP;
3930 case ISD::UINT_TO_FP:
3931 CastOpc = ISD::ZERO_EXTEND;
3932 Opc = ISD::UINT_TO_FP;
3936 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3937 return DAG.getNode(Opc, dl, VT, Op);
3940 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3941 EVT VT = Op.getValueType();
3943 return LowerVectorINT_TO_FP(Op, DAG);
3945 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3947 if (Op.getOpcode() == ISD::SINT_TO_FP)
3948 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3951 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3953 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3954 /*isSigned*/ false, SDLoc(Op)).first;
3960 switch (Op.getOpcode()) {
3961 default: llvm_unreachable("Invalid opcode!");
3962 case ISD::SINT_TO_FP:
3963 Opc = ARMISD::SITOF;
3965 case ISD::UINT_TO_FP:
3966 Opc = ARMISD::UITOF;
3970 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3971 return DAG.getNode(Opc, dl, VT, Op);
3974 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3975 // Implement fcopysign with a fabs and a conditional fneg.
3976 SDValue Tmp0 = Op.getOperand(0);
3977 SDValue Tmp1 = Op.getOperand(1);
3979 EVT VT = Op.getValueType();
3980 EVT SrcVT = Tmp1.getValueType();
3981 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3982 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3983 bool UseNEON = !InGPR && Subtarget->hasNEON();
3986 // Use VBSL to copy the sign bit.
3987 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3988 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3989 DAG.getTargetConstant(EncodedVal, MVT::i32));
3990 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3992 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3993 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3994 DAG.getConstant(32, MVT::i32));
3995 else /*if (VT == MVT::f32)*/
3996 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3997 if (SrcVT == MVT::f32) {
3998 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4000 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4001 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4002 DAG.getConstant(32, MVT::i32));
4003 } else if (VT == MVT::f32)
4004 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4005 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4006 DAG.getConstant(32, MVT::i32));
4007 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4008 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4010 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4012 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4013 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4014 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4016 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4017 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4018 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4019 if (VT == MVT::f32) {
4020 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4021 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4022 DAG.getConstant(0, MVT::i32));
4024 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4030 // Bitcast operand 1 to i32.
4031 if (SrcVT == MVT::f64)
4032 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4034 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4036 // Or in the signbit with integer operations.
4037 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
4038 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
4039 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4040 if (VT == MVT::f32) {
4041 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4042 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4043 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4044 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4047 // f64: Or the high part with signbit and then combine two parts.
4048 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4050 SDValue Lo = Tmp0.getValue(0);
4051 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4052 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4053 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4056 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4057 MachineFunction &MF = DAG.getMachineFunction();
4058 MachineFrameInfo *MFI = MF.getFrameInfo();
4059 MFI->setReturnAddressIsTaken(true);
4061 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4064 EVT VT = Op.getValueType();
4066 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4068 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4069 SDValue Offset = DAG.getConstant(4, MVT::i32);
4070 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4071 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4072 MachinePointerInfo(), false, false, false, 0);
4075 // Return LR, which contains the return address. Mark it an implicit live-in.
4076 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4077 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4080 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4081 const ARMBaseRegisterInfo &ARI =
4082 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4083 MachineFunction &MF = DAG.getMachineFunction();
4084 MachineFrameInfo *MFI = MF.getFrameInfo();
4085 MFI->setFrameAddressIsTaken(true);
4087 EVT VT = Op.getValueType();
4088 SDLoc dl(Op); // FIXME probably not meaningful
4089 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4090 unsigned FrameReg = ARI.getFrameRegister(MF);
4091 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4093 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4094 MachinePointerInfo(),
4095 false, false, false, 0);
4099 // FIXME? Maybe this could be a TableGen attribute on some registers and
4100 // this table could be generated automatically from RegInfo.
4101 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4103 unsigned Reg = StringSwitch<unsigned>(RegName)
4104 .Case("sp", ARM::SP)
4108 report_fatal_error("Invalid register name global variable");
4111 /// ExpandBITCAST - If the target supports VFP, this function is called to
4112 /// expand a bit convert where either the source or destination type is i64 to
4113 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4114 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4115 /// vectors), since the legalizer won't know what to do with that.
4116 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4117 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4119 SDValue Op = N->getOperand(0);
4121 // This function is only supposed to be called for i64 types, either as the
4122 // source or destination of the bit convert.
4123 EVT SrcVT = Op.getValueType();
4124 EVT DstVT = N->getValueType(0);
4125 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4126 "ExpandBITCAST called for non-i64 type");
4128 // Turn i64->f64 into VMOVDRR.
4129 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4130 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4131 DAG.getConstant(0, MVT::i32));
4132 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4133 DAG.getConstant(1, MVT::i32));
4134 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4135 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4138 // Turn f64->i64 into VMOVRRD.
4139 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4141 if (TLI.isBigEndian() && SrcVT.isVector() &&
4142 SrcVT.getVectorNumElements() > 1)
4143 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4144 DAG.getVTList(MVT::i32, MVT::i32),
4145 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4147 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4148 DAG.getVTList(MVT::i32, MVT::i32), Op);
4149 // Merge the pieces into a single i64 value.
4150 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4156 /// getZeroVector - Returns a vector of specified type with all zero elements.
4157 /// Zero vectors are used to represent vector negation and in those cases
4158 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4159 /// not support i64 elements, so sometimes the zero vectors will need to be
4160 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4162 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4163 assert(VT.isVector() && "Expected a vector type");
4164 // The canonical modified immediate encoding of a zero vector is....0!
4165 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4166 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4167 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4168 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4171 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4172 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4173 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4174 SelectionDAG &DAG) const {
4175 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4176 EVT VT = Op.getValueType();
4177 unsigned VTBits = VT.getSizeInBits();
4179 SDValue ShOpLo = Op.getOperand(0);
4180 SDValue ShOpHi = Op.getOperand(1);
4181 SDValue ShAmt = Op.getOperand(2);
4183 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4185 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4187 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4188 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4189 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4190 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4191 DAG.getConstant(VTBits, MVT::i32));
4192 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4193 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4194 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4196 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4197 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4199 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4200 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4203 SDValue Ops[2] = { Lo, Hi };
4204 return DAG.getMergeValues(Ops, dl);
4207 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4208 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4209 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4210 SelectionDAG &DAG) const {
4211 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4212 EVT VT = Op.getValueType();
4213 unsigned VTBits = VT.getSizeInBits();
4215 SDValue ShOpLo = Op.getOperand(0);
4216 SDValue ShOpHi = Op.getOperand(1);
4217 SDValue ShAmt = Op.getOperand(2);
4220 assert(Op.getOpcode() == ISD::SHL_PARTS);
4221 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4222 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4223 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4224 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4225 DAG.getConstant(VTBits, MVT::i32));
4226 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4227 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4229 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4230 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4231 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4233 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4234 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4237 SDValue Ops[2] = { Lo, Hi };
4238 return DAG.getMergeValues(Ops, dl);
4241 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4242 SelectionDAG &DAG) const {
4243 // The rounding mode is in bits 23:22 of the FPSCR.
4244 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4245 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4246 // so that the shift + and get folded into a bitfield extract.
4248 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4249 DAG.getConstant(Intrinsic::arm_get_fpscr,
4251 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4252 DAG.getConstant(1U << 22, MVT::i32));
4253 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4254 DAG.getConstant(22, MVT::i32));
4255 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4256 DAG.getConstant(3, MVT::i32));
4259 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4260 const ARMSubtarget *ST) {
4261 EVT VT = N->getValueType(0);
4264 if (!ST->hasV6T2Ops())
4267 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4268 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4271 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4272 /// for each 16-bit element from operand, repeated. The basic idea is to
4273 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4275 /// Trace for v4i16:
4276 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4277 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4278 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4279 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4280 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4281 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4282 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4283 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4284 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4285 EVT VT = N->getValueType(0);
4288 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4289 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4290 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4291 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4292 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4293 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4296 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4297 /// bit-count for each 16-bit element from the operand. We need slightly
4298 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4299 /// 64/128-bit registers.
4301 /// Trace for v4i16:
4302 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4303 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4304 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4305 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4306 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4307 EVT VT = N->getValueType(0);
4310 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4311 if (VT.is64BitVector()) {
4312 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4313 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4314 DAG.getIntPtrConstant(0));
4316 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4317 BitCounts, DAG.getIntPtrConstant(0));
4318 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4322 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4323 /// bit-count for each 32-bit element from the operand. The idea here is
4324 /// to split the vector into 16-bit elements, leverage the 16-bit count
4325 /// routine, and then combine the results.
4327 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4328 /// input = [v0 v1 ] (vi: 32-bit elements)
4329 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4330 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4331 /// vrev: N0 = [k1 k0 k3 k2 ]
4333 /// N1 =+[k1 k0 k3 k2 ]
4335 /// N2 =+[k1 k3 k0 k2 ]
4337 /// Extended =+[k1 k3 k0 k2 ]
4339 /// Extracted=+[k1 k3 ]
4341 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4342 EVT VT = N->getValueType(0);
4345 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4347 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4348 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4349 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4350 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4351 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4353 if (VT.is64BitVector()) {
4354 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4355 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4356 DAG.getIntPtrConstant(0));
4358 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4359 DAG.getIntPtrConstant(0));
4360 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4364 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4365 const ARMSubtarget *ST) {
4366 EVT VT = N->getValueType(0);
4368 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4369 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4370 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4371 "Unexpected type for custom ctpop lowering");
4373 if (VT.getVectorElementType() == MVT::i32)
4374 return lowerCTPOP32BitElements(N, DAG);
4376 return lowerCTPOP16BitElements(N, DAG);
4379 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4380 const ARMSubtarget *ST) {
4381 EVT VT = N->getValueType(0);
4387 // Lower vector shifts on NEON to use VSHL.
4388 assert(ST->hasNEON() && "unexpected vector shift");
4390 // Left shifts translate directly to the vshiftu intrinsic.
4391 if (N->getOpcode() == ISD::SHL)
4392 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4393 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4394 N->getOperand(0), N->getOperand(1));
4396 assert((N->getOpcode() == ISD::SRA ||
4397 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4399 // NEON uses the same intrinsics for both left and right shifts. For
4400 // right shifts, the shift amounts are negative, so negate the vector of
4402 EVT ShiftVT = N->getOperand(1).getValueType();
4403 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4404 getZeroVector(ShiftVT, DAG, dl),
4406 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4407 Intrinsic::arm_neon_vshifts :
4408 Intrinsic::arm_neon_vshiftu);
4409 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4410 DAG.getConstant(vshiftInt, MVT::i32),
4411 N->getOperand(0), NegatedCount);
4414 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4415 const ARMSubtarget *ST) {
4416 EVT VT = N->getValueType(0);
4419 // We can get here for a node like i32 = ISD::SHL i32, i64
4423 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4424 "Unknown shift to lower!");
4426 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4427 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4428 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4431 // If we are in thumb mode, we don't have RRX.
4432 if (ST->isThumb1Only()) return SDValue();
4434 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4435 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4436 DAG.getConstant(0, MVT::i32));
4437 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4438 DAG.getConstant(1, MVT::i32));
4440 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4441 // captures the result into a carry flag.
4442 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4443 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4445 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4446 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4448 // Merge the pieces into a single i64 value.
4449 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4452 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4453 SDValue TmpOp0, TmpOp1;
4454 bool Invert = false;
4458 SDValue Op0 = Op.getOperand(0);
4459 SDValue Op1 = Op.getOperand(1);
4460 SDValue CC = Op.getOperand(2);
4461 EVT VT = Op.getValueType();
4462 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4465 if (Op1.getValueType().isFloatingPoint()) {
4466 switch (SetCCOpcode) {
4467 default: llvm_unreachable("Illegal FP comparison");
4469 case ISD::SETNE: Invert = true; // Fallthrough
4471 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4473 case ISD::SETLT: Swap = true; // Fallthrough
4475 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4477 case ISD::SETLE: Swap = true; // Fallthrough
4479 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4480 case ISD::SETUGE: Swap = true; // Fallthrough
4481 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4482 case ISD::SETUGT: Swap = true; // Fallthrough
4483 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4484 case ISD::SETUEQ: Invert = true; // Fallthrough
4486 // Expand this to (OLT | OGT).
4490 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4491 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4493 case ISD::SETUO: Invert = true; // Fallthrough
4495 // Expand this to (OLT | OGE).
4499 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4500 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4504 // Integer comparisons.
4505 switch (SetCCOpcode) {
4506 default: llvm_unreachable("Illegal integer comparison");
4507 case ISD::SETNE: Invert = true;
4508 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4509 case ISD::SETLT: Swap = true;
4510 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4511 case ISD::SETLE: Swap = true;
4512 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4513 case ISD::SETULT: Swap = true;
4514 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4515 case ISD::SETULE: Swap = true;
4516 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4519 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4520 if (Opc == ARMISD::VCEQ) {
4523 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4525 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4528 // Ignore bitconvert.
4529 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4530 AndOp = AndOp.getOperand(0);
4532 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4534 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4535 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4542 std::swap(Op0, Op1);
4544 // If one of the operands is a constant vector zero, attempt to fold the
4545 // comparison to a specialized compare-against-zero form.
4547 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4549 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4550 if (Opc == ARMISD::VCGE)
4551 Opc = ARMISD::VCLEZ;
4552 else if (Opc == ARMISD::VCGT)
4553 Opc = ARMISD::VCLTZ;
4558 if (SingleOp.getNode()) {
4561 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4563 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4565 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4567 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4569 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4571 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4574 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4578 Result = DAG.getNOT(dl, Result, VT);
4583 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4584 /// valid vector constant for a NEON instruction with a "modified immediate"
4585 /// operand (e.g., VMOV). If so, return the encoded value.
4586 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4587 unsigned SplatBitSize, SelectionDAG &DAG,
4588 EVT &VT, bool is128Bits, NEONModImmType type) {
4589 unsigned OpCmode, Imm;
4591 // SplatBitSize is set to the smallest size that splats the vector, so a
4592 // zero vector will always have SplatBitSize == 8. However, NEON modified
4593 // immediate instructions others than VMOV do not support the 8-bit encoding
4594 // of a zero vector, and the default encoding of zero is supposed to be the
4599 switch (SplatBitSize) {
4601 if (type != VMOVModImm)
4603 // Any 1-byte value is OK. Op=0, Cmode=1110.
4604 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4607 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4611 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4612 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4613 if ((SplatBits & ~0xff) == 0) {
4614 // Value = 0x00nn: Op=x, Cmode=100x.
4619 if ((SplatBits & ~0xff00) == 0) {
4620 // Value = 0xnn00: Op=x, Cmode=101x.
4622 Imm = SplatBits >> 8;
4628 // NEON's 32-bit VMOV supports splat values where:
4629 // * only one byte is nonzero, or
4630 // * the least significant byte is 0xff and the second byte is nonzero, or
4631 // * the least significant 2 bytes are 0xff and the third is nonzero.
4632 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4633 if ((SplatBits & ~0xff) == 0) {
4634 // Value = 0x000000nn: Op=x, Cmode=000x.
4639 if ((SplatBits & ~0xff00) == 0) {
4640 // Value = 0x0000nn00: Op=x, Cmode=001x.
4642 Imm = SplatBits >> 8;
4645 if ((SplatBits & ~0xff0000) == 0) {
4646 // Value = 0x00nn0000: Op=x, Cmode=010x.
4648 Imm = SplatBits >> 16;
4651 if ((SplatBits & ~0xff000000) == 0) {
4652 // Value = 0xnn000000: Op=x, Cmode=011x.
4654 Imm = SplatBits >> 24;
4658 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4659 if (type == OtherModImm) return SDValue();
4661 if ((SplatBits & ~0xffff) == 0 &&
4662 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4663 // Value = 0x0000nnff: Op=x, Cmode=1100.
4665 Imm = SplatBits >> 8;
4669 if ((SplatBits & ~0xffffff) == 0 &&
4670 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4671 // Value = 0x00nnffff: Op=x, Cmode=1101.
4673 Imm = SplatBits >> 16;
4677 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4678 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4679 // VMOV.I32. A (very) minor optimization would be to replicate the value
4680 // and fall through here to test for a valid 64-bit splat. But, then the
4681 // caller would also need to check and handle the change in size.
4685 if (type != VMOVModImm)
4687 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4688 uint64_t BitMask = 0xff;
4690 unsigned ImmMask = 1;
4692 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4693 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4696 } else if ((SplatBits & BitMask) != 0) {
4703 if (DAG.getTargetLoweringInfo().isBigEndian())
4704 // swap higher and lower 32 bit word
4705 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4707 // Op=1, Cmode=1110.
4709 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4714 llvm_unreachable("unexpected size for isNEONModifiedImm");
4717 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4718 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4721 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4722 const ARMSubtarget *ST) const {
4726 bool IsDouble = Op.getValueType() == MVT::f64;
4727 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4729 // Use the default (constant pool) lowering for double constants when we have
4731 if (IsDouble && Subtarget->isFPOnlySP())
4734 // Try splatting with a VMOV.f32...
4735 APFloat FPVal = CFP->getValueAPF();
4736 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4739 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4740 // We have code in place to select a valid ConstantFP already, no need to
4745 // It's a float and we are trying to use NEON operations where
4746 // possible. Lower it to a splat followed by an extract.
4748 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4749 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4751 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4752 DAG.getConstant(0, MVT::i32));
4755 // The rest of our options are NEON only, make sure that's allowed before
4757 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4761 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4763 // It wouldn't really be worth bothering for doubles except for one very
4764 // important value, which does happen to match: 0.0. So make sure we don't do
4766 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4769 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4770 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4772 if (NewVal != SDValue()) {
4774 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4777 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4779 // It's a float: cast and extract a vector element.
4780 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4782 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4783 DAG.getConstant(0, MVT::i32));
4786 // Finally, try a VMVN.i32
4787 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4789 if (NewVal != SDValue()) {
4791 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4794 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4796 // It's a float: cast and extract a vector element.
4797 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4799 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4800 DAG.getConstant(0, MVT::i32));
4806 // check if an VEXT instruction can handle the shuffle mask when the
4807 // vector sources of the shuffle are the same.
4808 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4809 unsigned NumElts = VT.getVectorNumElements();
4811 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4817 // If this is a VEXT shuffle, the immediate value is the index of the first
4818 // element. The other shuffle indices must be the successive elements after
4820 unsigned ExpectedElt = Imm;
4821 for (unsigned i = 1; i < NumElts; ++i) {
4822 // Increment the expected index. If it wraps around, just follow it
4823 // back to index zero and keep going.
4825 if (ExpectedElt == NumElts)
4828 if (M[i] < 0) continue; // ignore UNDEF indices
4829 if (ExpectedElt != static_cast<unsigned>(M[i]))
4837 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4838 bool &ReverseVEXT, unsigned &Imm) {
4839 unsigned NumElts = VT.getVectorNumElements();
4840 ReverseVEXT = false;
4842 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4848 // If this is a VEXT shuffle, the immediate value is the index of the first
4849 // element. The other shuffle indices must be the successive elements after
4851 unsigned ExpectedElt = Imm;
4852 for (unsigned i = 1; i < NumElts; ++i) {
4853 // Increment the expected index. If it wraps around, it may still be
4854 // a VEXT but the source vectors must be swapped.
4856 if (ExpectedElt == NumElts * 2) {
4861 if (M[i] < 0) continue; // ignore UNDEF indices
4862 if (ExpectedElt != static_cast<unsigned>(M[i]))
4866 // Adjust the index value if the source operands will be swapped.
4873 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4874 /// instruction with the specified blocksize. (The order of the elements
4875 /// within each block of the vector is reversed.)
4876 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4877 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4878 "Only possible block sizes for VREV are: 16, 32, 64");
4880 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4884 unsigned NumElts = VT.getVectorNumElements();
4885 unsigned BlockElts = M[0] + 1;
4886 // If the first shuffle index is UNDEF, be optimistic.
4888 BlockElts = BlockSize / EltSz;
4890 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4893 for (unsigned i = 0; i < NumElts; ++i) {
4894 if (M[i] < 0) continue; // ignore UNDEF indices
4895 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4902 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4903 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4904 // range, then 0 is placed into the resulting vector. So pretty much any mask
4905 // of 8 elements can work here.
4906 return VT == MVT::v8i8 && M.size() == 8;
4909 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4910 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4914 unsigned NumElts = VT.getVectorNumElements();
4915 WhichResult = (M[0] == 0 ? 0 : 1);
4916 for (unsigned i = 0; i < NumElts; i += 2) {
4917 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4918 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4924 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4925 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4926 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4927 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4928 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4932 unsigned NumElts = VT.getVectorNumElements();
4933 WhichResult = (M[0] == 0 ? 0 : 1);
4934 for (unsigned i = 0; i < NumElts; i += 2) {
4935 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4936 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4942 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4943 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4947 unsigned NumElts = VT.getVectorNumElements();
4948 WhichResult = (M[0] == 0 ? 0 : 1);
4949 for (unsigned i = 0; i != NumElts; ++i) {
4950 if (M[i] < 0) continue; // ignore UNDEF indices
4951 if ((unsigned) M[i] != 2 * i + WhichResult)
4955 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4956 if (VT.is64BitVector() && EltSz == 32)
4962 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4963 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4964 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4965 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4966 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4970 unsigned Half = VT.getVectorNumElements() / 2;
4971 WhichResult = (M[0] == 0 ? 0 : 1);
4972 for (unsigned j = 0; j != 2; ++j) {
4973 unsigned Idx = WhichResult;
4974 for (unsigned i = 0; i != Half; ++i) {
4975 int MIdx = M[i + j * Half];
4976 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4982 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4983 if (VT.is64BitVector() && EltSz == 32)
4989 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4990 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4994 unsigned NumElts = VT.getVectorNumElements();
4995 WhichResult = (M[0] == 0 ? 0 : 1);
4996 unsigned Idx = WhichResult * NumElts / 2;
4997 for (unsigned i = 0; i != NumElts; i += 2) {
4998 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4999 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5004 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5005 if (VT.is64BitVector() && EltSz == 32)
5011 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5012 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5013 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5014 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5015 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5019 unsigned NumElts = VT.getVectorNumElements();
5020 WhichResult = (M[0] == 0 ? 0 : 1);
5021 unsigned Idx = WhichResult * NumElts / 2;
5022 for (unsigned i = 0; i != NumElts; i += 2) {
5023 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5024 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5029 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5030 if (VT.is64BitVector() && EltSz == 32)
5036 /// \return true if this is a reverse operation on an vector.
5037 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5038 unsigned NumElts = VT.getVectorNumElements();
5039 // Make sure the mask has the right size.
5040 if (NumElts != M.size())
5043 // Look for <15, ..., 3, -1, 1, 0>.
5044 for (unsigned i = 0; i != NumElts; ++i)
5045 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5051 // If N is an integer constant that can be moved into a register in one
5052 // instruction, return an SDValue of such a constant (will become a MOV
5053 // instruction). Otherwise return null.
5054 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5055 const ARMSubtarget *ST, SDLoc dl) {
5057 if (!isa<ConstantSDNode>(N))
5059 Val = cast<ConstantSDNode>(N)->getZExtValue();
5061 if (ST->isThumb1Only()) {
5062 if (Val <= 255 || ~Val <= 255)
5063 return DAG.getConstant(Val, MVT::i32);
5065 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5066 return DAG.getConstant(Val, MVT::i32);
5071 // If this is a case we can't handle, return null and let the default
5072 // expansion code take care of it.
5073 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5074 const ARMSubtarget *ST) const {
5075 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5077 EVT VT = Op.getValueType();
5079 APInt SplatBits, SplatUndef;
5080 unsigned SplatBitSize;
5082 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5083 if (SplatBitSize <= 64) {
5084 // Check if an immediate VMOV works.
5086 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5087 SplatUndef.getZExtValue(), SplatBitSize,
5088 DAG, VmovVT, VT.is128BitVector(),
5090 if (Val.getNode()) {
5091 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5092 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5095 // Try an immediate VMVN.
5096 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5097 Val = isNEONModifiedImm(NegatedImm,
5098 SplatUndef.getZExtValue(), SplatBitSize,
5099 DAG, VmovVT, VT.is128BitVector(),
5101 if (Val.getNode()) {
5102 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5103 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5106 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5107 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5108 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5110 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5111 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5117 // Scan through the operands to see if only one value is used.
5119 // As an optimisation, even if more than one value is used it may be more
5120 // profitable to splat with one value then change some lanes.
5122 // Heuristically we decide to do this if the vector has a "dominant" value,
5123 // defined as splatted to more than half of the lanes.
5124 unsigned NumElts = VT.getVectorNumElements();
5125 bool isOnlyLowElement = true;
5126 bool usesOnlyOneValue = true;
5127 bool hasDominantValue = false;
5128 bool isConstant = true;
5130 // Map of the number of times a particular SDValue appears in the
5132 DenseMap<SDValue, unsigned> ValueCounts;
5134 for (unsigned i = 0; i < NumElts; ++i) {
5135 SDValue V = Op.getOperand(i);
5136 if (V.getOpcode() == ISD::UNDEF)
5139 isOnlyLowElement = false;
5140 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5143 ValueCounts.insert(std::make_pair(V, 0));
5144 unsigned &Count = ValueCounts[V];
5146 // Is this value dominant? (takes up more than half of the lanes)
5147 if (++Count > (NumElts / 2)) {
5148 hasDominantValue = true;
5152 if (ValueCounts.size() != 1)
5153 usesOnlyOneValue = false;
5154 if (!Value.getNode() && ValueCounts.size() > 0)
5155 Value = ValueCounts.begin()->first;
5157 if (ValueCounts.size() == 0)
5158 return DAG.getUNDEF(VT);
5160 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5161 // Keep going if we are hitting this case.
5162 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5163 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5165 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5167 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5168 // i32 and try again.
5169 if (hasDominantValue && EltSize <= 32) {
5173 // If we are VDUPing a value that comes directly from a vector, that will
5174 // cause an unnecessary move to and from a GPR, where instead we could
5175 // just use VDUPLANE. We can only do this if the lane being extracted
5176 // is at a constant index, as the VDUP from lane instructions only have
5177 // constant-index forms.
5178 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5179 isa<ConstantSDNode>(Value->getOperand(1))) {
5180 // We need to create a new undef vector to use for the VDUPLANE if the
5181 // size of the vector from which we get the value is different than the
5182 // size of the vector that we need to create. We will insert the element
5183 // such that the register coalescer will remove unnecessary copies.
5184 if (VT != Value->getOperand(0).getValueType()) {
5185 ConstantSDNode *constIndex;
5186 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5187 assert(constIndex && "The index is not a constant!");
5188 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5189 VT.getVectorNumElements();
5190 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5191 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5192 Value, DAG.getConstant(index, MVT::i32)),
5193 DAG.getConstant(index, MVT::i32));
5195 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5196 Value->getOperand(0), Value->getOperand(1));
5198 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5200 if (!usesOnlyOneValue) {
5201 // The dominant value was splatted as 'N', but we now have to insert
5202 // all differing elements.
5203 for (unsigned I = 0; I < NumElts; ++I) {
5204 if (Op.getOperand(I) == Value)
5206 SmallVector<SDValue, 3> Ops;
5208 Ops.push_back(Op.getOperand(I));
5209 Ops.push_back(DAG.getConstant(I, MVT::i32));
5210 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5215 if (VT.getVectorElementType().isFloatingPoint()) {
5216 SmallVector<SDValue, 8> Ops;
5217 for (unsigned i = 0; i < NumElts; ++i)
5218 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5220 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5221 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5222 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5224 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5226 if (usesOnlyOneValue) {
5227 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5228 if (isConstant && Val.getNode())
5229 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5233 // If all elements are constants and the case above didn't get hit, fall back
5234 // to the default expansion, which will generate a load from the constant
5239 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5241 SDValue shuffle = ReconstructShuffle(Op, DAG);
5242 if (shuffle != SDValue())
5246 // Vectors with 32- or 64-bit elements can be built by directly assigning
5247 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5248 // will be legalized.
5249 if (EltSize >= 32) {
5250 // Do the expansion with floating-point types, since that is what the VFP
5251 // registers are defined to use, and since i64 is not legal.
5252 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5253 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5254 SmallVector<SDValue, 8> Ops;
5255 for (unsigned i = 0; i < NumElts; ++i)
5256 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5257 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5258 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5261 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5262 // know the default expansion would otherwise fall back on something even
5263 // worse. For a vector with one or two non-undef values, that's
5264 // scalar_to_vector for the elements followed by a shuffle (provided the
5265 // shuffle is valid for the target) and materialization element by element
5266 // on the stack followed by a load for everything else.
5267 if (!isConstant && !usesOnlyOneValue) {
5268 SDValue Vec = DAG.getUNDEF(VT);
5269 for (unsigned i = 0 ; i < NumElts; ++i) {
5270 SDValue V = Op.getOperand(i);
5271 if (V.getOpcode() == ISD::UNDEF)
5273 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5274 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5282 // Gather data to see if the operation can be modelled as a
5283 // shuffle in combination with VEXTs.
5284 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5285 SelectionDAG &DAG) const {
5287 EVT VT = Op.getValueType();
5288 unsigned NumElts = VT.getVectorNumElements();
5290 SmallVector<SDValue, 2> SourceVecs;
5291 SmallVector<unsigned, 2> MinElts;
5292 SmallVector<unsigned, 2> MaxElts;
5294 for (unsigned i = 0; i < NumElts; ++i) {
5295 SDValue V = Op.getOperand(i);
5296 if (V.getOpcode() == ISD::UNDEF)
5298 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5299 // A shuffle can only come from building a vector from various
5300 // elements of other vectors.
5302 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5303 VT.getVectorElementType()) {
5304 // This code doesn't know how to handle shuffles where the vector
5305 // element types do not match (this happens because type legalization
5306 // promotes the return type of EXTRACT_VECTOR_ELT).
5307 // FIXME: It might be appropriate to extend this code to handle
5308 // mismatched types.
5312 // Record this extraction against the appropriate vector if possible...
5313 SDValue SourceVec = V.getOperand(0);
5314 // If the element number isn't a constant, we can't effectively
5315 // analyze what's going on.
5316 if (!isa<ConstantSDNode>(V.getOperand(1)))
5318 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5319 bool FoundSource = false;
5320 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5321 if (SourceVecs[j] == SourceVec) {
5322 if (MinElts[j] > EltNo)
5324 if (MaxElts[j] < EltNo)
5331 // Or record a new source if not...
5333 SourceVecs.push_back(SourceVec);
5334 MinElts.push_back(EltNo);
5335 MaxElts.push_back(EltNo);
5339 // Currently only do something sane when at most two source vectors
5341 if (SourceVecs.size() > 2)
5344 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5345 int VEXTOffsets[2] = {0, 0};
5347 // This loop extracts the usage patterns of the source vectors
5348 // and prepares appropriate SDValues for a shuffle if possible.
5349 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5350 if (SourceVecs[i].getValueType() == VT) {
5351 // No VEXT necessary
5352 ShuffleSrcs[i] = SourceVecs[i];
5355 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5356 // It probably isn't worth padding out a smaller vector just to
5357 // break it down again in a shuffle.
5361 // Since only 64-bit and 128-bit vectors are legal on ARM and
5362 // we've eliminated the other cases...
5363 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5364 "unexpected vector sizes in ReconstructShuffle");
5366 if (MaxElts[i] - MinElts[i] >= NumElts) {
5367 // Span too large for a VEXT to cope
5371 if (MinElts[i] >= NumElts) {
5372 // The extraction can just take the second half
5373 VEXTOffsets[i] = NumElts;
5374 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5376 DAG.getIntPtrConstant(NumElts));
5377 } else if (MaxElts[i] < NumElts) {
5378 // The extraction can just take the first half
5380 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5382 DAG.getIntPtrConstant(0));
5384 // An actual VEXT is needed
5385 VEXTOffsets[i] = MinElts[i];
5386 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5388 DAG.getIntPtrConstant(0));
5389 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5391 DAG.getIntPtrConstant(NumElts));
5392 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5393 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5397 SmallVector<int, 8> Mask;
5399 for (unsigned i = 0; i < NumElts; ++i) {
5400 SDValue Entry = Op.getOperand(i);
5401 if (Entry.getOpcode() == ISD::UNDEF) {
5406 SDValue ExtractVec = Entry.getOperand(0);
5407 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5408 .getOperand(1))->getSExtValue();
5409 if (ExtractVec == SourceVecs[0]) {
5410 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5412 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5416 // Final check before we try to produce nonsense...
5417 if (isShuffleMaskLegal(Mask, VT))
5418 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5424 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5425 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5426 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5427 /// are assumed to be legal.
5429 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5431 if (VT.getVectorNumElements() == 4 &&
5432 (VT.is128BitVector() || VT.is64BitVector())) {
5433 unsigned PFIndexes[4];
5434 for (unsigned i = 0; i != 4; ++i) {
5438 PFIndexes[i] = M[i];
5441 // Compute the index in the perfect shuffle table.
5442 unsigned PFTableIndex =
5443 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5444 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5445 unsigned Cost = (PFEntry >> 30);
5452 unsigned Imm, WhichResult;
5454 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5455 return (EltSize >= 32 ||
5456 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5457 isVREVMask(M, VT, 64) ||
5458 isVREVMask(M, VT, 32) ||
5459 isVREVMask(M, VT, 16) ||
5460 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5461 isVTBLMask(M, VT) ||
5462 isVTRNMask(M, VT, WhichResult) ||
5463 isVUZPMask(M, VT, WhichResult) ||
5464 isVZIPMask(M, VT, WhichResult) ||
5465 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5466 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5467 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5468 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5471 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5472 /// the specified operations to build the shuffle.
5473 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5474 SDValue RHS, SelectionDAG &DAG,
5476 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5477 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5478 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5481 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5490 OP_VUZPL, // VUZP, left result
5491 OP_VUZPR, // VUZP, right result
5492 OP_VZIPL, // VZIP, left result
5493 OP_VZIPR, // VZIP, right result
5494 OP_VTRNL, // VTRN, left result
5495 OP_VTRNR // VTRN, right result
5498 if (OpNum == OP_COPY) {
5499 if (LHSID == (1*9+2)*9+3) return LHS;
5500 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5504 SDValue OpLHS, OpRHS;
5505 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5506 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5507 EVT VT = OpLHS.getValueType();
5510 default: llvm_unreachable("Unknown shuffle opcode!");
5512 // VREV divides the vector in half and swaps within the half.
5513 if (VT.getVectorElementType() == MVT::i32 ||
5514 VT.getVectorElementType() == MVT::f32)
5515 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5516 // vrev <4 x i16> -> VREV32
5517 if (VT.getVectorElementType() == MVT::i16)
5518 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5519 // vrev <4 x i8> -> VREV16
5520 assert(VT.getVectorElementType() == MVT::i8);
5521 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5526 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5527 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5531 return DAG.getNode(ARMISD::VEXT, dl, VT,
5533 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5536 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5537 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5540 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5541 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5544 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5545 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5549 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5550 ArrayRef<int> ShuffleMask,
5551 SelectionDAG &DAG) {
5552 // Check to see if we can use the VTBL instruction.
5553 SDValue V1 = Op.getOperand(0);
5554 SDValue V2 = Op.getOperand(1);
5557 SmallVector<SDValue, 8> VTBLMask;
5558 for (ArrayRef<int>::iterator
5559 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5560 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5562 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5563 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5564 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5566 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5567 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5570 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5571 SelectionDAG &DAG) {
5573 SDValue OpLHS = Op.getOperand(0);
5574 EVT VT = OpLHS.getValueType();
5576 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5577 "Expect an v8i16/v16i8 type");
5578 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5579 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5580 // extract the first 8 bytes into the top double word and the last 8 bytes
5581 // into the bottom double word. The v8i16 case is similar.
5582 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5583 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5584 DAG.getConstant(ExtractNum, MVT::i32));
5587 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5588 SDValue V1 = Op.getOperand(0);
5589 SDValue V2 = Op.getOperand(1);
5591 EVT VT = Op.getValueType();
5592 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5594 // Convert shuffles that are directly supported on NEON to target-specific
5595 // DAG nodes, instead of keeping them as shuffles and matching them again
5596 // during code selection. This is more efficient and avoids the possibility
5597 // of inconsistencies between legalization and selection.
5598 // FIXME: floating-point vectors should be canonicalized to integer vectors
5599 // of the same time so that they get CSEd properly.
5600 ArrayRef<int> ShuffleMask = SVN->getMask();
5602 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5603 if (EltSize <= 32) {
5604 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5605 int Lane = SVN->getSplatIndex();
5606 // If this is undef splat, generate it via "just" vdup, if possible.
5607 if (Lane == -1) Lane = 0;
5609 // Test if V1 is a SCALAR_TO_VECTOR.
5610 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5611 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5613 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5614 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5616 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5617 !isa<ConstantSDNode>(V1.getOperand(0))) {
5618 bool IsScalarToVector = true;
5619 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5620 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5621 IsScalarToVector = false;
5624 if (IsScalarToVector)
5625 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5627 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5628 DAG.getConstant(Lane, MVT::i32));
5633 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5636 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5637 DAG.getConstant(Imm, MVT::i32));
5640 if (isVREVMask(ShuffleMask, VT, 64))
5641 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5642 if (isVREVMask(ShuffleMask, VT, 32))
5643 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5644 if (isVREVMask(ShuffleMask, VT, 16))
5645 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5647 if (V2->getOpcode() == ISD::UNDEF &&
5648 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5649 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5650 DAG.getConstant(Imm, MVT::i32));
5653 // Check for Neon shuffles that modify both input vectors in place.
5654 // If both results are used, i.e., if there are two shuffles with the same
5655 // source operands and with masks corresponding to both results of one of
5656 // these operations, DAG memoization will ensure that a single node is
5657 // used for both shuffles.
5658 unsigned WhichResult;
5659 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5660 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5661 V1, V2).getValue(WhichResult);
5662 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5663 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5664 V1, V2).getValue(WhichResult);
5665 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5666 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5667 V1, V2).getValue(WhichResult);
5669 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5670 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5671 V1, V1).getValue(WhichResult);
5672 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5673 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5674 V1, V1).getValue(WhichResult);
5675 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5676 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5677 V1, V1).getValue(WhichResult);
5680 // If the shuffle is not directly supported and it has 4 elements, use
5681 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5682 unsigned NumElts = VT.getVectorNumElements();
5684 unsigned PFIndexes[4];
5685 for (unsigned i = 0; i != 4; ++i) {
5686 if (ShuffleMask[i] < 0)
5689 PFIndexes[i] = ShuffleMask[i];
5692 // Compute the index in the perfect shuffle table.
5693 unsigned PFTableIndex =
5694 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5695 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5696 unsigned Cost = (PFEntry >> 30);
5699 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5702 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5703 if (EltSize >= 32) {
5704 // Do the expansion with floating-point types, since that is what the VFP
5705 // registers are defined to use, and since i64 is not legal.
5706 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5707 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5708 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5709 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5710 SmallVector<SDValue, 8> Ops;
5711 for (unsigned i = 0; i < NumElts; ++i) {
5712 if (ShuffleMask[i] < 0)
5713 Ops.push_back(DAG.getUNDEF(EltVT));
5715 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5716 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5717 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5720 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5721 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5724 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5725 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5727 if (VT == MVT::v8i8) {
5728 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5729 if (NewOp.getNode())
5736 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5737 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5738 SDValue Lane = Op.getOperand(2);
5739 if (!isa<ConstantSDNode>(Lane))
5745 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5746 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5747 SDValue Lane = Op.getOperand(1);
5748 if (!isa<ConstantSDNode>(Lane))
5751 SDValue Vec = Op.getOperand(0);
5752 if (Op.getValueType() == MVT::i32 &&
5753 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5755 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5761 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5762 // The only time a CONCAT_VECTORS operation can have legal types is when
5763 // two 64-bit vectors are concatenated to a 128-bit vector.
5764 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5765 "unexpected CONCAT_VECTORS");
5767 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5768 SDValue Op0 = Op.getOperand(0);
5769 SDValue Op1 = Op.getOperand(1);
5770 if (Op0.getOpcode() != ISD::UNDEF)
5771 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5772 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5773 DAG.getIntPtrConstant(0));
5774 if (Op1.getOpcode() != ISD::UNDEF)
5775 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5776 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5777 DAG.getIntPtrConstant(1));
5778 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5781 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5782 /// element has been zero/sign-extended, depending on the isSigned parameter,
5783 /// from an integer type half its size.
5784 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5786 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5787 EVT VT = N->getValueType(0);
5788 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5789 SDNode *BVN = N->getOperand(0).getNode();
5790 if (BVN->getValueType(0) != MVT::v4i32 ||
5791 BVN->getOpcode() != ISD::BUILD_VECTOR)
5793 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5794 unsigned HiElt = 1 - LoElt;
5795 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5796 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5797 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5798 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5799 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5802 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5803 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5806 if (Hi0->isNullValue() && Hi1->isNullValue())
5812 if (N->getOpcode() != ISD::BUILD_VECTOR)
5815 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5816 SDNode *Elt = N->getOperand(i).getNode();
5817 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5818 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5819 unsigned HalfSize = EltSize / 2;
5821 if (!isIntN(HalfSize, C->getSExtValue()))
5824 if (!isUIntN(HalfSize, C->getZExtValue()))
5835 /// isSignExtended - Check if a node is a vector value that is sign-extended
5836 /// or a constant BUILD_VECTOR with sign-extended elements.
5837 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5838 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5840 if (isExtendedBUILD_VECTOR(N, DAG, true))
5845 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5846 /// or a constant BUILD_VECTOR with zero-extended elements.
5847 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5848 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5850 if (isExtendedBUILD_VECTOR(N, DAG, false))
5855 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5856 if (OrigVT.getSizeInBits() >= 64)
5859 assert(OrigVT.isSimple() && "Expecting a simple value type");
5861 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5862 switch (OrigSimpleTy) {
5863 default: llvm_unreachable("Unexpected Vector Type");
5872 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5873 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5874 /// We insert the required extension here to get the vector to fill a D register.
5875 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5878 unsigned ExtOpcode) {
5879 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5880 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5881 // 64-bits we need to insert a new extension so that it will be 64-bits.
5882 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5883 if (OrigTy.getSizeInBits() >= 64)
5886 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5887 EVT NewVT = getExtensionTo64Bits(OrigTy);
5889 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5892 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5893 /// does not do any sign/zero extension. If the original vector is less
5894 /// than 64 bits, an appropriate extension will be added after the load to
5895 /// reach a total size of 64 bits. We have to add the extension separately
5896 /// because ARM does not have a sign/zero extending load for vectors.
5897 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5898 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5900 // The load already has the right type.
5901 if (ExtendedTy == LD->getMemoryVT())
5902 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5903 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5904 LD->isNonTemporal(), LD->isInvariant(),
5905 LD->getAlignment());
5907 // We need to create a zextload/sextload. We cannot just create a load
5908 // followed by a zext/zext node because LowerMUL is also run during normal
5909 // operation legalization where we can't create illegal types.
5910 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5911 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5912 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5913 LD->isNonTemporal(), LD->getAlignment());
5916 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5917 /// extending load, or BUILD_VECTOR with extended elements, return the
5918 /// unextended value. The unextended vector should be 64 bits so that it can
5919 /// be used as an operand to a VMULL instruction. If the original vector size
5920 /// before extension is less than 64 bits we add a an extension to resize
5921 /// the vector to 64 bits.
5922 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5923 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5924 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5925 N->getOperand(0)->getValueType(0),
5929 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5930 return SkipLoadExtensionForVMULL(LD, DAG);
5932 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5933 // have been legalized as a BITCAST from v4i32.
5934 if (N->getOpcode() == ISD::BITCAST) {
5935 SDNode *BVN = N->getOperand(0).getNode();
5936 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5937 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5938 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5939 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5940 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5942 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5943 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5944 EVT VT = N->getValueType(0);
5945 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5946 unsigned NumElts = VT.getVectorNumElements();
5947 MVT TruncVT = MVT::getIntegerVT(EltSize);
5948 SmallVector<SDValue, 8> Ops;
5949 for (unsigned i = 0; i != NumElts; ++i) {
5950 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5951 const APInt &CInt = C->getAPIntValue();
5952 // Element types smaller than 32 bits are not legal, so use i32 elements.
5953 // The values are implicitly truncated so sext vs. zext doesn't matter.
5954 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5956 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5957 MVT::getVectorVT(TruncVT, NumElts), Ops);
5960 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5961 unsigned Opcode = N->getOpcode();
5962 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5963 SDNode *N0 = N->getOperand(0).getNode();
5964 SDNode *N1 = N->getOperand(1).getNode();
5965 return N0->hasOneUse() && N1->hasOneUse() &&
5966 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5971 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5972 unsigned Opcode = N->getOpcode();
5973 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5974 SDNode *N0 = N->getOperand(0).getNode();
5975 SDNode *N1 = N->getOperand(1).getNode();
5976 return N0->hasOneUse() && N1->hasOneUse() &&
5977 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5982 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5983 // Multiplications are only custom-lowered for 128-bit vectors so that
5984 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5985 EVT VT = Op.getValueType();
5986 assert(VT.is128BitVector() && VT.isInteger() &&
5987 "unexpected type for custom-lowering ISD::MUL");
5988 SDNode *N0 = Op.getOperand(0).getNode();
5989 SDNode *N1 = Op.getOperand(1).getNode();
5990 unsigned NewOpc = 0;
5992 bool isN0SExt = isSignExtended(N0, DAG);
5993 bool isN1SExt = isSignExtended(N1, DAG);
5994 if (isN0SExt && isN1SExt)
5995 NewOpc = ARMISD::VMULLs;
5997 bool isN0ZExt = isZeroExtended(N0, DAG);
5998 bool isN1ZExt = isZeroExtended(N1, DAG);
5999 if (isN0ZExt && isN1ZExt)
6000 NewOpc = ARMISD::VMULLu;
6001 else if (isN1SExt || isN1ZExt) {
6002 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6003 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6004 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6005 NewOpc = ARMISD::VMULLs;
6007 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6008 NewOpc = ARMISD::VMULLu;
6010 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6012 NewOpc = ARMISD::VMULLu;
6018 if (VT == MVT::v2i64)
6019 // Fall through to expand this. It is not legal.
6022 // Other vector multiplications are legal.
6027 // Legalize to a VMULL instruction.
6030 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6032 Op0 = SkipExtensionForVMULL(N0, DAG);
6033 assert(Op0.getValueType().is64BitVector() &&
6034 Op1.getValueType().is64BitVector() &&
6035 "unexpected types for extended operands to VMULL");
6036 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6039 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6040 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6047 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6048 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6049 EVT Op1VT = Op1.getValueType();
6050 return DAG.getNode(N0->getOpcode(), DL, VT,
6051 DAG.getNode(NewOpc, DL, VT,
6052 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6053 DAG.getNode(NewOpc, DL, VT,
6054 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6058 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6060 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6061 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6062 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6063 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6064 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6065 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6066 // Get reciprocal estimate.
6067 // float4 recip = vrecpeq_f32(yf);
6068 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6069 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
6070 // Because char has a smaller range than uchar, we can actually get away
6071 // without any newton steps. This requires that we use a weird bias
6072 // of 0xb000, however (again, this has been exhaustively tested).
6073 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6074 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6075 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6076 Y = DAG.getConstant(0xb000, MVT::i32);
6077 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6078 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6079 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6080 // Convert back to short.
6081 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6082 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6087 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6089 // Convert to float.
6090 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6091 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6092 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6093 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6094 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6095 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6097 // Use reciprocal estimate and one refinement step.
6098 // float4 recip = vrecpeq_f32(yf);
6099 // recip *= vrecpsq_f32(yf, recip);
6100 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6101 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6102 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6103 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6105 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6106 // Because short has a smaller range than ushort, we can actually get away
6107 // with only a single newton step. This requires that we use a weird bias
6108 // of 89, however (again, this has been exhaustively tested).
6109 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6110 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6111 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6112 N1 = DAG.getConstant(0x89, MVT::i32);
6113 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6114 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6115 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6116 // Convert back to integer and return.
6117 // return vmovn_s32(vcvt_s32_f32(result));
6118 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6119 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6123 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6124 EVT VT = Op.getValueType();
6125 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6126 "unexpected type for custom-lowering ISD::SDIV");
6129 SDValue N0 = Op.getOperand(0);
6130 SDValue N1 = Op.getOperand(1);
6133 if (VT == MVT::v8i8) {
6134 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6135 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6137 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6138 DAG.getIntPtrConstant(4));
6139 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6140 DAG.getIntPtrConstant(4));
6141 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6142 DAG.getIntPtrConstant(0));
6143 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6144 DAG.getIntPtrConstant(0));
6146 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6147 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6149 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6150 N0 = LowerCONCAT_VECTORS(N0, DAG);
6152 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6155 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6158 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6159 EVT VT = Op.getValueType();
6160 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6161 "unexpected type for custom-lowering ISD::UDIV");
6164 SDValue N0 = Op.getOperand(0);
6165 SDValue N1 = Op.getOperand(1);
6168 if (VT == MVT::v8i8) {
6169 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6170 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6172 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6173 DAG.getIntPtrConstant(4));
6174 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6175 DAG.getIntPtrConstant(4));
6176 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6177 DAG.getIntPtrConstant(0));
6178 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6179 DAG.getIntPtrConstant(0));
6181 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6182 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6184 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6185 N0 = LowerCONCAT_VECTORS(N0, DAG);
6187 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6188 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6193 // v4i16 sdiv ... Convert to float.
6194 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6195 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6196 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6197 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6198 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6199 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6201 // Use reciprocal estimate and two refinement steps.
6202 // float4 recip = vrecpeq_f32(yf);
6203 // recip *= vrecpsq_f32(yf, recip);
6204 // recip *= vrecpsq_f32(yf, recip);
6205 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6206 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6207 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6208 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6210 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6211 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6212 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6214 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6215 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6216 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6217 // and that it will never cause us to return an answer too large).
6218 // float4 result = as_float4(as_int4(xf*recip) + 2);
6219 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6220 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6221 N1 = DAG.getConstant(2, MVT::i32);
6222 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6223 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6224 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6225 // Convert back to integer and return.
6226 // return vmovn_u32(vcvt_s32_f32(result));
6227 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6228 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6232 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6233 EVT VT = Op.getNode()->getValueType(0);
6234 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6237 bool ExtraOp = false;
6238 switch (Op.getOpcode()) {
6239 default: llvm_unreachable("Invalid code");
6240 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6241 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6242 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6243 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6247 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6249 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6250 Op.getOperand(1), Op.getOperand(2));
6253 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6254 assert(Subtarget->isTargetDarwin());
6256 // For iOS, we want to call an alternative entry point: __sincos_stret,
6257 // return values are passed via sret.
6259 SDValue Arg = Op.getOperand(0);
6260 EVT ArgVT = Arg.getValueType();
6261 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6263 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6264 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6266 // Pair of floats / doubles used to pass the result.
6267 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6269 // Create stack object for sret.
6270 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6271 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6272 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6273 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6279 Entry.Ty = RetTy->getPointerTo();
6280 Entry.isSExt = false;
6281 Entry.isZExt = false;
6282 Entry.isSRet = true;
6283 Args.push_back(Entry);
6287 Entry.isSExt = false;
6288 Entry.isZExt = false;
6289 Args.push_back(Entry);
6291 const char *LibcallName = (ArgVT == MVT::f64)
6292 ? "__sincos_stret" : "__sincosf_stret";
6293 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6295 TargetLowering::CallLoweringInfo CLI(DAG);
6296 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6297 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6299 .setDiscardResult();
6301 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6303 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6304 MachinePointerInfo(), false, false, false, 0);
6306 // Address of cos field.
6307 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6308 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6309 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6310 MachinePointerInfo(), false, false, false, 0);
6312 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6313 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6314 LoadSin.getValue(0), LoadCos.getValue(0));
6317 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6318 // Monotonic load/store is legal for all targets
6319 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6322 // Acquire/Release load/store is not legal for targets without a
6323 // dmb or equivalent available.
6327 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6328 SmallVectorImpl<SDValue> &Results,
6330 const ARMSubtarget *Subtarget) {
6332 SDValue Cycles32, OutChain;
6334 if (Subtarget->hasPerfMon()) {
6335 // Under Power Management extensions, the cycle-count is:
6336 // mrc p15, #0, <Rt>, c9, c13, #0
6337 SDValue Ops[] = { N->getOperand(0), // Chain
6338 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6339 DAG.getConstant(15, MVT::i32),
6340 DAG.getConstant(0, MVT::i32),
6341 DAG.getConstant(9, MVT::i32),
6342 DAG.getConstant(13, MVT::i32),
6343 DAG.getConstant(0, MVT::i32)
6346 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6347 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6348 OutChain = Cycles32.getValue(1);
6350 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6351 // there are older ARM CPUs that have implementation-specific ways of
6352 // obtaining this information (FIXME!).
6353 Cycles32 = DAG.getConstant(0, MVT::i32);
6354 OutChain = DAG.getEntryNode();
6358 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6359 Cycles32, DAG.getConstant(0, MVT::i32));
6360 Results.push_back(Cycles64);
6361 Results.push_back(OutChain);
6364 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6365 switch (Op.getOpcode()) {
6366 default: llvm_unreachable("Don't know how to custom lower this!");
6367 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6368 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6369 case ISD::GlobalAddress:
6370 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6371 default: llvm_unreachable("unknown object format");
6373 return LowerGlobalAddressWindows(Op, DAG);
6375 return LowerGlobalAddressELF(Op, DAG);
6377 return LowerGlobalAddressDarwin(Op, DAG);
6379 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6380 case ISD::SELECT: return LowerSELECT(Op, DAG);
6381 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6382 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6383 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6384 case ISD::VASTART: return LowerVASTART(Op, DAG);
6385 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6386 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6387 case ISD::SINT_TO_FP:
6388 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6389 case ISD::FP_TO_SINT:
6390 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6391 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6392 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6393 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6394 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6395 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6396 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6397 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6399 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6402 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6403 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6404 case ISD::SRL_PARTS:
6405 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6406 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6407 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6408 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6409 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6410 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6411 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6412 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6413 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6414 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6415 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6416 case ISD::MUL: return LowerMUL(Op, DAG);
6417 case ISD::SDIV: return LowerSDIV(Op, DAG);
6418 case ISD::UDIV: return LowerUDIV(Op, DAG);
6422 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6427 return LowerXALUO(Op, DAG);
6428 case ISD::ATOMIC_LOAD:
6429 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6430 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6432 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6433 case ISD::DYNAMIC_STACKALLOC:
6434 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6435 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6436 llvm_unreachable("Don't know how to custom lower this!");
6437 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6438 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6442 /// ReplaceNodeResults - Replace the results of node with an illegal result
6443 /// type with new values built out of custom code.
6444 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6445 SmallVectorImpl<SDValue>&Results,
6446 SelectionDAG &DAG) const {
6448 switch (N->getOpcode()) {
6450 llvm_unreachable("Don't know how to custom expand this!");
6452 Res = ExpandBITCAST(N, DAG);
6456 Res = Expand64BitShift(N, DAG, Subtarget);
6458 case ISD::READCYCLECOUNTER:
6459 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6463 Results.push_back(Res);
6466 //===----------------------------------------------------------------------===//
6467 // ARM Scheduler Hooks
6468 //===----------------------------------------------------------------------===//
6470 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6471 /// registers the function context.
6472 void ARMTargetLowering::
6473 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6474 MachineBasicBlock *DispatchBB, int FI) const {
6475 const TargetInstrInfo *TII =
6476 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6477 DebugLoc dl = MI->getDebugLoc();
6478 MachineFunction *MF = MBB->getParent();
6479 MachineRegisterInfo *MRI = &MF->getRegInfo();
6480 MachineConstantPool *MCP = MF->getConstantPool();
6481 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6482 const Function *F = MF->getFunction();
6484 bool isThumb = Subtarget->isThumb();
6485 bool isThumb2 = Subtarget->isThumb2();
6487 unsigned PCLabelId = AFI->createPICLabelUId();
6488 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6489 ARMConstantPoolValue *CPV =
6490 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6491 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6493 const TargetRegisterClass *TRC = isThumb ?
6494 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6495 (const TargetRegisterClass*)&ARM::GPRRegClass;
6497 // Grab constant pool and fixed stack memory operands.
6498 MachineMemOperand *CPMMO =
6499 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6500 MachineMemOperand::MOLoad, 4, 4);
6502 MachineMemOperand *FIMMOSt =
6503 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6504 MachineMemOperand::MOStore, 4, 4);
6506 // Load the address of the dispatch MBB into the jump buffer.
6508 // Incoming value: jbuf
6509 // ldr.n r5, LCPI1_1
6512 // str r5, [$jbuf, #+4] ; &jbuf[1]
6513 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6514 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6515 .addConstantPoolIndex(CPI)
6516 .addMemOperand(CPMMO));
6517 // Set the low bit because of thumb mode.
6518 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6520 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6521 .addReg(NewVReg1, RegState::Kill)
6523 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6524 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6525 .addReg(NewVReg2, RegState::Kill)
6527 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6528 .addReg(NewVReg3, RegState::Kill)
6530 .addImm(36) // &jbuf[1] :: pc
6531 .addMemOperand(FIMMOSt));
6532 } else if (isThumb) {
6533 // Incoming value: jbuf
6534 // ldr.n r1, LCPI1_4
6538 // add r2, $jbuf, #+4 ; &jbuf[1]
6540 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6541 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6542 .addConstantPoolIndex(CPI)
6543 .addMemOperand(CPMMO));
6544 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6545 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6546 .addReg(NewVReg1, RegState::Kill)
6548 // Set the low bit because of thumb mode.
6549 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6550 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6551 .addReg(ARM::CPSR, RegState::Define)
6553 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6554 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6555 .addReg(ARM::CPSR, RegState::Define)
6556 .addReg(NewVReg2, RegState::Kill)
6557 .addReg(NewVReg3, RegState::Kill));
6558 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6559 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6561 .addImm(36)); // &jbuf[1] :: pc
6562 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6563 .addReg(NewVReg4, RegState::Kill)
6564 .addReg(NewVReg5, RegState::Kill)
6566 .addMemOperand(FIMMOSt));
6568 // Incoming value: jbuf
6571 // str r1, [$jbuf, #+4] ; &jbuf[1]
6572 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6573 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6574 .addConstantPoolIndex(CPI)
6576 .addMemOperand(CPMMO));
6577 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6578 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6579 .addReg(NewVReg1, RegState::Kill)
6580 .addImm(PCLabelId));
6581 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6582 .addReg(NewVReg2, RegState::Kill)
6584 .addImm(36) // &jbuf[1] :: pc
6585 .addMemOperand(FIMMOSt));
6589 MachineBasicBlock *ARMTargetLowering::
6590 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6591 const TargetInstrInfo *TII =
6592 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6593 DebugLoc dl = MI->getDebugLoc();
6594 MachineFunction *MF = MBB->getParent();
6595 MachineRegisterInfo *MRI = &MF->getRegInfo();
6596 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6597 MachineFrameInfo *MFI = MF->getFrameInfo();
6598 int FI = MFI->getFunctionContextIndex();
6600 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6601 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6602 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6604 // Get a mapping of the call site numbers to all of the landing pads they're
6606 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6607 unsigned MaxCSNum = 0;
6608 MachineModuleInfo &MMI = MF->getMMI();
6609 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6611 if (!BB->isLandingPad()) continue;
6613 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6615 for (MachineBasicBlock::iterator
6616 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6617 if (!II->isEHLabel()) continue;
6619 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6620 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6622 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6623 for (SmallVectorImpl<unsigned>::iterator
6624 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6625 CSI != CSE; ++CSI) {
6626 CallSiteNumToLPad[*CSI].push_back(BB);
6627 MaxCSNum = std::max(MaxCSNum, *CSI);
6633 // Get an ordered list of the machine basic blocks for the jump table.
6634 std::vector<MachineBasicBlock*> LPadList;
6635 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6636 LPadList.reserve(CallSiteNumToLPad.size());
6637 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6638 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6639 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6640 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6641 LPadList.push_back(*II);
6642 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6646 assert(!LPadList.empty() &&
6647 "No landing pad destinations for the dispatch jump table!");
6649 // Create the jump table and associated information.
6650 MachineJumpTableInfo *JTI =
6651 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6652 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6653 unsigned UId = AFI->createJumpTableUId();
6654 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6656 // Create the MBBs for the dispatch code.
6658 // Shove the dispatch's address into the return slot in the function context.
6659 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6660 DispatchBB->setIsLandingPad();
6662 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6663 unsigned trap_opcode;
6664 if (Subtarget->isThumb())
6665 trap_opcode = ARM::tTRAP;
6667 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6669 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6670 DispatchBB->addSuccessor(TrapBB);
6672 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6673 DispatchBB->addSuccessor(DispContBB);
6676 MF->insert(MF->end(), DispatchBB);
6677 MF->insert(MF->end(), DispContBB);
6678 MF->insert(MF->end(), TrapBB);
6680 // Insert code into the entry block that creates and registers the function
6682 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6684 MachineMemOperand *FIMMOLd =
6685 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6686 MachineMemOperand::MOLoad |
6687 MachineMemOperand::MOVolatile, 4, 4);
6689 MachineInstrBuilder MIB;
6690 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6692 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6693 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6695 // Add a register mask with no preserved registers. This results in all
6696 // registers being marked as clobbered.
6697 MIB.addRegMask(RI.getNoPreservedMask());
6699 unsigned NumLPads = LPadList.size();
6700 if (Subtarget->isThumb2()) {
6701 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6702 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6705 .addMemOperand(FIMMOLd));
6707 if (NumLPads < 256) {
6708 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6710 .addImm(LPadList.size()));
6712 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6713 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), 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::t2MOVTi16), VReg2)
6721 .addImm(NumLPads >> 16));
6724 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6729 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6734 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6735 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6736 .addJumpTableIndex(MJTI)
6739 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6742 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6743 .addReg(NewVReg3, RegState::Kill)
6745 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6747 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6748 .addReg(NewVReg4, RegState::Kill)
6750 .addJumpTableIndex(MJTI)
6752 } else if (Subtarget->isThumb()) {
6753 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6754 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6757 .addMemOperand(FIMMOLd));
6759 if (NumLPads < 256) {
6760 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6764 MachineConstantPool *ConstantPool = MF->getConstantPool();
6765 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6766 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6768 // MachineConstantPool wants an explicit alignment.
6769 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6771 Align = getDataLayout()->getTypeAllocSize(C->getType());
6772 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6774 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6775 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6776 .addReg(VReg1, RegState::Define)
6777 .addConstantPoolIndex(Idx));
6778 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6783 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6788 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6789 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6790 .addReg(ARM::CPSR, RegState::Define)
6794 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6795 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6796 .addJumpTableIndex(MJTI)
6799 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6800 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6801 .addReg(ARM::CPSR, RegState::Define)
6802 .addReg(NewVReg2, RegState::Kill)
6805 MachineMemOperand *JTMMOLd =
6806 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6807 MachineMemOperand::MOLoad, 4, 4);
6809 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6810 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6811 .addReg(NewVReg4, RegState::Kill)
6813 .addMemOperand(JTMMOLd));
6815 unsigned NewVReg6 = NewVReg5;
6816 if (RelocM == Reloc::PIC_) {
6817 NewVReg6 = MRI->createVirtualRegister(TRC);
6818 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6819 .addReg(ARM::CPSR, RegState::Define)
6820 .addReg(NewVReg5, RegState::Kill)
6824 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6825 .addReg(NewVReg6, RegState::Kill)
6826 .addJumpTableIndex(MJTI)
6829 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6830 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6833 .addMemOperand(FIMMOLd));
6835 if (NumLPads < 256) {
6836 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6839 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6840 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6841 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6842 .addImm(NumLPads & 0xFFFF));
6844 unsigned VReg2 = VReg1;
6845 if ((NumLPads & 0xFFFF0000) != 0) {
6846 VReg2 = MRI->createVirtualRegister(TRC);
6847 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6849 .addImm(NumLPads >> 16));
6852 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6856 MachineConstantPool *ConstantPool = MF->getConstantPool();
6857 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6858 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6860 // MachineConstantPool wants an explicit alignment.
6861 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6863 Align = getDataLayout()->getTypeAllocSize(C->getType());
6864 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6866 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6867 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6868 .addReg(VReg1, RegState::Define)
6869 .addConstantPoolIndex(Idx)
6871 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6873 .addReg(VReg1, RegState::Kill));
6876 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6881 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6883 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6885 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6886 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6887 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6888 .addJumpTableIndex(MJTI)
6891 MachineMemOperand *JTMMOLd =
6892 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6893 MachineMemOperand::MOLoad, 4, 4);
6894 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6896 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6897 .addReg(NewVReg3, RegState::Kill)
6900 .addMemOperand(JTMMOLd));
6902 if (RelocM == Reloc::PIC_) {
6903 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6904 .addReg(NewVReg5, RegState::Kill)
6906 .addJumpTableIndex(MJTI)
6909 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6910 .addReg(NewVReg5, RegState::Kill)
6911 .addJumpTableIndex(MJTI)
6916 // Add the jump table entries as successors to the MBB.
6917 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6918 for (std::vector<MachineBasicBlock*>::iterator
6919 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6920 MachineBasicBlock *CurMBB = *I;
6921 if (SeenMBBs.insert(CurMBB))
6922 DispContBB->addSuccessor(CurMBB);
6925 // N.B. the order the invoke BBs are processed in doesn't matter here.
6926 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6927 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6928 for (MachineBasicBlock *BB : InvokeBBs) {
6930 // Remove the landing pad successor from the invoke block and replace it
6931 // with the new dispatch block.
6932 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6934 while (!Successors.empty()) {
6935 MachineBasicBlock *SMBB = Successors.pop_back_val();
6936 if (SMBB->isLandingPad()) {
6937 BB->removeSuccessor(SMBB);
6938 MBBLPads.push_back(SMBB);
6942 BB->addSuccessor(DispatchBB);
6944 // Find the invoke call and mark all of the callee-saved registers as
6945 // 'implicit defined' so that they're spilled. This prevents code from
6946 // moving instructions to before the EH block, where they will never be
6948 for (MachineBasicBlock::reverse_iterator
6949 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6950 if (!II->isCall()) continue;
6952 DenseMap<unsigned, bool> DefRegs;
6953 for (MachineInstr::mop_iterator
6954 OI = II->operands_begin(), OE = II->operands_end();
6956 if (!OI->isReg()) continue;
6957 DefRegs[OI->getReg()] = true;
6960 MachineInstrBuilder MIB(*MF, &*II);
6962 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6963 unsigned Reg = SavedRegs[i];
6964 if (Subtarget->isThumb2() &&
6965 !ARM::tGPRRegClass.contains(Reg) &&
6966 !ARM::hGPRRegClass.contains(Reg))
6968 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6970 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6973 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6980 // Mark all former landing pads as non-landing pads. The dispatch is the only
6982 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6983 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6984 (*I)->setIsLandingPad(false);
6986 // The instruction is gone now.
6987 MI->eraseFromParent();
6993 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6994 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6995 E = MBB->succ_end(); I != E; ++I)
6998 llvm_unreachable("Expecting a BB with two successors!");
7001 /// Return the load opcode for a given load size. If load size >= 8,
7002 /// neon opcode will be returned.
7003 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7005 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7006 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7008 return LdSize == 4 ? ARM::tLDRi
7009 : LdSize == 2 ? ARM::tLDRHi
7010 : LdSize == 1 ? ARM::tLDRBi : 0;
7012 return LdSize == 4 ? ARM::t2LDR_POST
7013 : LdSize == 2 ? ARM::t2LDRH_POST
7014 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7015 return LdSize == 4 ? ARM::LDR_POST_IMM
7016 : LdSize == 2 ? ARM::LDRH_POST
7017 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7020 /// Return the store opcode for a given store size. If store size >= 8,
7021 /// neon opcode will be returned.
7022 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7024 return StSize == 16 ? ARM::VST1q32wb_fixed
7025 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7027 return StSize == 4 ? ARM::tSTRi
7028 : StSize == 2 ? ARM::tSTRHi
7029 : StSize == 1 ? ARM::tSTRBi : 0;
7031 return StSize == 4 ? ARM::t2STR_POST
7032 : StSize == 2 ? ARM::t2STRH_POST
7033 : StSize == 1 ? ARM::t2STRB_POST : 0;
7034 return StSize == 4 ? ARM::STR_POST_IMM
7035 : StSize == 2 ? ARM::STRH_POST
7036 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7039 /// Emit a post-increment load operation with given size. The instructions
7040 /// will be added to BB at Pos.
7041 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7042 const TargetInstrInfo *TII, DebugLoc dl,
7043 unsigned LdSize, unsigned Data, unsigned AddrIn,
7044 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7045 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7046 assert(LdOpc != 0 && "Should have a load opcode");
7048 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7049 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7051 } else if (IsThumb1) {
7052 // load + update AddrIn
7053 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7054 .addReg(AddrIn).addImm(0));
7055 MachineInstrBuilder MIB =
7056 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7057 MIB = AddDefaultT1CC(MIB);
7058 MIB.addReg(AddrIn).addImm(LdSize);
7059 AddDefaultPred(MIB);
7060 } else if (IsThumb2) {
7061 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7062 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7065 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7066 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7067 .addReg(0).addImm(LdSize));
7071 /// Emit a post-increment store operation with given size. The instructions
7072 /// will be added to BB at Pos.
7073 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7074 const TargetInstrInfo *TII, DebugLoc dl,
7075 unsigned StSize, unsigned Data, unsigned AddrIn,
7076 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7077 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7078 assert(StOpc != 0 && "Should have a store opcode");
7080 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7081 .addReg(AddrIn).addImm(0).addReg(Data));
7082 } else if (IsThumb1) {
7083 // store + update AddrIn
7084 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7085 .addReg(AddrIn).addImm(0));
7086 MachineInstrBuilder MIB =
7087 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7088 MIB = AddDefaultT1CC(MIB);
7089 MIB.addReg(AddrIn).addImm(StSize);
7090 AddDefaultPred(MIB);
7091 } else if (IsThumb2) {
7092 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7093 .addReg(Data).addReg(AddrIn).addImm(StSize));
7095 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7096 .addReg(Data).addReg(AddrIn).addReg(0)
7102 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7103 MachineBasicBlock *BB) const {
7104 // This pseudo instruction has 3 operands: dst, src, size
7105 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7106 // Otherwise, we will generate unrolled scalar copies.
7107 const TargetInstrInfo *TII =
7108 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7109 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7110 MachineFunction::iterator It = BB;
7113 unsigned dest = MI->getOperand(0).getReg();
7114 unsigned src = MI->getOperand(1).getReg();
7115 unsigned SizeVal = MI->getOperand(2).getImm();
7116 unsigned Align = MI->getOperand(3).getImm();
7117 DebugLoc dl = MI->getDebugLoc();
7119 MachineFunction *MF = BB->getParent();
7120 MachineRegisterInfo &MRI = MF->getRegInfo();
7121 unsigned UnitSize = 0;
7122 const TargetRegisterClass *TRC = nullptr;
7123 const TargetRegisterClass *VecTRC = nullptr;
7125 bool IsThumb1 = Subtarget->isThumb1Only();
7126 bool IsThumb2 = Subtarget->isThumb2();
7130 } else if (Align & 2) {
7133 // Check whether we can use NEON instructions.
7134 if (!MF->getFunction()->getAttributes().
7135 hasAttribute(AttributeSet::FunctionIndex,
7136 Attribute::NoImplicitFloat) &&
7137 Subtarget->hasNEON()) {
7138 if ((Align % 16 == 0) && SizeVal >= 16)
7140 else if ((Align % 8 == 0) && SizeVal >= 8)
7143 // Can't use NEON instructions.
7148 // Select the correct opcode and register class for unit size load/store
7149 bool IsNeon = UnitSize >= 8;
7150 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7151 : (const TargetRegisterClass *)&ARM::GPRRegClass;
7153 VecTRC = UnitSize == 16
7154 ? (const TargetRegisterClass *)&ARM::DPairRegClass
7156 ? (const TargetRegisterClass *)&ARM::DPRRegClass
7159 unsigned BytesLeft = SizeVal % UnitSize;
7160 unsigned LoopSize = SizeVal - BytesLeft;
7162 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7163 // Use LDR and STR to copy.
7164 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7165 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7166 unsigned srcIn = src;
7167 unsigned destIn = dest;
7168 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7169 unsigned srcOut = MRI.createVirtualRegister(TRC);
7170 unsigned destOut = MRI.createVirtualRegister(TRC);
7171 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7172 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7173 IsThumb1, IsThumb2);
7174 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7175 IsThumb1, IsThumb2);
7180 // Handle the leftover bytes with LDRB and STRB.
7181 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7182 // [destOut] = STRB_POST(scratch, destIn, 1)
7183 for (unsigned i = 0; i < BytesLeft; i++) {
7184 unsigned srcOut = MRI.createVirtualRegister(TRC);
7185 unsigned destOut = MRI.createVirtualRegister(TRC);
7186 unsigned scratch = MRI.createVirtualRegister(TRC);
7187 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7188 IsThumb1, IsThumb2);
7189 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7190 IsThumb1, IsThumb2);
7194 MI->eraseFromParent(); // The instruction is gone now.
7198 // Expand the pseudo op to a loop.
7201 // movw varEnd, # --> with thumb2
7203 // ldrcp varEnd, idx --> without thumb2
7204 // fallthrough --> loopMBB
7206 // PHI varPhi, varEnd, varLoop
7207 // PHI srcPhi, src, srcLoop
7208 // PHI destPhi, dst, destLoop
7209 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7210 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7211 // subs varLoop, varPhi, #UnitSize
7213 // fallthrough --> exitMBB
7215 // epilogue to handle left-over bytes
7216 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7217 // [destOut] = STRB_POST(scratch, destLoop, 1)
7218 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7219 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7220 MF->insert(It, loopMBB);
7221 MF->insert(It, exitMBB);
7223 // Transfer the remainder of BB and its successor edges to exitMBB.
7224 exitMBB->splice(exitMBB->begin(), BB,
7225 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7226 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7228 // Load an immediate to varEnd.
7229 unsigned varEnd = MRI.createVirtualRegister(TRC);
7231 unsigned Vtmp = varEnd;
7232 if ((LoopSize & 0xFFFF0000) != 0)
7233 Vtmp = MRI.createVirtualRegister(TRC);
7234 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7235 .addImm(LoopSize & 0xFFFF));
7237 if ((LoopSize & 0xFFFF0000) != 0)
7238 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7239 .addReg(Vtmp).addImm(LoopSize >> 16));
7241 MachineConstantPool *ConstantPool = MF->getConstantPool();
7242 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7243 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7245 // MachineConstantPool wants an explicit alignment.
7246 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7248 Align = getDataLayout()->getTypeAllocSize(C->getType());
7249 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7252 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7253 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7255 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7256 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7258 BB->addSuccessor(loopMBB);
7260 // Generate the loop body:
7261 // varPhi = PHI(varLoop, varEnd)
7262 // srcPhi = PHI(srcLoop, src)
7263 // destPhi = PHI(destLoop, dst)
7264 MachineBasicBlock *entryBB = BB;
7266 unsigned varLoop = MRI.createVirtualRegister(TRC);
7267 unsigned varPhi = MRI.createVirtualRegister(TRC);
7268 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7269 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7270 unsigned destLoop = MRI.createVirtualRegister(TRC);
7271 unsigned destPhi = MRI.createVirtualRegister(TRC);
7273 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7274 .addReg(varLoop).addMBB(loopMBB)
7275 .addReg(varEnd).addMBB(entryBB);
7276 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7277 .addReg(srcLoop).addMBB(loopMBB)
7278 .addReg(src).addMBB(entryBB);
7279 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7280 .addReg(destLoop).addMBB(loopMBB)
7281 .addReg(dest).addMBB(entryBB);
7283 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7284 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7285 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7286 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7287 IsThumb1, IsThumb2);
7288 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7289 IsThumb1, IsThumb2);
7291 // Decrement loop variable by UnitSize.
7293 MachineInstrBuilder MIB =
7294 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7295 MIB = AddDefaultT1CC(MIB);
7296 MIB.addReg(varPhi).addImm(UnitSize);
7297 AddDefaultPred(MIB);
7299 MachineInstrBuilder MIB =
7300 BuildMI(*BB, BB->end(), dl,
7301 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7302 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7303 MIB->getOperand(5).setReg(ARM::CPSR);
7304 MIB->getOperand(5).setIsDef(true);
7306 BuildMI(*BB, BB->end(), dl,
7307 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7308 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7310 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7311 BB->addSuccessor(loopMBB);
7312 BB->addSuccessor(exitMBB);
7314 // Add epilogue to handle BytesLeft.
7316 MachineInstr *StartOfExit = exitMBB->begin();
7318 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7319 // [destOut] = STRB_POST(scratch, destLoop, 1)
7320 unsigned srcIn = srcLoop;
7321 unsigned destIn = destLoop;
7322 for (unsigned i = 0; i < BytesLeft; i++) {
7323 unsigned srcOut = MRI.createVirtualRegister(TRC);
7324 unsigned destOut = MRI.createVirtualRegister(TRC);
7325 unsigned scratch = MRI.createVirtualRegister(TRC);
7326 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7327 IsThumb1, IsThumb2);
7328 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7329 IsThumb1, IsThumb2);
7334 MI->eraseFromParent(); // The instruction is gone now.
7339 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7340 MachineBasicBlock *MBB) const {
7341 const TargetMachine &TM = getTargetMachine();
7342 const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
7343 DebugLoc DL = MI->getDebugLoc();
7345 assert(Subtarget->isTargetWindows() &&
7346 "__chkstk is only supported on Windows");
7347 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7349 // __chkstk takes the number of words to allocate on the stack in R4, and
7350 // returns the stack adjustment in number of bytes in R4. This will not
7351 // clober any other registers (other than the obvious lr).
7353 // Although, technically, IP should be considered a register which may be
7354 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7355 // thumb-2 environment, so there is no interworking required. As a result, we
7356 // do not expect a veneer to be emitted by the linker, clobbering IP.
7358 // Each module receives its own copy of __chkstk, so no import thunk is
7359 // required, again, ensuring that IP is not clobbered.
7361 // Finally, although some linkers may theoretically provide a trampoline for
7362 // out of range calls (which is quite common due to a 32M range limitation of
7363 // branches for Thumb), we can generate the long-call version via
7364 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7367 switch (TM.getCodeModel()) {
7368 case CodeModel::Small:
7369 case CodeModel::Medium:
7370 case CodeModel::Default:
7371 case CodeModel::Kernel:
7372 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7373 .addImm((unsigned)ARMCC::AL).addReg(0)
7374 .addExternalSymbol("__chkstk")
7375 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7376 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7377 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7379 case CodeModel::Large:
7380 case CodeModel::JITDefault: {
7381 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7382 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7384 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7385 .addExternalSymbol("__chkstk");
7386 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7387 .addImm((unsigned)ARMCC::AL).addReg(0)
7388 .addReg(Reg, RegState::Kill)
7389 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7390 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7391 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7396 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7398 .addReg(ARM::SP).addReg(ARM::R4)));
7400 MI->eraseFromParent();
7405 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7406 MachineBasicBlock *BB) const {
7407 const TargetInstrInfo *TII =
7408 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7409 DebugLoc dl = MI->getDebugLoc();
7410 bool isThumb2 = Subtarget->isThumb2();
7411 switch (MI->getOpcode()) {
7414 llvm_unreachable("Unexpected instr type to insert");
7416 // The Thumb2 pre-indexed stores have the same MI operands, they just
7417 // define them differently in the .td files from the isel patterns, so
7418 // they need pseudos.
7419 case ARM::t2STR_preidx:
7420 MI->setDesc(TII->get(ARM::t2STR_PRE));
7422 case ARM::t2STRB_preidx:
7423 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7425 case ARM::t2STRH_preidx:
7426 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7429 case ARM::STRi_preidx:
7430 case ARM::STRBi_preidx: {
7431 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7432 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7433 // Decode the offset.
7434 unsigned Offset = MI->getOperand(4).getImm();
7435 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7436 Offset = ARM_AM::getAM2Offset(Offset);
7440 MachineMemOperand *MMO = *MI->memoperands_begin();
7441 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7442 .addOperand(MI->getOperand(0)) // Rn_wb
7443 .addOperand(MI->getOperand(1)) // Rt
7444 .addOperand(MI->getOperand(2)) // Rn
7445 .addImm(Offset) // offset (skip GPR==zero_reg)
7446 .addOperand(MI->getOperand(5)) // pred
7447 .addOperand(MI->getOperand(6))
7448 .addMemOperand(MMO);
7449 MI->eraseFromParent();
7452 case ARM::STRr_preidx:
7453 case ARM::STRBr_preidx:
7454 case ARM::STRH_preidx: {
7456 switch (MI->getOpcode()) {
7457 default: llvm_unreachable("unexpected opcode!");
7458 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7459 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7460 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7462 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7463 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7464 MIB.addOperand(MI->getOperand(i));
7465 MI->eraseFromParent();
7469 case ARM::tMOVCCr_pseudo: {
7470 // To "insert" a SELECT_CC instruction, we actually have to insert the
7471 // diamond control-flow pattern. The incoming instruction knows the
7472 // destination vreg to set, the condition code register to branch on, the
7473 // true/false values to select between, and a branch opcode to use.
7474 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7475 MachineFunction::iterator It = BB;
7481 // cmpTY ccX, r1, r2
7483 // fallthrough --> copy0MBB
7484 MachineBasicBlock *thisMBB = BB;
7485 MachineFunction *F = BB->getParent();
7486 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7487 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7488 F->insert(It, copy0MBB);
7489 F->insert(It, sinkMBB);
7491 // Transfer the remainder of BB and its successor edges to sinkMBB.
7492 sinkMBB->splice(sinkMBB->begin(), BB,
7493 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7494 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7496 BB->addSuccessor(copy0MBB);
7497 BB->addSuccessor(sinkMBB);
7499 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7500 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7503 // %FalseValue = ...
7504 // # fallthrough to sinkMBB
7507 // Update machine-CFG edges
7508 BB->addSuccessor(sinkMBB);
7511 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7514 BuildMI(*BB, BB->begin(), dl,
7515 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7516 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7517 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7519 MI->eraseFromParent(); // The pseudo instruction is gone now.
7524 case ARM::BCCZi64: {
7525 // If there is an unconditional branch to the other successor, remove it.
7526 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7528 // Compare both parts that make up the double comparison separately for
7530 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7532 unsigned LHS1 = MI->getOperand(1).getReg();
7533 unsigned LHS2 = MI->getOperand(2).getReg();
7535 AddDefaultPred(BuildMI(BB, dl,
7536 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7537 .addReg(LHS1).addImm(0));
7538 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7539 .addReg(LHS2).addImm(0)
7540 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7542 unsigned RHS1 = MI->getOperand(3).getReg();
7543 unsigned RHS2 = MI->getOperand(4).getReg();
7544 AddDefaultPred(BuildMI(BB, dl,
7545 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7546 .addReg(LHS1).addReg(RHS1));
7547 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7548 .addReg(LHS2).addReg(RHS2)
7549 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7552 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7553 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7554 if (MI->getOperand(0).getImm() == ARMCC::NE)
7555 std::swap(destMBB, exitMBB);
7557 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7558 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7560 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7562 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7564 MI->eraseFromParent(); // The pseudo instruction is gone now.
7568 case ARM::Int_eh_sjlj_setjmp:
7569 case ARM::Int_eh_sjlj_setjmp_nofp:
7570 case ARM::tInt_eh_sjlj_setjmp:
7571 case ARM::t2Int_eh_sjlj_setjmp:
7572 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7573 EmitSjLjDispatchBlock(MI, BB);
7578 // To insert an ABS instruction, we have to insert the
7579 // diamond control-flow pattern. The incoming instruction knows the
7580 // source vreg to test against 0, the destination vreg to set,
7581 // the condition code register to branch on, the
7582 // true/false values to select between, and a branch opcode to use.
7587 // BCC (branch to SinkBB if V0 >= 0)
7588 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7589 // SinkBB: V1 = PHI(V2, V3)
7590 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7591 MachineFunction::iterator BBI = BB;
7593 MachineFunction *Fn = BB->getParent();
7594 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7595 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7596 Fn->insert(BBI, RSBBB);
7597 Fn->insert(BBI, SinkBB);
7599 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7600 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7601 bool isThumb2 = Subtarget->isThumb2();
7602 MachineRegisterInfo &MRI = Fn->getRegInfo();
7603 // In Thumb mode S must not be specified if source register is the SP or
7604 // PC and if destination register is the SP, so restrict register class
7605 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7606 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7607 (const TargetRegisterClass*)&ARM::GPRRegClass);
7609 // Transfer the remainder of BB and its successor edges to sinkMBB.
7610 SinkBB->splice(SinkBB->begin(), BB,
7611 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7612 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7614 BB->addSuccessor(RSBBB);
7615 BB->addSuccessor(SinkBB);
7617 // fall through to SinkMBB
7618 RSBBB->addSuccessor(SinkBB);
7620 // insert a cmp at the end of BB
7621 AddDefaultPred(BuildMI(BB, dl,
7622 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7623 .addReg(ABSSrcReg).addImm(0));
7625 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7627 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7628 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7630 // insert rsbri in RSBBB
7631 // Note: BCC and rsbri will be converted into predicated rsbmi
7632 // by if-conversion pass
7633 BuildMI(*RSBBB, RSBBB->begin(), dl,
7634 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7635 .addReg(ABSSrcReg, RegState::Kill)
7636 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7638 // insert PHI in SinkBB,
7639 // reuse ABSDstReg to not change uses of ABS instruction
7640 BuildMI(*SinkBB, SinkBB->begin(), dl,
7641 TII->get(ARM::PHI), ABSDstReg)
7642 .addReg(NewRsbDstReg).addMBB(RSBBB)
7643 .addReg(ABSSrcReg).addMBB(BB);
7645 // remove ABS instruction
7646 MI->eraseFromParent();
7648 // return last added BB
7651 case ARM::COPY_STRUCT_BYVAL_I32:
7653 return EmitStructByval(MI, BB);
7654 case ARM::WIN__CHKSTK:
7655 return EmitLowered__chkstk(MI, BB);
7659 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7660 SDNode *Node) const {
7661 if (!MI->hasPostISelHook()) {
7662 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7663 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7667 const MCInstrDesc *MCID = &MI->getDesc();
7668 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7669 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7670 // operand is still set to noreg. If needed, set the optional operand's
7671 // register to CPSR, and remove the redundant implicit def.
7673 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7675 // Rename pseudo opcodes.
7676 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7678 const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
7679 getTargetMachine().getSubtargetImpl()->getInstrInfo());
7680 MCID = &TII->get(NewOpc);
7682 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7683 "converted opcode should be the same except for cc_out");
7687 // Add the optional cc_out operand
7688 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7690 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7692 // Any ARM instruction that sets the 's' bit should specify an optional
7693 // "cc_out" operand in the last operand position.
7694 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7695 assert(!NewOpc && "Optional cc_out operand required");
7698 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7699 // since we already have an optional CPSR def.
7700 bool definesCPSR = false;
7701 bool deadCPSR = false;
7702 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7704 const MachineOperand &MO = MI->getOperand(i);
7705 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7709 MI->RemoveOperand(i);
7714 assert(!NewOpc && "Optional cc_out operand required");
7717 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7719 assert(!MI->getOperand(ccOutIdx).getReg() &&
7720 "expect uninitialized optional cc_out operand");
7724 // If this instruction was defined with an optional CPSR def and its dag node
7725 // had a live implicit CPSR def, then activate the optional CPSR def.
7726 MachineOperand &MO = MI->getOperand(ccOutIdx);
7727 MO.setReg(ARM::CPSR);
7731 //===----------------------------------------------------------------------===//
7732 // ARM Optimization Hooks
7733 //===----------------------------------------------------------------------===//
7735 // Helper function that checks if N is a null or all ones constant.
7736 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7737 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7740 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7743 // Return true if N is conditionally 0 or all ones.
7744 // Detects these expressions where cc is an i1 value:
7746 // (select cc 0, y) [AllOnes=0]
7747 // (select cc y, 0) [AllOnes=0]
7748 // (zext cc) [AllOnes=0]
7749 // (sext cc) [AllOnes=0/1]
7750 // (select cc -1, y) [AllOnes=1]
7751 // (select cc y, -1) [AllOnes=1]
7753 // Invert is set when N is the null/all ones constant when CC is false.
7754 // OtherOp is set to the alternative value of N.
7755 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7756 SDValue &CC, bool &Invert,
7758 SelectionDAG &DAG) {
7759 switch (N->getOpcode()) {
7760 default: return false;
7762 CC = N->getOperand(0);
7763 SDValue N1 = N->getOperand(1);
7764 SDValue N2 = N->getOperand(2);
7765 if (isZeroOrAllOnes(N1, AllOnes)) {
7770 if (isZeroOrAllOnes(N2, AllOnes)) {
7777 case ISD::ZERO_EXTEND:
7778 // (zext cc) can never be the all ones value.
7782 case ISD::SIGN_EXTEND: {
7783 EVT VT = N->getValueType(0);
7784 CC = N->getOperand(0);
7785 if (CC.getValueType() != MVT::i1)
7789 // When looking for an AllOnes constant, N is an sext, and the 'other'
7791 OtherOp = DAG.getConstant(0, VT);
7792 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7793 // When looking for a 0 constant, N can be zext or sext.
7794 OtherOp = DAG.getConstant(1, VT);
7796 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7802 // Combine a constant select operand into its use:
7804 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7805 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7806 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7807 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7808 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7810 // The transform is rejected if the select doesn't have a constant operand that
7811 // is null, or all ones when AllOnes is set.
7813 // Also recognize sext/zext from i1:
7815 // (add (zext cc), x) -> (select cc (add x, 1), x)
7816 // (add (sext cc), x) -> (select cc (add x, -1), x)
7818 // These transformations eventually create predicated instructions.
7820 // @param N The node to transform.
7821 // @param Slct The N operand that is a select.
7822 // @param OtherOp The other N operand (x above).
7823 // @param DCI Context.
7824 // @param AllOnes Require the select constant to be all ones instead of null.
7825 // @returns The new node, or SDValue() on failure.
7827 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7828 TargetLowering::DAGCombinerInfo &DCI,
7829 bool AllOnes = false) {
7830 SelectionDAG &DAG = DCI.DAG;
7831 EVT VT = N->getValueType(0);
7832 SDValue NonConstantVal;
7835 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7836 NonConstantVal, DAG))
7839 // Slct is now know to be the desired identity constant when CC is true.
7840 SDValue TrueVal = OtherOp;
7841 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7842 OtherOp, NonConstantVal);
7843 // Unless SwapSelectOps says CC should be false.
7845 std::swap(TrueVal, FalseVal);
7847 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7848 CCOp, TrueVal, FalseVal);
7851 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7853 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7854 TargetLowering::DAGCombinerInfo &DCI) {
7855 SDValue N0 = N->getOperand(0);
7856 SDValue N1 = N->getOperand(1);
7857 if (N0.getNode()->hasOneUse()) {
7858 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7859 if (Result.getNode())
7862 if (N1.getNode()->hasOneUse()) {
7863 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7864 if (Result.getNode())
7870 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7871 // (only after legalization).
7872 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7873 TargetLowering::DAGCombinerInfo &DCI,
7874 const ARMSubtarget *Subtarget) {
7876 // Only perform optimization if after legalize, and if NEON is available. We
7877 // also expected both operands to be BUILD_VECTORs.
7878 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7879 || N0.getOpcode() != ISD::BUILD_VECTOR
7880 || N1.getOpcode() != ISD::BUILD_VECTOR)
7883 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7884 EVT VT = N->getValueType(0);
7885 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7888 // Check that the vector operands are of the right form.
7889 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7890 // operands, where N is the size of the formed vector.
7891 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7892 // index such that we have a pair wise add pattern.
7894 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7895 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7897 SDValue Vec = N0->getOperand(0)->getOperand(0);
7898 SDNode *V = Vec.getNode();
7899 unsigned nextIndex = 0;
7901 // For each operands to the ADD which are BUILD_VECTORs,
7902 // check to see if each of their operands are an EXTRACT_VECTOR with
7903 // the same vector and appropriate index.
7904 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7905 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7906 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7908 SDValue ExtVec0 = N0->getOperand(i);
7909 SDValue ExtVec1 = N1->getOperand(i);
7911 // First operand is the vector, verify its the same.
7912 if (V != ExtVec0->getOperand(0).getNode() ||
7913 V != ExtVec1->getOperand(0).getNode())
7916 // Second is the constant, verify its correct.
7917 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7918 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7920 // For the constant, we want to see all the even or all the odd.
7921 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7922 || C1->getZExtValue() != nextIndex+1)
7931 // Create VPADDL node.
7932 SelectionDAG &DAG = DCI.DAG;
7933 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7935 // Build operand list.
7936 SmallVector<SDValue, 8> Ops;
7937 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7938 TLI.getPointerTy()));
7940 // Input is the vector.
7943 // Get widened type and narrowed type.
7945 unsigned numElem = VT.getVectorNumElements();
7947 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7948 switch (inputLaneType.getSimpleVT().SimpleTy) {
7949 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7950 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7951 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7953 llvm_unreachable("Invalid vector element type for padd optimization.");
7956 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7957 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7958 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7961 static SDValue findMUL_LOHI(SDValue V) {
7962 if (V->getOpcode() == ISD::UMUL_LOHI ||
7963 V->getOpcode() == ISD::SMUL_LOHI)
7968 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7969 TargetLowering::DAGCombinerInfo &DCI,
7970 const ARMSubtarget *Subtarget) {
7972 if (Subtarget->isThumb1Only()) return SDValue();
7974 // Only perform the checks after legalize when the pattern is available.
7975 if (DCI.isBeforeLegalize()) return SDValue();
7977 // Look for multiply add opportunities.
7978 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7979 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7980 // a glue link from the first add to the second add.
7981 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7982 // a S/UMLAL instruction.
7985 // \ / \ [no multiline comment]
7991 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7992 SDValue AddcOp0 = AddcNode->getOperand(0);
7993 SDValue AddcOp1 = AddcNode->getOperand(1);
7995 // Check if the two operands are from the same mul_lohi node.
7996 if (AddcOp0.getNode() == AddcOp1.getNode())
7999 assert(AddcNode->getNumValues() == 2 &&
8000 AddcNode->getValueType(0) == MVT::i32 &&
8001 "Expect ADDC with two result values. First: i32");
8003 // Check that we have a glued ADDC node.
8004 if (AddcNode->getValueType(1) != MVT::Glue)
8007 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8008 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8009 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8010 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8011 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8014 // Look for the glued ADDE.
8015 SDNode* AddeNode = AddcNode->getGluedUser();
8019 // Make sure it is really an ADDE.
8020 if (AddeNode->getOpcode() != ISD::ADDE)
8023 assert(AddeNode->getNumOperands() == 3 &&
8024 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8025 "ADDE node has the wrong inputs");
8027 // Check for the triangle shape.
8028 SDValue AddeOp0 = AddeNode->getOperand(0);
8029 SDValue AddeOp1 = AddeNode->getOperand(1);
8031 // Make sure that the ADDE operands are not coming from the same node.
8032 if (AddeOp0.getNode() == AddeOp1.getNode())
8035 // Find the MUL_LOHI node walking up ADDE's operands.
8036 bool IsLeftOperandMUL = false;
8037 SDValue MULOp = findMUL_LOHI(AddeOp0);
8038 if (MULOp == SDValue())
8039 MULOp = findMUL_LOHI(AddeOp1);
8041 IsLeftOperandMUL = true;
8042 if (MULOp == SDValue())
8045 // Figure out the right opcode.
8046 unsigned Opc = MULOp->getOpcode();
8047 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8049 // Figure out the high and low input values to the MLAL node.
8050 SDValue* HiMul = &MULOp;
8051 SDValue* HiAdd = nullptr;
8052 SDValue* LoMul = nullptr;
8053 SDValue* LowAdd = nullptr;
8055 if (IsLeftOperandMUL)
8061 if (AddcOp0->getOpcode() == Opc) {
8065 if (AddcOp1->getOpcode() == Opc) {
8073 if (LoMul->getNode() != HiMul->getNode())
8076 // Create the merged node.
8077 SelectionDAG &DAG = DCI.DAG;
8079 // Build operand list.
8080 SmallVector<SDValue, 8> Ops;
8081 Ops.push_back(LoMul->getOperand(0));
8082 Ops.push_back(LoMul->getOperand(1));
8083 Ops.push_back(*LowAdd);
8084 Ops.push_back(*HiAdd);
8086 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8087 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8089 // Replace the ADDs' nodes uses by the MLA node's values.
8090 SDValue HiMLALResult(MLALNode.getNode(), 1);
8091 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8093 SDValue LoMLALResult(MLALNode.getNode(), 0);
8094 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8096 // Return original node to notify the driver to stop replacing.
8097 SDValue resNode(AddcNode, 0);
8101 /// PerformADDCCombine - Target-specific dag combine transform from
8102 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8103 static SDValue PerformADDCCombine(SDNode *N,
8104 TargetLowering::DAGCombinerInfo &DCI,
8105 const ARMSubtarget *Subtarget) {
8107 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8111 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8112 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8113 /// called with the default operands, and if that fails, with commuted
8115 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8116 TargetLowering::DAGCombinerInfo &DCI,
8117 const ARMSubtarget *Subtarget){
8119 // Attempt to create vpaddl for this add.
8120 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8121 if (Result.getNode())
8124 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8125 if (N0.getNode()->hasOneUse()) {
8126 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8127 if (Result.getNode()) return Result;
8132 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8134 static SDValue PerformADDCombine(SDNode *N,
8135 TargetLowering::DAGCombinerInfo &DCI,
8136 const ARMSubtarget *Subtarget) {
8137 SDValue N0 = N->getOperand(0);
8138 SDValue N1 = N->getOperand(1);
8140 // First try with the default operand order.
8141 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8142 if (Result.getNode())
8145 // If that didn't work, try again with the operands commuted.
8146 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8149 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8151 static SDValue PerformSUBCombine(SDNode *N,
8152 TargetLowering::DAGCombinerInfo &DCI) {
8153 SDValue N0 = N->getOperand(0);
8154 SDValue N1 = N->getOperand(1);
8156 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8157 if (N1.getNode()->hasOneUse()) {
8158 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8159 if (Result.getNode()) return Result;
8165 /// PerformVMULCombine
8166 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8167 /// special multiplier accumulator forwarding.
8173 // However, for (A + B) * (A + B),
8180 static SDValue PerformVMULCombine(SDNode *N,
8181 TargetLowering::DAGCombinerInfo &DCI,
8182 const ARMSubtarget *Subtarget) {
8183 if (!Subtarget->hasVMLxForwarding())
8186 SelectionDAG &DAG = DCI.DAG;
8187 SDValue N0 = N->getOperand(0);
8188 SDValue N1 = N->getOperand(1);
8189 unsigned Opcode = N0.getOpcode();
8190 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8191 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8192 Opcode = N1.getOpcode();
8193 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8194 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8202 EVT VT = N->getValueType(0);
8204 SDValue N00 = N0->getOperand(0);
8205 SDValue N01 = N0->getOperand(1);
8206 return DAG.getNode(Opcode, DL, VT,
8207 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8208 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8211 static SDValue PerformMULCombine(SDNode *N,
8212 TargetLowering::DAGCombinerInfo &DCI,
8213 const ARMSubtarget *Subtarget) {
8214 SelectionDAG &DAG = DCI.DAG;
8216 if (Subtarget->isThumb1Only())
8219 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8222 EVT VT = N->getValueType(0);
8223 if (VT.is64BitVector() || VT.is128BitVector())
8224 return PerformVMULCombine(N, DCI, Subtarget);
8228 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8232 int64_t MulAmt = C->getSExtValue();
8233 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8235 ShiftAmt = ShiftAmt & (32 - 1);
8236 SDValue V = N->getOperand(0);
8240 MulAmt >>= ShiftAmt;
8243 if (isPowerOf2_32(MulAmt - 1)) {
8244 // (mul x, 2^N + 1) => (add (shl x, N), x)
8245 Res = DAG.getNode(ISD::ADD, DL, VT,
8247 DAG.getNode(ISD::SHL, DL, VT,
8249 DAG.getConstant(Log2_32(MulAmt - 1),
8251 } else if (isPowerOf2_32(MulAmt + 1)) {
8252 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8253 Res = DAG.getNode(ISD::SUB, DL, VT,
8254 DAG.getNode(ISD::SHL, DL, VT,
8256 DAG.getConstant(Log2_32(MulAmt + 1),
8262 uint64_t MulAmtAbs = -MulAmt;
8263 if (isPowerOf2_32(MulAmtAbs + 1)) {
8264 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8265 Res = DAG.getNode(ISD::SUB, DL, VT,
8267 DAG.getNode(ISD::SHL, DL, VT,
8269 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8271 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8272 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8273 Res = DAG.getNode(ISD::ADD, DL, VT,
8275 DAG.getNode(ISD::SHL, DL, VT,
8277 DAG.getConstant(Log2_32(MulAmtAbs-1),
8279 Res = DAG.getNode(ISD::SUB, DL, VT,
8280 DAG.getConstant(0, MVT::i32),Res);
8287 Res = DAG.getNode(ISD::SHL, DL, VT,
8288 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8290 // Do not add new nodes to DAG combiner worklist.
8291 DCI.CombineTo(N, Res, false);
8295 static SDValue PerformANDCombine(SDNode *N,
8296 TargetLowering::DAGCombinerInfo &DCI,
8297 const ARMSubtarget *Subtarget) {
8299 // Attempt to use immediate-form VBIC
8300 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8302 EVT VT = N->getValueType(0);
8303 SelectionDAG &DAG = DCI.DAG;
8305 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8308 APInt SplatBits, SplatUndef;
8309 unsigned SplatBitSize;
8312 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8313 if (SplatBitSize <= 64) {
8315 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8316 SplatUndef.getZExtValue(), SplatBitSize,
8317 DAG, VbicVT, VT.is128BitVector(),
8319 if (Val.getNode()) {
8321 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8322 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8323 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8328 if (!Subtarget->isThumb1Only()) {
8329 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8330 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8331 if (Result.getNode())
8338 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8339 static SDValue PerformORCombine(SDNode *N,
8340 TargetLowering::DAGCombinerInfo &DCI,
8341 const ARMSubtarget *Subtarget) {
8342 // Attempt to use immediate-form VORR
8343 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8345 EVT VT = N->getValueType(0);
8346 SelectionDAG &DAG = DCI.DAG;
8348 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8351 APInt SplatBits, SplatUndef;
8352 unsigned SplatBitSize;
8354 if (BVN && Subtarget->hasNEON() &&
8355 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8356 if (SplatBitSize <= 64) {
8358 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8359 SplatUndef.getZExtValue(), SplatBitSize,
8360 DAG, VorrVT, VT.is128BitVector(),
8362 if (Val.getNode()) {
8364 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8365 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8366 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8371 if (!Subtarget->isThumb1Only()) {
8372 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8373 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8374 if (Result.getNode())
8378 // The code below optimizes (or (and X, Y), Z).
8379 // The AND operand needs to have a single user to make these optimizations
8381 SDValue N0 = N->getOperand(0);
8382 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8384 SDValue N1 = N->getOperand(1);
8386 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8387 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8388 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8390 unsigned SplatBitSize;
8393 APInt SplatBits0, SplatBits1;
8394 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8395 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8396 // Ensure that the second operand of both ands are constants
8397 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8398 HasAnyUndefs) && !HasAnyUndefs) {
8399 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8400 HasAnyUndefs) && !HasAnyUndefs) {
8401 // Ensure that the bit width of the constants are the same and that
8402 // the splat arguments are logical inverses as per the pattern we
8403 // are trying to simplify.
8404 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8405 SplatBits0 == ~SplatBits1) {
8406 // Canonicalize the vector type to make instruction selection
8408 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8409 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8413 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8419 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8422 // BFI is only available on V6T2+
8423 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8427 // 1) or (and A, mask), val => ARMbfi A, val, mask
8428 // iff (val & mask) == val
8430 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8431 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8432 // && mask == ~mask2
8433 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8434 // && ~mask == mask2
8435 // (i.e., copy a bitfield value into another bitfield of the same width)
8440 SDValue N00 = N0.getOperand(0);
8442 // The value and the mask need to be constants so we can verify this is
8443 // actually a bitfield set. If the mask is 0xffff, we can do better
8444 // via a movt instruction, so don't use BFI in that case.
8445 SDValue MaskOp = N0.getOperand(1);
8446 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8449 unsigned Mask = MaskC->getZExtValue();
8453 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8454 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8456 unsigned Val = N1C->getZExtValue();
8457 if ((Val & ~Mask) != Val)
8460 if (ARM::isBitFieldInvertedMask(Mask)) {
8461 Val >>= countTrailingZeros(~Mask);
8463 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8464 DAG.getConstant(Val, MVT::i32),
8465 DAG.getConstant(Mask, MVT::i32));
8467 // Do not add new nodes to DAG combiner worklist.
8468 DCI.CombineTo(N, Res, false);
8471 } else if (N1.getOpcode() == ISD::AND) {
8472 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8473 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8476 unsigned Mask2 = N11C->getZExtValue();
8478 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8480 if (ARM::isBitFieldInvertedMask(Mask) &&
8482 // The pack halfword instruction works better for masks that fit it,
8483 // so use that when it's available.
8484 if (Subtarget->hasT2ExtractPack() &&
8485 (Mask == 0xffff || Mask == 0xffff0000))
8488 unsigned amt = countTrailingZeros(Mask2);
8489 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8490 DAG.getConstant(amt, MVT::i32));
8491 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8492 DAG.getConstant(Mask, MVT::i32));
8493 // Do not add new nodes to DAG combiner worklist.
8494 DCI.CombineTo(N, Res, false);
8496 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8498 // The pack halfword instruction works better for masks that fit it,
8499 // so use that when it's available.
8500 if (Subtarget->hasT2ExtractPack() &&
8501 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8504 unsigned lsb = countTrailingZeros(Mask);
8505 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8506 DAG.getConstant(lsb, MVT::i32));
8507 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8508 DAG.getConstant(Mask2, MVT::i32));
8509 // Do not add new nodes to DAG combiner worklist.
8510 DCI.CombineTo(N, Res, false);
8515 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8516 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8517 ARM::isBitFieldInvertedMask(~Mask)) {
8518 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8519 // where lsb(mask) == #shamt and masked bits of B are known zero.
8520 SDValue ShAmt = N00.getOperand(1);
8521 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8522 unsigned LSB = countTrailingZeros(Mask);
8526 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8527 DAG.getConstant(~Mask, MVT::i32));
8529 // Do not add new nodes to DAG combiner worklist.
8530 DCI.CombineTo(N, Res, false);
8536 static SDValue PerformXORCombine(SDNode *N,
8537 TargetLowering::DAGCombinerInfo &DCI,
8538 const ARMSubtarget *Subtarget) {
8539 EVT VT = N->getValueType(0);
8540 SelectionDAG &DAG = DCI.DAG;
8542 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8545 if (!Subtarget->isThumb1Only()) {
8546 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8547 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8548 if (Result.getNode())
8555 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8556 /// the bits being cleared by the AND are not demanded by the BFI.
8557 static SDValue PerformBFICombine(SDNode *N,
8558 TargetLowering::DAGCombinerInfo &DCI) {
8559 SDValue N1 = N->getOperand(1);
8560 if (N1.getOpcode() == ISD::AND) {
8561 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8564 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8565 unsigned LSB = countTrailingZeros(~InvMask);
8566 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8567 unsigned Mask = (1 << Width)-1;
8568 unsigned Mask2 = N11C->getZExtValue();
8569 if ((Mask & (~Mask2)) == 0)
8570 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8571 N->getOperand(0), N1.getOperand(0),
8577 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8578 /// ARMISD::VMOVRRD.
8579 static SDValue PerformVMOVRRDCombine(SDNode *N,
8580 TargetLowering::DAGCombinerInfo &DCI,
8581 const ARMSubtarget *Subtarget) {
8582 // vmovrrd(vmovdrr x, y) -> x,y
8583 SDValue InDouble = N->getOperand(0);
8584 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8585 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8587 // vmovrrd(load f64) -> (load i32), (load i32)
8588 SDNode *InNode = InDouble.getNode();
8589 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8590 InNode->getValueType(0) == MVT::f64 &&
8591 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8592 !cast<LoadSDNode>(InNode)->isVolatile()) {
8593 // TODO: Should this be done for non-FrameIndex operands?
8594 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8596 SelectionDAG &DAG = DCI.DAG;
8598 SDValue BasePtr = LD->getBasePtr();
8599 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8600 LD->getPointerInfo(), LD->isVolatile(),
8601 LD->isNonTemporal(), LD->isInvariant(),
8602 LD->getAlignment());
8604 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8605 DAG.getConstant(4, MVT::i32));
8606 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8607 LD->getPointerInfo(), LD->isVolatile(),
8608 LD->isNonTemporal(), LD->isInvariant(),
8609 std::min(4U, LD->getAlignment() / 2));
8611 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8612 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8613 std::swap (NewLD1, NewLD2);
8614 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8621 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8622 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8623 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8624 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8625 SDValue Op0 = N->getOperand(0);
8626 SDValue Op1 = N->getOperand(1);
8627 if (Op0.getOpcode() == ISD::BITCAST)
8628 Op0 = Op0.getOperand(0);
8629 if (Op1.getOpcode() == ISD::BITCAST)
8630 Op1 = Op1.getOperand(0);
8631 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8632 Op0.getNode() == Op1.getNode() &&
8633 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8634 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8635 N->getValueType(0), Op0.getOperand(0));
8639 /// PerformSTORECombine - Target-specific dag combine xforms for
8641 static SDValue PerformSTORECombine(SDNode *N,
8642 TargetLowering::DAGCombinerInfo &DCI) {
8643 StoreSDNode *St = cast<StoreSDNode>(N);
8644 if (St->isVolatile())
8647 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8648 // pack all of the elements in one place. Next, store to memory in fewer
8650 SDValue StVal = St->getValue();
8651 EVT VT = StVal.getValueType();
8652 if (St->isTruncatingStore() && VT.isVector()) {
8653 SelectionDAG &DAG = DCI.DAG;
8654 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8655 EVT StVT = St->getMemoryVT();
8656 unsigned NumElems = VT.getVectorNumElements();
8657 assert(StVT != VT && "Cannot truncate to the same type");
8658 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8659 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8661 // From, To sizes and ElemCount must be pow of two
8662 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8664 // We are going to use the original vector elt for storing.
8665 // Accumulated smaller vector elements must be a multiple of the store size.
8666 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8668 unsigned SizeRatio = FromEltSz / ToEltSz;
8669 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8671 // Create a type on which we perform the shuffle.
8672 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8673 NumElems*SizeRatio);
8674 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8677 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8678 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8679 for (unsigned i = 0; i < NumElems; ++i)
8680 ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8682 // Can't shuffle using an illegal type.
8683 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8685 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8686 DAG.getUNDEF(WideVec.getValueType()),
8688 // At this point all of the data is stored at the bottom of the
8689 // register. We now need to save it to mem.
8691 // Find the largest store unit
8692 MVT StoreType = MVT::i8;
8693 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8694 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8695 MVT Tp = (MVT::SimpleValueType)tp;
8696 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8699 // Didn't find a legal store type.
8700 if (!TLI.isTypeLegal(StoreType))
8703 // Bitcast the original vector into a vector of store-size units
8704 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8705 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8706 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8707 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8708 SmallVector<SDValue, 8> Chains;
8709 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8710 TLI.getPointerTy());
8711 SDValue BasePtr = St->getBasePtr();
8713 // Perform one or more big stores into memory.
8714 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8715 for (unsigned I = 0; I < E; I++) {
8716 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8717 StoreType, ShuffWide,
8718 DAG.getIntPtrConstant(I));
8719 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8720 St->getPointerInfo(), St->isVolatile(),
8721 St->isNonTemporal(), St->getAlignment());
8722 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8724 Chains.push_back(Ch);
8726 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8729 if (!ISD::isNormalStore(St))
8732 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8733 // ARM stores of arguments in the same cache line.
8734 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8735 StVal.getNode()->hasOneUse()) {
8736 SelectionDAG &DAG = DCI.DAG;
8737 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8739 SDValue BasePtr = St->getBasePtr();
8740 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8741 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8742 BasePtr, St->getPointerInfo(), St->isVolatile(),
8743 St->isNonTemporal(), St->getAlignment());
8745 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8746 DAG.getConstant(4, MVT::i32));
8747 return DAG.getStore(NewST1.getValue(0), DL,
8748 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8749 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8750 St->isNonTemporal(),
8751 std::min(4U, St->getAlignment() / 2));
8754 if (StVal.getValueType() != MVT::i64 ||
8755 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8758 // Bitcast an i64 store extracted from a vector to f64.
8759 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8760 SelectionDAG &DAG = DCI.DAG;
8762 SDValue IntVec = StVal.getOperand(0);
8763 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8764 IntVec.getValueType().getVectorNumElements());
8765 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8766 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8767 Vec, StVal.getOperand(1));
8769 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8770 // Make the DAGCombiner fold the bitcasts.
8771 DCI.AddToWorklist(Vec.getNode());
8772 DCI.AddToWorklist(ExtElt.getNode());
8773 DCI.AddToWorklist(V.getNode());
8774 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8775 St->getPointerInfo(), St->isVolatile(),
8776 St->isNonTemporal(), St->getAlignment(),
8780 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8781 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8782 /// i64 vector to have f64 elements, since the value can then be loaded
8783 /// directly into a VFP register.
8784 static bool hasNormalLoadOperand(SDNode *N) {
8785 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8786 for (unsigned i = 0; i < NumElts; ++i) {
8787 SDNode *Elt = N->getOperand(i).getNode();
8788 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8794 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8795 /// ISD::BUILD_VECTOR.
8796 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8797 TargetLowering::DAGCombinerInfo &DCI,
8798 const ARMSubtarget *Subtarget) {
8799 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8800 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8801 // into a pair of GPRs, which is fine when the value is used as a scalar,
8802 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8803 SelectionDAG &DAG = DCI.DAG;
8804 if (N->getNumOperands() == 2) {
8805 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8810 // Load i64 elements as f64 values so that type legalization does not split
8811 // them up into i32 values.
8812 EVT VT = N->getValueType(0);
8813 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8816 SmallVector<SDValue, 8> Ops;
8817 unsigned NumElts = VT.getVectorNumElements();
8818 for (unsigned i = 0; i < NumElts; ++i) {
8819 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8821 // Make the DAGCombiner fold the bitcast.
8822 DCI.AddToWorklist(V.getNode());
8824 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8825 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8826 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8829 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8831 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8832 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8833 // At that time, we may have inserted bitcasts from integer to float.
8834 // If these bitcasts have survived DAGCombine, change the lowering of this
8835 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8836 // force to use floating point types.
8838 // Make sure we can change the type of the vector.
8839 // This is possible iff:
8840 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8841 // 1.1. Vector is used only once.
8842 // 1.2. Use is a bit convert to an integer type.
8843 // 2. The size of its operands are 32-bits (64-bits are not legal).
8844 EVT VT = N->getValueType(0);
8845 EVT EltVT = VT.getVectorElementType();
8847 // Check 1.1. and 2.
8848 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8851 // By construction, the input type must be float.
8852 assert(EltVT == MVT::f32 && "Unexpected type!");
8855 SDNode *Use = *N->use_begin();
8856 if (Use->getOpcode() != ISD::BITCAST ||
8857 Use->getValueType(0).isFloatingPoint())
8860 // Check profitability.
8861 // Model is, if more than half of the relevant operands are bitcast from
8862 // i32, turn the build_vector into a sequence of insert_vector_elt.
8863 // Relevant operands are everything that is not statically
8864 // (i.e., at compile time) bitcasted.
8865 unsigned NumOfBitCastedElts = 0;
8866 unsigned NumElts = VT.getVectorNumElements();
8867 unsigned NumOfRelevantElts = NumElts;
8868 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8869 SDValue Elt = N->getOperand(Idx);
8870 if (Elt->getOpcode() == ISD::BITCAST) {
8871 // Assume only bit cast to i32 will go away.
8872 if (Elt->getOperand(0).getValueType() == MVT::i32)
8873 ++NumOfBitCastedElts;
8874 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8875 // Constants are statically casted, thus do not count them as
8876 // relevant operands.
8877 --NumOfRelevantElts;
8880 // Check if more than half of the elements require a non-free bitcast.
8881 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8884 SelectionDAG &DAG = DCI.DAG;
8885 // Create the new vector type.
8886 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8887 // Check if the type is legal.
8888 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8889 if (!TLI.isTypeLegal(VecVT))
8893 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8894 // => BITCAST INSERT_VECTOR_ELT
8895 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8897 SDValue Vec = DAG.getUNDEF(VecVT);
8899 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8900 SDValue V = N->getOperand(Idx);
8901 if (V.getOpcode() == ISD::UNDEF)
8903 if (V.getOpcode() == ISD::BITCAST &&
8904 V->getOperand(0).getValueType() == MVT::i32)
8905 // Fold obvious case.
8906 V = V.getOperand(0);
8908 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8909 // Make the DAGCombiner fold the bitcasts.
8910 DCI.AddToWorklist(V.getNode());
8912 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8913 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8915 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8916 // Make the DAGCombiner fold the bitcasts.
8917 DCI.AddToWorklist(Vec.getNode());
8921 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8922 /// ISD::INSERT_VECTOR_ELT.
8923 static SDValue PerformInsertEltCombine(SDNode *N,
8924 TargetLowering::DAGCombinerInfo &DCI) {
8925 // Bitcast an i64 load inserted into a vector to f64.
8926 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8927 EVT VT = N->getValueType(0);
8928 SDNode *Elt = N->getOperand(1).getNode();
8929 if (VT.getVectorElementType() != MVT::i64 ||
8930 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8933 SelectionDAG &DAG = DCI.DAG;
8935 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8936 VT.getVectorNumElements());
8937 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8938 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8939 // Make the DAGCombiner fold the bitcasts.
8940 DCI.AddToWorklist(Vec.getNode());
8941 DCI.AddToWorklist(V.getNode());
8942 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8943 Vec, V, N->getOperand(2));
8944 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8947 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8948 /// ISD::VECTOR_SHUFFLE.
8949 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8950 // The LLVM shufflevector instruction does not require the shuffle mask
8951 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8952 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8953 // operands do not match the mask length, they are extended by concatenating
8954 // them with undef vectors. That is probably the right thing for other
8955 // targets, but for NEON it is better to concatenate two double-register
8956 // size vector operands into a single quad-register size vector. Do that
8957 // transformation here:
8958 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8959 // shuffle(concat(v1, v2), undef)
8960 SDValue Op0 = N->getOperand(0);
8961 SDValue Op1 = N->getOperand(1);
8962 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8963 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8964 Op0.getNumOperands() != 2 ||
8965 Op1.getNumOperands() != 2)
8967 SDValue Concat0Op1 = Op0.getOperand(1);
8968 SDValue Concat1Op1 = Op1.getOperand(1);
8969 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8970 Concat1Op1.getOpcode() != ISD::UNDEF)
8972 // Skip the transformation if any of the types are illegal.
8973 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8974 EVT VT = N->getValueType(0);
8975 if (!TLI.isTypeLegal(VT) ||
8976 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8977 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8980 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8981 Op0.getOperand(0), Op1.getOperand(0));
8982 // Translate the shuffle mask.
8983 SmallVector<int, 16> NewMask;
8984 unsigned NumElts = VT.getVectorNumElements();
8985 unsigned HalfElts = NumElts/2;
8986 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8987 for (unsigned n = 0; n < NumElts; ++n) {
8988 int MaskElt = SVN->getMaskElt(n);
8990 if (MaskElt < (int)HalfElts)
8992 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8993 NewElt = HalfElts + MaskElt - NumElts;
8994 NewMask.push_back(NewElt);
8996 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8997 DAG.getUNDEF(VT), NewMask.data());
9000 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9001 /// NEON load/store intrinsics to merge base address updates.
9002 static SDValue CombineBaseUpdate(SDNode *N,
9003 TargetLowering::DAGCombinerInfo &DCI) {
9004 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9007 SelectionDAG &DAG = DCI.DAG;
9008 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9009 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9010 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9011 SDValue Addr = N->getOperand(AddrOpIdx);
9013 // Search for a use of the address operand that is an increment.
9014 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9015 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9017 if (User->getOpcode() != ISD::ADD ||
9018 UI.getUse().getResNo() != Addr.getResNo())
9021 // Check that the add is independent of the load/store. Otherwise, folding
9022 // it would create a cycle.
9023 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9026 // Find the new opcode for the updating load/store.
9028 bool isLaneOp = false;
9029 unsigned NewOpc = 0;
9030 unsigned NumVecs = 0;
9032 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9034 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9035 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9037 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9039 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9041 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9043 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9044 NumVecs = 2; isLaneOp = true; break;
9045 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9046 NumVecs = 3; isLaneOp = true; break;
9047 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9048 NumVecs = 4; isLaneOp = true; break;
9049 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9050 NumVecs = 1; isLoad = false; break;
9051 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9052 NumVecs = 2; isLoad = false; break;
9053 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9054 NumVecs = 3; isLoad = false; break;
9055 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9056 NumVecs = 4; isLoad = false; break;
9057 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9058 NumVecs = 2; isLoad = false; isLaneOp = true; break;
9059 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9060 NumVecs = 3; isLoad = false; isLaneOp = true; break;
9061 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9062 NumVecs = 4; isLoad = false; isLaneOp = true; break;
9066 switch (N->getOpcode()) {
9067 default: llvm_unreachable("unexpected opcode for Neon base update");
9068 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9069 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9070 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9074 // Find the size of memory referenced by the load/store.
9077 VecTy = N->getValueType(0);
9079 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9080 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9082 NumBytes /= VecTy.getVectorNumElements();
9084 // If the increment is a constant, it must match the memory ref size.
9085 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9086 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9087 uint64_t IncVal = CInc->getZExtValue();
9088 if (IncVal != NumBytes)
9090 } else if (NumBytes >= 3 * 16) {
9091 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9092 // separate instructions that make it harder to use a non-constant update.
9096 // Create the new updating load/store node.
9098 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9100 for (n = 0; n < NumResultVecs; ++n)
9102 Tys[n++] = MVT::i32;
9103 Tys[n] = MVT::Other;
9104 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9105 SmallVector<SDValue, 8> Ops;
9106 Ops.push_back(N->getOperand(0)); // incoming chain
9107 Ops.push_back(N->getOperand(AddrOpIdx));
9109 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9110 Ops.push_back(N->getOperand(i));
9112 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9113 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9114 Ops, MemInt->getMemoryVT(),
9115 MemInt->getMemOperand());
9118 std::vector<SDValue> NewResults;
9119 for (unsigned i = 0; i < NumResultVecs; ++i) {
9120 NewResults.push_back(SDValue(UpdN.getNode(), i));
9122 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9123 DCI.CombineTo(N, NewResults);
9124 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9131 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9132 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9133 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9135 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9136 SelectionDAG &DAG = DCI.DAG;
9137 EVT VT = N->getValueType(0);
9138 // vldN-dup instructions only support 64-bit vectors for N > 1.
9139 if (!VT.is64BitVector())
9142 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9143 SDNode *VLD = N->getOperand(0).getNode();
9144 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9146 unsigned NumVecs = 0;
9147 unsigned NewOpc = 0;
9148 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9149 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9151 NewOpc = ARMISD::VLD2DUP;
9152 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9154 NewOpc = ARMISD::VLD3DUP;
9155 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9157 NewOpc = ARMISD::VLD4DUP;
9162 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9163 // numbers match the load.
9164 unsigned VLDLaneNo =
9165 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9166 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9168 // Ignore uses of the chain result.
9169 if (UI.getUse().getResNo() == NumVecs)
9172 if (User->getOpcode() != ARMISD::VDUPLANE ||
9173 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9177 // Create the vldN-dup node.
9180 for (n = 0; n < NumVecs; ++n)
9182 Tys[n] = MVT::Other;
9183 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9184 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9185 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9186 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9187 Ops, VLDMemInt->getMemoryVT(),
9188 VLDMemInt->getMemOperand());
9191 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9193 unsigned ResNo = UI.getUse().getResNo();
9194 // Ignore uses of the chain result.
9195 if (ResNo == NumVecs)
9198 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9201 // Now the vldN-lane intrinsic is dead except for its chain result.
9202 // Update uses of the chain.
9203 std::vector<SDValue> VLDDupResults;
9204 for (unsigned n = 0; n < NumVecs; ++n)
9205 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9206 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9207 DCI.CombineTo(VLD, VLDDupResults);
9212 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9213 /// ARMISD::VDUPLANE.
9214 static SDValue PerformVDUPLANECombine(SDNode *N,
9215 TargetLowering::DAGCombinerInfo &DCI) {
9216 SDValue Op = N->getOperand(0);
9218 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9219 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9220 if (CombineVLDDUP(N, DCI))
9221 return SDValue(N, 0);
9223 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9224 // redundant. Ignore bit_converts for now; element sizes are checked below.
9225 while (Op.getOpcode() == ISD::BITCAST)
9226 Op = Op.getOperand(0);
9227 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9230 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9231 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9232 // The canonical VMOV for a zero vector uses a 32-bit element size.
9233 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9235 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9237 EVT VT = N->getValueType(0);
9238 if (EltSize > VT.getVectorElementType().getSizeInBits())
9241 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9244 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9245 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9246 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9250 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9252 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9257 APFloat APF = C->getValueAPF();
9258 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9259 != APFloat::opOK || !isExact)
9262 c0 = (I == 0) ? cN : c0;
9263 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9270 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9271 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9272 /// when the VMUL has a constant operand that is a power of 2.
9274 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9275 /// vmul.f32 d16, d17, d16
9276 /// vcvt.s32.f32 d16, d16
9278 /// vcvt.s32.f32 d16, d16, #3
9279 static SDValue PerformVCVTCombine(SDNode *N,
9280 TargetLowering::DAGCombinerInfo &DCI,
9281 const ARMSubtarget *Subtarget) {
9282 SelectionDAG &DAG = DCI.DAG;
9283 SDValue Op = N->getOperand(0);
9285 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9286 Op.getOpcode() != ISD::FMUL)
9290 SDValue N0 = Op->getOperand(0);
9291 SDValue ConstVec = Op->getOperand(1);
9292 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9294 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9295 !isConstVecPow2(ConstVec, isSigned, C))
9298 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9299 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9300 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9301 // These instructions only exist converting from f32 to i32. We can handle
9302 // smaller integers by generating an extra truncate, but larger ones would
9307 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9308 Intrinsic::arm_neon_vcvtfp2fxu;
9309 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9310 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9311 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9312 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9313 DAG.getConstant(Log2_64(C), MVT::i32));
9315 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9316 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9321 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9322 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9323 /// when the VDIV has a constant operand that is a power of 2.
9325 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9326 /// vcvt.f32.s32 d16, d16
9327 /// vdiv.f32 d16, d17, d16
9329 /// vcvt.f32.s32 d16, d16, #3
9330 static SDValue PerformVDIVCombine(SDNode *N,
9331 TargetLowering::DAGCombinerInfo &DCI,
9332 const ARMSubtarget *Subtarget) {
9333 SelectionDAG &DAG = DCI.DAG;
9334 SDValue Op = N->getOperand(0);
9335 unsigned OpOpcode = Op.getNode()->getOpcode();
9337 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9338 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9342 SDValue ConstVec = N->getOperand(1);
9343 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9345 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9346 !isConstVecPow2(ConstVec, isSigned, C))
9349 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9350 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9351 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9352 // These instructions only exist converting from i32 to f32. We can handle
9353 // smaller integers by generating an extra extend, but larger ones would
9358 SDValue ConvInput = Op.getOperand(0);
9359 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9360 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9361 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9362 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9365 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9366 Intrinsic::arm_neon_vcvtfxu2fp;
9367 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9369 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9370 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9373 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9374 /// operand of a vector shift operation, where all the elements of the
9375 /// build_vector must have the same constant integer value.
9376 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9377 // Ignore bit_converts.
9378 while (Op.getOpcode() == ISD::BITCAST)
9379 Op = Op.getOperand(0);
9380 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9381 APInt SplatBits, SplatUndef;
9382 unsigned SplatBitSize;
9384 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9385 HasAnyUndefs, ElementBits) ||
9386 SplatBitSize > ElementBits)
9388 Cnt = SplatBits.getSExtValue();
9392 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9393 /// operand of a vector shift left operation. That value must be in the range:
9394 /// 0 <= Value < ElementBits for a left shift; or
9395 /// 0 <= Value <= ElementBits for a long left shift.
9396 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9397 assert(VT.isVector() && "vector shift count is not a vector type");
9398 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9399 if (! getVShiftImm(Op, ElementBits, Cnt))
9401 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9404 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9405 /// operand of a vector shift right operation. For a shift opcode, the value
9406 /// is positive, but for an intrinsic the value count must be negative. The
9407 /// absolute value must be in the range:
9408 /// 1 <= |Value| <= ElementBits for a right shift; or
9409 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9410 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9412 assert(VT.isVector() && "vector shift count is not a vector type");
9413 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9414 if (! getVShiftImm(Op, ElementBits, Cnt))
9418 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9421 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9422 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9423 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9426 // Don't do anything for most intrinsics.
9429 // Vector shifts: check for immediate versions and lower them.
9430 // Note: This is done during DAG combining instead of DAG legalizing because
9431 // the build_vectors for 64-bit vector element shift counts are generally
9432 // not legal, and it is hard to see their values after they get legalized to
9433 // loads from a constant pool.
9434 case Intrinsic::arm_neon_vshifts:
9435 case Intrinsic::arm_neon_vshiftu:
9436 case Intrinsic::arm_neon_vrshifts:
9437 case Intrinsic::arm_neon_vrshiftu:
9438 case Intrinsic::arm_neon_vrshiftn:
9439 case Intrinsic::arm_neon_vqshifts:
9440 case Intrinsic::arm_neon_vqshiftu:
9441 case Intrinsic::arm_neon_vqshiftsu:
9442 case Intrinsic::arm_neon_vqshiftns:
9443 case Intrinsic::arm_neon_vqshiftnu:
9444 case Intrinsic::arm_neon_vqshiftnsu:
9445 case Intrinsic::arm_neon_vqrshiftns:
9446 case Intrinsic::arm_neon_vqrshiftnu:
9447 case Intrinsic::arm_neon_vqrshiftnsu: {
9448 EVT VT = N->getOperand(1).getValueType();
9450 unsigned VShiftOpc = 0;
9453 case Intrinsic::arm_neon_vshifts:
9454 case Intrinsic::arm_neon_vshiftu:
9455 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9456 VShiftOpc = ARMISD::VSHL;
9459 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9460 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9461 ARMISD::VSHRs : ARMISD::VSHRu);
9466 case Intrinsic::arm_neon_vrshifts:
9467 case Intrinsic::arm_neon_vrshiftu:
9468 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9472 case Intrinsic::arm_neon_vqshifts:
9473 case Intrinsic::arm_neon_vqshiftu:
9474 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9478 case Intrinsic::arm_neon_vqshiftsu:
9479 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9481 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9483 case Intrinsic::arm_neon_vrshiftn:
9484 case Intrinsic::arm_neon_vqshiftns:
9485 case Intrinsic::arm_neon_vqshiftnu:
9486 case Intrinsic::arm_neon_vqshiftnsu:
9487 case Intrinsic::arm_neon_vqrshiftns:
9488 case Intrinsic::arm_neon_vqrshiftnu:
9489 case Intrinsic::arm_neon_vqrshiftnsu:
9490 // Narrowing shifts require an immediate right shift.
9491 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9493 llvm_unreachable("invalid shift count for narrowing vector shift "
9497 llvm_unreachable("unhandled vector shift");
9501 case Intrinsic::arm_neon_vshifts:
9502 case Intrinsic::arm_neon_vshiftu:
9503 // Opcode already set above.
9505 case Intrinsic::arm_neon_vrshifts:
9506 VShiftOpc = ARMISD::VRSHRs; break;
9507 case Intrinsic::arm_neon_vrshiftu:
9508 VShiftOpc = ARMISD::VRSHRu; break;
9509 case Intrinsic::arm_neon_vrshiftn:
9510 VShiftOpc = ARMISD::VRSHRN; break;
9511 case Intrinsic::arm_neon_vqshifts:
9512 VShiftOpc = ARMISD::VQSHLs; break;
9513 case Intrinsic::arm_neon_vqshiftu:
9514 VShiftOpc = ARMISD::VQSHLu; break;
9515 case Intrinsic::arm_neon_vqshiftsu:
9516 VShiftOpc = ARMISD::VQSHLsu; break;
9517 case Intrinsic::arm_neon_vqshiftns:
9518 VShiftOpc = ARMISD::VQSHRNs; break;
9519 case Intrinsic::arm_neon_vqshiftnu:
9520 VShiftOpc = ARMISD::VQSHRNu; break;
9521 case Intrinsic::arm_neon_vqshiftnsu:
9522 VShiftOpc = ARMISD::VQSHRNsu; break;
9523 case Intrinsic::arm_neon_vqrshiftns:
9524 VShiftOpc = ARMISD::VQRSHRNs; break;
9525 case Intrinsic::arm_neon_vqrshiftnu:
9526 VShiftOpc = ARMISD::VQRSHRNu; break;
9527 case Intrinsic::arm_neon_vqrshiftnsu:
9528 VShiftOpc = ARMISD::VQRSHRNsu; break;
9531 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9532 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9535 case Intrinsic::arm_neon_vshiftins: {
9536 EVT VT = N->getOperand(1).getValueType();
9538 unsigned VShiftOpc = 0;
9540 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9541 VShiftOpc = ARMISD::VSLI;
9542 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9543 VShiftOpc = ARMISD::VSRI;
9545 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9548 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9549 N->getOperand(1), N->getOperand(2),
9550 DAG.getConstant(Cnt, MVT::i32));
9553 case Intrinsic::arm_neon_vqrshifts:
9554 case Intrinsic::arm_neon_vqrshiftu:
9555 // No immediate versions of these to check for.
9562 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9563 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9564 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9565 /// vector element shift counts are generally not legal, and it is hard to see
9566 /// their values after they get legalized to loads from a constant pool.
9567 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9568 const ARMSubtarget *ST) {
9569 EVT VT = N->getValueType(0);
9570 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9571 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9572 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9573 SDValue N1 = N->getOperand(1);
9574 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9575 SDValue N0 = N->getOperand(0);
9576 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9577 DAG.MaskedValueIsZero(N0.getOperand(0),
9578 APInt::getHighBitsSet(32, 16)))
9579 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9583 // Nothing to be done for scalar shifts.
9584 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9585 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9588 assert(ST->hasNEON() && "unexpected vector shift");
9591 switch (N->getOpcode()) {
9592 default: llvm_unreachable("unexpected shift opcode");
9595 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9596 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9597 DAG.getConstant(Cnt, MVT::i32));
9602 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9603 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9604 ARMISD::VSHRs : ARMISD::VSHRu);
9605 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9606 DAG.getConstant(Cnt, MVT::i32));
9612 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9613 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9614 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9615 const ARMSubtarget *ST) {
9616 SDValue N0 = N->getOperand(0);
9618 // Check for sign- and zero-extensions of vector extract operations of 8-
9619 // and 16-bit vector elements. NEON supports these directly. They are
9620 // handled during DAG combining because type legalization will promote them
9621 // to 32-bit types and it is messy to recognize the operations after that.
9622 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9623 SDValue Vec = N0.getOperand(0);
9624 SDValue Lane = N0.getOperand(1);
9625 EVT VT = N->getValueType(0);
9626 EVT EltVT = N0.getValueType();
9627 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9629 if (VT == MVT::i32 &&
9630 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9631 TLI.isTypeLegal(Vec.getValueType()) &&
9632 isa<ConstantSDNode>(Lane)) {
9635 switch (N->getOpcode()) {
9636 default: llvm_unreachable("unexpected opcode");
9637 case ISD::SIGN_EXTEND:
9638 Opc = ARMISD::VGETLANEs;
9640 case ISD::ZERO_EXTEND:
9641 case ISD::ANY_EXTEND:
9642 Opc = ARMISD::VGETLANEu;
9645 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9652 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9653 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9654 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9655 const ARMSubtarget *ST) {
9656 // If the target supports NEON, try to use vmax/vmin instructions for f32
9657 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9658 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9659 // a NaN; only do the transformation when it matches that behavior.
9661 // For now only do this when using NEON for FP operations; if using VFP, it
9662 // is not obvious that the benefit outweighs the cost of switching to the
9664 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9665 N->getValueType(0) != MVT::f32)
9668 SDValue CondLHS = N->getOperand(0);
9669 SDValue CondRHS = N->getOperand(1);
9670 SDValue LHS = N->getOperand(2);
9671 SDValue RHS = N->getOperand(3);
9672 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9674 unsigned Opcode = 0;
9676 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9677 IsReversed = false; // x CC y ? x : y
9678 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9679 IsReversed = true ; // x CC y ? y : x
9693 // If LHS is NaN, an ordered comparison will be false and the result will
9694 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9695 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9696 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9697 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9699 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9700 // will return -0, so vmin can only be used for unsafe math or if one of
9701 // the operands is known to be nonzero.
9702 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9703 !DAG.getTarget().Options.UnsafeFPMath &&
9704 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9706 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9715 // If LHS is NaN, an ordered comparison will be false and the result will
9716 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9717 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9718 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9719 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9721 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9722 // will return +0, so vmax can only be used for unsafe math or if one of
9723 // the operands is known to be nonzero.
9724 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9725 !DAG.getTarget().Options.UnsafeFPMath &&
9726 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9728 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9734 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9737 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9739 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9740 SDValue Cmp = N->getOperand(4);
9741 if (Cmp.getOpcode() != ARMISD::CMPZ)
9742 // Only looking at EQ and NE cases.
9745 EVT VT = N->getValueType(0);
9747 SDValue LHS = Cmp.getOperand(0);
9748 SDValue RHS = Cmp.getOperand(1);
9749 SDValue FalseVal = N->getOperand(0);
9750 SDValue TrueVal = N->getOperand(1);
9751 SDValue ARMcc = N->getOperand(2);
9752 ARMCC::CondCodes CC =
9753 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9771 /// FIXME: Turn this into a target neutral optimization?
9773 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9774 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9775 N->getOperand(3), Cmp);
9776 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9778 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9779 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9780 N->getOperand(3), NewCmp);
9783 if (Res.getNode()) {
9784 APInt KnownZero, KnownOne;
9785 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9786 // Capture demanded bits information that would be otherwise lost.
9787 if (KnownZero == 0xfffffffe)
9788 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9789 DAG.getValueType(MVT::i1));
9790 else if (KnownZero == 0xffffff00)
9791 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9792 DAG.getValueType(MVT::i8));
9793 else if (KnownZero == 0xffff0000)
9794 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9795 DAG.getValueType(MVT::i16));
9801 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9802 DAGCombinerInfo &DCI) const {
9803 switch (N->getOpcode()) {
9805 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9806 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9807 case ISD::SUB: return PerformSUBCombine(N, DCI);
9808 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9809 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9810 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9811 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9812 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9813 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9814 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9815 case ISD::STORE: return PerformSTORECombine(N, DCI);
9816 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9817 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9818 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9819 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9820 case ISD::FP_TO_SINT:
9821 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9822 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9823 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9826 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9827 case ISD::SIGN_EXTEND:
9828 case ISD::ZERO_EXTEND:
9829 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9830 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9831 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9832 case ARMISD::VLD2DUP:
9833 case ARMISD::VLD3DUP:
9834 case ARMISD::VLD4DUP:
9835 return CombineBaseUpdate(N, DCI);
9836 case ARMISD::BUILD_VECTOR:
9837 return PerformARMBUILD_VECTORCombine(N, DCI);
9838 case ISD::INTRINSIC_VOID:
9839 case ISD::INTRINSIC_W_CHAIN:
9840 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9841 case Intrinsic::arm_neon_vld1:
9842 case Intrinsic::arm_neon_vld2:
9843 case Intrinsic::arm_neon_vld3:
9844 case Intrinsic::arm_neon_vld4:
9845 case Intrinsic::arm_neon_vld2lane:
9846 case Intrinsic::arm_neon_vld3lane:
9847 case Intrinsic::arm_neon_vld4lane:
9848 case Intrinsic::arm_neon_vst1:
9849 case Intrinsic::arm_neon_vst2:
9850 case Intrinsic::arm_neon_vst3:
9851 case Intrinsic::arm_neon_vst4:
9852 case Intrinsic::arm_neon_vst2lane:
9853 case Intrinsic::arm_neon_vst3lane:
9854 case Intrinsic::arm_neon_vst4lane:
9855 return CombineBaseUpdate(N, DCI);
9863 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9865 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9868 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9872 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9873 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9875 switch (VT.getSimpleVT().SimpleTy) {
9881 // Unaligned access can use (for example) LRDB, LRDH, LDR
9882 if (AllowsUnaligned) {
9884 *Fast = Subtarget->hasV7Ops();
9891 // For any little-endian targets with neon, we can support unaligned ld/st
9892 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9893 // A big-endian target may also explicitly support unaligned accesses
9894 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9904 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9905 unsigned AlignCheck) {
9906 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9907 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9910 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9911 unsigned DstAlign, unsigned SrcAlign,
9912 bool IsMemset, bool ZeroMemset,
9914 MachineFunction &MF) const {
9915 const Function *F = MF.getFunction();
9917 // See if we can use NEON instructions for this...
9918 if ((!IsMemset || ZeroMemset) &&
9919 Subtarget->hasNEON() &&
9920 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9921 Attribute::NoImplicitFloat)) {
9924 (memOpAlign(SrcAlign, DstAlign, 16) ||
9925 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9927 } else if (Size >= 8 &&
9928 (memOpAlign(SrcAlign, DstAlign, 8) ||
9929 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9935 // Lowering to i32/i16 if the size permits.
9941 // Let the target-independent logic figure it out.
9945 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9946 if (Val.getOpcode() != ISD::LOAD)
9949 EVT VT1 = Val.getValueType();
9950 if (!VT1.isSimple() || !VT1.isInteger() ||
9951 !VT2.isSimple() || !VT2.isInteger())
9954 switch (VT1.getSimpleVT().SimpleTy) {
9959 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9966 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9967 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9970 if (!isTypeLegal(EVT::getEVT(Ty1)))
9973 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9975 // Assuming the caller doesn't have a zeroext or signext return parameter,
9976 // truncation all the way down to i1 is valid.
9981 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9986 switch (VT.getSimpleVT().SimpleTy) {
9987 default: return false;
10002 if ((V & (Scale - 1)) != 0)
10005 return V == (V & ((1LL << 5) - 1));
10008 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10009 const ARMSubtarget *Subtarget) {
10010 bool isNeg = false;
10016 switch (VT.getSimpleVT().SimpleTy) {
10017 default: return false;
10022 // + imm12 or - imm8
10024 return V == (V & ((1LL << 8) - 1));
10025 return V == (V & ((1LL << 12) - 1));
10028 // Same as ARM mode. FIXME: NEON?
10029 if (!Subtarget->hasVFP2())
10034 return V == (V & ((1LL << 8) - 1));
10038 /// isLegalAddressImmediate - Return true if the integer value can be used
10039 /// as the offset of the target addressing mode for load / store of the
10041 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10042 const ARMSubtarget *Subtarget) {
10046 if (!VT.isSimple())
10049 if (Subtarget->isThumb1Only())
10050 return isLegalT1AddressImmediate(V, VT);
10051 else if (Subtarget->isThumb2())
10052 return isLegalT2AddressImmediate(V, VT, Subtarget);
10057 switch (VT.getSimpleVT().SimpleTy) {
10058 default: return false;
10063 return V == (V & ((1LL << 12) - 1));
10066 return V == (V & ((1LL << 8) - 1));
10069 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10074 return V == (V & ((1LL << 8) - 1));
10078 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10080 int Scale = AM.Scale;
10084 switch (VT.getSimpleVT().SimpleTy) {
10085 default: return false;
10093 Scale = Scale & ~1;
10094 return Scale == 2 || Scale == 4 || Scale == 8;
10097 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10101 // Note, we allow "void" uses (basically, uses that aren't loads or
10102 // stores), because arm allows folding a scale into many arithmetic
10103 // operations. This should be made more precise and revisited later.
10105 // Allow r << imm, but the imm has to be a multiple of two.
10106 if (Scale & 1) return false;
10107 return isPowerOf2_32(Scale);
10111 /// isLegalAddressingMode - Return true if the addressing mode represented
10112 /// by AM is legal for this target, for a load/store of the specified type.
10113 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10115 EVT VT = getValueType(Ty, true);
10116 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10119 // Can never fold addr of global into load/store.
10123 switch (AM.Scale) {
10124 case 0: // no scale reg, must be "r+i" or "r", or "i".
10127 if (Subtarget->isThumb1Only())
10131 // ARM doesn't support any R+R*scale+imm addr modes.
10135 if (!VT.isSimple())
10138 if (Subtarget->isThumb2())
10139 return isLegalT2ScaledAddressingMode(AM, VT);
10141 int Scale = AM.Scale;
10142 switch (VT.getSimpleVT().SimpleTy) {
10143 default: return false;
10147 if (Scale < 0) Scale = -Scale;
10151 return isPowerOf2_32(Scale & ~1);
10155 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10160 // Note, we allow "void" uses (basically, uses that aren't loads or
10161 // stores), because arm allows folding a scale into many arithmetic
10162 // operations. This should be made more precise and revisited later.
10164 // Allow r << imm, but the imm has to be a multiple of two.
10165 if (Scale & 1) return false;
10166 return isPowerOf2_32(Scale);
10172 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10173 /// icmp immediate, that is the target has icmp instructions which can compare
10174 /// a register against the immediate without having to materialize the
10175 /// immediate into a register.
10176 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10177 // Thumb2 and ARM modes can use cmn for negative immediates.
10178 if (!Subtarget->isThumb())
10179 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10180 if (Subtarget->isThumb2())
10181 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10182 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10183 return Imm >= 0 && Imm <= 255;
10186 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10187 /// *or sub* immediate, that is the target has add or sub instructions which can
10188 /// add a register with the immediate without having to materialize the
10189 /// immediate into a register.
10190 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10191 // Same encoding for add/sub, just flip the sign.
10192 int64_t AbsImm = llvm::abs64(Imm);
10193 if (!Subtarget->isThumb())
10194 return ARM_AM::getSOImmVal(AbsImm) != -1;
10195 if (Subtarget->isThumb2())
10196 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10197 // Thumb1 only has 8-bit unsigned immediate.
10198 return AbsImm >= 0 && AbsImm <= 255;
10201 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10202 bool isSEXTLoad, SDValue &Base,
10203 SDValue &Offset, bool &isInc,
10204 SelectionDAG &DAG) {
10205 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10208 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10209 // AddressingMode 3
10210 Base = Ptr->getOperand(0);
10211 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10212 int RHSC = (int)RHS->getZExtValue();
10213 if (RHSC < 0 && RHSC > -256) {
10214 assert(Ptr->getOpcode() == ISD::ADD);
10216 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10220 isInc = (Ptr->getOpcode() == ISD::ADD);
10221 Offset = Ptr->getOperand(1);
10223 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10224 // AddressingMode 2
10225 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10226 int RHSC = (int)RHS->getZExtValue();
10227 if (RHSC < 0 && RHSC > -0x1000) {
10228 assert(Ptr->getOpcode() == ISD::ADD);
10230 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10231 Base = Ptr->getOperand(0);
10236 if (Ptr->getOpcode() == ISD::ADD) {
10238 ARM_AM::ShiftOpc ShOpcVal=
10239 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10240 if (ShOpcVal != ARM_AM::no_shift) {
10241 Base = Ptr->getOperand(1);
10242 Offset = Ptr->getOperand(0);
10244 Base = Ptr->getOperand(0);
10245 Offset = Ptr->getOperand(1);
10250 isInc = (Ptr->getOpcode() == ISD::ADD);
10251 Base = Ptr->getOperand(0);
10252 Offset = Ptr->getOperand(1);
10256 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10260 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10261 bool isSEXTLoad, SDValue &Base,
10262 SDValue &Offset, bool &isInc,
10263 SelectionDAG &DAG) {
10264 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10267 Base = Ptr->getOperand(0);
10268 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10269 int RHSC = (int)RHS->getZExtValue();
10270 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10271 assert(Ptr->getOpcode() == ISD::ADD);
10273 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10275 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10276 isInc = Ptr->getOpcode() == ISD::ADD;
10277 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10285 /// getPreIndexedAddressParts - returns true by value, base pointer and
10286 /// offset pointer and addressing mode by reference if the node's address
10287 /// can be legally represented as pre-indexed load / store address.
10289 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10291 ISD::MemIndexedMode &AM,
10292 SelectionDAG &DAG) const {
10293 if (Subtarget->isThumb1Only())
10298 bool isSEXTLoad = false;
10299 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10300 Ptr = LD->getBasePtr();
10301 VT = LD->getMemoryVT();
10302 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10303 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10304 Ptr = ST->getBasePtr();
10305 VT = ST->getMemoryVT();
10310 bool isLegal = false;
10311 if (Subtarget->isThumb2())
10312 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10313 Offset, isInc, DAG);
10315 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10316 Offset, isInc, DAG);
10320 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10324 /// getPostIndexedAddressParts - returns true by value, base pointer and
10325 /// offset pointer and addressing mode by reference if this node can be
10326 /// combined with a load / store to form a post-indexed load / store.
10327 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10330 ISD::MemIndexedMode &AM,
10331 SelectionDAG &DAG) const {
10332 if (Subtarget->isThumb1Only())
10337 bool isSEXTLoad = false;
10338 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10339 VT = LD->getMemoryVT();
10340 Ptr = LD->getBasePtr();
10341 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10342 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10343 VT = ST->getMemoryVT();
10344 Ptr = ST->getBasePtr();
10349 bool isLegal = false;
10350 if (Subtarget->isThumb2())
10351 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10354 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10360 // Swap base ptr and offset to catch more post-index load / store when
10361 // it's legal. In Thumb2 mode, offset must be an immediate.
10362 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10363 !Subtarget->isThumb2())
10364 std::swap(Base, Offset);
10366 // Post-indexed load / store update the base pointer.
10371 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10375 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10378 const SelectionDAG &DAG,
10379 unsigned Depth) const {
10380 unsigned BitWidth = KnownOne.getBitWidth();
10381 KnownZero = KnownOne = APInt(BitWidth, 0);
10382 switch (Op.getOpcode()) {
10388 // These nodes' second result is a boolean
10389 if (Op.getResNo() == 0)
10391 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10393 case ARMISD::CMOV: {
10394 // Bits are known zero/one if known on the LHS and RHS.
10395 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10396 if (KnownZero == 0 && KnownOne == 0) return;
10398 APInt KnownZeroRHS, KnownOneRHS;
10399 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10400 KnownZero &= KnownZeroRHS;
10401 KnownOne &= KnownOneRHS;
10404 case ISD::INTRINSIC_W_CHAIN: {
10405 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10406 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10409 case Intrinsic::arm_ldaex:
10410 case Intrinsic::arm_ldrex: {
10411 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10412 unsigned MemBits = VT.getScalarType().getSizeInBits();
10413 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10421 //===----------------------------------------------------------------------===//
10422 // ARM Inline Assembly Support
10423 //===----------------------------------------------------------------------===//
10425 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10426 // Looking for "rev" which is V6+.
10427 if (!Subtarget->hasV6Ops())
10430 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10431 std::string AsmStr = IA->getAsmString();
10432 SmallVector<StringRef, 4> AsmPieces;
10433 SplitString(AsmStr, AsmPieces, ";\n");
10435 switch (AsmPieces.size()) {
10436 default: return false;
10438 AsmStr = AsmPieces[0];
10440 SplitString(AsmStr, AsmPieces, " \t,");
10443 if (AsmPieces.size() == 3 &&
10444 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10445 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10446 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10447 if (Ty && Ty->getBitWidth() == 32)
10448 return IntrinsicLowering::LowerToByteSwap(CI);
10456 /// getConstraintType - Given a constraint letter, return the type of
10457 /// constraint it is for this target.
10458 ARMTargetLowering::ConstraintType
10459 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10460 if (Constraint.size() == 1) {
10461 switch (Constraint[0]) {
10463 case 'l': return C_RegisterClass;
10464 case 'w': return C_RegisterClass;
10465 case 'h': return C_RegisterClass;
10466 case 'x': return C_RegisterClass;
10467 case 't': return C_RegisterClass;
10468 case 'j': return C_Other; // Constant for movw.
10469 // An address with a single base register. Due to the way we
10470 // currently handle addresses it is the same as an 'r' memory constraint.
10471 case 'Q': return C_Memory;
10473 } else if (Constraint.size() == 2) {
10474 switch (Constraint[0]) {
10476 // All 'U+' constraints are addresses.
10477 case 'U': return C_Memory;
10480 return TargetLowering::getConstraintType(Constraint);
10483 /// Examine constraint type and operand type and determine a weight value.
10484 /// This object must already have been set up with the operand type
10485 /// and the current alternative constraint selected.
10486 TargetLowering::ConstraintWeight
10487 ARMTargetLowering::getSingleConstraintMatchWeight(
10488 AsmOperandInfo &info, const char *constraint) const {
10489 ConstraintWeight weight = CW_Invalid;
10490 Value *CallOperandVal = info.CallOperandVal;
10491 // If we don't have a value, we can't do a match,
10492 // but allow it at the lowest weight.
10493 if (!CallOperandVal)
10495 Type *type = CallOperandVal->getType();
10496 // Look at the constraint type.
10497 switch (*constraint) {
10499 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10502 if (type->isIntegerTy()) {
10503 if (Subtarget->isThumb())
10504 weight = CW_SpecificReg;
10506 weight = CW_Register;
10510 if (type->isFloatingPointTy())
10511 weight = CW_Register;
10517 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10519 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10521 if (Constraint.size() == 1) {
10522 // GCC ARM Constraint Letters
10523 switch (Constraint[0]) {
10524 case 'l': // Low regs or general regs.
10525 if (Subtarget->isThumb())
10526 return RCPair(0U, &ARM::tGPRRegClass);
10527 return RCPair(0U, &ARM::GPRRegClass);
10528 case 'h': // High regs or no regs.
10529 if (Subtarget->isThumb())
10530 return RCPair(0U, &ARM::hGPRRegClass);
10533 return RCPair(0U, &ARM::GPRRegClass);
10535 if (VT == MVT::Other)
10537 if (VT == MVT::f32)
10538 return RCPair(0U, &ARM::SPRRegClass);
10539 if (VT.getSizeInBits() == 64)
10540 return RCPair(0U, &ARM::DPRRegClass);
10541 if (VT.getSizeInBits() == 128)
10542 return RCPair(0U, &ARM::QPRRegClass);
10545 if (VT == MVT::Other)
10547 if (VT == MVT::f32)
10548 return RCPair(0U, &ARM::SPR_8RegClass);
10549 if (VT.getSizeInBits() == 64)
10550 return RCPair(0U, &ARM::DPR_8RegClass);
10551 if (VT.getSizeInBits() == 128)
10552 return RCPair(0U, &ARM::QPR_8RegClass);
10555 if (VT == MVT::f32)
10556 return RCPair(0U, &ARM::SPRRegClass);
10560 if (StringRef("{cc}").equals_lower(Constraint))
10561 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10563 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10566 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10567 /// vector. If it is invalid, don't add anything to Ops.
10568 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10569 std::string &Constraint,
10570 std::vector<SDValue>&Ops,
10571 SelectionDAG &DAG) const {
10574 // Currently only support length 1 constraints.
10575 if (Constraint.length() != 1) return;
10577 char ConstraintLetter = Constraint[0];
10578 switch (ConstraintLetter) {
10581 case 'I': case 'J': case 'K': case 'L':
10582 case 'M': case 'N': case 'O':
10583 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10587 int64_t CVal64 = C->getSExtValue();
10588 int CVal = (int) CVal64;
10589 // None of these constraints allow values larger than 32 bits. Check
10590 // that the value fits in an int.
10591 if (CVal != CVal64)
10594 switch (ConstraintLetter) {
10596 // Constant suitable for movw, must be between 0 and
10598 if (Subtarget->hasV6T2Ops())
10599 if (CVal >= 0 && CVal <= 65535)
10603 if (Subtarget->isThumb1Only()) {
10604 // This must be a constant between 0 and 255, for ADD
10606 if (CVal >= 0 && CVal <= 255)
10608 } else if (Subtarget->isThumb2()) {
10609 // A constant that can be used as an immediate value in a
10610 // data-processing instruction.
10611 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10614 // A constant that can be used as an immediate value in a
10615 // data-processing instruction.
10616 if (ARM_AM::getSOImmVal(CVal) != -1)
10622 if (Subtarget->isThumb()) { // FIXME thumb2
10623 // This must be a constant between -255 and -1, for negated ADD
10624 // immediates. This can be used in GCC with an "n" modifier that
10625 // prints the negated value, for use with SUB instructions. It is
10626 // not useful otherwise but is implemented for compatibility.
10627 if (CVal >= -255 && CVal <= -1)
10630 // This must be a constant between -4095 and 4095. It is not clear
10631 // what this constraint is intended for. Implemented for
10632 // compatibility with GCC.
10633 if (CVal >= -4095 && CVal <= 4095)
10639 if (Subtarget->isThumb1Only()) {
10640 // A 32-bit value where only one byte has a nonzero value. Exclude
10641 // zero to match GCC. This constraint is used by GCC internally for
10642 // constants that can be loaded with a move/shift combination.
10643 // It is not useful otherwise but is implemented for compatibility.
10644 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10646 } else if (Subtarget->isThumb2()) {
10647 // A constant whose bitwise inverse can be used as an immediate
10648 // value in a data-processing instruction. This can be used in GCC
10649 // with a "B" modifier that prints the inverted value, for use with
10650 // BIC and MVN instructions. It is not useful otherwise but is
10651 // implemented for compatibility.
10652 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10655 // A constant whose bitwise inverse can be used as an immediate
10656 // value in a data-processing instruction. This can be used in GCC
10657 // with a "B" modifier that prints the inverted value, for use with
10658 // BIC and MVN instructions. It is not useful otherwise but is
10659 // implemented for compatibility.
10660 if (ARM_AM::getSOImmVal(~CVal) != -1)
10666 if (Subtarget->isThumb1Only()) {
10667 // This must be a constant between -7 and 7,
10668 // for 3-operand ADD/SUB immediate instructions.
10669 if (CVal >= -7 && CVal < 7)
10671 } else if (Subtarget->isThumb2()) {
10672 // A constant whose negation can be used as an immediate value in a
10673 // data-processing instruction. This can be used in GCC with an "n"
10674 // modifier that prints the negated value, for use with SUB
10675 // instructions. It is not useful otherwise but is implemented for
10677 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10680 // A constant whose negation can be used as an immediate value in a
10681 // data-processing instruction. This can be used in GCC with an "n"
10682 // modifier that prints the negated value, for use with SUB
10683 // instructions. It is not useful otherwise but is implemented for
10685 if (ARM_AM::getSOImmVal(-CVal) != -1)
10691 if (Subtarget->isThumb()) { // FIXME thumb2
10692 // This must be a multiple of 4 between 0 and 1020, for
10693 // ADD sp + immediate.
10694 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10697 // A power of two or a constant between 0 and 32. This is used in
10698 // GCC for the shift amount on shifted register operands, but it is
10699 // useful in general for any shift amounts.
10700 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10706 if (Subtarget->isThumb()) { // FIXME thumb2
10707 // This must be a constant between 0 and 31, for shift amounts.
10708 if (CVal >= 0 && CVal <= 31)
10714 if (Subtarget->isThumb()) { // FIXME thumb2
10715 // This must be a multiple of 4 between -508 and 508, for
10716 // ADD/SUB sp = sp + immediate.
10717 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10722 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10726 if (Result.getNode()) {
10727 Ops.push_back(Result);
10730 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10733 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10734 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10735 unsigned Opcode = Op->getOpcode();
10736 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10737 "Invalid opcode for Div/Rem lowering");
10738 bool isSigned = (Opcode == ISD::SDIVREM);
10739 EVT VT = Op->getValueType(0);
10740 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10743 switch (VT.getSimpleVT().SimpleTy) {
10744 default: llvm_unreachable("Unexpected request for libcall!");
10745 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10746 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10747 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10748 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10751 SDValue InChain = DAG.getEntryNode();
10753 TargetLowering::ArgListTy Args;
10754 TargetLowering::ArgListEntry Entry;
10755 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10756 EVT ArgVT = Op->getOperand(i).getValueType();
10757 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10758 Entry.Node = Op->getOperand(i);
10760 Entry.isSExt = isSigned;
10761 Entry.isZExt = !isSigned;
10762 Args.push_back(Entry);
10765 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10768 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10771 TargetLowering::CallLoweringInfo CLI(DAG);
10772 CLI.setDebugLoc(dl).setChain(InChain)
10773 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10774 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10776 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10777 return CallInfo.first;
10781 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10782 assert(Subtarget->isTargetWindows() && "unsupported target platform");
10786 SDValue Chain = Op.getOperand(0);
10787 SDValue Size = Op.getOperand(1);
10789 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10790 DAG.getConstant(2, MVT::i32));
10793 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10794 Flag = Chain.getValue(1);
10796 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10797 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10799 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10800 Chain = NewSP.getValue(1);
10802 SDValue Ops[2] = { NewSP, Chain };
10803 return DAG.getMergeValues(Ops, DL);
10806 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10807 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10808 "Unexpected type for custom-lowering FP_EXTEND");
10811 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10813 SDValue SrcVal = Op.getOperand(0);
10814 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10815 /*isSigned*/ false, SDLoc(Op)).first;
10818 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10819 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10820 Subtarget->isFPOnlySP() &&
10821 "Unexpected type for custom-lowering FP_ROUND");
10824 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10826 SDValue SrcVal = Op.getOperand(0);
10827 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10828 /*isSigned*/ false, SDLoc(Op)).first;
10832 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10833 // The ARM target isn't yet aware of offsets.
10837 bool ARM::isBitFieldInvertedMask(unsigned v) {
10838 if (v == 0xffffffff)
10841 // there can be 1's on either or both "outsides", all the "inside"
10842 // bits must be 0's
10843 unsigned TO = CountTrailingOnes_32(v);
10844 unsigned LO = CountLeadingOnes_32(v);
10845 v = (v >> TO) << TO;
10846 v = (v << LO) >> LO;
10850 /// isFPImmLegal - Returns true if the target can instruction select the
10851 /// specified FP immediate natively. If false, the legalizer will
10852 /// materialize the FP immediate as a load from a constant pool.
10853 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10854 if (!Subtarget->hasVFP3())
10856 if (VT == MVT::f32)
10857 return ARM_AM::getFP32Imm(Imm) != -1;
10858 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10859 return ARM_AM::getFP64Imm(Imm) != -1;
10863 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10864 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10865 /// specified in the intrinsic calls.
10866 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10868 unsigned Intrinsic) const {
10869 switch (Intrinsic) {
10870 case Intrinsic::arm_neon_vld1:
10871 case Intrinsic::arm_neon_vld2:
10872 case Intrinsic::arm_neon_vld3:
10873 case Intrinsic::arm_neon_vld4:
10874 case Intrinsic::arm_neon_vld2lane:
10875 case Intrinsic::arm_neon_vld3lane:
10876 case Intrinsic::arm_neon_vld4lane: {
10877 Info.opc = ISD::INTRINSIC_W_CHAIN;
10878 // Conservatively set memVT to the entire set of vectors loaded.
10879 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10880 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10881 Info.ptrVal = I.getArgOperand(0);
10883 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10884 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10885 Info.vol = false; // volatile loads with NEON intrinsics not supported
10886 Info.readMem = true;
10887 Info.writeMem = false;
10890 case Intrinsic::arm_neon_vst1:
10891 case Intrinsic::arm_neon_vst2:
10892 case Intrinsic::arm_neon_vst3:
10893 case Intrinsic::arm_neon_vst4:
10894 case Intrinsic::arm_neon_vst2lane:
10895 case Intrinsic::arm_neon_vst3lane:
10896 case Intrinsic::arm_neon_vst4lane: {
10897 Info.opc = ISD::INTRINSIC_VOID;
10898 // Conservatively set memVT to the entire set of vectors stored.
10899 unsigned NumElts = 0;
10900 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10901 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10902 if (!ArgTy->isVectorTy())
10904 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10906 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10907 Info.ptrVal = I.getArgOperand(0);
10909 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10910 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10911 Info.vol = false; // volatile stores with NEON intrinsics not supported
10912 Info.readMem = false;
10913 Info.writeMem = true;
10916 case Intrinsic::arm_ldaex:
10917 case Intrinsic::arm_ldrex: {
10918 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10919 Info.opc = ISD::INTRINSIC_W_CHAIN;
10920 Info.memVT = MVT::getVT(PtrTy->getElementType());
10921 Info.ptrVal = I.getArgOperand(0);
10923 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10925 Info.readMem = true;
10926 Info.writeMem = false;
10929 case Intrinsic::arm_stlex:
10930 case Intrinsic::arm_strex: {
10931 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10932 Info.opc = ISD::INTRINSIC_W_CHAIN;
10933 Info.memVT = MVT::getVT(PtrTy->getElementType());
10934 Info.ptrVal = I.getArgOperand(1);
10936 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10938 Info.readMem = false;
10939 Info.writeMem = true;
10942 case Intrinsic::arm_stlexd:
10943 case Intrinsic::arm_strexd: {
10944 Info.opc = ISD::INTRINSIC_W_CHAIN;
10945 Info.memVT = MVT::i64;
10946 Info.ptrVal = I.getArgOperand(2);
10950 Info.readMem = false;
10951 Info.writeMem = true;
10954 case Intrinsic::arm_ldaexd:
10955 case Intrinsic::arm_ldrexd: {
10956 Info.opc = ISD::INTRINSIC_W_CHAIN;
10957 Info.memVT = MVT::i64;
10958 Info.ptrVal = I.getArgOperand(0);
10962 Info.readMem = true;
10963 Info.writeMem = false;
10973 /// \brief Returns true if it is beneficial to convert a load of a constant
10974 /// to just the constant itself.
10975 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10977 assert(Ty->isIntegerTy());
10979 unsigned Bits = Ty->getPrimitiveSizeInBits();
10980 if (Bits == 0 || Bits > 32)
10985 static void makeDMB(IRBuilder<> &Builder, ARM_MB::MemBOpt Domain) {
10986 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10987 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
10988 Constant *CDomain = Builder.getInt32(Domain);
10989 Builder.CreateCall(DMB, CDomain);
10992 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10993 void ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10994 AtomicOrdering Ord, bool IsStore,
10995 bool IsLoad) const {
10996 if (!getInsertFencesForAtomic())
11002 llvm_unreachable("Invalid fence: unordered/non-atomic");
11005 return; // Nothing to do
11006 case SequentiallyConsistent:
11008 return; // Nothing to do
11011 case AcquireRelease:
11012 if (Subtarget->isSwift())
11013 makeDMB(Builder, ARM_MB::ISHST);
11014 // FIXME: add a comment with a link to documentation justifying this.
11016 makeDMB(Builder, ARM_MB::ISH);
11021 void ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11022 AtomicOrdering Ord, bool IsStore,
11023 bool IsLoad) const {
11024 if (!getInsertFencesForAtomic())
11030 llvm_unreachable("Invalid fence: unordered/not-atomic");
11033 return; // Nothing to do
11035 case AcquireRelease:
11036 case SequentiallyConsistent:
11037 makeDMB(Builder, ARM_MB::ISH);
11042 // Loads and stores less than 64-bits are already atomic; ones above that
11043 // are doomed anyway, so defer to the default libcall and blame the OS when
11044 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11045 // anything for those.
11046 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11047 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11048 return (Size == 64) && !Subtarget->isMClass();
11051 // Loads and stores less than 64-bits are already atomic; ones above that
11052 // are doomed anyway, so defer to the default libcall and blame the OS when
11053 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11054 // anything for those.
11055 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11056 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11057 return (Size == 64) && !Subtarget->isMClass();
11060 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11061 // and up to 64 bits on the non-M profiles
11062 bool ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11063 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11064 return Size <= (Subtarget->isMClass() ? 32 : 64);
11067 // This has so far only been implemented for MachO.
11068 bool ARMTargetLowering::useLoadStackGuardNode() const {
11069 return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO;
11072 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11073 AtomicOrdering Ord) const {
11074 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11075 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11076 bool IsAcquire = isAtLeastAcquire(Ord);
11078 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11079 // intrinsic must return {i32, i32} and we have to recombine them into a
11080 // single i64 here.
11081 if (ValTy->getPrimitiveSizeInBits() == 64) {
11082 Intrinsic::ID Int =
11083 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11084 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11086 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11087 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11089 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11090 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11091 if (!Subtarget->isLittle())
11092 std::swap (Lo, Hi);
11093 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11094 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11095 return Builder.CreateOr(
11096 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11099 Type *Tys[] = { Addr->getType() };
11100 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11101 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11103 return Builder.CreateTruncOrBitCast(
11104 Builder.CreateCall(Ldrex, Addr),
11105 cast<PointerType>(Addr->getType())->getElementType());
11108 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11110 AtomicOrdering Ord) const {
11111 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11112 bool IsRelease = isAtLeastRelease(Ord);
11114 // Since the intrinsics must have legal type, the i64 intrinsics take two
11115 // parameters: "i32, i32". We must marshal Val into the appropriate form
11116 // before the call.
11117 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11118 Intrinsic::ID Int =
11119 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11120 Function *Strex = Intrinsic::getDeclaration(M, Int);
11121 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11123 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11124 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11125 if (!Subtarget->isLittle())
11126 std::swap (Lo, Hi);
11127 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11128 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11131 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11132 Type *Tys[] = { Addr->getType() };
11133 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11135 return Builder.CreateCall2(
11136 Strex, Builder.CreateZExtOrBitCast(
11137 Val, Strex->getFunctionType()->getParamType(0)),
11149 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11150 uint64_t &Members) {
11151 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11152 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11153 uint64_t SubMembers = 0;
11154 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11156 Members += SubMembers;
11158 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11159 uint64_t SubMembers = 0;
11160 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11162 Members += SubMembers * AT->getNumElements();
11163 } else if (Ty->isFloatTy()) {
11164 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11168 } else if (Ty->isDoubleTy()) {
11169 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11173 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11180 return VT->getBitWidth() == 64;
11182 return VT->getBitWidth() == 128;
11184 switch (VT->getBitWidth()) {
11197 return (Members > 0 && Members <= 4);
11200 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
11201 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11202 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11203 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11204 CallingConv::ARM_AAPCS_VFP)
11207 HABaseType Base = HA_UNKNOWN;
11208 uint64_t Members = 0;
11209 bool result = isHomogeneousAggregate(Ty, Base, Members);
11210 DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump());