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 "ARMBaseInstrInfo.h"
17 #include "ARMBaseRegisterInfo.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMRegisterInfo.h"
23 #include "ARMSelectionDAGInfo.h"
24 #include "ARMSubtarget.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "MCTargetDesc/ARMBaseInfo.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/APInt.h"
29 #include "llvm/ADT/ArrayRef.h"
30 #include "llvm/ADT/BitVector.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ADT/StringSwitch.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/ADT/Twine.h"
41 #include "llvm/Analysis/VectorUtils.h"
42 #include "llvm/CodeGen/CallingConvLower.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/IntrinsicLowering.h"
45 #include "llvm/CodeGen/MachineBasicBlock.h"
46 #include "llvm/CodeGen/MachineConstantPool.h"
47 #include "llvm/CodeGen/MachineFrameInfo.h"
48 #include "llvm/CodeGen/MachineFunction.h"
49 #include "llvm/CodeGen/MachineInstr.h"
50 #include "llvm/CodeGen/MachineInstrBuilder.h"
51 #include "llvm/CodeGen/MachineJumpTableInfo.h"
52 #include "llvm/CodeGen/MachineMemOperand.h"
53 #include "llvm/CodeGen/MachineOperand.h"
54 #include "llvm/CodeGen/MachineRegisterInfo.h"
55 #include "llvm/CodeGen/MachineValueType.h"
56 #include "llvm/CodeGen/RuntimeLibcalls.h"
57 #include "llvm/CodeGen/SelectionDAG.h"
58 #include "llvm/CodeGen/SelectionDAGNodes.h"
59 #include "llvm/CodeGen/ValueTypes.h"
60 #include "llvm/IR/Attributes.h"
61 #include "llvm/IR/CallingConv.h"
62 #include "llvm/IR/Constant.h"
63 #include "llvm/IR/Constants.h"
64 #include "llvm/IR/DataLayout.h"
65 #include "llvm/IR/DebugLoc.h"
66 #include "llvm/IR/DerivedTypes.h"
67 #include "llvm/IR/Function.h"
68 #include "llvm/IR/GlobalAlias.h"
69 #include "llvm/IR/GlobalValue.h"
70 #include "llvm/IR/GlobalVariable.h"
71 #include "llvm/IR/IRBuilder.h"
72 #include "llvm/IR/InlineAsm.h"
73 #include "llvm/IR/Instruction.h"
74 #include "llvm/IR/Instructions.h"
75 #include "llvm/IR/IntrinsicInst.h"
76 #include "llvm/IR/Intrinsics.h"
77 #include "llvm/IR/Module.h"
78 #include "llvm/IR/Type.h"
79 #include "llvm/IR/User.h"
80 #include "llvm/IR/Value.h"
81 #include "llvm/MC/MCInstrDesc.h"
82 #include "llvm/MC/MCInstrItineraries.h"
83 #include "llvm/MC/MCRegisterInfo.h"
84 #include "llvm/MC/MCSchedule.h"
85 #include "llvm/Support/AtomicOrdering.h"
86 #include "llvm/Support/BranchProbability.h"
87 #include "llvm/Support/Casting.h"
88 #include "llvm/Support/CodeGen.h"
89 #include "llvm/Support/CommandLine.h"
90 #include "llvm/Support/Compiler.h"
91 #include "llvm/Support/Debug.h"
92 #include "llvm/Support/ErrorHandling.h"
93 #include "llvm/Support/KnownBits.h"
94 #include "llvm/Support/MathExtras.h"
95 #include "llvm/Support/raw_ostream.h"
96 #include "llvm/Target/TargetInstrInfo.h"
97 #include "llvm/Target/TargetMachine.h"
98 #include "llvm/Target/TargetOptions.h"
110 using namespace llvm;
112 #define DEBUG_TYPE "arm-isel"
114 STATISTIC(NumTailCalls, "Number of tail calls");
115 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
116 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
117 STATISTIC(NumConstpoolPromoted,
118 "Number of constants with their storage promoted into constant pools");
121 ARMInterworking("arm-interworking", cl::Hidden,
122 cl::desc("Enable / disable ARM interworking (for debugging only)"),
125 static cl::opt<bool> EnableConstpoolPromotion(
126 "arm-promote-constant", cl::Hidden,
127 cl::desc("Enable / disable promotion of unnamed_addr constants into "
129 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
130 static cl::opt<unsigned> ConstpoolPromotionMaxSize(
131 "arm-promote-constant-max-size", cl::Hidden,
132 cl::desc("Maximum size of constant to promote into a constant pool"),
134 static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
135 "arm-promote-constant-max-total", cl::Hidden,
136 cl::desc("Maximum size of ALL constants to promote into a constant pool"),
139 // The APCS parameter registers.
140 static const MCPhysReg GPRArgRegs[] = {
141 ARM::R0, ARM::R1, ARM::R2, ARM::R3
144 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
145 MVT PromotedBitwiseVT) {
146 if (VT != PromotedLdStVT) {
147 setOperationAction(ISD::LOAD, VT, Promote);
148 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
150 setOperationAction(ISD::STORE, VT, Promote);
151 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
154 MVT ElemTy = VT.getVectorElementType();
155 if (ElemTy != MVT::f64)
156 setOperationAction(ISD::SETCC, VT, Custom);
157 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
158 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
159 if (ElemTy == MVT::i32) {
160 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
161 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
162 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
163 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
165 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
166 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
167 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
168 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
170 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
171 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
172 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
173 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
174 setOperationAction(ISD::SELECT, VT, Expand);
175 setOperationAction(ISD::SELECT_CC, VT, Expand);
176 setOperationAction(ISD::VSELECT, VT, Expand);
177 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
178 if (VT.isInteger()) {
179 setOperationAction(ISD::SHL, VT, Custom);
180 setOperationAction(ISD::SRA, VT, Custom);
181 setOperationAction(ISD::SRL, VT, Custom);
184 // Promote all bit-wise operations.
185 if (VT.isInteger() && VT != PromotedBitwiseVT) {
186 setOperationAction(ISD::AND, VT, Promote);
187 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
188 setOperationAction(ISD::OR, VT, Promote);
189 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
190 setOperationAction(ISD::XOR, VT, Promote);
191 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
194 // Neon does not support vector divide/remainder operations.
195 setOperationAction(ISD::SDIV, VT, Expand);
196 setOperationAction(ISD::UDIV, VT, Expand);
197 setOperationAction(ISD::FDIV, VT, Expand);
198 setOperationAction(ISD::SREM, VT, Expand);
199 setOperationAction(ISD::UREM, VT, Expand);
200 setOperationAction(ISD::FREM, VT, Expand);
202 if (!VT.isFloatingPoint() &&
203 VT != MVT::v2i64 && VT != MVT::v1i64)
204 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
205 setOperationAction(Opcode, VT, Legal);
208 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
209 addRegisterClass(VT, &ARM::DPRRegClass);
210 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
213 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
214 addRegisterClass(VT, &ARM::DPairRegClass);
215 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
218 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
219 const ARMSubtarget &STI)
220 : TargetLowering(TM), Subtarget(&STI) {
221 RegInfo = Subtarget->getRegisterInfo();
222 Itins = Subtarget->getInstrItineraryData();
224 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
226 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
227 !Subtarget->isTargetWatchOS()) {
228 const auto &E = Subtarget->getTargetTriple().getEnvironment();
230 bool IsHFTarget = E == Triple::EABIHF || E == Triple::GNUEABIHF ||
231 E == Triple::MuslEABIHF;
232 // Windows is a special case. Technically, we will replace all of the "GNU"
233 // calls with calls to MSVCRT if appropriate and adjust the calling
235 IsHFTarget = IsHFTarget || Subtarget->isTargetWindows();
237 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
238 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
239 IsHFTarget ? CallingConv::ARM_AAPCS_VFP
240 : CallingConv::ARM_AAPCS);
243 if (Subtarget->isTargetMachO()) {
244 // Uses VFP for Thumb libfuncs if available.
245 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
246 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
247 static const struct {
248 const RTLIB::Libcall Op;
249 const char * const Name;
250 const ISD::CondCode Cond;
252 // Single-precision floating-point arithmetic.
253 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
254 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
255 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
256 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
258 // Double-precision floating-point arithmetic.
259 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
260 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
261 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
262 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
264 // Single-precision comparisons.
265 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
266 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
267 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
268 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
269 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
270 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
271 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
272 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
274 // Double-precision comparisons.
275 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
276 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
277 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
278 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
279 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
280 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
281 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
282 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
284 // Floating-point to integer conversions.
285 // i64 conversions are done via library routines even when generating VFP
286 // instructions, so use the same ones.
287 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
288 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
289 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
290 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
292 // Conversions between floating types.
293 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
294 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
296 // Integer to floating-point conversions.
297 // i64 conversions are done via library routines even when generating VFP
298 // instructions, so use the same ones.
299 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
300 // e.g., __floatunsidf vs. __floatunssidfvfp.
301 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
302 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
303 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
304 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
307 for (const auto &LC : LibraryCalls) {
308 setLibcallName(LC.Op, LC.Name);
309 if (LC.Cond != ISD::SETCC_INVALID)
310 setCmpLibcallCC(LC.Op, LC.Cond);
314 // Set the correct calling convention for ARMv7k WatchOS. It's just
315 // AAPCS_VFP for functions as simple as libcalls.
316 if (Subtarget->isTargetWatchABI()) {
317 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
318 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
322 // These libcalls are not available in 32-bit.
323 setLibcallName(RTLIB::SHL_I128, nullptr);
324 setLibcallName(RTLIB::SRL_I128, nullptr);
325 setLibcallName(RTLIB::SRA_I128, nullptr);
328 if (Subtarget->isAAPCS_ABI() &&
329 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
330 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
331 static const struct {
332 const RTLIB::Libcall Op;
333 const char * const Name;
334 const CallingConv::ID CC;
335 const ISD::CondCode Cond;
337 // Double-precision floating-point arithmetic helper functions
338 // RTABI chapter 4.1.2, Table 2
339 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 // Double-precision floating-point comparison helper functions
345 // RTABI chapter 4.1.2, Table 3
346 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
347 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
348 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
349 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
350 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
351 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
352 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
353 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
355 // Single-precision floating-point arithmetic helper functions
356 // RTABI chapter 4.1.2, Table 4
357 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
358 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
359 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
360 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
362 // Single-precision floating-point comparison helper functions
363 // RTABI chapter 4.1.2, Table 5
364 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
365 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
366 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
367 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
368 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
369 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
370 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
371 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
373 // Floating-point to integer conversions.
374 // RTABI chapter 4.1.2, Table 6
375 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
376 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
377 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
378 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
379 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
380 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
381 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
382 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
384 // Conversions between floating types.
385 // RTABI chapter 4.1.2, Table 7
386 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
387 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
388 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
390 // Integer to floating-point conversions.
391 // RTABI chapter 4.1.2, Table 8
392 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
393 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
394 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
395 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
396 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
397 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
398 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
399 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
401 // Long long helper functions
402 // RTABI chapter 4.2, Table 9
403 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
404 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
405 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
406 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
408 // Integer division functions
409 // RTABI chapter 4.3.1
410 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
411 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
412 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
413 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
414 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
415 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
416 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
417 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
420 for (const auto &LC : LibraryCalls) {
421 setLibcallName(LC.Op, LC.Name);
422 setLibcallCallingConv(LC.Op, LC.CC);
423 if (LC.Cond != ISD::SETCC_INVALID)
424 setCmpLibcallCC(LC.Op, LC.Cond);
427 // EABI dependent RTLIB
428 if (TM.Options.EABIVersion == EABI::EABI4 ||
429 TM.Options.EABIVersion == EABI::EABI5) {
430 static const struct {
431 const RTLIB::Libcall Op;
432 const char *const Name;
433 const CallingConv::ID CC;
434 const ISD::CondCode Cond;
435 } MemOpsLibraryCalls[] = {
437 // RTABI chapter 4.3.4
438 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
439 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
440 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
443 for (const auto &LC : MemOpsLibraryCalls) {
444 setLibcallName(LC.Op, LC.Name);
445 setLibcallCallingConv(LC.Op, LC.CC);
446 if (LC.Cond != ISD::SETCC_INVALID)
447 setCmpLibcallCC(LC.Op, LC.Cond);
452 if (Subtarget->isTargetWindows()) {
453 static const struct {
454 const RTLIB::Libcall Op;
455 const char * const Name;
456 const CallingConv::ID CC;
458 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
459 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
460 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
461 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
462 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
463 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
464 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
465 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
468 for (const auto &LC : LibraryCalls) {
469 setLibcallName(LC.Op, LC.Name);
470 setLibcallCallingConv(LC.Op, LC.CC);
474 // Use divmod compiler-rt calls for iOS 5.0 and later.
475 if (Subtarget->isTargetMachO() &&
476 !(Subtarget->isTargetIOS() &&
477 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
478 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
479 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
482 // The half <-> float conversion functions are always soft-float on
483 // non-watchos platforms, but are needed for some targets which use a
484 // hard-float calling convention by default.
485 if (!Subtarget->isTargetWatchABI()) {
486 if (Subtarget->isAAPCS_ABI()) {
487 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
488 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
489 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
491 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
492 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
493 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
497 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
498 // a __gnu_ prefix (which is the default).
499 if (Subtarget->isTargetAEABI()) {
500 static const struct {
501 const RTLIB::Libcall Op;
502 const char * const Name;
503 const CallingConv::ID CC;
505 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
506 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
507 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
510 for (const auto &LC : LibraryCalls) {
511 setLibcallName(LC.Op, LC.Name);
512 setLibcallCallingConv(LC.Op, LC.CC);
516 if (Subtarget->isThumb1Only())
517 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
519 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
521 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
522 !Subtarget->isThumb1Only()) {
523 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
524 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
527 for (MVT VT : MVT::vector_valuetypes()) {
528 for (MVT InnerVT : MVT::vector_valuetypes()) {
529 setTruncStoreAction(VT, InnerVT, Expand);
530 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
531 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
532 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
535 setOperationAction(ISD::MULHS, VT, Expand);
536 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
537 setOperationAction(ISD::MULHU, VT, Expand);
538 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
540 setOperationAction(ISD::BSWAP, VT, Expand);
543 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
544 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
546 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
547 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
549 if (Subtarget->hasNEON()) {
550 addDRTypeForNEON(MVT::v2f32);
551 addDRTypeForNEON(MVT::v8i8);
552 addDRTypeForNEON(MVT::v4i16);
553 addDRTypeForNEON(MVT::v2i32);
554 addDRTypeForNEON(MVT::v1i64);
556 addQRTypeForNEON(MVT::v4f32);
557 addQRTypeForNEON(MVT::v2f64);
558 addQRTypeForNEON(MVT::v16i8);
559 addQRTypeForNEON(MVT::v8i16);
560 addQRTypeForNEON(MVT::v4i32);
561 addQRTypeForNEON(MVT::v2i64);
563 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
564 // neither Neon nor VFP support any arithmetic operations on it.
565 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
566 // supported for v4f32.
567 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
568 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
569 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
570 // FIXME: Code duplication: FDIV and FREM are expanded always, see
571 // ARMTargetLowering::addTypeForNEON method for details.
572 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
573 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
574 // FIXME: Create unittest.
575 // In another words, find a way when "copysign" appears in DAG with vector
577 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
578 // FIXME: Code duplication: SETCC has custom operation action, see
579 // ARMTargetLowering::addTypeForNEON method for details.
580 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
581 // FIXME: Create unittest for FNEG and for FABS.
582 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
583 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
584 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
585 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
586 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
587 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
588 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
589 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
590 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
591 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
592 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
593 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
594 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
595 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
596 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
597 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
598 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
599 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
601 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
602 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
603 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
604 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
605 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
606 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
607 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
608 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
609 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
610 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
611 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
612 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
613 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
614 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
616 // Mark v2f32 intrinsics.
617 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
618 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
619 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
620 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
621 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
622 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
623 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
624 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
625 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
626 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
627 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
628 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
629 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
630 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
632 // Neon does not support some operations on v1i64 and v2i64 types.
633 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
634 // Custom handling for some quad-vector types to detect VMULL.
635 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
636 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
637 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
638 // Custom handling for some vector types to avoid expensive expansions
639 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
640 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
641 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
642 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
643 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
644 // a destination type that is wider than the source, and nor does
645 // it have a FP_TO_[SU]INT instruction with a narrower destination than
647 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
648 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
649 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
650 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
652 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
653 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
655 // NEON does not have single instruction CTPOP for vectors with element
656 // types wider than 8-bits. However, custom lowering can leverage the
657 // v8i8/v16i8 vcnt instruction.
658 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
659 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
660 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
661 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
662 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand);
663 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand);
665 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
666 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
668 // NEON does not have single instruction CTTZ for vectors.
669 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
670 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
671 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
672 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
674 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
675 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
676 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
677 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
679 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
680 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
681 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
682 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
684 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
685 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
686 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
687 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
689 // NEON only has FMA instructions as of VFP4.
690 if (!Subtarget->hasVFP4()) {
691 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
692 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
695 setTargetDAGCombine(ISD::INTRINSIC_VOID);
696 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
697 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
698 setTargetDAGCombine(ISD::SHL);
699 setTargetDAGCombine(ISD::SRL);
700 setTargetDAGCombine(ISD::SRA);
701 setTargetDAGCombine(ISD::SIGN_EXTEND);
702 setTargetDAGCombine(ISD::ZERO_EXTEND);
703 setTargetDAGCombine(ISD::ANY_EXTEND);
704 setTargetDAGCombine(ISD::BUILD_VECTOR);
705 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
706 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
707 setTargetDAGCombine(ISD::STORE);
708 setTargetDAGCombine(ISD::FP_TO_SINT);
709 setTargetDAGCombine(ISD::FP_TO_UINT);
710 setTargetDAGCombine(ISD::FDIV);
711 setTargetDAGCombine(ISD::LOAD);
713 // It is legal to extload from v4i8 to v4i16 or v4i32.
714 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
716 for (MVT VT : MVT::integer_vector_valuetypes()) {
717 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
718 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
719 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
724 if (Subtarget->isFPOnlySP()) {
725 // When targeting a floating-point unit with only single-precision
726 // operations, f64 is legal for the few double-precision instructions which
727 // are present However, no double-precision operations other than moves,
728 // loads and stores are provided by the hardware.
729 setOperationAction(ISD::FADD, MVT::f64, Expand);
730 setOperationAction(ISD::FSUB, MVT::f64, Expand);
731 setOperationAction(ISD::FMUL, MVT::f64, Expand);
732 setOperationAction(ISD::FMA, MVT::f64, Expand);
733 setOperationAction(ISD::FDIV, MVT::f64, Expand);
734 setOperationAction(ISD::FREM, MVT::f64, Expand);
735 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
736 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
737 setOperationAction(ISD::FNEG, MVT::f64, Expand);
738 setOperationAction(ISD::FABS, MVT::f64, Expand);
739 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
740 setOperationAction(ISD::FSIN, MVT::f64, Expand);
741 setOperationAction(ISD::FCOS, MVT::f64, Expand);
742 setOperationAction(ISD::FPOW, MVT::f64, Expand);
743 setOperationAction(ISD::FLOG, MVT::f64, Expand);
744 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
745 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
746 setOperationAction(ISD::FEXP, MVT::f64, Expand);
747 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
748 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
749 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
750 setOperationAction(ISD::FRINT, MVT::f64, Expand);
751 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
752 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
753 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
754 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
755 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
756 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
757 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
758 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
759 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
760 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
763 computeRegisterProperties(Subtarget->getRegisterInfo());
765 // ARM does not have floating-point extending loads.
766 for (MVT VT : MVT::fp_valuetypes()) {
767 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
768 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
771 // ... or truncating stores
772 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
773 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
774 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
776 // ARM does not have i1 sign extending load.
777 for (MVT VT : MVT::integer_valuetypes())
778 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
780 // ARM supports all 4 flavors of integer indexed load / store.
781 if (!Subtarget->isThumb1Only()) {
782 for (unsigned im = (unsigned)ISD::PRE_INC;
783 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
784 setIndexedLoadAction(im, MVT::i1, Legal);
785 setIndexedLoadAction(im, MVT::i8, Legal);
786 setIndexedLoadAction(im, MVT::i16, Legal);
787 setIndexedLoadAction(im, MVT::i32, Legal);
788 setIndexedStoreAction(im, MVT::i1, Legal);
789 setIndexedStoreAction(im, MVT::i8, Legal);
790 setIndexedStoreAction(im, MVT::i16, Legal);
791 setIndexedStoreAction(im, MVT::i32, Legal);
794 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
795 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal);
796 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal);
799 setOperationAction(ISD::SADDO, MVT::i32, Custom);
800 setOperationAction(ISD::UADDO, MVT::i32, Custom);
801 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
802 setOperationAction(ISD::USUBO, MVT::i32, Custom);
804 // i64 operation support.
805 setOperationAction(ISD::MUL, MVT::i64, Expand);
806 setOperationAction(ISD::MULHU, MVT::i32, Expand);
807 if (Subtarget->isThumb1Only()) {
808 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
809 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
811 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
812 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
813 setOperationAction(ISD::MULHS, MVT::i32, Expand);
815 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
816 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
817 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
818 setOperationAction(ISD::SRL, MVT::i64, Custom);
819 setOperationAction(ISD::SRA, MVT::i64, Custom);
820 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
822 setOperationAction(ISD::ADDC, MVT::i32, Custom);
823 setOperationAction(ISD::ADDE, MVT::i32, Custom);
824 setOperationAction(ISD::SUBC, MVT::i32, Custom);
825 setOperationAction(ISD::SUBE, MVT::i32, Custom);
827 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
828 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
830 // ARM does not have ROTL.
831 setOperationAction(ISD::ROTL, MVT::i32, Expand);
832 for (MVT VT : MVT::vector_valuetypes()) {
833 setOperationAction(ISD::ROTL, VT, Expand);
834 setOperationAction(ISD::ROTR, VT, Expand);
836 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
837 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
838 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
839 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
841 // @llvm.readcyclecounter requires the Performance Monitors extension.
842 // Default to the 0 expansion on unsupported platforms.
843 // FIXME: Technically there are older ARM CPUs that have
844 // implementation-specific ways of obtaining this information.
845 if (Subtarget->hasPerfMon())
846 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
848 // Only ARMv6 has BSWAP.
849 if (!Subtarget->hasV6Ops())
850 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
852 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
853 : Subtarget->hasDivideInARMMode();
855 // These are expanded into libcalls if the cpu doesn't have HW divider.
856 setOperationAction(ISD::SDIV, MVT::i32, LibCall);
857 setOperationAction(ISD::UDIV, MVT::i32, LibCall);
860 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
861 setOperationAction(ISD::SDIV, MVT::i32, Custom);
862 setOperationAction(ISD::UDIV, MVT::i32, Custom);
864 setOperationAction(ISD::SDIV, MVT::i64, Custom);
865 setOperationAction(ISD::UDIV, MVT::i64, Custom);
868 setOperationAction(ISD::SREM, MVT::i32, Expand);
869 setOperationAction(ISD::UREM, MVT::i32, Expand);
871 // Register based DivRem for AEABI (RTABI 4.2)
872 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
873 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
874 Subtarget->isTargetWindows()) {
875 setOperationAction(ISD::SREM, MVT::i64, Custom);
876 setOperationAction(ISD::UREM, MVT::i64, Custom);
877 HasStandaloneRem = false;
879 if (Subtarget->isTargetWindows()) {
881 const RTLIB::Libcall Op;
882 const char * const Name;
883 const CallingConv::ID CC;
885 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
886 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
887 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
888 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
890 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
891 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
892 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
893 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
896 for (const auto &LC : LibraryCalls) {
897 setLibcallName(LC.Op, LC.Name);
898 setLibcallCallingConv(LC.Op, LC.CC);
902 const RTLIB::Libcall Op;
903 const char * const Name;
904 const CallingConv::ID CC;
906 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
907 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
908 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
909 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
911 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
912 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
913 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
914 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
917 for (const auto &LC : LibraryCalls) {
918 setLibcallName(LC.Op, LC.Name);
919 setLibcallCallingConv(LC.Op, LC.CC);
923 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
924 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
925 setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
926 setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
928 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
929 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
932 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
933 for (auto &VT : {MVT::f32, MVT::f64})
934 setOperationAction(ISD::FPOWI, VT, Custom);
936 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
937 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
938 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
939 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
941 setOperationAction(ISD::TRAP, MVT::Other, Legal);
943 // Use the default implementation.
944 setOperationAction(ISD::VASTART, MVT::Other, Custom);
945 setOperationAction(ISD::VAARG, MVT::Other, Expand);
946 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
947 setOperationAction(ISD::VAEND, MVT::Other, Expand);
948 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
949 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
951 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
952 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
954 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
956 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
957 // the default expansion.
958 InsertFencesForAtomic = false;
959 if (Subtarget->hasAnyDataBarrier() &&
960 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
961 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
962 // to ldrex/strex loops already.
963 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
964 if (!Subtarget->isThumb() || !Subtarget->isMClass())
965 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
967 // On v8, we have particularly efficient implementations of atomic fences
968 // if they can be combined with nearby atomic loads and stores.
969 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) {
970 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
971 InsertFencesForAtomic = true;
974 // If there's anything we can use as a barrier, go through custom lowering
976 // If target has DMB in thumb, Fences can be inserted.
977 if (Subtarget->hasDataBarrier())
978 InsertFencesForAtomic = true;
980 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
981 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
983 // Set them all for expansion, which will force libcalls.
984 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
985 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
986 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
987 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
988 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
989 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
990 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
991 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
992 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
993 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
994 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
995 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
996 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
997 // Unordered/Monotonic case.
998 if (!InsertFencesForAtomic) {
999 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1000 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1004 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
1006 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1007 if (!Subtarget->hasV6Ops()) {
1008 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1009 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
1011 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1013 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1014 !Subtarget->isThumb1Only()) {
1015 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1016 // iff target supports vfp2.
1017 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1018 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1021 // We want to custom lower some of our intrinsics.
1022 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1023 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1024 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1025 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1026 if (Subtarget->useSjLjEH())
1027 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1029 setOperationAction(ISD::SETCC, MVT::i32, Expand);
1030 setOperationAction(ISD::SETCC, MVT::f32, Expand);
1031 setOperationAction(ISD::SETCC, MVT::f64, Expand);
1032 setOperationAction(ISD::SELECT, MVT::i32, Custom);
1033 setOperationAction(ISD::SELECT, MVT::f32, Custom);
1034 setOperationAction(ISD::SELECT, MVT::f64, Custom);
1035 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1036 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1037 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1039 // Thumb-1 cannot currently select ARMISD::SUBE.
1040 if (!Subtarget->isThumb1Only())
1041 setOperationAction(ISD::SETCCE, MVT::i32, Custom);
1043 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
1044 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
1045 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
1046 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
1047 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1049 // We don't support sin/cos/fmod/copysign/pow
1050 setOperationAction(ISD::FSIN, MVT::f64, Expand);
1051 setOperationAction(ISD::FSIN, MVT::f32, Expand);
1052 setOperationAction(ISD::FCOS, MVT::f32, Expand);
1053 setOperationAction(ISD::FCOS, MVT::f64, Expand);
1054 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1055 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1056 setOperationAction(ISD::FREM, MVT::f64, Expand);
1057 setOperationAction(ISD::FREM, MVT::f32, Expand);
1058 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1059 !Subtarget->isThumb1Only()) {
1060 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1061 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1063 setOperationAction(ISD::FPOW, MVT::f64, Expand);
1064 setOperationAction(ISD::FPOW, MVT::f32, Expand);
1066 if (!Subtarget->hasVFP4()) {
1067 setOperationAction(ISD::FMA, MVT::f64, Expand);
1068 setOperationAction(ISD::FMA, MVT::f32, Expand);
1071 // Various VFP goodness
1072 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1073 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1074 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
1075 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1076 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1079 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1080 if (!Subtarget->hasFP16()) {
1081 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1082 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1086 // Combine sin / cos into one node or libcall if possible.
1087 if (Subtarget->hasSinCos()) {
1088 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1089 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1090 if (Subtarget->isTargetWatchABI()) {
1091 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
1092 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
1094 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
1095 // For iOS, we don't want to the normal expansion of a libcall to
1096 // sincos. We want to issue a libcall to __sincos_stret.
1097 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1098 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1102 // FP-ARMv8 implements a lot of rounding-like FP operations.
1103 if (Subtarget->hasFPARMv8()) {
1104 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1105 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1106 setOperationAction(ISD::FROUND, MVT::f32, Legal);
1107 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1108 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1109 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1110 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1111 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1112 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1113 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1114 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1115 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1117 if (!Subtarget->isFPOnlySP()) {
1118 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1119 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1120 setOperationAction(ISD::FROUND, MVT::f64, Legal);
1121 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1122 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1123 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1124 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1125 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1129 if (Subtarget->hasNEON()) {
1130 // vmin and vmax aren't available in a scalar form, so we use
1131 // a NEON instruction with an undef lane instead.
1132 setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1133 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1134 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1135 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1136 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1137 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1140 // We have target-specific dag combine patterns for the following nodes:
1141 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1142 setTargetDAGCombine(ISD::ADD);
1143 setTargetDAGCombine(ISD::SUB);
1144 setTargetDAGCombine(ISD::MUL);
1145 setTargetDAGCombine(ISD::AND);
1146 setTargetDAGCombine(ISD::OR);
1147 setTargetDAGCombine(ISD::XOR);
1149 if (Subtarget->hasV6Ops())
1150 setTargetDAGCombine(ISD::SRL);
1152 setStackPointerRegisterToSaveRestore(ARM::SP);
1154 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1155 !Subtarget->hasVFP2())
1156 setSchedulingPreference(Sched::RegPressure);
1158 setSchedulingPreference(Sched::Hybrid);
1160 //// temporary - rewrite interface to use type
1161 MaxStoresPerMemset = 8;
1162 MaxStoresPerMemsetOptSize = 4;
1163 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1164 MaxStoresPerMemcpyOptSize = 2;
1165 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1166 MaxStoresPerMemmoveOptSize = 2;
1168 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1169 // are at least 4 bytes aligned.
1170 setMinStackArgumentAlignment(4);
1172 // Prefer likely predicted branches to selects on out-of-order cores.
1173 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1175 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1178 bool ARMTargetLowering::useSoftFloat() const {
1179 return Subtarget->useSoftFloat();
1182 // FIXME: It might make sense to define the representative register class as the
1183 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1184 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1185 // SPR's representative would be DPR_VFP2. This should work well if register
1186 // pressure tracking were modified such that a register use would increment the
1187 // pressure of the register class's representative and all of it's super
1188 // classes' representatives transitively. We have not implemented this because
1189 // of the difficulty prior to coalescing of modeling operand register classes
1190 // due to the common occurrence of cross class copies and subregister insertions
1192 std::pair<const TargetRegisterClass *, uint8_t>
1193 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1195 const TargetRegisterClass *RRC = nullptr;
1197 switch (VT.SimpleTy) {
1199 return TargetLowering::findRepresentativeClass(TRI, VT);
1200 // Use DPR as representative register class for all floating point
1201 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1202 // the cost is 1 for both f32 and f64.
1203 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1204 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1205 RRC = &ARM::DPRRegClass;
1206 // When NEON is used for SP, only half of the register file is available
1207 // because operations that define both SP and DP results will be constrained
1208 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1209 // coalescing by double-counting the SP regs. See the FIXME above.
1210 if (Subtarget->useNEONForSinglePrecisionFP())
1213 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1214 case MVT::v4f32: case MVT::v2f64:
1215 RRC = &ARM::DPRRegClass;
1219 RRC = &ARM::DPRRegClass;
1223 RRC = &ARM::DPRRegClass;
1227 return std::make_pair(RRC, Cost);
1230 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1231 switch ((ARMISD::NodeType)Opcode) {
1232 case ARMISD::FIRST_NUMBER: break;
1233 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1234 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1235 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1236 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1237 case ARMISD::CALL: return "ARMISD::CALL";
1238 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1239 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1240 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1241 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1242 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1243 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1244 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1245 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1246 case ARMISD::CMP: return "ARMISD::CMP";
1247 case ARMISD::CMN: return "ARMISD::CMN";
1248 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1249 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1250 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1251 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1252 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1254 case ARMISD::CMOV: return "ARMISD::CMOV";
1256 case ARMISD::SSAT: return "ARMISD::SSAT";
1258 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1259 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1260 case ARMISD::RRX: return "ARMISD::RRX";
1262 case ARMISD::ADDC: return "ARMISD::ADDC";
1263 case ARMISD::ADDE: return "ARMISD::ADDE";
1264 case ARMISD::SUBC: return "ARMISD::SUBC";
1265 case ARMISD::SUBE: return "ARMISD::SUBE";
1267 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1268 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1270 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1271 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1272 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1274 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1276 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1278 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1280 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1282 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1284 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK";
1285 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1287 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1288 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1289 case ARMISD::VCGE: return "ARMISD::VCGE";
1290 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1291 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1292 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1293 case ARMISD::VCGT: return "ARMISD::VCGT";
1294 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1295 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1296 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1297 case ARMISD::VTST: return "ARMISD::VTST";
1299 case ARMISD::VSHL: return "ARMISD::VSHL";
1300 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1301 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1302 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1303 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1304 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1305 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1306 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1307 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1308 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1309 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1310 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1311 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1312 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1313 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1314 case ARMISD::VSLI: return "ARMISD::VSLI";
1315 case ARMISD::VSRI: return "ARMISD::VSRI";
1316 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1317 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1318 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1319 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1320 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1321 case ARMISD::VDUP: return "ARMISD::VDUP";
1322 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1323 case ARMISD::VEXT: return "ARMISD::VEXT";
1324 case ARMISD::VREV64: return "ARMISD::VREV64";
1325 case ARMISD::VREV32: return "ARMISD::VREV32";
1326 case ARMISD::VREV16: return "ARMISD::VREV16";
1327 case ARMISD::VZIP: return "ARMISD::VZIP";
1328 case ARMISD::VUZP: return "ARMISD::VUZP";
1329 case ARMISD::VTRN: return "ARMISD::VTRN";
1330 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1331 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1332 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1333 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1334 case ARMISD::UMAAL: return "ARMISD::UMAAL";
1335 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1336 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1337 case ARMISD::SMLALBB: return "ARMISD::SMLALBB";
1338 case ARMISD::SMLALBT: return "ARMISD::SMLALBT";
1339 case ARMISD::SMLALTB: return "ARMISD::SMLALTB";
1340 case ARMISD::SMLALTT: return "ARMISD::SMLALTT";
1341 case ARMISD::SMULWB: return "ARMISD::SMULWB";
1342 case ARMISD::SMULWT: return "ARMISD::SMULWT";
1343 case ARMISD::SMLALD: return "ARMISD::SMLALD";
1344 case ARMISD::SMLALDX: return "ARMISD::SMLALDX";
1345 case ARMISD::SMLSLD: return "ARMISD::SMLSLD";
1346 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX";
1347 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1348 case ARMISD::BFI: return "ARMISD::BFI";
1349 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1350 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1351 case ARMISD::VBSL: return "ARMISD::VBSL";
1352 case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1353 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP";
1354 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1355 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1356 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1357 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1358 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1359 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1360 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1361 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1362 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1363 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1364 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD";
1365 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1366 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1367 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1368 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1369 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1370 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1371 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1372 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1373 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1374 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1379 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1382 return getPointerTy(DL);
1383 return VT.changeVectorElementTypeToInteger();
1386 /// getRegClassFor - Return the register class that should be used for the
1387 /// specified value type.
1388 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1389 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1390 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1391 // load / store 4 to 8 consecutive D registers.
1392 if (Subtarget->hasNEON()) {
1393 if (VT == MVT::v4i64)
1394 return &ARM::QQPRRegClass;
1395 if (VT == MVT::v8i64)
1396 return &ARM::QQQQPRRegClass;
1398 return TargetLowering::getRegClassFor(VT);
1401 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1402 // source/dest is aligned and the copy size is large enough. We therefore want
1403 // to align such objects passed to memory intrinsics.
1404 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1405 unsigned &PrefAlign) const {
1406 if (!isa<MemIntrinsic>(CI))
1409 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1410 // cycle faster than 4-byte aligned LDM.
1411 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1415 // Create a fast isel object.
1417 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1418 const TargetLibraryInfo *libInfo) const {
1419 return ARM::createFastISel(funcInfo, libInfo);
1422 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1423 unsigned NumVals = N->getNumValues();
1425 return Sched::RegPressure;
1427 for (unsigned i = 0; i != NumVals; ++i) {
1428 EVT VT = N->getValueType(i);
1429 if (VT == MVT::Glue || VT == MVT::Other)
1431 if (VT.isFloatingPoint() || VT.isVector())
1435 if (!N->isMachineOpcode())
1436 return Sched::RegPressure;
1438 // Load are scheduled for latency even if there instruction itinerary
1439 // is not available.
1440 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1441 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1443 if (MCID.getNumDefs() == 0)
1444 return Sched::RegPressure;
1445 if (!Itins->isEmpty() &&
1446 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1449 return Sched::RegPressure;
1452 //===----------------------------------------------------------------------===//
1454 //===----------------------------------------------------------------------===//
1456 static bool isSRL16(const SDValue &Op) {
1457 if (Op.getOpcode() != ISD::SRL)
1459 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1460 return Const->getZExtValue() == 16;
1464 static bool isSRA16(const SDValue &Op) {
1465 if (Op.getOpcode() != ISD::SRA)
1467 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1468 return Const->getZExtValue() == 16;
1472 static bool isSHL16(const SDValue &Op) {
1473 if (Op.getOpcode() != ISD::SHL)
1475 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1476 return Const->getZExtValue() == 16;
1480 // Check for a signed 16-bit value. We special case SRA because it makes it
1481 // more simple when also looking for SRAs that aren't sign extending a
1482 // smaller value. Without the check, we'd need to take extra care with
1483 // checking order for some operations.
1484 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1486 return isSHL16(Op.getOperand(0));
1487 return DAG.ComputeNumSignBits(Op) == 17;
1490 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1491 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1493 default: llvm_unreachable("Unknown condition code!");
1494 case ISD::SETNE: return ARMCC::NE;
1495 case ISD::SETEQ: return ARMCC::EQ;
1496 case ISD::SETGT: return ARMCC::GT;
1497 case ISD::SETGE: return ARMCC::GE;
1498 case ISD::SETLT: return ARMCC::LT;
1499 case ISD::SETLE: return ARMCC::LE;
1500 case ISD::SETUGT: return ARMCC::HI;
1501 case ISD::SETUGE: return ARMCC::HS;
1502 case ISD::SETULT: return ARMCC::LO;
1503 case ISD::SETULE: return ARMCC::LS;
1507 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1508 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1509 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1510 CondCode2 = ARMCC::AL;
1511 InvalidOnQNaN = true;
1513 default: llvm_unreachable("Unknown FP condition!");
1516 CondCode = ARMCC::EQ;
1517 InvalidOnQNaN = false;
1520 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1522 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1523 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1524 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1526 CondCode = ARMCC::MI;
1527 CondCode2 = ARMCC::GT;
1528 InvalidOnQNaN = false;
1530 case ISD::SETO: CondCode = ARMCC::VC; break;
1531 case ISD::SETUO: CondCode = ARMCC::VS; break;
1533 CondCode = ARMCC::EQ;
1534 CondCode2 = ARMCC::VS;
1535 InvalidOnQNaN = false;
1537 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1538 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1540 case ISD::SETULT: CondCode = ARMCC::LT; break;
1542 case ISD::SETULE: CondCode = ARMCC::LE; break;
1545 CondCode = ARMCC::NE;
1546 InvalidOnQNaN = false;
1551 //===----------------------------------------------------------------------===//
1552 // Calling Convention Implementation
1553 //===----------------------------------------------------------------------===//
1555 #include "ARMGenCallingConv.inc"
1557 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1558 /// account presence of floating point hardware and calling convention
1559 /// limitations, such as support for variadic functions.
1561 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1562 bool isVarArg) const {
1565 llvm_unreachable("Unsupported calling convention");
1566 case CallingConv::ARM_AAPCS:
1567 case CallingConv::ARM_APCS:
1568 case CallingConv::GHC:
1570 case CallingConv::PreserveMost:
1571 return CallingConv::PreserveMost;
1572 case CallingConv::ARM_AAPCS_VFP:
1573 case CallingConv::Swift:
1574 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1575 case CallingConv::C:
1576 if (!Subtarget->isAAPCS_ABI())
1577 return CallingConv::ARM_APCS;
1578 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1579 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1581 return CallingConv::ARM_AAPCS_VFP;
1583 return CallingConv::ARM_AAPCS;
1584 case CallingConv::Fast:
1585 case CallingConv::CXX_FAST_TLS:
1586 if (!Subtarget->isAAPCS_ABI()) {
1587 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1588 return CallingConv::Fast;
1589 return CallingConv::ARM_APCS;
1590 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1591 return CallingConv::ARM_AAPCS_VFP;
1593 return CallingConv::ARM_AAPCS;
1597 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1598 bool isVarArg) const {
1599 return CCAssignFnForNode(CC, false, isVarArg);
1602 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1603 bool isVarArg) const {
1604 return CCAssignFnForNode(CC, true, isVarArg);
1607 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1608 /// CallingConvention.
1609 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1611 bool isVarArg) const {
1612 switch (getEffectiveCallingConv(CC, isVarArg)) {
1614 llvm_unreachable("Unsupported calling convention");
1615 case CallingConv::ARM_APCS:
1616 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1617 case CallingConv::ARM_AAPCS:
1618 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1619 case CallingConv::ARM_AAPCS_VFP:
1620 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1621 case CallingConv::Fast:
1622 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1623 case CallingConv::GHC:
1624 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1625 case CallingConv::PreserveMost:
1626 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1630 /// LowerCallResult - Lower the result values of a call into the
1631 /// appropriate copies out of appropriate physical registers.
1632 SDValue ARMTargetLowering::LowerCallResult(
1633 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1634 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1635 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1636 SDValue ThisVal) const {
1638 // Assign locations to each value returned by this call.
1639 SmallVector<CCValAssign, 16> RVLocs;
1640 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1642 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1644 // Copy all of the result registers out of their specified physreg.
1645 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1646 CCValAssign VA = RVLocs[i];
1648 // Pass 'this' value directly from the argument to return value, to avoid
1649 // reg unit interference
1650 if (i == 0 && isThisReturn) {
1651 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1652 "unexpected return calling convention register assignment");
1653 InVals.push_back(ThisVal);
1658 if (VA.needsCustom()) {
1659 // Handle f64 or half of a v2f64.
1660 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1662 Chain = Lo.getValue(1);
1663 InFlag = Lo.getValue(2);
1664 VA = RVLocs[++i]; // skip ahead to next loc
1665 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1667 Chain = Hi.getValue(1);
1668 InFlag = Hi.getValue(2);
1669 if (!Subtarget->isLittle())
1671 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1673 if (VA.getLocVT() == MVT::v2f64) {
1674 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1675 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1676 DAG.getConstant(0, dl, MVT::i32));
1678 VA = RVLocs[++i]; // skip ahead to next loc
1679 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1680 Chain = Lo.getValue(1);
1681 InFlag = Lo.getValue(2);
1682 VA = RVLocs[++i]; // skip ahead to next loc
1683 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1684 Chain = Hi.getValue(1);
1685 InFlag = Hi.getValue(2);
1686 if (!Subtarget->isLittle())
1688 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1689 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1690 DAG.getConstant(1, dl, MVT::i32));
1693 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1695 Chain = Val.getValue(1);
1696 InFlag = Val.getValue(2);
1699 switch (VA.getLocInfo()) {
1700 default: llvm_unreachable("Unknown loc info!");
1701 case CCValAssign::Full: break;
1702 case CCValAssign::BCvt:
1703 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1707 InVals.push_back(Val);
1713 /// LowerMemOpCallTo - Store the argument to the stack.
1714 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1715 SDValue Arg, const SDLoc &dl,
1717 const CCValAssign &VA,
1718 ISD::ArgFlagsTy Flags) const {
1719 unsigned LocMemOffset = VA.getLocMemOffset();
1720 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1721 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1723 return DAG.getStore(
1724 Chain, dl, Arg, PtrOff,
1725 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1728 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1729 SDValue Chain, SDValue &Arg,
1730 RegsToPassVector &RegsToPass,
1731 CCValAssign &VA, CCValAssign &NextVA,
1733 SmallVectorImpl<SDValue> &MemOpChains,
1734 ISD::ArgFlagsTy Flags) const {
1736 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1737 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1738 unsigned id = Subtarget->isLittle() ? 0 : 1;
1739 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1741 if (NextVA.isRegLoc())
1742 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1744 assert(NextVA.isMemLoc());
1745 if (!StackPtr.getNode())
1746 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1747 getPointerTy(DAG.getDataLayout()));
1749 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1755 /// LowerCall - Lowering a call into a callseq_start <-
1756 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1759 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1760 SmallVectorImpl<SDValue> &InVals) const {
1761 SelectionDAG &DAG = CLI.DAG;
1763 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1764 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1765 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1766 SDValue Chain = CLI.Chain;
1767 SDValue Callee = CLI.Callee;
1768 bool &isTailCall = CLI.IsTailCall;
1769 CallingConv::ID CallConv = CLI.CallConv;
1770 bool doesNotRet = CLI.DoesNotReturn;
1771 bool isVarArg = CLI.IsVarArg;
1773 MachineFunction &MF = DAG.getMachineFunction();
1774 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1775 bool isThisReturn = false;
1776 bool isSibCall = false;
1777 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1779 // Disable tail calls if they're not supported.
1780 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1784 // Check if it's really possible to do a tail call.
1785 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1786 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1787 Outs, OutVals, Ins, DAG);
1788 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1789 report_fatal_error("failed to perform tail call elimination on a call "
1790 "site marked musttail");
1791 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1792 // detected sibcalls.
1799 // Analyze operands of the call, assigning locations to each operand.
1800 SmallVector<CCValAssign, 16> ArgLocs;
1801 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1803 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
1805 // Get a count of how many bytes are to be pushed on the stack.
1806 unsigned NumBytes = CCInfo.getNextStackOffset();
1808 // For tail calls, memory operands are available in our caller's stack.
1812 // Adjust the stack pointer for the new arguments...
1813 // These operations are automatically eliminated by the prolog/epilog pass
1815 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
1818 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1820 RegsToPassVector RegsToPass;
1821 SmallVector<SDValue, 8> MemOpChains;
1823 // Walk the register/memloc assignments, inserting copies/loads. In the case
1824 // of tail call optimization, arguments are handled later.
1825 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1827 ++i, ++realArgIdx) {
1828 CCValAssign &VA = ArgLocs[i];
1829 SDValue Arg = OutVals[realArgIdx];
1830 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1831 bool isByVal = Flags.isByVal();
1833 // Promote the value if needed.
1834 switch (VA.getLocInfo()) {
1835 default: llvm_unreachable("Unknown loc info!");
1836 case CCValAssign::Full: break;
1837 case CCValAssign::SExt:
1838 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1840 case CCValAssign::ZExt:
1841 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1843 case CCValAssign::AExt:
1844 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1846 case CCValAssign::BCvt:
1847 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1851 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1852 if (VA.needsCustom()) {
1853 if (VA.getLocVT() == MVT::v2f64) {
1854 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1855 DAG.getConstant(0, dl, MVT::i32));
1856 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1857 DAG.getConstant(1, dl, MVT::i32));
1859 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1860 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1862 VA = ArgLocs[++i]; // skip ahead to next loc
1863 if (VA.isRegLoc()) {
1864 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1865 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1867 assert(VA.isMemLoc());
1869 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1870 dl, DAG, VA, Flags));
1873 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1874 StackPtr, MemOpChains, Flags);
1876 } else if (VA.isRegLoc()) {
1877 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
1878 Outs[0].VT == MVT::i32) {
1879 assert(VA.getLocVT() == MVT::i32 &&
1880 "unexpected calling convention register assignment");
1881 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1882 "unexpected use of 'returned'");
1883 isThisReturn = true;
1885 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1886 } else if (isByVal) {
1887 assert(VA.isMemLoc());
1888 unsigned offset = 0;
1890 // True if this byval aggregate will be split between registers
1892 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1893 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1895 if (CurByValIdx < ByValArgsCount) {
1897 unsigned RegBegin, RegEnd;
1898 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1901 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1903 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1904 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1905 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1906 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1907 MachinePointerInfo(),
1908 DAG.InferPtrAlignment(AddArg));
1909 MemOpChains.push_back(Load.getValue(1));
1910 RegsToPass.push_back(std::make_pair(j, Load));
1913 // If parameter size outsides register area, "offset" value
1914 // helps us to calculate stack slot for remained part properly.
1915 offset = RegEnd - RegBegin;
1917 CCInfo.nextInRegsParam();
1920 if (Flags.getByValSize() > 4*offset) {
1921 auto PtrVT = getPointerTy(DAG.getDataLayout());
1922 unsigned LocMemOffset = VA.getLocMemOffset();
1923 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1924 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1925 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1926 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1927 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1929 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1932 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1933 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1934 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1937 } else if (!isSibCall) {
1938 assert(VA.isMemLoc());
1940 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1941 dl, DAG, VA, Flags));
1945 if (!MemOpChains.empty())
1946 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1948 // Build a sequence of copy-to-reg nodes chained together with token chain
1949 // and flag operands which copy the outgoing args into the appropriate regs.
1951 // Tail call byval lowering might overwrite argument registers so in case of
1952 // tail call optimization the copies to registers are lowered later.
1954 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1955 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1956 RegsToPass[i].second, InFlag);
1957 InFlag = Chain.getValue(1);
1960 // For tail calls lower the arguments to the 'real' stack slot.
1962 // Force all the incoming stack arguments to be loaded from the stack
1963 // before any new outgoing arguments are stored to the stack, because the
1964 // outgoing stack slots may alias the incoming argument stack slots, and
1965 // the alias isn't otherwise explicit. This is slightly more conservative
1966 // than necessary, because it means that each store effectively depends
1967 // on every argument instead of just those arguments it would clobber.
1969 // Do not flag preceding copytoreg stuff together with the following stuff.
1971 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1972 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1973 RegsToPass[i].second, InFlag);
1974 InFlag = Chain.getValue(1);
1979 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1980 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1981 // node so that legalize doesn't hack it.
1982 bool isDirect = false;
1984 const TargetMachine &TM = getTargetMachine();
1985 const Module *Mod = MF.getFunction()->getParent();
1986 const GlobalValue *GV = nullptr;
1987 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1988 GV = G->getGlobal();
1990 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
1992 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1993 bool isLocalARMFunc = false;
1994 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1995 auto PtrVt = getPointerTy(DAG.getDataLayout());
1997 if (Subtarget->genLongCalls()) {
1998 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
1999 "long-calls codegen is not position independent!");
2000 // Handle a global address or an external symbol. If it's not one of
2001 // those, the target's already in a register, so we don't need to do
2003 if (isa<GlobalAddressSDNode>(Callee)) {
2004 // Create a constant pool entry for the callee address
2005 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2006 ARMConstantPoolValue *CPV =
2007 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2009 // Get the address of the callee into a register
2010 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2011 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2012 Callee = DAG.getLoad(
2013 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2014 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2015 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2016 const char *Sym = S->getSymbol();
2018 // Create a constant pool entry for the callee address
2019 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2020 ARMConstantPoolValue *CPV =
2021 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2022 ARMPCLabelIndex, 0);
2023 // Get the address of the callee into a register
2024 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2025 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2026 Callee = DAG.getLoad(
2027 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2028 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2030 } else if (isa<GlobalAddressSDNode>(Callee)) {
2031 // If we're optimizing for minimum size and the function is called three or
2032 // more times in this block, we can improve codesize by calling indirectly
2033 // as BLXr has a 16-bit encoding.
2034 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2035 auto *BB = CLI.CS->getParent();
2036 bool PreferIndirect =
2037 Subtarget->isThumb() && MF.getFunction()->optForMinSize() &&
2038 count_if(GV->users(), [&BB](const User *U) {
2039 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
2042 if (!PreferIndirect) {
2044 bool isDef = GV->isStrongDefinitionForLinker();
2046 // ARM call to a local ARM function is predicable.
2047 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2048 // tBX takes a register source operand.
2049 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2050 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2051 Callee = DAG.getNode(
2052 ARMISD::WrapperPIC, dl, PtrVt,
2053 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2054 Callee = DAG.getLoad(
2055 PtrVt, dl, DAG.getEntryNode(), Callee,
2056 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2057 /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2058 MachineMemOperand::MOInvariant);
2059 } else if (Subtarget->isTargetCOFF()) {
2060 assert(Subtarget->isTargetWindows() &&
2061 "Windows is the only supported COFF target");
2062 unsigned TargetFlags = GV->hasDLLImportStorageClass()
2063 ? ARMII::MO_DLLIMPORT
2064 : ARMII::MO_NO_FLAG;
2065 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2067 if (GV->hasDLLImportStorageClass())
2069 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2070 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2071 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2073 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2076 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2078 // tBX takes a register source operand.
2079 const char *Sym = S->getSymbol();
2080 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2081 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2082 ARMConstantPoolValue *CPV =
2083 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2084 ARMPCLabelIndex, 4);
2085 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2086 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2087 Callee = DAG.getLoad(
2088 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2089 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2090 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2091 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2093 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2097 // FIXME: handle tail calls differently.
2099 if (Subtarget->isThumb()) {
2100 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2101 CallOpc = ARMISD::CALL_NOLINK;
2103 CallOpc = ARMISD::CALL;
2105 if (!isDirect && !Subtarget->hasV5TOps())
2106 CallOpc = ARMISD::CALL_NOLINK;
2107 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2108 // Emit regular call when code size is the priority
2109 !MF.getFunction()->optForMinSize())
2110 // "mov lr, pc; b _foo" to avoid confusing the RSP
2111 CallOpc = ARMISD::CALL_NOLINK;
2113 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2116 std::vector<SDValue> Ops;
2117 Ops.push_back(Chain);
2118 Ops.push_back(Callee);
2120 // Add argument registers to the end of the list so that they are known live
2122 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2123 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2124 RegsToPass[i].second.getValueType()));
2126 // Add a register mask operand representing the call-preserved registers.
2128 const uint32_t *Mask;
2129 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2131 // For 'this' returns, use the R0-preserving mask if applicable
2132 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2134 // Set isThisReturn to false if the calling convention is not one that
2135 // allows 'returned' to be modeled in this way, so LowerCallResult does
2136 // not try to pass 'this' straight through
2137 isThisReturn = false;
2138 Mask = ARI->getCallPreservedMask(MF, CallConv);
2141 Mask = ARI->getCallPreservedMask(MF, CallConv);
2143 assert(Mask && "Missing call preserved mask for calling convention");
2144 Ops.push_back(DAG.getRegisterMask(Mask));
2147 if (InFlag.getNode())
2148 Ops.push_back(InFlag);
2150 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2152 MF.getFrameInfo().setHasTailCall();
2153 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2156 // Returns a chain and a flag for retval copy to use.
2157 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2158 InFlag = Chain.getValue(1);
2160 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2161 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2163 InFlag = Chain.getValue(1);
2165 // Handle result values, copying them out of physregs into vregs that we
2167 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2168 InVals, isThisReturn,
2169 isThisReturn ? OutVals[0] : SDValue());
2172 /// HandleByVal - Every parameter *after* a byval parameter is passed
2173 /// on the stack. Remember the next parameter register to allocate,
2174 /// and then confiscate the rest of the parameter registers to insure
2176 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2177 unsigned Align) const {
2178 // Byval (as with any stack) slots are always at least 4 byte aligned.
2179 Align = std::max(Align, 4U);
2181 unsigned Reg = State->AllocateReg(GPRArgRegs);
2185 unsigned AlignInRegs = Align / 4;
2186 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2187 for (unsigned i = 0; i < Waste; ++i)
2188 Reg = State->AllocateReg(GPRArgRegs);
2193 unsigned Excess = 4 * (ARM::R4 - Reg);
2195 // Special case when NSAA != SP and parameter size greater than size of
2196 // all remained GPR regs. In that case we can't split parameter, we must
2197 // send it to stack. We also must set NCRN to R4, so waste all
2198 // remained registers.
2199 const unsigned NSAAOffset = State->getNextStackOffset();
2200 if (NSAAOffset != 0 && Size > Excess) {
2201 while (State->AllocateReg(GPRArgRegs))
2206 // First register for byval parameter is the first register that wasn't
2207 // allocated before this method call, so it would be "reg".
2208 // If parameter is small enough to be saved in range [reg, r4), then
2209 // the end (first after last) register would be reg + param-size-in-regs,
2210 // else parameter would be splitted between registers and stack,
2211 // end register would be r4 in this case.
2212 unsigned ByValRegBegin = Reg;
2213 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2214 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2215 // Note, first register is allocated in the beginning of function already,
2216 // allocate remained amount of registers we need.
2217 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2218 State->AllocateReg(GPRArgRegs);
2219 // A byval parameter that is split between registers and memory needs its
2220 // size truncated here.
2221 // In the case where the entire structure fits in registers, we set the
2222 // size in memory to zero.
2223 Size = std::max<int>(Size - Excess, 0);
2226 /// MatchingStackOffset - Return true if the given stack call argument is
2227 /// already available in the same position (relatively) of the caller's
2228 /// incoming argument stack.
2230 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2231 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2232 const TargetInstrInfo *TII) {
2233 unsigned Bytes = Arg.getValueSizeInBits() / 8;
2234 int FI = std::numeric_limits<int>::max();
2235 if (Arg.getOpcode() == ISD::CopyFromReg) {
2236 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2237 if (!TargetRegisterInfo::isVirtualRegister(VR))
2239 MachineInstr *Def = MRI->getVRegDef(VR);
2242 if (!Flags.isByVal()) {
2243 if (!TII->isLoadFromStackSlot(*Def, FI))
2248 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2249 if (Flags.isByVal())
2250 // ByVal argument is passed in as a pointer but it's now being
2251 // dereferenced. e.g.
2252 // define @foo(%struct.X* %A) {
2253 // tail call @bar(%struct.X* byval %A)
2256 SDValue Ptr = Ld->getBasePtr();
2257 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2260 FI = FINode->getIndex();
2264 assert(FI != std::numeric_limits<int>::max());
2265 if (!MFI.isFixedObjectIndex(FI))
2267 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2270 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2271 /// for tail call optimization. Targets which want to do tail call
2272 /// optimization should implement this function.
2274 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2275 CallingConv::ID CalleeCC,
2277 bool isCalleeStructRet,
2278 bool isCallerStructRet,
2279 const SmallVectorImpl<ISD::OutputArg> &Outs,
2280 const SmallVectorImpl<SDValue> &OutVals,
2281 const SmallVectorImpl<ISD::InputArg> &Ins,
2282 SelectionDAG& DAG) const {
2283 MachineFunction &MF = DAG.getMachineFunction();
2284 const Function *CallerF = MF.getFunction();
2285 CallingConv::ID CallerCC = CallerF->getCallingConv();
2287 assert(Subtarget->supportsTailCall());
2289 // Look for obvious safe cases to perform tail call optimization that do not
2290 // require ABI changes. This is what gcc calls sibcall.
2292 // Exception-handling functions need a special set of instructions to indicate
2293 // a return to the hardware. Tail-calling another function would probably
2295 if (CallerF->hasFnAttribute("interrupt"))
2298 // Also avoid sibcall optimization if either caller or callee uses struct
2299 // return semantics.
2300 if (isCalleeStructRet || isCallerStructRet)
2303 // Externally-defined functions with weak linkage should not be
2304 // tail-called on ARM when the OS does not support dynamic
2305 // pre-emption of symbols, as the AAELF spec requires normal calls
2306 // to undefined weak functions to be replaced with a NOP or jump to the
2307 // next instruction. The behaviour of branch instructions in this
2308 // situation (as used for tail calls) is implementation-defined, so we
2309 // cannot rely on the linker replacing the tail call with a return.
2310 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2311 const GlobalValue *GV = G->getGlobal();
2312 const Triple &TT = getTargetMachine().getTargetTriple();
2313 if (GV->hasExternalWeakLinkage() &&
2314 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2318 // Check that the call results are passed in the same way.
2319 LLVMContext &C = *DAG.getContext();
2320 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2321 CCAssignFnForReturn(CalleeCC, isVarArg),
2322 CCAssignFnForReturn(CallerCC, isVarArg)))
2324 // The callee has to preserve all registers the caller needs to preserve.
2325 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2326 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2327 if (CalleeCC != CallerCC) {
2328 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2329 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2333 // If Caller's vararg or byval argument has been split between registers and
2334 // stack, do not perform tail call, since part of the argument is in caller's
2336 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2337 if (AFI_Caller->getArgRegsSaveSize())
2340 // If the callee takes no arguments then go on to check the results of the
2342 if (!Outs.empty()) {
2343 // Check if stack adjustment is needed. For now, do not do this if any
2344 // argument is passed on the stack.
2345 SmallVector<CCValAssign, 16> ArgLocs;
2346 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2347 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2348 if (CCInfo.getNextStackOffset()) {
2349 // Check if the arguments are already laid out in the right way as
2350 // the caller's fixed stack objects.
2351 MachineFrameInfo &MFI = MF.getFrameInfo();
2352 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2353 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2354 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2356 ++i, ++realArgIdx) {
2357 CCValAssign &VA = ArgLocs[i];
2358 EVT RegVT = VA.getLocVT();
2359 SDValue Arg = OutVals[realArgIdx];
2360 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2361 if (VA.getLocInfo() == CCValAssign::Indirect)
2363 if (VA.needsCustom()) {
2364 // f64 and vector types are split into multiple registers or
2365 // register/stack-slot combinations. The types will not match
2366 // the registers; give up on memory f64 refs until we figure
2367 // out what to do about this.
2370 if (!ArgLocs[++i].isRegLoc())
2372 if (RegVT == MVT::v2f64) {
2373 if (!ArgLocs[++i].isRegLoc())
2375 if (!ArgLocs[++i].isRegLoc())
2378 } else if (!VA.isRegLoc()) {
2379 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2386 const MachineRegisterInfo &MRI = MF.getRegInfo();
2387 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2395 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2396 MachineFunction &MF, bool isVarArg,
2397 const SmallVectorImpl<ISD::OutputArg> &Outs,
2398 LLVMContext &Context) const {
2399 SmallVector<CCValAssign, 16> RVLocs;
2400 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2401 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2404 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2405 const SDLoc &DL, SelectionDAG &DAG) {
2406 const MachineFunction &MF = DAG.getMachineFunction();
2407 const Function *F = MF.getFunction();
2409 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2411 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2412 // version of the "preferred return address". These offsets affect the return
2413 // instruction if this is a return from PL1 without hypervisor extensions.
2414 // IRQ/FIQ: +4 "subs pc, lr, #4"
2415 // SWI: 0 "subs pc, lr, #0"
2416 // ABORT: +4 "subs pc, lr, #4"
2417 // UNDEF: +4/+2 "subs pc, lr, #0"
2418 // UNDEF varies depending on where the exception came from ARM or Thumb
2419 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2422 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2425 else if (IntKind == "SWI" || IntKind == "UNDEF")
2428 report_fatal_error("Unsupported interrupt attribute. If present, value "
2429 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2431 RetOps.insert(RetOps.begin() + 1,
2432 DAG.getConstant(LROffset, DL, MVT::i32, false));
2434 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2438 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2440 const SmallVectorImpl<ISD::OutputArg> &Outs,
2441 const SmallVectorImpl<SDValue> &OutVals,
2442 const SDLoc &dl, SelectionDAG &DAG) const {
2444 // CCValAssign - represent the assignment of the return value to a location.
2445 SmallVector<CCValAssign, 16> RVLocs;
2447 // CCState - Info about the registers and stack slots.
2448 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2451 // Analyze outgoing return values.
2452 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2455 SmallVector<SDValue, 4> RetOps;
2456 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2457 bool isLittleEndian = Subtarget->isLittle();
2459 MachineFunction &MF = DAG.getMachineFunction();
2460 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2461 AFI->setReturnRegsCount(RVLocs.size());
2463 // Copy the result values into the output registers.
2464 for (unsigned i = 0, realRVLocIdx = 0;
2466 ++i, ++realRVLocIdx) {
2467 CCValAssign &VA = RVLocs[i];
2468 assert(VA.isRegLoc() && "Can only return in registers!");
2470 SDValue Arg = OutVals[realRVLocIdx];
2472 switch (VA.getLocInfo()) {
2473 default: llvm_unreachable("Unknown loc info!");
2474 case CCValAssign::Full: break;
2475 case CCValAssign::BCvt:
2476 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2480 if (VA.needsCustom()) {
2481 if (VA.getLocVT() == MVT::v2f64) {
2482 // Extract the first half and return it in two registers.
2483 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2484 DAG.getConstant(0, dl, MVT::i32));
2485 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2486 DAG.getVTList(MVT::i32, MVT::i32), Half);
2488 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2489 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2491 Flag = Chain.getValue(1);
2492 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2493 VA = RVLocs[++i]; // skip ahead to next loc
2494 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2495 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2497 Flag = Chain.getValue(1);
2498 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2499 VA = RVLocs[++i]; // skip ahead to next loc
2501 // Extract the 2nd half and fall through to handle it as an f64 value.
2502 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2503 DAG.getConstant(1, dl, MVT::i32));
2505 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2507 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2508 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2509 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2510 fmrrd.getValue(isLittleEndian ? 0 : 1),
2512 Flag = Chain.getValue(1);
2513 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2514 VA = RVLocs[++i]; // skip ahead to next loc
2515 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2516 fmrrd.getValue(isLittleEndian ? 1 : 0),
2519 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2521 // Guarantee that all emitted copies are
2522 // stuck together, avoiding something bad.
2523 Flag = Chain.getValue(1);
2524 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2526 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2527 const MCPhysReg *I =
2528 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2531 if (ARM::GPRRegClass.contains(*I))
2532 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2533 else if (ARM::DPRRegClass.contains(*I))
2534 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2536 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2540 // Update chain and glue.
2543 RetOps.push_back(Flag);
2545 // CPUs which aren't M-class use a special sequence to return from
2546 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2547 // though we use "subs pc, lr, #N").
2549 // M-class CPUs actually use a normal return sequence with a special
2550 // (hardware-provided) value in LR, so the normal code path works.
2551 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2552 !Subtarget->isMClass()) {
2553 if (Subtarget->isThumb1Only())
2554 report_fatal_error("interrupt attribute is not supported in Thumb1");
2555 return LowerInterruptReturn(RetOps, dl, DAG);
2558 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2561 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2562 if (N->getNumValues() != 1)
2564 if (!N->hasNUsesOfValue(1, 0))
2567 SDValue TCChain = Chain;
2568 SDNode *Copy = *N->use_begin();
2569 if (Copy->getOpcode() == ISD::CopyToReg) {
2570 // If the copy has a glue operand, we conservatively assume it isn't safe to
2571 // perform a tail call.
2572 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2574 TCChain = Copy->getOperand(0);
2575 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2576 SDNode *VMov = Copy;
2577 // f64 returned in a pair of GPRs.
2578 SmallPtrSet<SDNode*, 2> Copies;
2579 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2581 if (UI->getOpcode() != ISD::CopyToReg)
2585 if (Copies.size() > 2)
2588 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2590 SDValue UseChain = UI->getOperand(0);
2591 if (Copies.count(UseChain.getNode()))
2595 // We are at the top of this chain.
2596 // If the copy has a glue operand, we conservatively assume it
2597 // isn't safe to perform a tail call.
2598 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2604 } else if (Copy->getOpcode() == ISD::BITCAST) {
2605 // f32 returned in a single GPR.
2606 if (!Copy->hasOneUse())
2608 Copy = *Copy->use_begin();
2609 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2611 // If the copy has a glue operand, we conservatively assume it isn't safe to
2612 // perform a tail call.
2613 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2615 TCChain = Copy->getOperand(0);
2620 bool HasRet = false;
2621 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2623 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2624 UI->getOpcode() != ARMISD::INTRET_FLAG)
2636 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2637 if (!Subtarget->supportsTailCall())
2641 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2642 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2648 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2649 // and pass the lower and high parts through.
2650 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2652 SDValue WriteValue = Op->getOperand(2);
2654 // This function is only supposed to be called for i64 type argument.
2655 assert(WriteValue.getValueType() == MVT::i64
2656 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2658 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2659 DAG.getConstant(0, DL, MVT::i32));
2660 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2661 DAG.getConstant(1, DL, MVT::i32));
2662 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2663 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2666 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2667 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2668 // one of the above mentioned nodes. It has to be wrapped because otherwise
2669 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2670 // be used to form addressing mode. These wrapped nodes will be selected
2672 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2673 SelectionDAG &DAG) const {
2674 EVT PtrVT = Op.getValueType();
2675 // FIXME there is no actual debug info here
2677 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2680 // When generating execute-only code Constant Pools must be promoted to the
2681 // global data section. It's a bit ugly that we can't share them across basic
2682 // blocks, but this way we guarantee that execute-only behaves correct with
2683 // position-independent addressing modes.
2684 if (Subtarget->genExecuteOnly()) {
2685 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2686 auto T = const_cast<Type*>(CP->getType());
2687 auto C = const_cast<Constant*>(CP->getConstVal());
2688 auto M = const_cast<Module*>(DAG.getMachineFunction().
2689 getFunction()->getParent());
2690 auto GV = new GlobalVariable(
2691 *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C,
2692 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2693 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2694 Twine(AFI->createPICLabelUId())
2696 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2698 return LowerGlobalAddress(GA, DAG);
2701 if (CP->isMachineConstantPoolEntry())
2702 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2703 CP->getAlignment());
2705 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2706 CP->getAlignment());
2707 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2710 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2711 return MachineJumpTableInfo::EK_Inline;
2714 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2715 SelectionDAG &DAG) const {
2716 MachineFunction &MF = DAG.getMachineFunction();
2717 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2718 unsigned ARMPCLabelIndex = 0;
2720 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2721 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2723 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2724 if (!IsPositionIndependent) {
2725 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2727 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2728 ARMPCLabelIndex = AFI->createPICLabelUId();
2729 ARMConstantPoolValue *CPV =
2730 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2731 ARMCP::CPBlockAddress, PCAdj);
2732 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2734 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2735 SDValue Result = DAG.getLoad(
2736 PtrVT, DL, DAG.getEntryNode(), CPAddr,
2737 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2738 if (!IsPositionIndependent)
2740 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2741 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2744 /// \brief Convert a TLS address reference into the correct sequence of loads
2745 /// and calls to compute the variable's address for Darwin, and return an
2746 /// SDValue containing the final node.
2748 /// Darwin only has one TLS scheme which must be capable of dealing with the
2749 /// fully general situation, in the worst case. This means:
2750 /// + "extern __thread" declaration.
2751 /// + Defined in a possibly unknown dynamic library.
2753 /// The general system is that each __thread variable has a [3 x i32] descriptor
2754 /// which contains information used by the runtime to calculate the address. The
2755 /// only part of this the compiler needs to know about is the first word, which
2756 /// contains a function pointer that must be called with the address of the
2757 /// entire descriptor in "r0".
2759 /// Since this descriptor may be in a different unit, in general access must
2760 /// proceed along the usual ARM rules. A common sequence to produce is:
2762 /// movw rT1, :lower16:_var$non_lazy_ptr
2763 /// movt rT1, :upper16:_var$non_lazy_ptr
2767 /// [...address now in r0...]
2769 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2770 SelectionDAG &DAG) const {
2771 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2774 // First step is to get the address of the actua global symbol. This is where
2775 // the TLS descriptor lives.
2776 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2778 // The first entry in the descriptor is a function pointer that we must call
2779 // to obtain the address of the variable.
2780 SDValue Chain = DAG.getEntryNode();
2781 SDValue FuncTLVGet = DAG.getLoad(
2782 MVT::i32, DL, Chain, DescAddr,
2783 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2784 /* Alignment = */ 4,
2785 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
2786 MachineMemOperand::MOInvariant);
2787 Chain = FuncTLVGet.getValue(1);
2789 MachineFunction &F = DAG.getMachineFunction();
2790 MachineFrameInfo &MFI = F.getFrameInfo();
2791 MFI.setAdjustsStack(true);
2793 // TLS calls preserve all registers except those that absolutely must be
2794 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2797 getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo();
2798 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2799 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2801 // Finally, we can make the call. This is just a degenerate version of a
2802 // normal AArch64 call node: r0 takes the address of the descriptor, and
2803 // returns the address of the variable in this thread.
2804 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2806 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2807 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2808 DAG.getRegisterMask(Mask), Chain.getValue(1));
2809 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2813 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2814 SelectionDAG &DAG) const {
2815 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2817 SDValue Chain = DAG.getEntryNode();
2818 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2821 // Load the current TEB (thread environment block)
2822 SDValue Ops[] = {Chain,
2823 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2824 DAG.getConstant(15, DL, MVT::i32),
2825 DAG.getConstant(0, DL, MVT::i32),
2826 DAG.getConstant(13, DL, MVT::i32),
2827 DAG.getConstant(0, DL, MVT::i32),
2828 DAG.getConstant(2, DL, MVT::i32)};
2829 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2830 DAG.getVTList(MVT::i32, MVT::Other), Ops);
2832 SDValue TEB = CurrentTEB.getValue(0);
2833 Chain = CurrentTEB.getValue(1);
2835 // Load the ThreadLocalStoragePointer from the TEB
2836 // A pointer to the TLS array is located at offset 0x2c from the TEB.
2838 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2839 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2841 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2842 // offset into the TLSArray.
2844 // Load the TLS index from the C runtime
2846 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2847 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2848 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2850 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2851 DAG.getConstant(2, DL, MVT::i32));
2852 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2853 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2854 MachinePointerInfo());
2856 // Get the offset of the start of the .tls section (section base)
2857 const auto *GA = cast<GlobalAddressSDNode>(Op);
2858 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2859 SDValue Offset = DAG.getLoad(
2860 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2861 DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2862 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2864 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2867 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2869 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2870 SelectionDAG &DAG) const {
2872 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2873 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2874 MachineFunction &MF = DAG.getMachineFunction();
2875 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2876 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2877 ARMConstantPoolValue *CPV =
2878 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2879 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2880 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2881 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2882 Argument = DAG.getLoad(
2883 PtrVT, dl, DAG.getEntryNode(), Argument,
2884 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2885 SDValue Chain = Argument.getValue(1);
2887 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2888 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2890 // call __tls_get_addr.
2893 Entry.Node = Argument;
2894 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2895 Args.push_back(Entry);
2897 // FIXME: is there useful debug info available here?
2898 TargetLowering::CallLoweringInfo CLI(DAG);
2899 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2900 CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2901 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2903 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2904 return CallResult.first;
2907 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2908 // "local exec" model.
2910 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2912 TLSModel::Model model) const {
2913 const GlobalValue *GV = GA->getGlobal();
2916 SDValue Chain = DAG.getEntryNode();
2917 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2918 // Get the Thread Pointer
2919 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2921 if (model == TLSModel::InitialExec) {
2922 MachineFunction &MF = DAG.getMachineFunction();
2923 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2924 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2925 // Initial exec model.
2926 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2927 ARMConstantPoolValue *CPV =
2928 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2929 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2931 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2932 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2933 Offset = DAG.getLoad(
2934 PtrVT, dl, Chain, Offset,
2935 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2936 Chain = Offset.getValue(1);
2938 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2939 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2941 Offset = DAG.getLoad(
2942 PtrVT, dl, Chain, Offset,
2943 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2946 assert(model == TLSModel::LocalExec);
2947 ARMConstantPoolValue *CPV =
2948 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2949 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2950 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2951 Offset = DAG.getLoad(
2952 PtrVT, dl, Chain, Offset,
2953 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2956 // The address of the thread local variable is the add of the thread
2957 // pointer with the offset of the variable.
2958 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2962 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2963 if (Subtarget->isTargetDarwin())
2964 return LowerGlobalTLSAddressDarwin(Op, DAG);
2966 if (Subtarget->isTargetWindows())
2967 return LowerGlobalTLSAddressWindows(Op, DAG);
2969 // TODO: implement the "local dynamic" model
2970 assert(Subtarget->isTargetELF() && "Only ELF implemented here");
2971 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2972 if (DAG.getTarget().Options.EmulatedTLS)
2973 return LowerToTLSEmulatedModel(GA, DAG);
2975 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2978 case TLSModel::GeneralDynamic:
2979 case TLSModel::LocalDynamic:
2980 return LowerToTLSGeneralDynamicModel(GA, DAG);
2981 case TLSModel::InitialExec:
2982 case TLSModel::LocalExec:
2983 return LowerToTLSExecModels(GA, DAG, model);
2985 llvm_unreachable("bogus TLS model");
2988 /// Return true if all users of V are within function F, looking through
2990 static bool allUsersAreInFunction(const Value *V, const Function *F) {
2991 SmallVector<const User*,4> Worklist;
2992 for (auto *U : V->users())
2993 Worklist.push_back(U);
2994 while (!Worklist.empty()) {
2995 auto *U = Worklist.pop_back_val();
2996 if (isa<ConstantExpr>(U)) {
2997 for (auto *UU : U->users())
2998 Worklist.push_back(UU);
3002 auto *I = dyn_cast<Instruction>(U);
3003 if (!I || I->getParent()->getParent() != F)
3009 /// Return true if all users of V are within some (any) function, looking through
3010 /// ConstantExprs. In other words, are there any global constant users?
3011 static bool allUsersAreInFunctions(const Value *V) {
3012 SmallVector<const User*,4> Worklist;
3013 for (auto *U : V->users())
3014 Worklist.push_back(U);
3015 while (!Worklist.empty()) {
3016 auto *U = Worklist.pop_back_val();
3017 if (isa<ConstantExpr>(U)) {
3018 for (auto *UU : U->users())
3019 Worklist.push_back(UU);
3023 if (!isa<Instruction>(U))
3029 // Return true if T is an integer, float or an array/vector of either.
3030 static bool isSimpleType(Type *T) {
3031 if (T->isIntegerTy() || T->isFloatingPointTy())
3033 Type *SubT = nullptr;
3035 SubT = T->getArrayElementType();
3036 else if (T->isVectorTy())
3037 SubT = T->getVectorElementType();
3040 return SubT->isIntegerTy() || SubT->isFloatingPointTy();
3043 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG,
3044 EVT PtrVT, const SDLoc &dl) {
3045 // If we're creating a pool entry for a constant global with unnamed address,
3046 // and the global is small enough, we can emit it inline into the constant pool
3047 // to save ourselves an indirection.
3049 // This is a win if the constant is only used in one function (so it doesn't
3050 // need to be duplicated) or duplicating the constant wouldn't increase code
3051 // size (implying the constant is no larger than 4 bytes).
3052 const Function *F = DAG.getMachineFunction().getFunction();
3054 // We rely on this decision to inline being idemopotent and unrelated to the
3055 // use-site. We know that if we inline a variable at one use site, we'll
3056 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3057 // doesn't know about this optimization, so bail out if it's enabled else
3058 // we could decide to inline here (and thus never emit the GV) but require
3059 // the GV from fast-isel generated code.
3060 if (!EnableConstpoolPromotion ||
3061 DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3064 auto *GVar = dyn_cast<GlobalVariable>(GV);
3065 if (!GVar || !GVar->hasInitializer() ||
3066 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3067 !GVar->hasLocalLinkage())
3070 // Ensure that we don't try and inline any type that contains pointers. If
3071 // we inline a value that contains relocations, we move the relocations from
3072 // .data to .text which is not ideal.
3073 auto *Init = GVar->getInitializer();
3074 if (!isSimpleType(Init->getType()))
3077 // The constant islands pass can only really deal with alignment requests
3078 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3079 // any type wanting greater alignment requirements than 4 bytes. We also
3080 // can only promote constants that are multiples of 4 bytes in size or
3081 // are paddable to a multiple of 4. Currently we only try and pad constants
3082 // that are strings for simplicity.
3083 auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3084 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3085 unsigned Align = GVar->getAlignment();
3086 unsigned RequiredPadding = 4 - (Size % 4);
3087 bool PaddingPossible =
3088 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3089 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3093 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3094 MachineFunction &MF = DAG.getMachineFunction();
3095 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3097 // We can't bloat the constant pool too much, else the ConstantIslands pass
3098 // may fail to converge. If we haven't promoted this global yet (it may have
3099 // multiple uses), and promoting it would increase the constant pool size (Sz
3100 // > 4), ensure we have space to do so up to MaxTotal.
3101 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3102 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3103 ConstpoolPromotionMaxTotal)
3106 // This is only valid if all users are in a single function OR it has users
3107 // in multiple functions but it no larger than a pointer. We also check if
3108 // GVar has constant (non-ConstantExpr) users. If so, it essentially has its
3110 if (!allUsersAreInFunction(GVar, F) &&
3111 !(Size <= 4 && allUsersAreInFunctions(GVar)))
3114 // We're going to inline this global. Pad it out if needed.
3115 if (RequiredPadding != 4) {
3116 StringRef S = CDAInit->getAsString();
3118 SmallVector<uint8_t,16> V(S.size());
3119 std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3120 while (RequiredPadding--)
3122 Init = ConstantDataArray::get(*DAG.getContext(), V);
3125 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3127 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3128 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3129 AFI->markGlobalAsPromotedToConstantPool(GVar);
3130 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3133 ++NumConstpoolPromoted;
3134 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3137 static bool isReadOnly(const GlobalValue *GV) {
3138 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3139 GV = GA->getBaseObject();
3140 return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) ||
3144 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3145 SelectionDAG &DAG) const {
3146 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3147 default: llvm_unreachable("unknown object format");
3149 return LowerGlobalAddressWindows(Op, DAG);
3151 return LowerGlobalAddressELF(Op, DAG);
3153 return LowerGlobalAddressDarwin(Op, DAG);
3157 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3158 SelectionDAG &DAG) const {
3159 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3161 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3162 const TargetMachine &TM = getTargetMachine();
3163 bool IsRO = isReadOnly(GV);
3165 // promoteToConstantPool only if not generating XO text section
3166 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3167 if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl))
3170 if (isPositionIndependent()) {
3171 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3173 MachineFunction &MF = DAG.getMachineFunction();
3174 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3175 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3176 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3178 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3179 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
3180 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
3181 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
3182 /*AddCurrentAddress=*/UseGOT_PREL);
3183 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3184 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3185 SDValue Result = DAG.getLoad(
3186 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3187 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3188 SDValue Chain = Result.getValue(1);
3189 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3190 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3193 DAG.getLoad(PtrVT, dl, Chain, Result,
3194 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3196 } else if (Subtarget->isROPI() && IsRO) {
3198 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3199 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3201 } else if (Subtarget->isRWPI() && !IsRO) {
3204 if (Subtarget->useMovt(DAG.getMachineFunction())) {
3206 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3207 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3208 } else { // use literal pool for address constant
3209 ARMConstantPoolValue *CPV =
3210 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3211 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3212 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3213 RelAddr = DAG.getLoad(
3214 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3215 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3217 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3218 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3222 // If we have T2 ops, we can materialize the address directly via movt/movw
3223 // pair. This is always cheaper.
3224 if (Subtarget->useMovt(DAG.getMachineFunction())) {
3226 // FIXME: Once remat is capable of dealing with instructions with register
3227 // operands, expand this into two nodes.
3228 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3229 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3231 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3232 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3234 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3235 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3239 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3240 SelectionDAG &DAG) const {
3241 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3242 "ROPI/RWPI not currently supported for Darwin");
3243 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3245 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3247 if (Subtarget->useMovt(DAG.getMachineFunction()))
3250 // FIXME: Once remat is capable of dealing with instructions with register
3251 // operands, expand this into multiple nodes
3253 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3255 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3256 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3258 if (Subtarget->isGVIndirectSymbol(GV))
3259 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3260 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3264 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3265 SelectionDAG &DAG) const {
3266 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3267 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
3268 "Windows on ARM expects to use movw/movt");
3269 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3270 "ROPI/RWPI not currently supported for Windows");
3272 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3273 const ARMII::TOF TargetFlags =
3274 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
3275 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3281 // FIXME: Once remat is capable of dealing with instructions with register
3282 // operands, expand this into two nodes.
3283 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3284 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3286 if (GV->hasDLLImportStorageClass())
3287 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3288 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3293 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3295 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3296 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3297 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3298 Op.getOperand(1), Val);
3302 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3304 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3305 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3308 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3309 SelectionDAG &DAG) const {
3311 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3316 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3317 const ARMSubtarget *Subtarget) const {
3318 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3321 default: return SDValue(); // Don't custom lower most intrinsics.
3322 case Intrinsic::thread_pointer: {
3323 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3324 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3326 case Intrinsic::eh_sjlj_lsda: {
3327 MachineFunction &MF = DAG.getMachineFunction();
3328 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3329 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3330 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3332 bool IsPositionIndependent = isPositionIndependent();
3333 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3334 ARMConstantPoolValue *CPV =
3335 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
3336 ARMCP::CPLSDA, PCAdj);
3337 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3338 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3339 SDValue Result = DAG.getLoad(
3340 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3341 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3343 if (IsPositionIndependent) {
3344 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3345 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3349 case Intrinsic::arm_neon_vabs:
3350 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3352 case Intrinsic::arm_neon_vmulls:
3353 case Intrinsic::arm_neon_vmullu: {
3354 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3355 ? ARMISD::VMULLs : ARMISD::VMULLu;
3356 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3357 Op.getOperand(1), Op.getOperand(2));
3359 case Intrinsic::arm_neon_vminnm:
3360 case Intrinsic::arm_neon_vmaxnm: {
3361 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3362 ? ISD::FMINNUM : ISD::FMAXNUM;
3363 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3364 Op.getOperand(1), Op.getOperand(2));
3366 case Intrinsic::arm_neon_vminu:
3367 case Intrinsic::arm_neon_vmaxu: {
3368 if (Op.getValueType().isFloatingPoint())
3370 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3371 ? ISD::UMIN : ISD::UMAX;
3372 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3373 Op.getOperand(1), Op.getOperand(2));
3375 case Intrinsic::arm_neon_vmins:
3376 case Intrinsic::arm_neon_vmaxs: {
3377 // v{min,max}s is overloaded between signed integers and floats.
3378 if (!Op.getValueType().isFloatingPoint()) {
3379 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3380 ? ISD::SMIN : ISD::SMAX;
3381 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3382 Op.getOperand(1), Op.getOperand(2));
3384 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3385 ? ISD::FMINNAN : ISD::FMAXNAN;
3386 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3387 Op.getOperand(1), Op.getOperand(2));
3389 case Intrinsic::arm_neon_vtbl1:
3390 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3391 Op.getOperand(1), Op.getOperand(2));
3392 case Intrinsic::arm_neon_vtbl2:
3393 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3394 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3398 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3399 const ARMSubtarget *Subtarget) {
3401 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3402 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3403 if (SSID == SyncScope::SingleThread)
3406 if (!Subtarget->hasDataBarrier()) {
3407 // Some ARMv6 cpus can support data barriers with an mcr instruction.
3408 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3410 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3411 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3412 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3413 DAG.getConstant(0, dl, MVT::i32));
3416 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3417 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3418 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3419 if (Subtarget->isMClass()) {
3420 // Only a full system barrier exists in the M-class architectures.
3421 Domain = ARM_MB::SY;
3422 } else if (Subtarget->preferISHSTBarriers() &&
3423 Ord == AtomicOrdering::Release) {
3424 // Swift happens to implement ISHST barriers in a way that's compatible with
3425 // Release semantics but weaker than ISH so we'd be fools not to use
3426 // it. Beware: other processors probably don't!
3427 Domain = ARM_MB::ISHST;
3430 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3431 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3432 DAG.getConstant(Domain, dl, MVT::i32));
3435 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3436 const ARMSubtarget *Subtarget) {
3437 // ARM pre v5TE and Thumb1 does not have preload instructions.
3438 if (!(Subtarget->isThumb2() ||
3439 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3440 // Just preserve the chain.
3441 return Op.getOperand(0);
3444 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3446 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3447 // ARMv7 with MP extension has PLDW.
3448 return Op.getOperand(0);
3450 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3451 if (Subtarget->isThumb()) {
3453 isRead = ~isRead & 1;
3454 isData = ~isData & 1;
3457 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3458 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3459 DAG.getConstant(isData, dl, MVT::i32));
3462 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3463 MachineFunction &MF = DAG.getMachineFunction();
3464 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3466 // vastart just stores the address of the VarArgsFrameIndex slot into the
3467 // memory location argument.
3469 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3470 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3471 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3472 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3473 MachinePointerInfo(SV));
3476 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3477 CCValAssign &NextVA,
3480 const SDLoc &dl) const {
3481 MachineFunction &MF = DAG.getMachineFunction();
3482 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3484 const TargetRegisterClass *RC;
3485 if (AFI->isThumb1OnlyFunction())
3486 RC = &ARM::tGPRRegClass;
3488 RC = &ARM::GPRRegClass;
3490 // Transform the arguments stored in physical registers into virtual ones.
3491 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3492 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3495 if (NextVA.isMemLoc()) {
3496 MachineFrameInfo &MFI = MF.getFrameInfo();
3497 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3499 // Create load node to retrieve arguments from the stack.
3500 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3501 ArgValue2 = DAG.getLoad(
3502 MVT::i32, dl, Root, FIN,
3503 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3505 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3506 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3508 if (!Subtarget->isLittle())
3509 std::swap (ArgValue, ArgValue2);
3510 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3513 // The remaining GPRs hold either the beginning of variable-argument
3514 // data, or the beginning of an aggregate passed by value (usually
3515 // byval). Either way, we allocate stack slots adjacent to the data
3516 // provided by our caller, and store the unallocated registers there.
3517 // If this is a variadic function, the va_list pointer will begin with
3518 // these values; otherwise, this reassembles a (byval) structure that
3519 // was split between registers and memory.
3520 // Return: The frame index registers were stored into.
3521 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3522 const SDLoc &dl, SDValue &Chain,
3523 const Value *OrigArg,
3524 unsigned InRegsParamRecordIdx,
3525 int ArgOffset, unsigned ArgSize) const {
3526 // Currently, two use-cases possible:
3527 // Case #1. Non-var-args function, and we meet first byval parameter.
3528 // Setup first unallocated register as first byval register;
3529 // eat all remained registers
3530 // (these two actions are performed by HandleByVal method).
3531 // Then, here, we initialize stack frame with
3532 // "store-reg" instructions.
3533 // Case #2. Var-args function, that doesn't contain byval parameters.
3534 // The same: eat all remained unallocated registers,
3535 // initialize stack frame.
3537 MachineFunction &MF = DAG.getMachineFunction();
3538 MachineFrameInfo &MFI = MF.getFrameInfo();
3539 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3540 unsigned RBegin, REnd;
3541 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3542 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3544 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3545 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3550 ArgOffset = -4 * (ARM::R4 - RBegin);
3552 auto PtrVT = getPointerTy(DAG.getDataLayout());
3553 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3554 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3556 SmallVector<SDValue, 4> MemOps;
3557 const TargetRegisterClass *RC =
3558 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3560 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3561 unsigned VReg = MF.addLiveIn(Reg, RC);
3562 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3563 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3564 MachinePointerInfo(OrigArg, 4 * i));
3565 MemOps.push_back(Store);
3566 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3569 if (!MemOps.empty())
3570 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3574 // Setup stack frame, the va_list pointer will start from.
3575 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3576 const SDLoc &dl, SDValue &Chain,
3578 unsigned TotalArgRegsSaveSize,
3579 bool ForceMutable) const {
3580 MachineFunction &MF = DAG.getMachineFunction();
3581 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3583 // Try to store any remaining integer argument regs
3584 // to their spots on the stack so that they may be loaded by dereferencing
3585 // the result of va_next.
3586 // If there is no regs to be stored, just point address after last
3587 // argument passed via stack.
3588 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3589 CCInfo.getInRegsParamsCount(),
3590 CCInfo.getNextStackOffset(), 4);
3591 AFI->setVarArgsFrameIndex(FrameIndex);
3594 SDValue ARMTargetLowering::LowerFormalArguments(
3595 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3596 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3597 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3598 MachineFunction &MF = DAG.getMachineFunction();
3599 MachineFrameInfo &MFI = MF.getFrameInfo();
3601 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3603 // Assign locations to all of the incoming arguments.
3604 SmallVector<CCValAssign, 16> ArgLocs;
3605 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3607 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3609 SmallVector<SDValue, 16> ArgValues;
3611 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3612 unsigned CurArgIdx = 0;
3614 // Initially ArgRegsSaveSize is zero.
3615 // Then we increase this value each time we meet byval parameter.
3616 // We also increase this value in case of varargs function.
3617 AFI->setArgRegsSaveSize(0);
3619 // Calculate the amount of stack space that we need to allocate to store
3620 // byval and variadic arguments that are passed in registers.
3621 // We need to know this before we allocate the first byval or variadic
3622 // argument, as they will be allocated a stack slot below the CFA (Canonical
3623 // Frame Address, the stack pointer at entry to the function).
3624 unsigned ArgRegBegin = ARM::R4;
3625 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3626 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3629 CCValAssign &VA = ArgLocs[i];
3630 unsigned Index = VA.getValNo();
3631 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3632 if (!Flags.isByVal())
3635 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3636 unsigned RBegin, REnd;
3637 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3638 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3640 CCInfo.nextInRegsParam();
3642 CCInfo.rewindByValRegsInfo();
3644 int lastInsIndex = -1;
3645 if (isVarArg && MFI.hasVAStart()) {
3646 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3647 if (RegIdx != array_lengthof(GPRArgRegs))
3648 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3651 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3652 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3653 auto PtrVT = getPointerTy(DAG.getDataLayout());
3655 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3656 CCValAssign &VA = ArgLocs[i];
3657 if (Ins[VA.getValNo()].isOrigArg()) {
3658 std::advance(CurOrigArg,
3659 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3660 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3662 // Arguments stored in registers.
3663 if (VA.isRegLoc()) {
3664 EVT RegVT = VA.getLocVT();
3666 if (VA.needsCustom()) {
3667 // f64 and vector types are split up into multiple registers or
3668 // combinations of registers and stack slots.
3669 if (VA.getLocVT() == MVT::v2f64) {
3670 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3672 VA = ArgLocs[++i]; // skip ahead to next loc
3674 if (VA.isMemLoc()) {
3675 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3676 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3677 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3678 MachinePointerInfo::getFixedStack(
3679 DAG.getMachineFunction(), FI));
3681 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3684 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3685 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3686 ArgValue, ArgValue1,
3687 DAG.getIntPtrConstant(0, dl));
3688 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3689 ArgValue, ArgValue2,
3690 DAG.getIntPtrConstant(1, dl));
3692 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3695 const TargetRegisterClass *RC;
3697 if (RegVT == MVT::f32)
3698 RC = &ARM::SPRRegClass;
3699 else if (RegVT == MVT::f64)
3700 RC = &ARM::DPRRegClass;
3701 else if (RegVT == MVT::v2f64)
3702 RC = &ARM::QPRRegClass;
3703 else if (RegVT == MVT::i32)
3704 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3705 : &ARM::GPRRegClass;
3707 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3709 // Transform the arguments in physical registers into virtual ones.
3710 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3711 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3714 // If this is an 8 or 16-bit value, it is really passed promoted
3715 // to 32 bits. Insert an assert[sz]ext to capture this, then
3716 // truncate to the right size.
3717 switch (VA.getLocInfo()) {
3718 default: llvm_unreachable("Unknown loc info!");
3719 case CCValAssign::Full: break;
3720 case CCValAssign::BCvt:
3721 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3723 case CCValAssign::SExt:
3724 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3725 DAG.getValueType(VA.getValVT()));
3726 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3728 case CCValAssign::ZExt:
3729 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3730 DAG.getValueType(VA.getValVT()));
3731 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3735 InVals.push_back(ArgValue);
3737 } else { // VA.isRegLoc()
3739 assert(VA.isMemLoc());
3740 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3742 int index = VA.getValNo();
3744 // Some Ins[] entries become multiple ArgLoc[] entries.
3745 // Process them only once.
3746 if (index != lastInsIndex)
3748 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3749 // FIXME: For now, all byval parameter objects are marked mutable.
3750 // This can be changed with more analysis.
3751 // In case of tail call optimization mark all arguments mutable.
3752 // Since they could be overwritten by lowering of arguments in case of
3754 if (Flags.isByVal()) {
3755 assert(Ins[index].isOrigArg() &&
3756 "Byval arguments cannot be implicit");
3757 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3759 int FrameIndex = StoreByValRegs(
3760 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3761 VA.getLocMemOffset(), Flags.getByValSize());
3762 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3763 CCInfo.nextInRegsParam();
3765 unsigned FIOffset = VA.getLocMemOffset();
3766 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3769 // Create load nodes to retrieve arguments from the stack.
3770 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3771 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3772 MachinePointerInfo::getFixedStack(
3773 DAG.getMachineFunction(), FI)));
3775 lastInsIndex = index;
3781 if (isVarArg && MFI.hasVAStart())
3782 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3783 CCInfo.getNextStackOffset(),
3784 TotalArgRegsSaveSize);
3786 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3791 /// isFloatingPointZero - Return true if this is +0.0.
3792 static bool isFloatingPointZero(SDValue Op) {
3793 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3794 return CFP->getValueAPF().isPosZero();
3795 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3796 // Maybe this has already been legalized into the constant pool?
3797 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3798 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3799 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3800 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3801 return CFP->getValueAPF().isPosZero();
3803 } else if (Op->getOpcode() == ISD::BITCAST &&
3804 Op->getValueType(0) == MVT::f64) {
3805 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3806 // created by LowerConstantFP().
3807 SDValue BitcastOp = Op->getOperand(0);
3808 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3809 isNullConstant(BitcastOp->getOperand(0)))
3815 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3816 /// the given operands.
3817 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3818 SDValue &ARMcc, SelectionDAG &DAG,
3819 const SDLoc &dl) const {
3820 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3821 unsigned C = RHSC->getZExtValue();
3822 if (!isLegalICmpImmediate(C)) {
3823 // Constant does not fit, try adjusting it by one?
3828 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3829 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3830 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3835 if (C != 0 && isLegalICmpImmediate(C-1)) {
3836 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3837 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3842 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3843 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3844 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3849 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3850 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3851 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3858 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3859 ARMISD::NodeType CompareType;
3862 CompareType = ARMISD::CMP;
3867 CompareType = ARMISD::CMPZ;
3870 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3871 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3874 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3875 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3876 SelectionDAG &DAG, const SDLoc &dl,
3877 bool InvalidOnQNaN) const {
3878 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3880 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
3881 if (!isFloatingPointZero(RHS))
3882 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
3884 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
3885 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3888 /// duplicateCmp - Glue values can have only one use, so this function
3889 /// duplicates a comparison node.
3891 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3892 unsigned Opc = Cmp.getOpcode();
3894 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3895 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3897 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3898 Cmp = Cmp.getOperand(0);
3899 Opc = Cmp.getOpcode();
3900 if (Opc == ARMISD::CMPFP)
3901 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3902 Cmp.getOperand(1), Cmp.getOperand(2));
3904 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3905 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3908 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3911 std::pair<SDValue, SDValue>
3912 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3913 SDValue &ARMcc) const {
3914 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3916 SDValue Value, OverflowCmp;
3917 SDValue LHS = Op.getOperand(0);
3918 SDValue RHS = Op.getOperand(1);
3921 // FIXME: We are currently always generating CMPs because we don't support
3922 // generating CMN through the backend. This is not as good as the natural
3923 // CMP case because it causes a register dependency and cannot be folded
3926 switch (Op.getOpcode()) {
3928 llvm_unreachable("Unknown overflow instruction!");
3930 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3931 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3932 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3935 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3936 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3937 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3940 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3941 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3942 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3945 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3946 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3947 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3951 return std::make_pair(Value, OverflowCmp);
3955 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3956 // Let legalize expand this if it isn't a legal type yet.
3957 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3960 SDValue Value, OverflowCmp;
3962 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3963 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3965 // We use 0 and 1 as false and true values.
3966 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3967 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3968 EVT VT = Op.getValueType();
3970 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3971 ARMcc, CCR, OverflowCmp);
3973 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3974 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3977 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3978 SDValue Cond = Op.getOperand(0);
3979 SDValue SelectTrue = Op.getOperand(1);
3980 SDValue SelectFalse = Op.getOperand(2);
3982 unsigned Opc = Cond.getOpcode();
3984 if (Cond.getResNo() == 1 &&
3985 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3986 Opc == ISD::USUBO)) {
3987 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3990 SDValue Value, OverflowCmp;
3992 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3993 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3994 EVT VT = Op.getValueType();
3996 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4002 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4003 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4005 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4006 const ConstantSDNode *CMOVTrue =
4007 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4008 const ConstantSDNode *CMOVFalse =
4009 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4011 if (CMOVTrue && CMOVFalse) {
4012 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4013 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4017 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4019 False = SelectFalse;
4020 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4025 if (True.getNode() && False.getNode()) {
4026 EVT VT = Op.getValueType();
4027 SDValue ARMcc = Cond.getOperand(2);
4028 SDValue CCR = Cond.getOperand(3);
4029 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4030 assert(True.getValueType() == VT);
4031 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4036 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4037 // undefined bits before doing a full-word comparison with zero.
4038 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4039 DAG.getConstant(1, dl, Cond.getValueType()));
4041 return DAG.getSelectCC(dl, Cond,
4042 DAG.getConstant(0, dl, Cond.getValueType()),
4043 SelectTrue, SelectFalse, ISD::SETNE);
4046 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4047 bool &swpCmpOps, bool &swpVselOps) {
4048 // Start by selecting the GE condition code for opcodes that return true for
4050 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4052 CondCode = ARMCC::GE;
4054 // and GT for opcodes that return false for 'equality'.
4055 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4057 CondCode = ARMCC::GT;
4059 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4060 // to swap the compare operands.
4061 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4065 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4066 // If we have an unordered opcode, we need to swap the operands to the VSEL
4067 // instruction (effectively negating the condition).
4069 // This also has the effect of swapping which one of 'less' or 'greater'
4070 // returns true, so we also swap the compare operands. It also switches
4071 // whether we return true for 'equality', so we compensate by picking the
4072 // opposite condition code to our original choice.
4073 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4074 CC == ISD::SETUGT) {
4075 swpCmpOps = !swpCmpOps;
4076 swpVselOps = !swpVselOps;
4077 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4080 // 'ordered' is 'anything but unordered', so use the VS condition code and
4081 // swap the VSEL operands.
4082 if (CC == ISD::SETO) {
4083 CondCode = ARMCC::VS;
4087 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4088 // code and swap the VSEL operands.
4089 if (CC == ISD::SETUNE) {
4090 CondCode = ARMCC::EQ;
4095 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4096 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4097 SDValue Cmp, SelectionDAG &DAG) const {
4098 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
4099 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4100 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4101 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4102 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4104 SDValue TrueLow = TrueVal.getValue(0);
4105 SDValue TrueHigh = TrueVal.getValue(1);
4106 SDValue FalseLow = FalseVal.getValue(0);
4107 SDValue FalseHigh = FalseVal.getValue(1);
4109 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4111 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4112 ARMcc, CCR, duplicateCmp(Cmp, DAG));
4114 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4116 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4121 static bool isGTorGE(ISD::CondCode CC) {
4122 return CC == ISD::SETGT || CC == ISD::SETGE;
4125 static bool isLTorLE(ISD::CondCode CC) {
4126 return CC == ISD::SETLT || CC == ISD::SETLE;
4129 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4130 // All of these conditions (and their <= and >= counterparts) will do:
4135 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4136 const SDValue TrueVal, const SDValue FalseVal,
4137 const ISD::CondCode CC, const SDValue K) {
4138 return (isGTorGE(CC) &&
4139 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4141 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4144 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4145 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4146 const SDValue TrueVal, const SDValue FalseVal,
4147 const ISD::CondCode CC, const SDValue K) {
4148 return (isGTorGE(CC) &&
4149 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4151 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4154 // Check if two chained conditionals could be converted into SSAT.
4156 // SSAT can replace a set of two conditional selectors that bound a number to an
4157 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4159 // x < -k ? -k : (x > k ? k : x)
4160 // x < -k ? -k : (x < k ? x : k)
4161 // x > -k ? (x > k ? k : x) : -k
4162 // x < k ? (x < -k ? -k : x) : k
4165 // It returns true if the conversion can be done, false otherwise.
4166 // Additionally, the variable is returned in parameter V and the constant in K.
4167 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4169 SDValue LHS1 = Op.getOperand(0);
4170 SDValue RHS1 = Op.getOperand(1);
4171 SDValue TrueVal1 = Op.getOperand(2);
4172 SDValue FalseVal1 = Op.getOperand(3);
4173 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4175 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4176 if (Op2.getOpcode() != ISD::SELECT_CC)
4179 SDValue LHS2 = Op2.getOperand(0);
4180 SDValue RHS2 = Op2.getOperand(1);
4181 SDValue TrueVal2 = Op2.getOperand(2);
4182 SDValue FalseVal2 = Op2.getOperand(3);
4183 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4185 // Find out which are the constants and which are the variables
4186 // in each conditional
4187 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4190 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4193 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4194 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4195 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4196 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4198 // We must detect cases where the original operations worked with 16- or
4199 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4200 // must work with sign-extended values but the select operations return
4201 // the original non-extended value.
4202 SDValue V2TmpReg = V2Tmp;
4203 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4204 V2TmpReg = V2Tmp->getOperand(0);
4206 // Check that the registers and the constants have the correct values
4207 // in both conditionals
4208 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4212 // Figure out which conditional is saturating the lower/upper bound.
4213 const SDValue *LowerCheckOp =
4214 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4216 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4219 const SDValue *UpperCheckOp =
4220 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4222 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4226 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4229 // Check that the constant in the lower-bound check is
4230 // the opposite of the constant in the upper-bound check
4231 // in 1's complement.
4232 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4233 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4234 int64_t PosVal = std::max(Val1, Val2);
4236 if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4237 (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4238 Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) {
4241 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4248 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4249 EVT VT = Op.getValueType();
4252 // Try to convert two saturating conditional selects into a single SSAT
4254 uint64_t SatConstant;
4255 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4256 isSaturatingConditional(Op, SatValue, SatConstant))
4257 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4258 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4260 SDValue LHS = Op.getOperand(0);
4261 SDValue RHS = Op.getOperand(1);
4262 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4263 SDValue TrueVal = Op.getOperand(2);
4264 SDValue FalseVal = Op.getOperand(3);
4266 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4267 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4270 // If softenSetCCOperands only returned one value, we should compare it to
4272 if (!RHS.getNode()) {
4273 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4278 if (LHS.getValueType() == MVT::i32) {
4279 // Try to generate VSEL on ARMv8.
4280 // The VSEL instruction can't use all the usual ARM condition
4281 // codes: it only has two bits to select the condition code, so it's
4282 // constrained to use only GE, GT, VS and EQ.
4284 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4285 // swap the operands of the previous compare instruction (effectively
4286 // inverting the compare condition, swapping 'less' and 'greater') and
4287 // sometimes need to swap the operands to the VSEL (which inverts the
4288 // condition in the sense of firing whenever the previous condition didn't)
4289 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4290 TrueVal.getValueType() == MVT::f64)) {
4291 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4292 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4293 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4294 CC = ISD::getSetCCInverse(CC, true);
4295 std::swap(TrueVal, FalseVal);
4300 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4301 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4302 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4305 ARMCC::CondCodes CondCode, CondCode2;
4307 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4309 // Try to generate VMAXNM/VMINNM on ARMv8.
4310 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4311 TrueVal.getValueType() == MVT::f64)) {
4312 bool swpCmpOps = false;
4313 bool swpVselOps = false;
4314 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4316 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4317 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4319 std::swap(LHS, RHS);
4321 std::swap(TrueVal, FalseVal);
4325 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4326 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4327 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4328 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4329 if (CondCode2 != ARMCC::AL) {
4330 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4331 // FIXME: Needs another CMP because flag can have but one use.
4332 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4333 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4338 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4339 /// to morph to an integer compare sequence.
4340 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4341 const ARMSubtarget *Subtarget) {
4342 SDNode *N = Op.getNode();
4343 if (!N->hasOneUse())
4344 // Otherwise it requires moving the value from fp to integer registers.
4346 if (!N->getNumValues())
4348 EVT VT = Op.getValueType();
4349 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4350 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4351 // vmrs are very slow, e.g. cortex-a8.
4354 if (isFloatingPointZero(Op)) {
4358 return ISD::isNormalLoad(N);
4361 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4362 if (isFloatingPointZero(Op))
4363 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4365 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4366 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4367 Ld->getPointerInfo(), Ld->getAlignment(),
4368 Ld->getMemOperand()->getFlags());
4370 llvm_unreachable("Unknown VFP cmp argument!");
4373 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4374 SDValue &RetVal1, SDValue &RetVal2) {
4377 if (isFloatingPointZero(Op)) {
4378 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4379 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4383 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4384 SDValue Ptr = Ld->getBasePtr();
4386 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4387 Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4389 EVT PtrType = Ptr.getValueType();
4390 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4391 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4392 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4393 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4394 Ld->getPointerInfo().getWithOffset(4), NewAlign,
4395 Ld->getMemOperand()->getFlags());
4399 llvm_unreachable("Unknown VFP cmp argument!");
4402 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4403 /// f32 and even f64 comparisons to integer ones.
4405 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4406 SDValue Chain = Op.getOperand(0);
4407 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4408 SDValue LHS = Op.getOperand(2);
4409 SDValue RHS = Op.getOperand(3);
4410 SDValue Dest = Op.getOperand(4);
4413 bool LHSSeenZero = false;
4414 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4415 bool RHSSeenZero = false;
4416 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4417 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4418 // If unsafe fp math optimization is enabled and there are no other uses of
4419 // the CMP operands, and the condition code is EQ or NE, we can optimize it
4420 // to an integer comparison.
4421 if (CC == ISD::SETOEQ)
4423 else if (CC == ISD::SETUNE)
4426 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4428 if (LHS.getValueType() == MVT::f32) {
4429 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4430 bitcastf32Toi32(LHS, DAG), Mask);
4431 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4432 bitcastf32Toi32(RHS, DAG), Mask);
4433 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4434 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4435 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4436 Chain, Dest, ARMcc, CCR, Cmp);
4441 expandf64Toi32(LHS, DAG, LHS1, LHS2);
4442 expandf64Toi32(RHS, DAG, RHS1, RHS2);
4443 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4444 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4445 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4446 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4447 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4448 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4449 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4455 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4456 SDValue Chain = Op.getOperand(0);
4457 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4458 SDValue LHS = Op.getOperand(2);
4459 SDValue RHS = Op.getOperand(3);
4460 SDValue Dest = Op.getOperand(4);
4463 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4464 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4467 // If softenSetCCOperands only returned one value, we should compare it to
4469 if (!RHS.getNode()) {
4470 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4475 if (LHS.getValueType() == MVT::i32) {
4477 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4478 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4479 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4480 Chain, Dest, ARMcc, CCR, Cmp);
4483 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4485 if (getTargetMachine().Options.UnsafeFPMath &&
4486 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4487 CC == ISD::SETNE || CC == ISD::SETUNE)) {
4488 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4492 ARMCC::CondCodes CondCode, CondCode2;
4494 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4496 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4497 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4498 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4499 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4500 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4501 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4502 if (CondCode2 != ARMCC::AL) {
4503 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4504 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4505 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4510 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4511 SDValue Chain = Op.getOperand(0);
4512 SDValue Table = Op.getOperand(1);
4513 SDValue Index = Op.getOperand(2);
4516 EVT PTy = getPointerTy(DAG.getDataLayout());
4517 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4518 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4519 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4520 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4521 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
4522 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
4523 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
4524 // which does another jump to the destination. This also makes it easier
4525 // to translate it to TBB / TBH later (Thumb2 only).
4526 // FIXME: This might not work if the function is extremely large.
4527 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4528 Addr, Op.getOperand(2), JTI);
4530 if (isPositionIndependent() || Subtarget->isROPI()) {
4532 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4533 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4534 Chain = Addr.getValue(1);
4535 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
4536 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4539 DAG.getLoad(PTy, dl, Chain, Addr,
4540 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4541 Chain = Addr.getValue(1);
4542 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4546 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4547 EVT VT = Op.getValueType();
4550 if (Op.getValueType().getVectorElementType() == MVT::i32) {
4551 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4553 return DAG.UnrollVectorOp(Op.getNode());
4556 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
4557 "Invalid type for custom lowering!");
4558 if (VT != MVT::v4i16)
4559 return DAG.UnrollVectorOp(Op.getNode());
4561 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
4562 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4565 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4566 EVT VT = Op.getValueType();
4568 return LowerVectorFP_TO_INT(Op, DAG);
4569 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4571 if (Op.getOpcode() == ISD::FP_TO_SINT)
4572 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4575 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4577 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4578 /*isSigned*/ false, SDLoc(Op)).first;
4584 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4585 EVT VT = Op.getValueType();
4588 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4589 if (VT.getVectorElementType() == MVT::f32)
4591 return DAG.UnrollVectorOp(Op.getNode());
4594 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4595 "Invalid type for custom lowering!");
4596 if (VT != MVT::v4f32)
4597 return DAG.UnrollVectorOp(Op.getNode());
4601 switch (Op.getOpcode()) {
4602 default: llvm_unreachable("Invalid opcode!");
4603 case ISD::SINT_TO_FP:
4604 CastOpc = ISD::SIGN_EXTEND;
4605 Opc = ISD::SINT_TO_FP;
4607 case ISD::UINT_TO_FP:
4608 CastOpc = ISD::ZERO_EXTEND;
4609 Opc = ISD::UINT_TO_FP;
4613 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4614 return DAG.getNode(Opc, dl, VT, Op);
4617 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4618 EVT VT = Op.getValueType();
4620 return LowerVectorINT_TO_FP(Op, DAG);
4621 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4623 if (Op.getOpcode() == ISD::SINT_TO_FP)
4624 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4627 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4629 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4630 /*isSigned*/ false, SDLoc(Op)).first;
4636 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4637 // Implement fcopysign with a fabs and a conditional fneg.
4638 SDValue Tmp0 = Op.getOperand(0);
4639 SDValue Tmp1 = Op.getOperand(1);
4641 EVT VT = Op.getValueType();
4642 EVT SrcVT = Tmp1.getValueType();
4643 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4644 Tmp0.getOpcode() == ARMISD::VMOVDRR;
4645 bool UseNEON = !InGPR && Subtarget->hasNEON();
4648 // Use VBSL to copy the sign bit.
4649 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4650 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4651 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4652 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4654 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4655 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4656 DAG.getConstant(32, dl, MVT::i32));
4657 else /*if (VT == MVT::f32)*/
4658 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4659 if (SrcVT == MVT::f32) {
4660 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4662 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4663 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4664 DAG.getConstant(32, dl, MVT::i32));
4665 } else if (VT == MVT::f32)
4666 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4667 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4668 DAG.getConstant(32, dl, MVT::i32));
4669 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4670 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4672 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4674 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4675 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4676 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4678 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4679 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4680 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4681 if (VT == MVT::f32) {
4682 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4683 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4684 DAG.getConstant(0, dl, MVT::i32));
4686 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4692 // Bitcast operand 1 to i32.
4693 if (SrcVT == MVT::f64)
4694 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4696 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4698 // Or in the signbit with integer operations.
4699 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4700 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4701 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4702 if (VT == MVT::f32) {
4703 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4704 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4705 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4706 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4709 // f64: Or the high part with signbit and then combine two parts.
4710 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4712 SDValue Lo = Tmp0.getValue(0);
4713 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4714 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4715 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4718 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4719 MachineFunction &MF = DAG.getMachineFunction();
4720 MachineFrameInfo &MFI = MF.getFrameInfo();
4721 MFI.setReturnAddressIsTaken(true);
4723 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4726 EVT VT = Op.getValueType();
4728 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4730 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4731 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4732 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4733 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4734 MachinePointerInfo());
4737 // Return LR, which contains the return address. Mark it an implicit live-in.
4738 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4739 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4742 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4743 const ARMBaseRegisterInfo &ARI =
4744 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4745 MachineFunction &MF = DAG.getMachineFunction();
4746 MachineFrameInfo &MFI = MF.getFrameInfo();
4747 MFI.setFrameAddressIsTaken(true);
4749 EVT VT = Op.getValueType();
4750 SDLoc dl(Op); // FIXME probably not meaningful
4751 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4752 unsigned FrameReg = ARI.getFrameRegister(MF);
4753 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4755 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4756 MachinePointerInfo());
4760 // FIXME? Maybe this could be a TableGen attribute on some registers and
4761 // this table could be generated automatically from RegInfo.
4762 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4763 SelectionDAG &DAG) const {
4764 unsigned Reg = StringSwitch<unsigned>(RegName)
4765 .Case("sp", ARM::SP)
4769 report_fatal_error(Twine("Invalid register name \""
4770 + StringRef(RegName) + "\"."));
4773 // Result is 64 bit value so split into two 32 bit values and return as a
4775 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4776 SelectionDAG &DAG) {
4779 // This function is only supposed to be called for i64 type destination.
4780 assert(N->getValueType(0) == MVT::i64
4781 && "ExpandREAD_REGISTER called for non-i64 type result.");
4783 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4784 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4788 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4790 Results.push_back(Read.getOperand(0));
4793 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4794 /// When \p DstVT, the destination type of \p BC, is on the vector
4795 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4796 /// it might be possible to combine them, such that everything stays on the
4797 /// vector register bank.
4798 /// \p return The node that would replace \p BT, if the combine
4800 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4801 SelectionDAG &DAG) {
4802 SDValue Op = BC->getOperand(0);
4803 EVT DstVT = BC->getValueType(0);
4805 // The only vector instruction that can produce a scalar (remember,
4806 // since the bitcast was about to be turned into VMOVDRR, the source
4807 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4808 // Moreover, we can do this combine only if there is one use.
4809 // Finally, if the destination type is not a vector, there is not
4810 // much point on forcing everything on the vector bank.
4811 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4815 // If the index is not constant, we will introduce an additional
4816 // multiply that will stick.
4817 // Give up in that case.
4818 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4821 unsigned DstNumElt = DstVT.getVectorNumElements();
4823 // Compute the new index.
4824 const APInt &APIntIndex = Index->getAPIntValue();
4825 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4826 NewIndex *= APIntIndex;
4827 // Check if the new constant index fits into i32.
4828 if (NewIndex.getBitWidth() > 32)
4831 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4832 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4834 SDValue ExtractSrc = Op.getOperand(0);
4835 EVT VecVT = EVT::getVectorVT(
4836 *DAG.getContext(), DstVT.getScalarType(),
4837 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4838 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4839 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4840 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4843 /// ExpandBITCAST - If the target supports VFP, this function is called to
4844 /// expand a bit convert where either the source or destination type is i64 to
4845 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4846 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4847 /// vectors), since the legalizer won't know what to do with that.
4848 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4849 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4851 SDValue Op = N->getOperand(0);
4853 // This function is only supposed to be called for i64 types, either as the
4854 // source or destination of the bit convert.
4855 EVT SrcVT = Op.getValueType();
4856 EVT DstVT = N->getValueType(0);
4857 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4858 "ExpandBITCAST called for non-i64 type");
4860 // Turn i64->f64 into VMOVDRR.
4861 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4862 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4863 // if we can combine the bitcast with its source.
4864 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
4867 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4868 DAG.getConstant(0, dl, MVT::i32));
4869 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4870 DAG.getConstant(1, dl, MVT::i32));
4871 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4872 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4875 // Turn f64->i64 into VMOVRRD.
4876 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4878 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4879 SrcVT.getVectorNumElements() > 1)
4880 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4881 DAG.getVTList(MVT::i32, MVT::i32),
4882 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4884 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4885 DAG.getVTList(MVT::i32, MVT::i32), Op);
4886 // Merge the pieces into a single i64 value.
4887 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4893 /// getZeroVector - Returns a vector of specified type with all zero elements.
4894 /// Zero vectors are used to represent vector negation and in those cases
4895 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4896 /// not support i64 elements, so sometimes the zero vectors will need to be
4897 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4899 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4900 assert(VT.isVector() && "Expected a vector type");
4901 // The canonical modified immediate encoding of a zero vector is....0!
4902 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4903 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4904 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4905 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4908 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4909 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4910 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4911 SelectionDAG &DAG) const {
4912 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4913 EVT VT = Op.getValueType();
4914 unsigned VTBits = VT.getSizeInBits();
4916 SDValue ShOpLo = Op.getOperand(0);
4917 SDValue ShOpHi = Op.getOperand(1);
4918 SDValue ShAmt = Op.getOperand(2);
4920 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4921 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4923 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4925 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4926 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4927 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4928 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4929 DAG.getConstant(VTBits, dl, MVT::i32));
4930 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4931 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4932 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4933 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4934 ISD::SETGE, ARMcc, DAG, dl);
4935 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
4939 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4940 SDValue HiBigShift = Opc == ISD::SRA
4941 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4942 DAG.getConstant(VTBits - 1, dl, VT))
4943 : DAG.getConstant(0, dl, VT);
4944 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4945 ISD::SETGE, ARMcc, DAG, dl);
4946 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
4949 SDValue Ops[2] = { Lo, Hi };
4950 return DAG.getMergeValues(Ops, dl);
4953 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4954 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4955 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4956 SelectionDAG &DAG) const {
4957 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4958 EVT VT = Op.getValueType();
4959 unsigned VTBits = VT.getSizeInBits();
4961 SDValue ShOpLo = Op.getOperand(0);
4962 SDValue ShOpHi = Op.getOperand(1);
4963 SDValue ShAmt = Op.getOperand(2);
4965 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4967 assert(Op.getOpcode() == ISD::SHL_PARTS);
4968 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4969 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4970 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4971 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4972 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4974 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4975 DAG.getConstant(VTBits, dl, MVT::i32));
4976 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4977 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4978 ISD::SETGE, ARMcc, DAG, dl);
4979 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
4982 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4983 ISD::SETGE, ARMcc, DAG, dl);
4984 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4985 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
4986 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
4988 SDValue Ops[2] = { Lo, Hi };
4989 return DAG.getMergeValues(Ops, dl);
4992 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4993 SelectionDAG &DAG) const {
4994 // The rounding mode is in bits 23:22 of the FPSCR.
4995 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4996 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4997 // so that the shift + and get folded into a bitfield extract.
4999 SDValue Ops[] = { DAG.getEntryNode(),
5000 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5002 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5003 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5004 DAG.getConstant(1U << 22, dl, MVT::i32));
5005 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5006 DAG.getConstant(22, dl, MVT::i32));
5007 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5008 DAG.getConstant(3, dl, MVT::i32));
5011 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5012 const ARMSubtarget *ST) {
5014 EVT VT = N->getValueType(0);
5015 if (VT.isVector()) {
5016 assert(ST->hasNEON());
5018 // Compute the least significant set bit: LSB = X & -X
5019 SDValue X = N->getOperand(0);
5020 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5021 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5023 EVT ElemTy = VT.getVectorElementType();
5025 if (ElemTy == MVT::i8) {
5026 // Compute with: cttz(x) = ctpop(lsb - 1)
5027 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5028 DAG.getTargetConstant(1, dl, ElemTy));
5029 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5030 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5033 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5034 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5035 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5036 unsigned NumBits = ElemTy.getSizeInBits();
5037 SDValue WidthMinus1 =
5038 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5039 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5040 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5041 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5044 // Compute with: cttz(x) = ctpop(lsb - 1)
5046 // Since we can only compute the number of bits in a byte with vcnt.8, we
5047 // have to gather the result with pairwise addition (vpaddl) for i16, i32,
5052 if (ElemTy == MVT::i64) {
5053 // Load constant 0xffff'ffff'ffff'ffff to register.
5054 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5055 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5056 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5058 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5059 DAG.getTargetConstant(1, dl, ElemTy));
5060 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5063 // Count #bits with vcnt.8.
5064 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5065 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
5066 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
5068 // Gather the #bits with vpaddl (pairwise add.)
5069 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5070 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
5071 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5073 if (ElemTy == MVT::i16)
5076 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
5077 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
5078 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5080 if (ElemTy == MVT::i32)
5083 assert(ElemTy == MVT::i64);
5084 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5085 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5090 if (!ST->hasV6T2Ops())
5093 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5094 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5097 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
5098 /// for each 16-bit element from operand, repeated. The basic idea is to
5099 /// leverage vcnt to get the 8-bit counts, gather and add the results.
5101 /// Trace for v4i16:
5102 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
5103 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
5104 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
5105 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
5106 /// [b0 b1 b2 b3 b4 b5 b6 b7]
5107 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
5108 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
5109 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
5110 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
5111 EVT VT = N->getValueType(0);
5114 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5115 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
5116 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
5117 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
5118 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
5119 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
5122 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
5123 /// bit-count for each 16-bit element from the operand. We need slightly
5124 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
5125 /// 64/128-bit registers.
5127 /// Trace for v4i16:
5128 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
5129 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
5130 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
5131 /// v4i16:Extracted = [k0 k1 k2 k3 ]
5132 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
5133 EVT VT = N->getValueType(0);
5136 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
5137 if (VT.is64BitVector()) {
5138 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
5139 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
5140 DAG.getIntPtrConstant(0, DL));
5142 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
5143 BitCounts, DAG.getIntPtrConstant(0, DL));
5144 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
5148 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
5149 /// bit-count for each 32-bit element from the operand. The idea here is
5150 /// to split the vector into 16-bit elements, leverage the 16-bit count
5151 /// routine, and then combine the results.
5153 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
5154 /// input = [v0 v1 ] (vi: 32-bit elements)
5155 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
5156 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
5157 /// vrev: N0 = [k1 k0 k3 k2 ]
5159 /// N1 =+[k1 k0 k3 k2 ]
5161 /// N2 =+[k1 k3 k0 k2 ]
5163 /// Extended =+[k1 k3 k0 k2 ]
5165 /// Extracted=+[k1 k3 ]
5167 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
5168 EVT VT = N->getValueType(0);
5171 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5173 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
5174 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
5175 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
5176 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
5177 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
5179 if (VT.is64BitVector()) {
5180 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
5181 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
5182 DAG.getIntPtrConstant(0, DL));
5184 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
5185 DAG.getIntPtrConstant(0, DL));
5186 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
5190 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5191 const ARMSubtarget *ST) {
5192 EVT VT = N->getValueType(0);
5194 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5195 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
5196 VT == MVT::v4i16 || VT == MVT::v8i16) &&
5197 "Unexpected type for custom ctpop lowering");
5199 if (VT.getVectorElementType() == MVT::i32)
5200 return lowerCTPOP32BitElements(N, DAG);
5202 return lowerCTPOP16BitElements(N, DAG);
5205 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5206 const ARMSubtarget *ST) {
5207 EVT VT = N->getValueType(0);
5213 // Lower vector shifts on NEON to use VSHL.
5214 assert(ST->hasNEON() && "unexpected vector shift");
5216 // Left shifts translate directly to the vshiftu intrinsic.
5217 if (N->getOpcode() == ISD::SHL)
5218 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5219 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5221 N->getOperand(0), N->getOperand(1));
5223 assert((N->getOpcode() == ISD::SRA ||
5224 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5226 // NEON uses the same intrinsics for both left and right shifts. For
5227 // right shifts, the shift amounts are negative, so negate the vector of
5229 EVT ShiftVT = N->getOperand(1).getValueType();
5230 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5231 getZeroVector(ShiftVT, DAG, dl),
5233 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5234 Intrinsic::arm_neon_vshifts :
5235 Intrinsic::arm_neon_vshiftu);
5236 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5237 DAG.getConstant(vshiftInt, dl, MVT::i32),
5238 N->getOperand(0), NegatedCount);
5241 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5242 const ARMSubtarget *ST) {
5243 EVT VT = N->getValueType(0);
5246 // We can get here for a node like i32 = ISD::SHL i32, i64
5250 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
5251 "Unknown shift to lower!");
5253 // We only lower SRA, SRL of 1 here, all others use generic lowering.
5254 if (!isOneConstant(N->getOperand(1)))
5257 // If we are in thumb mode, we don't have RRX.
5258 if (ST->isThumb1Only()) return SDValue();
5260 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
5261 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5262 DAG.getConstant(0, dl, MVT::i32));
5263 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5264 DAG.getConstant(1, dl, MVT::i32));
5266 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5267 // captures the result into a carry flag.
5268 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5269 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5271 // The low part is an ARMISD::RRX operand, which shifts the carry in.
5272 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5274 // Merge the pieces into a single i64 value.
5275 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5278 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5279 SDValue TmpOp0, TmpOp1;
5280 bool Invert = false;
5284 SDValue Op0 = Op.getOperand(0);
5285 SDValue Op1 = Op.getOperand(1);
5286 SDValue CC = Op.getOperand(2);
5287 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5288 EVT VT = Op.getValueType();
5289 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5292 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5293 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5294 // Special-case integer 64-bit equality comparisons. They aren't legal,
5295 // but they can be lowered with a few vector instructions.
5296 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5297 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5298 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5299 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5300 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5301 DAG.getCondCode(ISD::SETEQ));
5302 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5303 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5304 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5305 if (SetCCOpcode == ISD::SETNE)
5306 Merged = DAG.getNOT(dl, Merged, CmpVT);
5307 Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5311 if (CmpVT.getVectorElementType() == MVT::i64)
5312 // 64-bit comparisons are not legal in general.
5315 if (Op1.getValueType().isFloatingPoint()) {
5316 switch (SetCCOpcode) {
5317 default: llvm_unreachable("Illegal FP comparison");
5319 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH;
5321 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
5323 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5325 case ISD::SETGT: Opc = ARMISD::VCGT; break;
5327 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
5329 case ISD::SETGE: Opc = ARMISD::VCGE; break;
5330 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5331 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5332 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5333 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5334 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5336 // Expand this to (OLT | OGT).
5340 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5341 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5347 // Expand this to (OLT | OGE).
5351 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5352 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5356 // Integer comparisons.
5357 switch (SetCCOpcode) {
5358 default: llvm_unreachable("Illegal integer comparison");
5359 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH;
5360 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
5361 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5362 case ISD::SETGT: Opc = ARMISD::VCGT; break;
5363 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
5364 case ISD::SETGE: Opc = ARMISD::VCGE; break;
5365 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
5366 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5367 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
5368 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5371 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5372 if (Opc == ARMISD::VCEQ) {
5375 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5377 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5380 // Ignore bitconvert.
5381 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5382 AndOp = AndOp.getOperand(0);
5384 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5386 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5387 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5394 std::swap(Op0, Op1);
5396 // If one of the operands is a constant vector zero, attempt to fold the
5397 // comparison to a specialized compare-against-zero form.
5399 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5401 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5402 if (Opc == ARMISD::VCGE)
5403 Opc = ARMISD::VCLEZ;
5404 else if (Opc == ARMISD::VCGT)
5405 Opc = ARMISD::VCLTZ;
5410 if (SingleOp.getNode()) {
5413 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5415 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5417 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5419 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5421 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5423 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5426 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5429 Result = DAG.getSExtOrTrunc(Result, dl, VT);
5432 Result = DAG.getNOT(dl, Result, VT);
5437 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) {
5438 SDValue LHS = Op.getOperand(0);
5439 SDValue RHS = Op.getOperand(1);
5440 SDValue Carry = Op.getOperand(2);
5441 SDValue Cond = Op.getOperand(3);
5444 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
5446 assert(Carry.getOpcode() != ISD::CARRY_FALSE);
5447 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5448 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5450 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5451 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5452 SDValue ARMcc = DAG.getConstant(
5453 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5454 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5455 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5456 Cmp.getValue(1), SDValue());
5457 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5458 CCR, Chain.getValue(1));
5461 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5462 /// valid vector constant for a NEON instruction with a "modified immediate"
5463 /// operand (e.g., VMOV). If so, return the encoded value.
5464 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5465 unsigned SplatBitSize, SelectionDAG &DAG,
5466 const SDLoc &dl, EVT &VT, bool is128Bits,
5467 NEONModImmType type) {
5468 unsigned OpCmode, Imm;
5470 // SplatBitSize is set to the smallest size that splats the vector, so a
5471 // zero vector will always have SplatBitSize == 8. However, NEON modified
5472 // immediate instructions others than VMOV do not support the 8-bit encoding
5473 // of a zero vector, and the default encoding of zero is supposed to be the
5478 switch (SplatBitSize) {
5480 if (type != VMOVModImm)
5482 // Any 1-byte value is OK. Op=0, Cmode=1110.
5483 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5486 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5490 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5491 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5492 if ((SplatBits & ~0xff) == 0) {
5493 // Value = 0x00nn: Op=x, Cmode=100x.
5498 if ((SplatBits & ~0xff00) == 0) {
5499 // Value = 0xnn00: Op=x, Cmode=101x.
5501 Imm = SplatBits >> 8;
5507 // NEON's 32-bit VMOV supports splat values where:
5508 // * only one byte is nonzero, or
5509 // * the least significant byte is 0xff and the second byte is nonzero, or
5510 // * the least significant 2 bytes are 0xff and the third is nonzero.
5511 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5512 if ((SplatBits & ~0xff) == 0) {
5513 // Value = 0x000000nn: Op=x, Cmode=000x.
5518 if ((SplatBits & ~0xff00) == 0) {
5519 // Value = 0x0000nn00: Op=x, Cmode=001x.
5521 Imm = SplatBits >> 8;
5524 if ((SplatBits & ~0xff0000) == 0) {
5525 // Value = 0x00nn0000: Op=x, Cmode=010x.
5527 Imm = SplatBits >> 16;
5530 if ((SplatBits & ~0xff000000) == 0) {
5531 // Value = 0xnn000000: Op=x, Cmode=011x.
5533 Imm = SplatBits >> 24;
5537 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5538 if (type == OtherModImm) return SDValue();
5540 if ((SplatBits & ~0xffff) == 0 &&
5541 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5542 // Value = 0x0000nnff: Op=x, Cmode=1100.
5544 Imm = SplatBits >> 8;
5548 if ((SplatBits & ~0xffffff) == 0 &&
5549 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5550 // Value = 0x00nnffff: Op=x, Cmode=1101.
5552 Imm = SplatBits >> 16;
5556 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5557 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5558 // VMOV.I32. A (very) minor optimization would be to replicate the value
5559 // and fall through here to test for a valid 64-bit splat. But, then the
5560 // caller would also need to check and handle the change in size.
5564 if (type != VMOVModImm)
5566 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5567 uint64_t BitMask = 0xff;
5569 unsigned ImmMask = 1;
5571 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5572 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5575 } else if ((SplatBits & BitMask) != 0) {
5582 if (DAG.getDataLayout().isBigEndian())
5583 // swap higher and lower 32 bit word
5584 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5586 // Op=1, Cmode=1110.
5588 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5593 llvm_unreachable("unexpected size for isNEONModifiedImm");
5596 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5597 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5600 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5601 const ARMSubtarget *ST) const {
5602 bool IsDouble = Op.getValueType() == MVT::f64;
5603 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5604 const APFloat &FPVal = CFP->getValueAPF();
5606 // Prevent floating-point constants from using literal loads
5607 // when execute-only is enabled.
5608 if (ST->genExecuteOnly()) {
5609 APInt INTVal = FPVal.bitcastToAPInt();
5612 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
5613 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
5614 if (!ST->isLittle())
5616 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
5618 return DAG.getConstant(INTVal, DL, MVT::i32);
5625 // Use the default (constant pool) lowering for double constants when we have
5627 if (IsDouble && Subtarget->isFPOnlySP())
5630 // Try splatting with a VMOV.f32...
5631 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5634 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5635 // We have code in place to select a valid ConstantFP already, no need to
5640 // It's a float and we are trying to use NEON operations where
5641 // possible. Lower it to a splat followed by an extract.
5643 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5644 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5646 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5647 DAG.getConstant(0, DL, MVT::i32));
5650 // The rest of our options are NEON only, make sure that's allowed before
5652 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5656 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5658 // It wouldn't really be worth bothering for doubles except for one very
5659 // important value, which does happen to match: 0.0. So make sure we don't do
5661 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5664 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5665 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5666 VMovVT, false, VMOVModImm);
5667 if (NewVal != SDValue()) {
5669 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5672 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5674 // It's a float: cast and extract a vector element.
5675 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5677 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5678 DAG.getConstant(0, DL, MVT::i32));
5681 // Finally, try a VMVN.i32
5682 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5684 if (NewVal != SDValue()) {
5686 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5689 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5691 // It's a float: cast and extract a vector element.
5692 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5694 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5695 DAG.getConstant(0, DL, MVT::i32));
5701 // check if an VEXT instruction can handle the shuffle mask when the
5702 // vector sources of the shuffle are the same.
5703 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5704 unsigned NumElts = VT.getVectorNumElements();
5706 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5712 // If this is a VEXT shuffle, the immediate value is the index of the first
5713 // element. The other shuffle indices must be the successive elements after
5715 unsigned ExpectedElt = Imm;
5716 for (unsigned i = 1; i < NumElts; ++i) {
5717 // Increment the expected index. If it wraps around, just follow it
5718 // back to index zero and keep going.
5720 if (ExpectedElt == NumElts)
5723 if (M[i] < 0) continue; // ignore UNDEF indices
5724 if (ExpectedElt != static_cast<unsigned>(M[i]))
5731 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5732 bool &ReverseVEXT, unsigned &Imm) {
5733 unsigned NumElts = VT.getVectorNumElements();
5734 ReverseVEXT = false;
5736 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5742 // If this is a VEXT shuffle, the immediate value is the index of the first
5743 // element. The other shuffle indices must be the successive elements after
5745 unsigned ExpectedElt = Imm;
5746 for (unsigned i = 1; i < NumElts; ++i) {
5747 // Increment the expected index. If it wraps around, it may still be
5748 // a VEXT but the source vectors must be swapped.
5750 if (ExpectedElt == NumElts * 2) {
5755 if (M[i] < 0) continue; // ignore UNDEF indices
5756 if (ExpectedElt != static_cast<unsigned>(M[i]))
5760 // Adjust the index value if the source operands will be swapped.
5767 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5768 /// instruction with the specified blocksize. (The order of the elements
5769 /// within each block of the vector is reversed.)
5770 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5771 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5772 "Only possible block sizes for VREV are: 16, 32, 64");
5774 unsigned EltSz = VT.getScalarSizeInBits();
5778 unsigned NumElts = VT.getVectorNumElements();
5779 unsigned BlockElts = M[0] + 1;
5780 // If the first shuffle index is UNDEF, be optimistic.
5782 BlockElts = BlockSize / EltSz;
5784 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5787 for (unsigned i = 0; i < NumElts; ++i) {
5788 if (M[i] < 0) continue; // ignore UNDEF indices
5789 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5796 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5797 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5798 // range, then 0 is placed into the resulting vector. So pretty much any mask
5799 // of 8 elements can work here.
5800 return VT == MVT::v8i8 && M.size() == 8;
5803 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5804 // checking that pairs of elements in the shuffle mask represent the same index
5805 // in each vector, incrementing the expected index by 2 at each step.
5806 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5807 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5809 // WhichResult gives the offset for each element in the mask based on which
5810 // of the two results it belongs to.
5812 // The transpose can be represented either as:
5813 // result1 = shufflevector v1, v2, result1_shuffle_mask
5814 // result2 = shufflevector v1, v2, result2_shuffle_mask
5815 // where v1/v2 and the shuffle masks have the same number of elements
5816 // (here WhichResult (see below) indicates which result is being checked)
5819 // results = shufflevector v1, v2, shuffle_mask
5820 // where both results are returned in one vector and the shuffle mask has twice
5821 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5822 // want to check the low half and high half of the shuffle mask as if it were
5824 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5825 unsigned EltSz = VT.getScalarSizeInBits();
5829 unsigned NumElts = VT.getVectorNumElements();
5830 if (M.size() != NumElts && M.size() != NumElts*2)
5833 // If the mask is twice as long as the input vector then we need to check the
5834 // upper and lower parts of the mask with a matching value for WhichResult
5835 // FIXME: A mask with only even values will be rejected in case the first
5836 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5837 // M[0] is used to determine WhichResult
5838 for (unsigned i = 0; i < M.size(); i += NumElts) {
5839 if (M.size() == NumElts * 2)
5840 WhichResult = i / NumElts;
5842 WhichResult = M[i] == 0 ? 0 : 1;
5843 for (unsigned j = 0; j < NumElts; j += 2) {
5844 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5845 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5850 if (M.size() == NumElts*2)
5856 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5857 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5858 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5859 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5860 unsigned EltSz = VT.getScalarSizeInBits();
5864 unsigned NumElts = VT.getVectorNumElements();
5865 if (M.size() != NumElts && M.size() != NumElts*2)
5868 for (unsigned i = 0; i < M.size(); i += NumElts) {
5869 if (M.size() == NumElts * 2)
5870 WhichResult = i / NumElts;
5872 WhichResult = M[i] == 0 ? 0 : 1;
5873 for (unsigned j = 0; j < NumElts; j += 2) {
5874 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5875 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5880 if (M.size() == NumElts*2)
5886 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5887 // that the mask elements are either all even and in steps of size 2 or all odd
5888 // and in steps of size 2.
5889 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5890 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5892 // Requires similar checks to that of isVTRNMask with
5893 // respect the how results are returned.
5894 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5895 unsigned EltSz = VT.getScalarSizeInBits();
5899 unsigned NumElts = VT.getVectorNumElements();
5900 if (M.size() != NumElts && M.size() != NumElts*2)
5903 for (unsigned i = 0; i < M.size(); i += NumElts) {
5904 if (M.size() == NumElts * 2)
5905 WhichResult = i / NumElts;
5907 WhichResult = M[i] == 0 ? 0 : 1;
5908 for (unsigned j = 0; j < NumElts; ++j) {
5909 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5914 if (M.size() == NumElts*2)
5917 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5918 if (VT.is64BitVector() && EltSz == 32)
5924 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5925 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5926 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5927 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5928 unsigned EltSz = VT.getScalarSizeInBits();
5932 unsigned NumElts = VT.getVectorNumElements();
5933 if (M.size() != NumElts && M.size() != NumElts*2)
5936 unsigned Half = NumElts / 2;
5937 for (unsigned i = 0; i < M.size(); i += NumElts) {
5938 if (M.size() == NumElts * 2)
5939 WhichResult = i / NumElts;
5941 WhichResult = M[i] == 0 ? 0 : 1;
5942 for (unsigned j = 0; j < NumElts; j += Half) {
5943 unsigned Idx = WhichResult;
5944 for (unsigned k = 0; k < Half; ++k) {
5945 int MIdx = M[i + j + k];
5946 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5953 if (M.size() == NumElts*2)
5956 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5957 if (VT.is64BitVector() && EltSz == 32)
5963 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5964 // that pairs of elements of the shufflemask represent the same index in each
5965 // vector incrementing sequentially through the vectors.
5966 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5967 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5969 // Requires similar checks to that of isVTRNMask with respect the how results
5971 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5972 unsigned EltSz = VT.getScalarSizeInBits();
5976 unsigned NumElts = VT.getVectorNumElements();
5977 if (M.size() != NumElts && M.size() != NumElts*2)
5980 for (unsigned i = 0; i < M.size(); i += NumElts) {
5981 if (M.size() == NumElts * 2)
5982 WhichResult = i / NumElts;
5984 WhichResult = M[i] == 0 ? 0 : 1;
5985 unsigned Idx = WhichResult * NumElts / 2;
5986 for (unsigned j = 0; j < NumElts; j += 2) {
5987 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5988 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5994 if (M.size() == NumElts*2)
5997 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5998 if (VT.is64BitVector() && EltSz == 32)
6004 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6005 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6006 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6007 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6008 unsigned EltSz = VT.getScalarSizeInBits();
6012 unsigned NumElts = VT.getVectorNumElements();
6013 if (M.size() != NumElts && M.size() != NumElts*2)
6016 for (unsigned i = 0; i < M.size(); i += NumElts) {
6017 if (M.size() == NumElts * 2)
6018 WhichResult = i / NumElts;
6020 WhichResult = M[i] == 0 ? 0 : 1;
6021 unsigned Idx = WhichResult * NumElts / 2;
6022 for (unsigned j = 0; j < NumElts; j += 2) {
6023 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6024 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6030 if (M.size() == NumElts*2)
6033 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6034 if (VT.is64BitVector() && EltSz == 32)
6040 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6041 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6042 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6043 unsigned &WhichResult,
6046 if (isVTRNMask(ShuffleMask, VT, WhichResult))
6047 return ARMISD::VTRN;
6048 if (isVUZPMask(ShuffleMask, VT, WhichResult))
6049 return ARMISD::VUZP;
6050 if (isVZIPMask(ShuffleMask, VT, WhichResult))
6051 return ARMISD::VZIP;
6054 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6055 return ARMISD::VTRN;
6056 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6057 return ARMISD::VUZP;
6058 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6059 return ARMISD::VZIP;
6064 /// \return true if this is a reverse operation on an vector.
6065 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6066 unsigned NumElts = VT.getVectorNumElements();
6067 // Make sure the mask has the right size.
6068 if (NumElts != M.size())
6071 // Look for <15, ..., 3, -1, 1, 0>.
6072 for (unsigned i = 0; i != NumElts; ++i)
6073 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6079 // If N is an integer constant that can be moved into a register in one
6080 // instruction, return an SDValue of such a constant (will become a MOV
6081 // instruction). Otherwise return null.
6082 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6083 const ARMSubtarget *ST, const SDLoc &dl) {
6085 if (!isa<ConstantSDNode>(N))
6087 Val = cast<ConstantSDNode>(N)->getZExtValue();
6089 if (ST->isThumb1Only()) {
6090 if (Val <= 255 || ~Val <= 255)
6091 return DAG.getConstant(Val, dl, MVT::i32);
6093 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6094 return DAG.getConstant(Val, dl, MVT::i32);
6099 // If this is a case we can't handle, return null and let the default
6100 // expansion code take care of it.
6101 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6102 const ARMSubtarget *ST) const {
6103 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6105 EVT VT = Op.getValueType();
6107 APInt SplatBits, SplatUndef;
6108 unsigned SplatBitSize;
6110 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6111 if (SplatUndef.isAllOnesValue())
6112 return DAG.getUNDEF(VT);
6114 if (SplatBitSize <= 64) {
6115 // Check if an immediate VMOV works.
6117 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6118 SplatUndef.getZExtValue(), SplatBitSize,
6119 DAG, dl, VmovVT, VT.is128BitVector(),
6121 if (Val.getNode()) {
6122 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6123 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6126 // Try an immediate VMVN.
6127 uint64_t NegatedImm = (~SplatBits).getZExtValue();
6128 Val = isNEONModifiedImm(NegatedImm,
6129 SplatUndef.getZExtValue(), SplatBitSize,
6130 DAG, dl, VmovVT, VT.is128BitVector(),
6132 if (Val.getNode()) {
6133 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6134 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6137 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6138 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6139 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6141 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6142 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6148 // Scan through the operands to see if only one value is used.
6150 // As an optimisation, even if more than one value is used it may be more
6151 // profitable to splat with one value then change some lanes.
6153 // Heuristically we decide to do this if the vector has a "dominant" value,
6154 // defined as splatted to more than half of the lanes.
6155 unsigned NumElts = VT.getVectorNumElements();
6156 bool isOnlyLowElement = true;
6157 bool usesOnlyOneValue = true;
6158 bool hasDominantValue = false;
6159 bool isConstant = true;
6161 // Map of the number of times a particular SDValue appears in the
6163 DenseMap<SDValue, unsigned> ValueCounts;
6165 for (unsigned i = 0; i < NumElts; ++i) {
6166 SDValue V = Op.getOperand(i);
6170 isOnlyLowElement = false;
6171 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6174 ValueCounts.insert(std::make_pair(V, 0));
6175 unsigned &Count = ValueCounts[V];
6177 // Is this value dominant? (takes up more than half of the lanes)
6178 if (++Count > (NumElts / 2)) {
6179 hasDominantValue = true;
6183 if (ValueCounts.size() != 1)
6184 usesOnlyOneValue = false;
6185 if (!Value.getNode() && !ValueCounts.empty())
6186 Value = ValueCounts.begin()->first;
6188 if (ValueCounts.empty())
6189 return DAG.getUNDEF(VT);
6191 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6192 // Keep going if we are hitting this case.
6193 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6194 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6196 unsigned EltSize = VT.getScalarSizeInBits();
6198 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
6199 // i32 and try again.
6200 if (hasDominantValue && EltSize <= 32) {
6204 // If we are VDUPing a value that comes directly from a vector, that will
6205 // cause an unnecessary move to and from a GPR, where instead we could
6206 // just use VDUPLANE. We can only do this if the lane being extracted
6207 // is at a constant index, as the VDUP from lane instructions only have
6208 // constant-index forms.
6209 ConstantSDNode *constIndex;
6210 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6211 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6212 // We need to create a new undef vector to use for the VDUPLANE if the
6213 // size of the vector from which we get the value is different than the
6214 // size of the vector that we need to create. We will insert the element
6215 // such that the register coalescer will remove unnecessary copies.
6216 if (VT != Value->getOperand(0).getValueType()) {
6217 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6218 VT.getVectorNumElements();
6219 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6220 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6221 Value, DAG.getConstant(index, dl, MVT::i32)),
6222 DAG.getConstant(index, dl, MVT::i32));
6224 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6225 Value->getOperand(0), Value->getOperand(1));
6227 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6229 if (!usesOnlyOneValue) {
6230 // The dominant value was splatted as 'N', but we now have to insert
6231 // all differing elements.
6232 for (unsigned I = 0; I < NumElts; ++I) {
6233 if (Op.getOperand(I) == Value)
6235 SmallVector<SDValue, 3> Ops;
6237 Ops.push_back(Op.getOperand(I));
6238 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6239 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6244 if (VT.getVectorElementType().isFloatingPoint()) {
6245 SmallVector<SDValue, 8> Ops;
6246 for (unsigned i = 0; i < NumElts; ++i)
6247 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
6249 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
6250 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6251 Val = LowerBUILD_VECTOR(Val, DAG, ST);
6253 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6255 if (usesOnlyOneValue) {
6256 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6257 if (isConstant && Val.getNode())
6258 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6262 // If all elements are constants and the case above didn't get hit, fall back
6263 // to the default expansion, which will generate a load from the constant
6268 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6270 SDValue shuffle = ReconstructShuffle(Op, DAG);
6271 if (shuffle != SDValue())
6275 if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6276 // If we haven't found an efficient lowering, try splitting a 128-bit vector
6277 // into two 64-bit vectors; we might discover a better way to lower it.
6278 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6279 EVT ExtVT = VT.getVectorElementType();
6280 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6282 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6283 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6284 Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6285 SDValue Upper = DAG.getBuildVector(
6286 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6287 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6288 Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6290 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6293 // Vectors with 32- or 64-bit elements can be built by directly assigning
6294 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
6295 // will be legalized.
6296 if (EltSize >= 32) {
6297 // Do the expansion with floating-point types, since that is what the VFP
6298 // registers are defined to use, and since i64 is not legal.
6299 EVT EltVT = EVT::getFloatingPointVT(EltSize);
6300 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6301 SmallVector<SDValue, 8> Ops;
6302 for (unsigned i = 0; i < NumElts; ++i)
6303 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6304 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6305 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6308 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6309 // know the default expansion would otherwise fall back on something even
6310 // worse. For a vector with one or two non-undef values, that's
6311 // scalar_to_vector for the elements followed by a shuffle (provided the
6312 // shuffle is valid for the target) and materialization element by element
6313 // on the stack followed by a load for everything else.
6314 if (!isConstant && !usesOnlyOneValue) {
6315 SDValue Vec = DAG.getUNDEF(VT);
6316 for (unsigned i = 0 ; i < NumElts; ++i) {
6317 SDValue V = Op.getOperand(i);
6320 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6321 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6329 // Gather data to see if the operation can be modelled as a
6330 // shuffle in combination with VEXTs.
6331 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6332 SelectionDAG &DAG) const {
6333 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6335 EVT VT = Op.getValueType();
6336 unsigned NumElts = VT.getVectorNumElements();
6338 struct ShuffleSourceInfo {
6340 unsigned MinElt = std::numeric_limits<unsigned>::max();
6341 unsigned MaxElt = 0;
6343 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6344 // be compatible with the shuffle we intend to construct. As a result
6345 // ShuffleVec will be some sliding window into the original Vec.
6348 // Code should guarantee that element i in Vec starts at element "WindowBase
6349 // + i * WindowScale in ShuffleVec".
6351 int WindowScale = 1;
6353 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
6355 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6358 // First gather all vectors used as an immediate source for this BUILD_VECTOR
6360 SmallVector<ShuffleSourceInfo, 2> Sources;
6361 for (unsigned i = 0; i < NumElts; ++i) {
6362 SDValue V = Op.getOperand(i);
6365 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6366 // A shuffle can only come from building a vector from various
6367 // elements of other vectors.
6369 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6370 // Furthermore, shuffles require a constant mask, whereas extractelts
6371 // accept variable indices.
6375 // Add this element source to the list if it's not already there.
6376 SDValue SourceVec = V.getOperand(0);
6377 auto Source = llvm::find(Sources, SourceVec);
6378 if (Source == Sources.end())
6379 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6381 // Update the minimum and maximum lane number seen.
6382 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6383 Source->MinElt = std::min(Source->MinElt, EltNo);
6384 Source->MaxElt = std::max(Source->MaxElt, EltNo);
6387 // Currently only do something sane when at most two source vectors
6389 if (Sources.size() > 2)
6392 // Find out the smallest element size among result and two sources, and use
6393 // it as element size to build the shuffle_vector.
6394 EVT SmallestEltTy = VT.getVectorElementType();
6395 for (auto &Source : Sources) {
6396 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6397 if (SrcEltTy.bitsLT(SmallestEltTy))
6398 SmallestEltTy = SrcEltTy;
6400 unsigned ResMultiplier =
6401 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6402 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6403 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6405 // If the source vector is too wide or too narrow, we may nevertheless be able
6406 // to construct a compatible shuffle either by concatenating it with UNDEF or
6407 // extracting a suitable range of elements.
6408 for (auto &Src : Sources) {
6409 EVT SrcVT = Src.ShuffleVec.getValueType();
6411 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6414 // This stage of the search produces a source with the same element type as
6415 // the original, but with a total width matching the BUILD_VECTOR output.
6416 EVT EltVT = SrcVT.getVectorElementType();
6417 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6418 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6420 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6421 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6423 // We can pad out the smaller vector for free, so if it's part of a
6426 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6427 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6431 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6434 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6435 // Span too large for a VEXT to cope
6439 if (Src.MinElt >= NumSrcElts) {
6440 // The extraction can just take the second half
6442 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6443 DAG.getConstant(NumSrcElts, dl, MVT::i32));
6444 Src.WindowBase = -NumSrcElts;
6445 } else if (Src.MaxElt < NumSrcElts) {
6446 // The extraction can just take the first half
6448 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6449 DAG.getConstant(0, dl, MVT::i32));
6451 // An actual VEXT is needed
6453 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6454 DAG.getConstant(0, dl, MVT::i32));
6456 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6457 DAG.getConstant(NumSrcElts, dl, MVT::i32));
6459 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6461 DAG.getConstant(Src.MinElt, dl, MVT::i32));
6462 Src.WindowBase = -Src.MinElt;
6466 // Another possible incompatibility occurs from the vector element types. We
6467 // can fix this by bitcasting the source vectors to the same type we intend
6469 for (auto &Src : Sources) {
6470 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6471 if (SrcEltTy == SmallestEltTy)
6473 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6474 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6475 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6476 Src.WindowBase *= Src.WindowScale;
6479 // Final sanity check before we try to actually produce a shuffle.
6481 for (auto Src : Sources)
6482 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
6485 // The stars all align, our next step is to produce the mask for the shuffle.
6486 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6487 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6488 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6489 SDValue Entry = Op.getOperand(i);
6490 if (Entry.isUndef())
6493 auto Src = llvm::find(Sources, Entry.getOperand(0));
6494 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6496 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6497 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6499 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6500 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6501 VT.getScalarSizeInBits());
6502 int LanesDefined = BitsDefined / BitsPerShuffleLane;
6504 // This source is expected to fill ResMultiplier lanes of the final shuffle,
6505 // starting at the appropriate offset.
6506 int *LaneMask = &Mask[i * ResMultiplier];
6508 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6509 ExtractBase += NumElts * (Src - Sources.begin());
6510 for (int j = 0; j < LanesDefined; ++j)
6511 LaneMask[j] = ExtractBase + j;
6514 // Final check before we try to produce nonsense...
6515 if (!isShuffleMaskLegal(Mask, ShuffleVT))
6518 // We can't handle more than two sources. This should have already
6519 // been checked before this point.
6520 assert(Sources.size() <= 2 && "Too many sources!");
6522 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6523 for (unsigned i = 0; i < Sources.size(); ++i)
6524 ShuffleOps[i] = Sources[i].ShuffleVec;
6526 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6527 ShuffleOps[1], Mask);
6528 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6531 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6532 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6533 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6534 /// are assumed to be legal.
6536 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6538 if (VT.getVectorNumElements() == 4 &&
6539 (VT.is128BitVector() || VT.is64BitVector())) {
6540 unsigned PFIndexes[4];
6541 for (unsigned i = 0; i != 4; ++i) {
6545 PFIndexes[i] = M[i];
6548 // Compute the index in the perfect shuffle table.
6549 unsigned PFTableIndex =
6550 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6551 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6552 unsigned Cost = (PFEntry >> 30);
6558 bool ReverseVEXT, isV_UNDEF;
6559 unsigned Imm, WhichResult;
6561 unsigned EltSize = VT.getScalarSizeInBits();
6562 return (EltSize >= 32 ||
6563 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6564 isVREVMask(M, VT, 64) ||
6565 isVREVMask(M, VT, 32) ||
6566 isVREVMask(M, VT, 16) ||
6567 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6568 isVTBLMask(M, VT) ||
6569 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6570 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6573 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6574 /// the specified operations to build the shuffle.
6575 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6576 SDValue RHS, SelectionDAG &DAG,
6578 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6579 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6580 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
6583 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6592 OP_VUZPL, // VUZP, left result
6593 OP_VUZPR, // VUZP, right result
6594 OP_VZIPL, // VZIP, left result
6595 OP_VZIPR, // VZIP, right result
6596 OP_VTRNL, // VTRN, left result
6597 OP_VTRNR // VTRN, right result
6600 if (OpNum == OP_COPY) {
6601 if (LHSID == (1*9+2)*9+3) return LHS;
6602 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6606 SDValue OpLHS, OpRHS;
6607 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6608 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6609 EVT VT = OpLHS.getValueType();
6612 default: llvm_unreachable("Unknown shuffle opcode!");
6614 // VREV divides the vector in half and swaps within the half.
6615 if (VT.getVectorElementType() == MVT::i32 ||
6616 VT.getVectorElementType() == MVT::f32)
6617 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6618 // vrev <4 x i16> -> VREV32
6619 if (VT.getVectorElementType() == MVT::i16)
6620 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6621 // vrev <4 x i8> -> VREV16
6622 assert(VT.getVectorElementType() == MVT::i8);
6623 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6628 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6629 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6633 return DAG.getNode(ARMISD::VEXT, dl, VT,
6635 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6638 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6639 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6642 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6643 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6646 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6647 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6651 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6652 ArrayRef<int> ShuffleMask,
6653 SelectionDAG &DAG) {
6654 // Check to see if we can use the VTBL instruction.
6655 SDValue V1 = Op.getOperand(0);
6656 SDValue V2 = Op.getOperand(1);
6659 SmallVector<SDValue, 8> VTBLMask;
6660 for (ArrayRef<int>::iterator
6661 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6662 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6664 if (V2.getNode()->isUndef())
6665 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6666 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6668 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6669 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6672 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6673 SelectionDAG &DAG) {
6675 SDValue OpLHS = Op.getOperand(0);
6676 EVT VT = OpLHS.getValueType();
6678 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6679 "Expect an v8i16/v16i8 type");
6680 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6681 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6682 // extract the first 8 bytes into the top double word and the last 8 bytes
6683 // into the bottom double word. The v8i16 case is similar.
6684 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6685 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6686 DAG.getConstant(ExtractNum, DL, MVT::i32));
6689 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6690 SDValue V1 = Op.getOperand(0);
6691 SDValue V2 = Op.getOperand(1);
6693 EVT VT = Op.getValueType();
6694 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6696 // Convert shuffles that are directly supported on NEON to target-specific
6697 // DAG nodes, instead of keeping them as shuffles and matching them again
6698 // during code selection. This is more efficient and avoids the possibility
6699 // of inconsistencies between legalization and selection.
6700 // FIXME: floating-point vectors should be canonicalized to integer vectors
6701 // of the same time so that they get CSEd properly.
6702 ArrayRef<int> ShuffleMask = SVN->getMask();
6704 unsigned EltSize = VT.getScalarSizeInBits();
6705 if (EltSize <= 32) {
6706 if (SVN->isSplat()) {
6707 int Lane = SVN->getSplatIndex();
6708 // If this is undef splat, generate it via "just" vdup, if possible.
6709 if (Lane == -1) Lane = 0;
6711 // Test if V1 is a SCALAR_TO_VECTOR.
6712 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6713 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6715 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6716 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6718 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6719 !isa<ConstantSDNode>(V1.getOperand(0))) {
6720 bool IsScalarToVector = true;
6721 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6722 if (!V1.getOperand(i).isUndef()) {
6723 IsScalarToVector = false;
6726 if (IsScalarToVector)
6727 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6729 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6730 DAG.getConstant(Lane, dl, MVT::i32));
6735 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6738 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6739 DAG.getConstant(Imm, dl, MVT::i32));
6742 if (isVREVMask(ShuffleMask, VT, 64))
6743 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6744 if (isVREVMask(ShuffleMask, VT, 32))
6745 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6746 if (isVREVMask(ShuffleMask, VT, 16))
6747 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6749 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6750 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6751 DAG.getConstant(Imm, dl, MVT::i32));
6754 // Check for Neon shuffles that modify both input vectors in place.
6755 // If both results are used, i.e., if there are two shuffles with the same
6756 // source operands and with masks corresponding to both results of one of
6757 // these operations, DAG memoization will ensure that a single node is
6758 // used for both shuffles.
6759 unsigned WhichResult;
6761 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6762 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6765 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6766 .getValue(WhichResult);
6769 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6770 // shuffles that produce a result larger than their operands with:
6771 // shuffle(concat(v1, undef), concat(v2, undef))
6773 // shuffle(concat(v1, v2), undef)
6774 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6776 // This is useful in the general case, but there are special cases where
6777 // native shuffles produce larger results: the two-result ops.
6779 // Look through the concat when lowering them:
6780 // shuffle(concat(v1, v2), undef)
6782 // concat(VZIP(v1, v2):0, :1)
6784 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
6785 SDValue SubV1 = V1->getOperand(0);
6786 SDValue SubV2 = V1->getOperand(1);
6787 EVT SubVT = SubV1.getValueType();
6789 // We expect these to have been canonicalized to -1.
6790 assert(llvm::all_of(ShuffleMask, [&](int i) {
6791 return i < (int)VT.getVectorNumElements();
6792 }) && "Unexpected shuffle index into UNDEF operand!");
6794 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6795 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6798 assert((WhichResult == 0) &&
6799 "In-place shuffle of concat can only have one result!");
6800 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6802 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6808 // If the shuffle is not directly supported and it has 4 elements, use
6809 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6810 unsigned NumElts = VT.getVectorNumElements();
6812 unsigned PFIndexes[4];
6813 for (unsigned i = 0; i != 4; ++i) {
6814 if (ShuffleMask[i] < 0)
6817 PFIndexes[i] = ShuffleMask[i];
6820 // Compute the index in the perfect shuffle table.
6821 unsigned PFTableIndex =
6822 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6823 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6824 unsigned Cost = (PFEntry >> 30);
6827 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6830 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6831 if (EltSize >= 32) {
6832 // Do the expansion with floating-point types, since that is what the VFP
6833 // registers are defined to use, and since i64 is not legal.
6834 EVT EltVT = EVT::getFloatingPointVT(EltSize);
6835 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6836 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6837 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6838 SmallVector<SDValue, 8> Ops;
6839 for (unsigned i = 0; i < NumElts; ++i) {
6840 if (ShuffleMask[i] < 0)
6841 Ops.push_back(DAG.getUNDEF(EltVT));
6843 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6844 ShuffleMask[i] < (int)NumElts ? V1 : V2,
6845 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6848 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6849 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6852 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6853 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6855 if (VT == MVT::v8i8)
6856 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
6862 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6863 // INSERT_VECTOR_ELT is legal only for immediate indexes.
6864 SDValue Lane = Op.getOperand(2);
6865 if (!isa<ConstantSDNode>(Lane))
6871 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6872 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6873 SDValue Lane = Op.getOperand(1);
6874 if (!isa<ConstantSDNode>(Lane))
6877 SDValue Vec = Op.getOperand(0);
6878 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
6880 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6886 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6887 // The only time a CONCAT_VECTORS operation can have legal types is when
6888 // two 64-bit vectors are concatenated to a 128-bit vector.
6889 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6890 "unexpected CONCAT_VECTORS");
6892 SDValue Val = DAG.getUNDEF(MVT::v2f64);
6893 SDValue Op0 = Op.getOperand(0);
6894 SDValue Op1 = Op.getOperand(1);
6896 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6897 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6898 DAG.getIntPtrConstant(0, dl));
6900 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6901 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6902 DAG.getIntPtrConstant(1, dl));
6903 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6906 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6907 /// element has been zero/sign-extended, depending on the isSigned parameter,
6908 /// from an integer type half its size.
6909 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6911 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6912 EVT VT = N->getValueType(0);
6913 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6914 SDNode *BVN = N->getOperand(0).getNode();
6915 if (BVN->getValueType(0) != MVT::v4i32 ||
6916 BVN->getOpcode() != ISD::BUILD_VECTOR)
6918 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6919 unsigned HiElt = 1 - LoElt;
6920 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6921 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6922 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6923 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6924 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6927 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6928 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6931 if (Hi0->isNullValue() && Hi1->isNullValue())
6937 if (N->getOpcode() != ISD::BUILD_VECTOR)
6940 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6941 SDNode *Elt = N->getOperand(i).getNode();
6942 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6943 unsigned EltSize = VT.getScalarSizeInBits();
6944 unsigned HalfSize = EltSize / 2;
6946 if (!isIntN(HalfSize, C->getSExtValue()))
6949 if (!isUIntN(HalfSize, C->getZExtValue()))
6960 /// isSignExtended - Check if a node is a vector value that is sign-extended
6961 /// or a constant BUILD_VECTOR with sign-extended elements.
6962 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6963 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6965 if (isExtendedBUILD_VECTOR(N, DAG, true))
6970 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6971 /// or a constant BUILD_VECTOR with zero-extended elements.
6972 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6973 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6975 if (isExtendedBUILD_VECTOR(N, DAG, false))
6980 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6981 if (OrigVT.getSizeInBits() >= 64)
6984 assert(OrigVT.isSimple() && "Expecting a simple value type");
6986 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6987 switch (OrigSimpleTy) {
6988 default: llvm_unreachable("Unexpected Vector Type");
6997 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6998 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6999 /// We insert the required extension here to get the vector to fill a D register.
7000 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
7003 unsigned ExtOpcode) {
7004 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
7005 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
7006 // 64-bits we need to insert a new extension so that it will be 64-bits.
7007 assert(ExtTy.is128BitVector() && "Unexpected extension size");
7008 if (OrigTy.getSizeInBits() >= 64)
7011 // Must extend size to at least 64 bits to be used as an operand for VMULL.
7012 EVT NewVT = getExtensionTo64Bits(OrigTy);
7014 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
7017 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
7018 /// does not do any sign/zero extension. If the original vector is less
7019 /// than 64 bits, an appropriate extension will be added after the load to
7020 /// reach a total size of 64 bits. We have to add the extension separately
7021 /// because ARM does not have a sign/zero extending load for vectors.
7022 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
7023 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
7025 // The load already has the right type.
7026 if (ExtendedTy == LD->getMemoryVT())
7027 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
7028 LD->getBasePtr(), LD->getPointerInfo(),
7029 LD->getAlignment(), LD->getMemOperand()->getFlags());
7031 // We need to create a zextload/sextload. We cannot just create a load
7032 // followed by a zext/zext node because LowerMUL is also run during normal
7033 // operation legalization where we can't create illegal types.
7034 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
7035 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
7036 LD->getMemoryVT(), LD->getAlignment(),
7037 LD->getMemOperand()->getFlags());
7040 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
7041 /// extending load, or BUILD_VECTOR with extended elements, return the
7042 /// unextended value. The unextended vector should be 64 bits so that it can
7043 /// be used as an operand to a VMULL instruction. If the original vector size
7044 /// before extension is less than 64 bits we add a an extension to resize
7045 /// the vector to 64 bits.
7046 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
7047 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
7048 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
7049 N->getOperand(0)->getValueType(0),
7053 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7054 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
7055 "Expected extending load");
7057 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
7058 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
7059 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
7061 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
7062 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
7067 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
7068 // have been legalized as a BITCAST from v4i32.
7069 if (N->getOpcode() == ISD::BITCAST) {
7070 SDNode *BVN = N->getOperand(0).getNode();
7071 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
7072 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
7073 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7074 return DAG.getBuildVector(
7075 MVT::v2i32, SDLoc(N),
7076 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
7078 // Construct a new BUILD_VECTOR with elements truncated to half the size.
7079 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
7080 EVT VT = N->getValueType(0);
7081 unsigned EltSize = VT.getScalarSizeInBits() / 2;
7082 unsigned NumElts = VT.getVectorNumElements();
7083 MVT TruncVT = MVT::getIntegerVT(EltSize);
7084 SmallVector<SDValue, 8> Ops;
7086 for (unsigned i = 0; i != NumElts; ++i) {
7087 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
7088 const APInt &CInt = C->getAPIntValue();
7089 // Element types smaller than 32 bits are not legal, so use i32 elements.
7090 // The values are implicitly truncated so sext vs. zext doesn't matter.
7091 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
7093 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
7096 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
7097 unsigned Opcode = N->getOpcode();
7098 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7099 SDNode *N0 = N->getOperand(0).getNode();
7100 SDNode *N1 = N->getOperand(1).getNode();
7101 return N0->hasOneUse() && N1->hasOneUse() &&
7102 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
7107 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
7108 unsigned Opcode = N->getOpcode();
7109 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7110 SDNode *N0 = N->getOperand(0).getNode();
7111 SDNode *N1 = N->getOperand(1).getNode();
7112 return N0->hasOneUse() && N1->hasOneUse() &&
7113 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
7118 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
7119 // Multiplications are only custom-lowered for 128-bit vectors so that
7120 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
7121 EVT VT = Op.getValueType();
7122 assert(VT.is128BitVector() && VT.isInteger() &&
7123 "unexpected type for custom-lowering ISD::MUL");
7124 SDNode *N0 = Op.getOperand(0).getNode();
7125 SDNode *N1 = Op.getOperand(1).getNode();
7126 unsigned NewOpc = 0;
7128 bool isN0SExt = isSignExtended(N0, DAG);
7129 bool isN1SExt = isSignExtended(N1, DAG);
7130 if (isN0SExt && isN1SExt)
7131 NewOpc = ARMISD::VMULLs;
7133 bool isN0ZExt = isZeroExtended(N0, DAG);
7134 bool isN1ZExt = isZeroExtended(N1, DAG);
7135 if (isN0ZExt && isN1ZExt)
7136 NewOpc = ARMISD::VMULLu;
7137 else if (isN1SExt || isN1ZExt) {
7138 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7139 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7140 if (isN1SExt && isAddSubSExt(N0, DAG)) {
7141 NewOpc = ARMISD::VMULLs;
7143 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7144 NewOpc = ARMISD::VMULLu;
7146 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7148 NewOpc = ARMISD::VMULLu;
7154 if (VT == MVT::v2i64)
7155 // Fall through to expand this. It is not legal.
7158 // Other vector multiplications are legal.
7163 // Legalize to a VMULL instruction.
7166 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7168 Op0 = SkipExtensionForVMULL(N0, DAG);
7169 assert(Op0.getValueType().is64BitVector() &&
7170 Op1.getValueType().is64BitVector() &&
7171 "unexpected types for extended operands to VMULL");
7172 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7175 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7176 // isel lowering to take advantage of no-stall back to back vmul + vmla.
7183 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7184 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7185 EVT Op1VT = Op1.getValueType();
7186 return DAG.getNode(N0->getOpcode(), DL, VT,
7187 DAG.getNode(NewOpc, DL, VT,
7188 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7189 DAG.getNode(NewOpc, DL, VT,
7190 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7193 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7194 SelectionDAG &DAG) {
7195 // TODO: Should this propagate fast-math-flags?
7198 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7199 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7200 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7201 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7202 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7203 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7204 // Get reciprocal estimate.
7205 // float4 recip = vrecpeq_f32(yf);
7206 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7207 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7209 // Because char has a smaller range than uchar, we can actually get away
7210 // without any newton steps. This requires that we use a weird bias
7211 // of 0xb000, however (again, this has been exhaustively tested).
7212 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7213 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7214 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7215 Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7216 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7217 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7218 // Convert back to short.
7219 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7220 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7224 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7225 SelectionDAG &DAG) {
7226 // TODO: Should this propagate fast-math-flags?
7229 // Convert to float.
7230 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7231 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7232 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7233 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7234 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7235 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7237 // Use reciprocal estimate and one refinement step.
7238 // float4 recip = vrecpeq_f32(yf);
7239 // recip *= vrecpsq_f32(yf, recip);
7240 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7241 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7243 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7244 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7246 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7247 // Because short has a smaller range than ushort, we can actually get away
7248 // with only a single newton step. This requires that we use a weird bias
7249 // of 89, however (again, this has been exhaustively tested).
7250 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7251 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7252 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7253 N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7254 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7255 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7256 // Convert back to integer and return.
7257 // return vmovn_s32(vcvt_s32_f32(result));
7258 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7259 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7263 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7264 EVT VT = Op.getValueType();
7265 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7266 "unexpected type for custom-lowering ISD::SDIV");
7269 SDValue N0 = Op.getOperand(0);
7270 SDValue N1 = Op.getOperand(1);
7273 if (VT == MVT::v8i8) {
7274 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7275 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7277 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7278 DAG.getIntPtrConstant(4, dl));
7279 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7280 DAG.getIntPtrConstant(4, dl));
7281 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7282 DAG.getIntPtrConstant(0, dl));
7283 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7284 DAG.getIntPtrConstant(0, dl));
7286 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7287 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7289 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7290 N0 = LowerCONCAT_VECTORS(N0, DAG);
7292 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7295 return LowerSDIV_v4i16(N0, N1, dl, DAG);
7298 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7299 // TODO: Should this propagate fast-math-flags?
7300 EVT VT = Op.getValueType();
7301 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7302 "unexpected type for custom-lowering ISD::UDIV");
7305 SDValue N0 = Op.getOperand(0);
7306 SDValue N1 = Op.getOperand(1);
7309 if (VT == MVT::v8i8) {
7310 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
7311 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
7313 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7314 DAG.getIntPtrConstant(4, dl));
7315 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7316 DAG.getIntPtrConstant(4, dl));
7317 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7318 DAG.getIntPtrConstant(0, dl));
7319 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7320 DAG.getIntPtrConstant(0, dl));
7322 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
7323 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
7325 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7326 N0 = LowerCONCAT_VECTORS(N0, DAG);
7328 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7329 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7335 // v4i16 sdiv ... Convert to float.
7336 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7337 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7338 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7339 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7340 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7341 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7343 // Use reciprocal estimate and two refinement steps.
7344 // float4 recip = vrecpeq_f32(yf);
7345 // recip *= vrecpsq_f32(yf, recip);
7346 // recip *= vrecpsq_f32(yf, recip);
7347 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7348 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7350 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7351 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7353 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7354 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7355 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7357 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7358 // Simply multiplying by the reciprocal estimate can leave us a few ulps
7359 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7360 // and that it will never cause us to return an answer too large).
7361 // float4 result = as_float4(as_int4(xf*recip) + 2);
7362 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7363 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7364 N1 = DAG.getConstant(2, dl, MVT::v4i32);
7365 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7366 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7367 // Convert back to integer and return.
7368 // return vmovn_u32(vcvt_s32_f32(result));
7369 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7370 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7374 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
7375 EVT VT = Op.getNode()->getValueType(0);
7376 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7379 bool ExtraOp = false;
7380 switch (Op.getOpcode()) {
7381 default: llvm_unreachable("Invalid code");
7382 case ISD::ADDC: Opc = ARMISD::ADDC; break;
7383 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
7384 case ISD::SUBC: Opc = ARMISD::SUBC; break;
7385 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
7389 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7391 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7392 Op.getOperand(1), Op.getOperand(2));
7395 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7396 assert(Subtarget->isTargetDarwin());
7398 // For iOS, we want to call an alternative entry point: __sincos_stret,
7399 // return values are passed via sret.
7401 SDValue Arg = Op.getOperand(0);
7402 EVT ArgVT = Arg.getValueType();
7403 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7404 auto PtrVT = getPointerTy(DAG.getDataLayout());
7406 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7407 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7409 // Pair of floats / doubles used to pass the result.
7410 Type *RetTy = StructType::get(ArgTy, ArgTy);
7411 auto &DL = DAG.getDataLayout();
7414 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
7416 if (ShouldUseSRet) {
7417 // Create stack object for sret.
7418 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
7419 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
7420 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
7421 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
7425 Entry.Ty = RetTy->getPointerTo();
7426 Entry.IsSExt = false;
7427 Entry.IsZExt = false;
7428 Entry.IsSRet = true;
7429 Args.push_back(Entry);
7430 RetTy = Type::getVoidTy(*DAG.getContext());
7436 Entry.IsSExt = false;
7437 Entry.IsZExt = false;
7438 Args.push_back(Entry);
7440 const char *LibcallName =
7441 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
7443 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
7444 CallingConv::ID CC = getLibcallCallingConv(LC);
7445 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
7447 TargetLowering::CallLoweringInfo CLI(DAG);
7449 .setChain(DAG.getEntryNode())
7450 .setCallee(CC, RetTy, Callee, std::move(Args))
7451 .setDiscardResult(ShouldUseSRet);
7452 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7455 return CallResult.first;
7458 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
7460 // Address of cos field.
7461 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
7462 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
7464 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
7466 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
7467 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
7468 LoadSin.getValue(0), LoadCos.getValue(0));
7471 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
7473 SDValue &Chain) const {
7474 EVT VT = Op.getValueType();
7475 assert((VT == MVT::i32 || VT == MVT::i64) &&
7476 "unexpected type for custom lowering DIV");
7479 const auto &DL = DAG.getDataLayout();
7480 const auto &TLI = DAG.getTargetLoweringInfo();
7482 const char *Name = nullptr;
7484 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
7486 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7488 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7490 ARMTargetLowering::ArgListTy Args;
7492 for (auto AI : {1, 0}) {
7494 Arg.Node = Op.getOperand(AI);
7495 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7496 Args.push_back(Arg);
7499 CallLoweringInfo CLI(DAG);
7502 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7503 ES, std::move(Args));
7505 return LowerCallTo(CLI).first;
7508 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7509 bool Signed) const {
7510 assert(Op.getValueType() == MVT::i32 &&
7511 "unexpected type for custom lowering DIV");
7514 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7515 DAG.getEntryNode(), Op.getOperand(1));
7517 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7520 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
7522 SDValue Op = N->getOperand(1);
7523 if (N->getValueType(0) == MVT::i32)
7524 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
7525 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7526 DAG.getConstant(0, DL, MVT::i32));
7527 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7528 DAG.getConstant(1, DL, MVT::i32));
7529 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
7530 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
7533 void ARMTargetLowering::ExpandDIV_Windows(
7534 SDValue Op, SelectionDAG &DAG, bool Signed,
7535 SmallVectorImpl<SDValue> &Results) const {
7536 const auto &DL = DAG.getDataLayout();
7537 const auto &TLI = DAG.getTargetLoweringInfo();
7539 assert(Op.getValueType() == MVT::i64 &&
7540 "unexpected type for custom lowering DIV");
7543 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
7545 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7547 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7548 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7549 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7550 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7552 Results.push_back(Lower);
7553 Results.push_back(Upper);
7556 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7557 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7558 // Acquire/Release load/store is not legal for targets without a dmb or
7559 // equivalent available.
7562 // Monotonic load/store is legal for all targets.
7566 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7567 SmallVectorImpl<SDValue> &Results,
7569 const ARMSubtarget *Subtarget) {
7571 // Under Power Management extensions, the cycle-count is:
7572 // mrc p15, #0, <Rt>, c9, c13, #0
7573 SDValue Ops[] = { N->getOperand(0), // Chain
7574 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7575 DAG.getConstant(15, DL, MVT::i32),
7576 DAG.getConstant(0, DL, MVT::i32),
7577 DAG.getConstant(9, DL, MVT::i32),
7578 DAG.getConstant(13, DL, MVT::i32),
7579 DAG.getConstant(0, DL, MVT::i32)
7582 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7583 DAG.getVTList(MVT::i32, MVT::Other), Ops);
7584 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7585 DAG.getConstant(0, DL, MVT::i32)));
7586 Results.push_back(Cycles32.getValue(1));
7589 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7590 SDLoc dl(V.getNode());
7591 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7592 SDValue VHi = DAG.getAnyExtOrTrunc(
7593 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7595 bool isBigEndian = DAG.getDataLayout().isBigEndian();
7597 std::swap (VLo, VHi);
7599 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7600 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7601 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7602 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7604 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7607 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7608 SmallVectorImpl<SDValue> & Results,
7609 SelectionDAG &DAG) {
7610 assert(N->getValueType(0) == MVT::i64 &&
7611 "AtomicCmpSwap on types less than 64 should be legal");
7612 SDValue Ops[] = {N->getOperand(1),
7613 createGPRPairNode(DAG, N->getOperand(2)),
7614 createGPRPairNode(DAG, N->getOperand(3)),
7616 SDNode *CmpSwap = DAG.getMachineNode(
7617 ARM::CMP_SWAP_64, SDLoc(N),
7618 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7620 MachineFunction &MF = DAG.getMachineFunction();
7621 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
7622 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
7623 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
7625 bool isBigEndian = DAG.getDataLayout().isBigEndian();
7628 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
7629 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7631 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
7632 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7633 Results.push_back(SDValue(CmpSwap, 2));
7636 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
7637 SelectionDAG &DAG) {
7638 const auto &TLI = DAG.getTargetLoweringInfo();
7640 assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
7641 "Custom lowering is MSVCRT specific!");
7644 SDValue Val = Op.getOperand(0);
7645 MVT Ty = Val->getSimpleValueType(0);
7646 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
7647 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
7648 TLI.getPointerTy(DAG.getDataLayout()));
7650 TargetLowering::ArgListTy Args;
7651 TargetLowering::ArgListEntry Entry;
7654 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
7655 Entry.IsZExt = true;
7656 Args.push_back(Entry);
7658 Entry.Node = Exponent;
7659 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
7660 Entry.IsZExt = true;
7661 Args.push_back(Entry);
7663 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
7665 // In the in-chain to the call is the entry node If we are emitting a
7666 // tailcall, the chain will be mutated if the node has a non-entry input
7668 SDValue InChain = DAG.getEntryNode();
7669 SDValue TCChain = InChain;
7671 const auto *F = DAG.getMachineFunction().getFunction();
7672 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
7673 F->getReturnType() == LCRTy;
7677 TargetLowering::CallLoweringInfo CLI(DAG);
7680 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
7682 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
7684 // Return the chain (the DAG root) if it is a tail call
7685 return !CI.second.getNode() ? DAG.getRoot() : CI.first;
7688 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7689 switch (Op.getOpcode()) {
7690 default: llvm_unreachable("Don't know how to custom lower this!");
7691 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
7692 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7693 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7694 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7695 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7696 case ISD::SELECT: return LowerSELECT(Op, DAG);
7697 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
7698 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
7699 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
7700 case ISD::VASTART: return LowerVASTART(Op, DAG);
7701 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
7702 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
7703 case ISD::SINT_TO_FP:
7704 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
7705 case ISD::FP_TO_SINT:
7706 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
7707 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7708 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7709 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7710 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
7711 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
7712 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
7713 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
7715 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
7718 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
7719 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
7720 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
7721 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
7722 case ISD::SRL_PARTS:
7723 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
7725 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
7726 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
7727 case ISD::SETCC: return LowerVSETCC(Op, DAG);
7728 case ISD::SETCCE: return LowerSETCCE(Op, DAG);
7729 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
7730 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
7731 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7732 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7733 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7734 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7735 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7736 case ISD::MUL: return LowerMUL(Op, DAG);
7738 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7739 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
7740 return LowerSDIV(Op, DAG);
7742 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7743 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
7744 return LowerUDIV(Op, DAG);
7748 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
7753 return LowerXALUO(Op, DAG);
7754 case ISD::ATOMIC_LOAD:
7755 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
7756 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
7758 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
7759 case ISD::DYNAMIC_STACKALLOC:
7760 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
7761 return LowerDYNAMIC_STACKALLOC(Op, DAG);
7762 llvm_unreachable("Don't know how to custom lower this!");
7763 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
7764 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
7765 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
7766 case ARMISD::WIN__DBZCHK: return SDValue();
7770 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
7771 SelectionDAG &DAG) {
7772 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7774 if (IntNo == Intrinsic::arm_smlald)
7775 Opc = ARMISD::SMLALD;
7776 else if (IntNo == Intrinsic::arm_smlaldx)
7777 Opc = ARMISD::SMLALDX;
7778 else if (IntNo == Intrinsic::arm_smlsld)
7779 Opc = ARMISD::SMLSLD;
7780 else if (IntNo == Intrinsic::arm_smlsldx)
7781 Opc = ARMISD::SMLSLDX;
7786 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7788 DAG.getConstant(0, dl, MVT::i32));
7789 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7791 DAG.getConstant(1, dl, MVT::i32));
7793 SDValue LongMul = DAG.getNode(Opc, dl,
7794 DAG.getVTList(MVT::i32, MVT::i32),
7795 N->getOperand(1), N->getOperand(2),
7797 Results.push_back(LongMul.getValue(0));
7798 Results.push_back(LongMul.getValue(1));
7801 /// ReplaceNodeResults - Replace the results of node with an illegal result
7802 /// type with new values built out of custom code.
7803 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
7804 SmallVectorImpl<SDValue> &Results,
7805 SelectionDAG &DAG) const {
7807 switch (N->getOpcode()) {
7809 llvm_unreachable("Don't know how to custom expand this!");
7810 case ISD::READ_REGISTER:
7811 ExpandREAD_REGISTER(N, Results, DAG);
7814 Res = ExpandBITCAST(N, DAG);
7818 Res = Expand64BitShift(N, DAG, Subtarget);
7822 Res = LowerREM(N, DAG);
7826 Res = LowerDivRem(SDValue(N, 0), DAG);
7827 assert(Res.getNumOperands() == 2 && "DivRem needs two values");
7828 Results.push_back(Res.getValue(0));
7829 Results.push_back(Res.getValue(1));
7831 case ISD::READCYCLECOUNTER:
7832 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
7836 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
7837 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
7839 case ISD::ATOMIC_CMP_SWAP:
7840 ReplaceCMP_SWAP_64Results(N, Results, DAG);
7842 case ISD::INTRINSIC_WO_CHAIN:
7843 return ReplaceLongIntrinsic(N, Results, DAG);
7846 Results.push_back(Res);
7849 //===----------------------------------------------------------------------===//
7850 // ARM Scheduler Hooks
7851 //===----------------------------------------------------------------------===//
7853 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
7854 /// registers the function context.
7855 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
7856 MachineBasicBlock *MBB,
7857 MachineBasicBlock *DispatchBB,
7859 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
7860 "ROPI/RWPI not currently supported with SjLj");
7861 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7862 DebugLoc dl = MI.getDebugLoc();
7863 MachineFunction *MF = MBB->getParent();
7864 MachineRegisterInfo *MRI = &MF->getRegInfo();
7865 MachineConstantPool *MCP = MF->getConstantPool();
7866 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
7867 const Function *F = MF->getFunction();
7869 bool isThumb = Subtarget->isThumb();
7870 bool isThumb2 = Subtarget->isThumb2();
7872 unsigned PCLabelId = AFI->createPICLabelUId();
7873 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
7874 ARMConstantPoolValue *CPV =
7875 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
7876 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
7878 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
7879 : &ARM::GPRRegClass;
7881 // Grab constant pool and fixed stack memory operands.
7882 MachineMemOperand *CPMMO =
7883 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
7884 MachineMemOperand::MOLoad, 4, 4);
7886 MachineMemOperand *FIMMOSt =
7887 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
7888 MachineMemOperand::MOStore, 4, 4);
7890 // Load the address of the dispatch MBB into the jump buffer.
7892 // Incoming value: jbuf
7893 // ldr.n r5, LCPI1_1
7896 // str r5, [$jbuf, #+4] ; &jbuf[1]
7897 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7898 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
7899 .addConstantPoolIndex(CPI)
7900 .addMemOperand(CPMMO)
7901 .add(predOps(ARMCC::AL));
7902 // Set the low bit because of thumb mode.
7903 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7904 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
7905 .addReg(NewVReg1, RegState::Kill)
7907 .add(predOps(ARMCC::AL))
7909 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7910 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
7911 .addReg(NewVReg2, RegState::Kill)
7913 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
7914 .addReg(NewVReg3, RegState::Kill)
7916 .addImm(36) // &jbuf[1] :: pc
7917 .addMemOperand(FIMMOSt)
7918 .add(predOps(ARMCC::AL));
7919 } else if (isThumb) {
7920 // Incoming value: jbuf
7921 // ldr.n r1, LCPI1_4
7925 // add r2, $jbuf, #+4 ; &jbuf[1]
7927 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7928 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
7929 .addConstantPoolIndex(CPI)
7930 .addMemOperand(CPMMO)
7931 .add(predOps(ARMCC::AL));
7932 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7933 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
7934 .addReg(NewVReg1, RegState::Kill)
7936 // Set the low bit because of thumb mode.
7937 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7938 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
7939 .addReg(ARM::CPSR, RegState::Define)
7941 .add(predOps(ARMCC::AL));
7942 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7943 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
7944 .addReg(ARM::CPSR, RegState::Define)
7945 .addReg(NewVReg2, RegState::Kill)
7946 .addReg(NewVReg3, RegState::Kill)
7947 .add(predOps(ARMCC::AL));
7948 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7949 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
7951 .addImm(36); // &jbuf[1] :: pc
7952 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
7953 .addReg(NewVReg4, RegState::Kill)
7954 .addReg(NewVReg5, RegState::Kill)
7956 .addMemOperand(FIMMOSt)
7957 .add(predOps(ARMCC::AL));
7959 // Incoming value: jbuf
7962 // str r1, [$jbuf, #+4] ; &jbuf[1]
7963 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7964 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
7965 .addConstantPoolIndex(CPI)
7967 .addMemOperand(CPMMO)
7968 .add(predOps(ARMCC::AL));
7969 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7970 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7971 .addReg(NewVReg1, RegState::Kill)
7973 .add(predOps(ARMCC::AL));
7974 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7975 .addReg(NewVReg2, RegState::Kill)
7977 .addImm(36) // &jbuf[1] :: pc
7978 .addMemOperand(FIMMOSt)
7979 .add(predOps(ARMCC::AL));
7983 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
7984 MachineBasicBlock *MBB) const {
7985 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7986 DebugLoc dl = MI.getDebugLoc();
7987 MachineFunction *MF = MBB->getParent();
7988 MachineRegisterInfo *MRI = &MF->getRegInfo();
7989 MachineFrameInfo &MFI = MF->getFrameInfo();
7990 int FI = MFI.getFunctionContextIndex();
7992 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7993 : &ARM::GPRnopcRegClass;
7995 // Get a mapping of the call site numbers to all of the landing pads they're
7997 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
7998 unsigned MaxCSNum = 0;
7999 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
8001 if (!BB->isEHPad()) continue;
8003 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
8005 for (MachineBasicBlock::iterator
8006 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
8007 if (!II->isEHLabel()) continue;
8009 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
8010 if (!MF->hasCallSiteLandingPad(Sym)) continue;
8012 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
8013 for (SmallVectorImpl<unsigned>::iterator
8014 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
8015 CSI != CSE; ++CSI) {
8016 CallSiteNumToLPad[*CSI].push_back(&*BB);
8017 MaxCSNum = std::max(MaxCSNum, *CSI);
8023 // Get an ordered list of the machine basic blocks for the jump table.
8024 std::vector<MachineBasicBlock*> LPadList;
8025 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
8026 LPadList.reserve(CallSiteNumToLPad.size());
8027 for (unsigned I = 1; I <= MaxCSNum; ++I) {
8028 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
8029 for (SmallVectorImpl<MachineBasicBlock*>::iterator
8030 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
8031 LPadList.push_back(*II);
8032 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
8036 assert(!LPadList.empty() &&
8037 "No landing pad destinations for the dispatch jump table!");
8039 // Create the jump table and associated information.
8040 MachineJumpTableInfo *JTI =
8041 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
8042 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
8044 // Create the MBBs for the dispatch code.
8046 // Shove the dispatch's address into the return slot in the function context.
8047 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
8048 DispatchBB->setIsEHPad();
8050 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8051 unsigned trap_opcode;
8052 if (Subtarget->isThumb())
8053 trap_opcode = ARM::tTRAP;
8055 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
8057 BuildMI(TrapBB, dl, TII->get(trap_opcode));
8058 DispatchBB->addSuccessor(TrapBB);
8060 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
8061 DispatchBB->addSuccessor(DispContBB);
8064 MF->insert(MF->end(), DispatchBB);
8065 MF->insert(MF->end(), DispContBB);
8066 MF->insert(MF->end(), TrapBB);
8068 // Insert code into the entry block that creates and registers the function
8070 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
8072 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
8073 MachinePointerInfo::getFixedStack(*MF, FI),
8074 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
8076 MachineInstrBuilder MIB;
8077 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
8079 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
8080 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
8082 // Add a register mask with no preserved registers. This results in all
8083 // registers being marked as clobbered. This can't work if the dispatch block
8084 // is in a Thumb1 function and is linked with ARM code which uses the FP
8085 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
8086 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
8088 bool IsPositionIndependent = isPositionIndependent();
8089 unsigned NumLPads = LPadList.size();
8090 if (Subtarget->isThumb2()) {
8091 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8092 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
8095 .addMemOperand(FIMMOLd)
8096 .add(predOps(ARMCC::AL));
8098 if (NumLPads < 256) {
8099 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
8101 .addImm(LPadList.size())
8102 .add(predOps(ARMCC::AL));
8104 unsigned VReg1 = MRI->createVirtualRegister(TRC);
8105 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
8106 .addImm(NumLPads & 0xFFFF)
8107 .add(predOps(ARMCC::AL));
8109 unsigned VReg2 = VReg1;
8110 if ((NumLPads & 0xFFFF0000) != 0) {
8111 VReg2 = MRI->createVirtualRegister(TRC);
8112 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
8114 .addImm(NumLPads >> 16)
8115 .add(predOps(ARMCC::AL));
8118 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
8121 .add(predOps(ARMCC::AL));
8124 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
8129 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8130 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
8131 .addJumpTableIndex(MJTI)
8132 .add(predOps(ARMCC::AL));
8134 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8135 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
8136 .addReg(NewVReg3, RegState::Kill)
8138 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8139 .add(predOps(ARMCC::AL))
8142 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
8143 .addReg(NewVReg4, RegState::Kill)
8145 .addJumpTableIndex(MJTI);
8146 } else if (Subtarget->isThumb()) {
8147 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8148 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
8151 .addMemOperand(FIMMOLd)
8152 .add(predOps(ARMCC::AL));
8154 if (NumLPads < 256) {
8155 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
8158 .add(predOps(ARMCC::AL));
8160 MachineConstantPool *ConstantPool = MF->getConstantPool();
8161 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8162 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8164 // MachineConstantPool wants an explicit alignment.
8165 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8167 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8168 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8170 unsigned VReg1 = MRI->createVirtualRegister(TRC);
8171 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
8172 .addReg(VReg1, RegState::Define)
8173 .addConstantPoolIndex(Idx)
8174 .add(predOps(ARMCC::AL));
8175 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
8178 .add(predOps(ARMCC::AL));
8181 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
8186 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8187 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
8188 .addReg(ARM::CPSR, RegState::Define)
8191 .add(predOps(ARMCC::AL));
8193 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8194 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
8195 .addJumpTableIndex(MJTI)
8196 .add(predOps(ARMCC::AL));
8198 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8199 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
8200 .addReg(ARM::CPSR, RegState::Define)
8201 .addReg(NewVReg2, RegState::Kill)
8203 .add(predOps(ARMCC::AL));
8205 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8206 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8208 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8209 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
8210 .addReg(NewVReg4, RegState::Kill)
8212 .addMemOperand(JTMMOLd)
8213 .add(predOps(ARMCC::AL));
8215 unsigned NewVReg6 = NewVReg5;
8216 if (IsPositionIndependent) {
8217 NewVReg6 = MRI->createVirtualRegister(TRC);
8218 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8219 .addReg(ARM::CPSR, RegState::Define)
8220 .addReg(NewVReg5, RegState::Kill)
8222 .add(predOps(ARMCC::AL));
8225 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8226 .addReg(NewVReg6, RegState::Kill)
8227 .addJumpTableIndex(MJTI);
8229 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8230 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8233 .addMemOperand(FIMMOLd)
8234 .add(predOps(ARMCC::AL));
8236 if (NumLPads < 256) {
8237 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8240 .add(predOps(ARMCC::AL));
8241 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8242 unsigned VReg1 = MRI->createVirtualRegister(TRC);
8243 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8244 .addImm(NumLPads & 0xFFFF)
8245 .add(predOps(ARMCC::AL));
8247 unsigned VReg2 = VReg1;
8248 if ((NumLPads & 0xFFFF0000) != 0) {
8249 VReg2 = MRI->createVirtualRegister(TRC);
8250 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8252 .addImm(NumLPads >> 16)
8253 .add(predOps(ARMCC::AL));
8256 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8259 .add(predOps(ARMCC::AL));
8261 MachineConstantPool *ConstantPool = MF->getConstantPool();
8262 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8263 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8265 // MachineConstantPool wants an explicit alignment.
8266 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8268 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8269 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8271 unsigned VReg1 = MRI->createVirtualRegister(TRC);
8272 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8273 .addReg(VReg1, RegState::Define)
8274 .addConstantPoolIndex(Idx)
8276 .add(predOps(ARMCC::AL));
8277 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8279 .addReg(VReg1, RegState::Kill)
8280 .add(predOps(ARMCC::AL));
8283 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8288 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8289 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8291 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8292 .add(predOps(ARMCC::AL))
8294 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8295 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8296 .addJumpTableIndex(MJTI)
8297 .add(predOps(ARMCC::AL));
8299 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8300 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8301 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8302 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8303 .addReg(NewVReg3, RegState::Kill)
8306 .addMemOperand(JTMMOLd)
8307 .add(predOps(ARMCC::AL));
8309 if (IsPositionIndependent) {
8310 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8311 .addReg(NewVReg5, RegState::Kill)
8313 .addJumpTableIndex(MJTI);
8315 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8316 .addReg(NewVReg5, RegState::Kill)
8317 .addJumpTableIndex(MJTI);
8321 // Add the jump table entries as successors to the MBB.
8322 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8323 for (std::vector<MachineBasicBlock*>::iterator
8324 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8325 MachineBasicBlock *CurMBB = *I;
8326 if (SeenMBBs.insert(CurMBB).second)
8327 DispContBB->addSuccessor(CurMBB);
8330 // N.B. the order the invoke BBs are processed in doesn't matter here.
8331 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8332 SmallVector<MachineBasicBlock*, 64> MBBLPads;
8333 for (MachineBasicBlock *BB : InvokeBBs) {
8335 // Remove the landing pad successor from the invoke block and replace it
8336 // with the new dispatch block.
8337 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8339 while (!Successors.empty()) {
8340 MachineBasicBlock *SMBB = Successors.pop_back_val();
8341 if (SMBB->isEHPad()) {
8342 BB->removeSuccessor(SMBB);
8343 MBBLPads.push_back(SMBB);
8347 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8348 BB->normalizeSuccProbs();
8350 // Find the invoke call and mark all of the callee-saved registers as
8351 // 'implicit defined' so that they're spilled. This prevents code from
8352 // moving instructions to before the EH block, where they will never be
8354 for (MachineBasicBlock::reverse_iterator
8355 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8356 if (!II->isCall()) continue;
8358 DenseMap<unsigned, bool> DefRegs;
8359 for (MachineInstr::mop_iterator
8360 OI = II->operands_begin(), OE = II->operands_end();
8362 if (!OI->isReg()) continue;
8363 DefRegs[OI->getReg()] = true;
8366 MachineInstrBuilder MIB(*MF, &*II);
8368 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
8369 unsigned Reg = SavedRegs[i];
8370 if (Subtarget->isThumb2() &&
8371 !ARM::tGPRRegClass.contains(Reg) &&
8372 !ARM::hGPRRegClass.contains(Reg))
8374 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
8376 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
8379 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
8386 // Mark all former landing pads as non-landing pads. The dispatch is the only
8388 for (SmallVectorImpl<MachineBasicBlock*>::iterator
8389 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
8390 (*I)->setIsEHPad(false);
8392 // The instruction is gone now.
8393 MI.eraseFromParent();
8397 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
8398 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
8399 E = MBB->succ_end(); I != E; ++I)
8402 llvm_unreachable("Expecting a BB with two successors!");
8405 /// Return the load opcode for a given load size. If load size >= 8,
8406 /// neon opcode will be returned.
8407 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
8409 return LdSize == 16 ? ARM::VLD1q32wb_fixed
8410 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
8412 return LdSize == 4 ? ARM::tLDRi
8413 : LdSize == 2 ? ARM::tLDRHi
8414 : LdSize == 1 ? ARM::tLDRBi : 0;
8416 return LdSize == 4 ? ARM::t2LDR_POST
8417 : LdSize == 2 ? ARM::t2LDRH_POST
8418 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
8419 return LdSize == 4 ? ARM::LDR_POST_IMM
8420 : LdSize == 2 ? ARM::LDRH_POST
8421 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
8424 /// Return the store opcode for a given store size. If store size >= 8,
8425 /// neon opcode will be returned.
8426 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
8428 return StSize == 16 ? ARM::VST1q32wb_fixed
8429 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
8431 return StSize == 4 ? ARM::tSTRi
8432 : StSize == 2 ? ARM::tSTRHi
8433 : StSize == 1 ? ARM::tSTRBi : 0;
8435 return StSize == 4 ? ARM::t2STR_POST
8436 : StSize == 2 ? ARM::t2STRH_POST
8437 : StSize == 1 ? ARM::t2STRB_POST : 0;
8438 return StSize == 4 ? ARM::STR_POST_IMM
8439 : StSize == 2 ? ARM::STRH_POST
8440 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
8443 /// Emit a post-increment load operation with given size. The instructions
8444 /// will be added to BB at Pos.
8445 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8446 const TargetInstrInfo *TII, const DebugLoc &dl,
8447 unsigned LdSize, unsigned Data, unsigned AddrIn,
8448 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8449 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
8450 assert(LdOpc != 0 && "Should have a load opcode");
8452 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8453 .addReg(AddrOut, RegState::Define)
8456 .add(predOps(ARMCC::AL));
8457 } else if (IsThumb1) {
8458 // load + update AddrIn
8459 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8462 .add(predOps(ARMCC::AL));
8463 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8464 .add(t1CondCodeOp())
8467 .add(predOps(ARMCC::AL));
8468 } else if (IsThumb2) {
8469 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8470 .addReg(AddrOut, RegState::Define)
8473 .add(predOps(ARMCC::AL));
8475 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8476 .addReg(AddrOut, RegState::Define)
8480 .add(predOps(ARMCC::AL));
8484 /// Emit a post-increment store operation with given size. The instructions
8485 /// will be added to BB at Pos.
8486 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8487 const TargetInstrInfo *TII, const DebugLoc &dl,
8488 unsigned StSize, unsigned Data, unsigned AddrIn,
8489 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8490 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
8491 assert(StOpc != 0 && "Should have a store opcode");
8493 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8497 .add(predOps(ARMCC::AL));
8498 } else if (IsThumb1) {
8499 // store + update AddrIn
8500 BuildMI(*BB, Pos, dl, TII->get(StOpc))
8504 .add(predOps(ARMCC::AL));
8505 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8506 .add(t1CondCodeOp())
8509 .add(predOps(ARMCC::AL));
8510 } else if (IsThumb2) {
8511 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8515 .add(predOps(ARMCC::AL));
8517 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8522 .add(predOps(ARMCC::AL));
8527 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
8528 MachineBasicBlock *BB) const {
8529 // This pseudo instruction has 3 operands: dst, src, size
8530 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
8531 // Otherwise, we will generate unrolled scalar copies.
8532 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8533 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8534 MachineFunction::iterator It = ++BB->getIterator();
8536 unsigned dest = MI.getOperand(0).getReg();
8537 unsigned src = MI.getOperand(1).getReg();
8538 unsigned SizeVal = MI.getOperand(2).getImm();
8539 unsigned Align = MI.getOperand(3).getImm();
8540 DebugLoc dl = MI.getDebugLoc();
8542 MachineFunction *MF = BB->getParent();
8543 MachineRegisterInfo &MRI = MF->getRegInfo();
8544 unsigned UnitSize = 0;
8545 const TargetRegisterClass *TRC = nullptr;
8546 const TargetRegisterClass *VecTRC = nullptr;
8548 bool IsThumb1 = Subtarget->isThumb1Only();
8549 bool IsThumb2 = Subtarget->isThumb2();
8550 bool IsThumb = Subtarget->isThumb();
8554 } else if (Align & 2) {
8557 // Check whether we can use NEON instructions.
8558 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
8559 Subtarget->hasNEON()) {
8560 if ((Align % 16 == 0) && SizeVal >= 16)
8562 else if ((Align % 8 == 0) && SizeVal >= 8)
8565 // Can't use NEON instructions.
8570 // Select the correct opcode and register class for unit size load/store
8571 bool IsNeon = UnitSize >= 8;
8572 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
8574 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
8575 : UnitSize == 8 ? &ARM::DPRRegClass
8578 unsigned BytesLeft = SizeVal % UnitSize;
8579 unsigned LoopSize = SizeVal - BytesLeft;
8581 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
8582 // Use LDR and STR to copy.
8583 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
8584 // [destOut] = STR_POST(scratch, destIn, UnitSize)
8585 unsigned srcIn = src;
8586 unsigned destIn = dest;
8587 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
8588 unsigned srcOut = MRI.createVirtualRegister(TRC);
8589 unsigned destOut = MRI.createVirtualRegister(TRC);
8590 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8591 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
8592 IsThumb1, IsThumb2);
8593 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
8594 IsThumb1, IsThumb2);
8599 // Handle the leftover bytes with LDRB and STRB.
8600 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
8601 // [destOut] = STRB_POST(scratch, destIn, 1)
8602 for (unsigned i = 0; i < BytesLeft; i++) {
8603 unsigned srcOut = MRI.createVirtualRegister(TRC);
8604 unsigned destOut = MRI.createVirtualRegister(TRC);
8605 unsigned scratch = MRI.createVirtualRegister(TRC);
8606 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
8607 IsThumb1, IsThumb2);
8608 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
8609 IsThumb1, IsThumb2);
8613 MI.eraseFromParent(); // The instruction is gone now.
8617 // Expand the pseudo op to a loop.
8620 // movw varEnd, # --> with thumb2
8622 // ldrcp varEnd, idx --> without thumb2
8623 // fallthrough --> loopMBB
8625 // PHI varPhi, varEnd, varLoop
8626 // PHI srcPhi, src, srcLoop
8627 // PHI destPhi, dst, destLoop
8628 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8629 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
8630 // subs varLoop, varPhi, #UnitSize
8632 // fallthrough --> exitMBB
8634 // epilogue to handle left-over bytes
8635 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8636 // [destOut] = STRB_POST(scratch, destLoop, 1)
8637 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8638 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8639 MF->insert(It, loopMBB);
8640 MF->insert(It, exitMBB);
8642 // Transfer the remainder of BB and its successor edges to exitMBB.
8643 exitMBB->splice(exitMBB->begin(), BB,
8644 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8645 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8647 // Load an immediate to varEnd.
8648 unsigned varEnd = MRI.createVirtualRegister(TRC);
8649 if (Subtarget->useMovt(*MF)) {
8650 unsigned Vtmp = varEnd;
8651 if ((LoopSize & 0xFFFF0000) != 0)
8652 Vtmp = MRI.createVirtualRegister(TRC);
8653 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
8654 .addImm(LoopSize & 0xFFFF)
8655 .add(predOps(ARMCC::AL));
8657 if ((LoopSize & 0xFFFF0000) != 0)
8658 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
8660 .addImm(LoopSize >> 16)
8661 .add(predOps(ARMCC::AL));
8663 MachineConstantPool *ConstantPool = MF->getConstantPool();
8664 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8665 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
8667 // MachineConstantPool wants an explicit alignment.
8668 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8670 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8671 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8674 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
8675 .addReg(varEnd, RegState::Define)
8676 .addConstantPoolIndex(Idx)
8677 .add(predOps(ARMCC::AL));
8679 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
8680 .addReg(varEnd, RegState::Define)
8681 .addConstantPoolIndex(Idx)
8683 .add(predOps(ARMCC::AL));
8685 BB->addSuccessor(loopMBB);
8687 // Generate the loop body:
8688 // varPhi = PHI(varLoop, varEnd)
8689 // srcPhi = PHI(srcLoop, src)
8690 // destPhi = PHI(destLoop, dst)
8691 MachineBasicBlock *entryBB = BB;
8693 unsigned varLoop = MRI.createVirtualRegister(TRC);
8694 unsigned varPhi = MRI.createVirtualRegister(TRC);
8695 unsigned srcLoop = MRI.createVirtualRegister(TRC);
8696 unsigned srcPhi = MRI.createVirtualRegister(TRC);
8697 unsigned destLoop = MRI.createVirtualRegister(TRC);
8698 unsigned destPhi = MRI.createVirtualRegister(TRC);
8700 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
8701 .addReg(varLoop).addMBB(loopMBB)
8702 .addReg(varEnd).addMBB(entryBB);
8703 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
8704 .addReg(srcLoop).addMBB(loopMBB)
8705 .addReg(src).addMBB(entryBB);
8706 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
8707 .addReg(destLoop).addMBB(loopMBB)
8708 .addReg(dest).addMBB(entryBB);
8710 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8711 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
8712 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8713 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
8714 IsThumb1, IsThumb2);
8715 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
8716 IsThumb1, IsThumb2);
8718 // Decrement loop variable by UnitSize.
8720 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
8721 .add(t1CondCodeOp())
8724 .add(predOps(ARMCC::AL));
8726 MachineInstrBuilder MIB =
8727 BuildMI(*BB, BB->end(), dl,
8728 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
8731 .add(predOps(ARMCC::AL))
8733 MIB->getOperand(5).setReg(ARM::CPSR);
8734 MIB->getOperand(5).setIsDef(true);
8736 BuildMI(*BB, BB->end(), dl,
8737 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
8738 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
8740 // loopMBB can loop back to loopMBB or fall through to exitMBB.
8741 BB->addSuccessor(loopMBB);
8742 BB->addSuccessor(exitMBB);
8744 // Add epilogue to handle BytesLeft.
8746 auto StartOfExit = exitMBB->begin();
8748 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8749 // [destOut] = STRB_POST(scratch, destLoop, 1)
8750 unsigned srcIn = srcLoop;
8751 unsigned destIn = destLoop;
8752 for (unsigned i = 0; i < BytesLeft; i++) {
8753 unsigned srcOut = MRI.createVirtualRegister(TRC);
8754 unsigned destOut = MRI.createVirtualRegister(TRC);
8755 unsigned scratch = MRI.createVirtualRegister(TRC);
8756 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
8757 IsThumb1, IsThumb2);
8758 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
8759 IsThumb1, IsThumb2);
8764 MI.eraseFromParent(); // The instruction is gone now.
8769 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
8770 MachineBasicBlock *MBB) const {
8771 const TargetMachine &TM = getTargetMachine();
8772 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
8773 DebugLoc DL = MI.getDebugLoc();
8775 assert(Subtarget->isTargetWindows() &&
8776 "__chkstk is only supported on Windows");
8777 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
8779 // __chkstk takes the number of words to allocate on the stack in R4, and
8780 // returns the stack adjustment in number of bytes in R4. This will not
8781 // clober any other registers (other than the obvious lr).
8783 // Although, technically, IP should be considered a register which may be
8784 // clobbered, the call itself will not touch it. Windows on ARM is a pure
8785 // thumb-2 environment, so there is no interworking required. As a result, we
8786 // do not expect a veneer to be emitted by the linker, clobbering IP.
8788 // Each module receives its own copy of __chkstk, so no import thunk is
8789 // required, again, ensuring that IP is not clobbered.
8791 // Finally, although some linkers may theoretically provide a trampoline for
8792 // out of range calls (which is quite common due to a 32M range limitation of
8793 // branches for Thumb), we can generate the long-call version via
8794 // -mcmodel=large, alleviating the need for the trampoline which may clobber
8797 switch (TM.getCodeModel()) {
8798 case CodeModel::Small:
8799 case CodeModel::Medium:
8800 case CodeModel::Default:
8801 case CodeModel::Kernel:
8802 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
8803 .add(predOps(ARMCC::AL))
8804 .addExternalSymbol("__chkstk")
8805 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8806 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8808 RegState::Implicit | RegState::Define | RegState::Dead)
8810 RegState::Implicit | RegState::Define | RegState::Dead);
8812 case CodeModel::Large:
8813 case CodeModel::JITDefault: {
8814 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
8815 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
8817 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
8818 .addExternalSymbol("__chkstk");
8819 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
8820 .add(predOps(ARMCC::AL))
8821 .addReg(Reg, RegState::Kill)
8822 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8823 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8825 RegState::Implicit | RegState::Define | RegState::Dead)
8827 RegState::Implicit | RegState::Define | RegState::Dead);
8832 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
8833 .addReg(ARM::SP, RegState::Kill)
8834 .addReg(ARM::R4, RegState::Kill)
8835 .setMIFlags(MachineInstr::FrameSetup)
8836 .add(predOps(ARMCC::AL))
8839 MI.eraseFromParent();
8844 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
8845 MachineBasicBlock *MBB) const {
8846 DebugLoc DL = MI.getDebugLoc();
8847 MachineFunction *MF = MBB->getParent();
8848 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8850 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
8851 MF->insert(++MBB->getIterator(), ContBB);
8852 ContBB->splice(ContBB->begin(), MBB,
8853 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8854 ContBB->transferSuccessorsAndUpdatePHIs(MBB);
8855 MBB->addSuccessor(ContBB);
8857 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8858 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
8859 MF->push_back(TrapBB);
8860 MBB->addSuccessor(TrapBB);
8862 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
8863 .addReg(MI.getOperand(0).getReg())
8865 .add(predOps(ARMCC::AL));
8866 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
8871 MI.eraseFromParent();
8876 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8877 MachineBasicBlock *BB) const {
8878 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8879 DebugLoc dl = MI.getDebugLoc();
8880 bool isThumb2 = Subtarget->isThumb2();
8881 switch (MI.getOpcode()) {
8884 llvm_unreachable("Unexpected instr type to insert");
8887 // Thumb1 post-indexed loads are really just single-register LDMs.
8888 case ARM::tLDR_postidx: {
8889 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
8890 .add(MI.getOperand(1)) // Rn_wb
8891 .add(MI.getOperand(2)) // Rn
8892 .add(MI.getOperand(3)) // PredImm
8893 .add(MI.getOperand(4)) // PredReg
8894 .add(MI.getOperand(0)); // Rt
8895 MI.eraseFromParent();
8899 // The Thumb2 pre-indexed stores have the same MI operands, they just
8900 // define them differently in the .td files from the isel patterns, so
8901 // they need pseudos.
8902 case ARM::t2STR_preidx:
8903 MI.setDesc(TII->get(ARM::t2STR_PRE));
8905 case ARM::t2STRB_preidx:
8906 MI.setDesc(TII->get(ARM::t2STRB_PRE));
8908 case ARM::t2STRH_preidx:
8909 MI.setDesc(TII->get(ARM::t2STRH_PRE));
8912 case ARM::STRi_preidx:
8913 case ARM::STRBi_preidx: {
8914 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
8915 : ARM::STRB_PRE_IMM;
8916 // Decode the offset.
8917 unsigned Offset = MI.getOperand(4).getImm();
8918 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
8919 Offset = ARM_AM::getAM2Offset(Offset);
8923 MachineMemOperand *MMO = *MI.memoperands_begin();
8924 BuildMI(*BB, MI, dl, TII->get(NewOpc))
8925 .add(MI.getOperand(0)) // Rn_wb
8926 .add(MI.getOperand(1)) // Rt
8927 .add(MI.getOperand(2)) // Rn
8928 .addImm(Offset) // offset (skip GPR==zero_reg)
8929 .add(MI.getOperand(5)) // pred
8930 .add(MI.getOperand(6))
8931 .addMemOperand(MMO);
8932 MI.eraseFromParent();
8935 case ARM::STRr_preidx:
8936 case ARM::STRBr_preidx:
8937 case ARM::STRH_preidx: {
8939 switch (MI.getOpcode()) {
8940 default: llvm_unreachable("unexpected opcode!");
8941 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
8942 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
8943 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
8945 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
8946 for (unsigned i = 0; i < MI.getNumOperands(); ++i)
8947 MIB.add(MI.getOperand(i));
8948 MI.eraseFromParent();
8952 case ARM::tMOVCCr_pseudo: {
8953 // To "insert" a SELECT_CC instruction, we actually have to insert the
8954 // diamond control-flow pattern. The incoming instruction knows the
8955 // destination vreg to set, the condition code register to branch on, the
8956 // true/false values to select between, and a branch opcode to use.
8957 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8958 MachineFunction::iterator It = ++BB->getIterator();
8963 // cmpTY ccX, r1, r2
8965 // fallthrough --> copy0MBB
8966 MachineBasicBlock *thisMBB = BB;
8967 MachineFunction *F = BB->getParent();
8968 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8969 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8970 F->insert(It, copy0MBB);
8971 F->insert(It, sinkMBB);
8973 // Transfer the remainder of BB and its successor edges to sinkMBB.
8974 sinkMBB->splice(sinkMBB->begin(), BB,
8975 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8976 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8978 BB->addSuccessor(copy0MBB);
8979 BB->addSuccessor(sinkMBB);
8981 BuildMI(BB, dl, TII->get(ARM::tBcc))
8983 .addImm(MI.getOperand(3).getImm())
8984 .addReg(MI.getOperand(4).getReg());
8987 // %FalseValue = ...
8988 // # fallthrough to sinkMBB
8991 // Update machine-CFG edges
8992 BB->addSuccessor(sinkMBB);
8995 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8998 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
8999 .addReg(MI.getOperand(1).getReg())
9001 .addReg(MI.getOperand(2).getReg())
9004 MI.eraseFromParent(); // The pseudo instruction is gone now.
9009 case ARM::BCCZi64: {
9010 // If there is an unconditional branch to the other successor, remove it.
9011 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
9013 // Compare both parts that make up the double comparison separately for
9015 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
9017 unsigned LHS1 = MI.getOperand(1).getReg();
9018 unsigned LHS2 = MI.getOperand(2).getReg();
9020 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9023 .add(predOps(ARMCC::AL));
9024 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9025 .addReg(LHS2).addImm(0)
9026 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9028 unsigned RHS1 = MI.getOperand(3).getReg();
9029 unsigned RHS2 = MI.getOperand(4).getReg();
9030 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9033 .add(predOps(ARMCC::AL));
9034 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9035 .addReg(LHS2).addReg(RHS2)
9036 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9039 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
9040 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
9041 if (MI.getOperand(0).getImm() == ARMCC::NE)
9042 std::swap(destMBB, exitMBB);
9044 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
9045 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
9047 BuildMI(BB, dl, TII->get(ARM::t2B))
9049 .add(predOps(ARMCC::AL));
9051 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
9053 MI.eraseFromParent(); // The pseudo instruction is gone now.
9057 case ARM::Int_eh_sjlj_setjmp:
9058 case ARM::Int_eh_sjlj_setjmp_nofp:
9059 case ARM::tInt_eh_sjlj_setjmp:
9060 case ARM::t2Int_eh_sjlj_setjmp:
9061 case ARM::t2Int_eh_sjlj_setjmp_nofp:
9064 case ARM::Int_eh_sjlj_setup_dispatch:
9065 EmitSjLjDispatchBlock(MI, BB);
9070 // To insert an ABS instruction, we have to insert the
9071 // diamond control-flow pattern. The incoming instruction knows the
9072 // source vreg to test against 0, the destination vreg to set,
9073 // the condition code register to branch on, the
9074 // true/false values to select between, and a branch opcode to use.
9079 // BCC (branch to SinkBB if V0 >= 0)
9080 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
9081 // SinkBB: V1 = PHI(V2, V3)
9082 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9083 MachineFunction::iterator BBI = ++BB->getIterator();
9084 MachineFunction *Fn = BB->getParent();
9085 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
9086 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
9087 Fn->insert(BBI, RSBBB);
9088 Fn->insert(BBI, SinkBB);
9090 unsigned int ABSSrcReg = MI.getOperand(1).getReg();
9091 unsigned int ABSDstReg = MI.getOperand(0).getReg();
9092 bool ABSSrcKIll = MI.getOperand(1).isKill();
9093 bool isThumb2 = Subtarget->isThumb2();
9094 MachineRegisterInfo &MRI = Fn->getRegInfo();
9095 // In Thumb mode S must not be specified if source register is the SP or
9096 // PC and if destination register is the SP, so restrict register class
9097 unsigned NewRsbDstReg =
9098 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
9100 // Transfer the remainder of BB and its successor edges to sinkMBB.
9101 SinkBB->splice(SinkBB->begin(), BB,
9102 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9103 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
9105 BB->addSuccessor(RSBBB);
9106 BB->addSuccessor(SinkBB);
9108 // fall through to SinkMBB
9109 RSBBB->addSuccessor(SinkBB);
9111 // insert a cmp at the end of BB
9112 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9115 .add(predOps(ARMCC::AL));
9117 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
9119 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
9120 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
9122 // insert rsbri in RSBBB
9123 // Note: BCC and rsbri will be converted into predicated rsbmi
9124 // by if-conversion pass
9125 BuildMI(*RSBBB, RSBBB->begin(), dl,
9126 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
9127 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
9129 .add(predOps(ARMCC::AL))
9132 // insert PHI in SinkBB,
9133 // reuse ABSDstReg to not change uses of ABS instruction
9134 BuildMI(*SinkBB, SinkBB->begin(), dl,
9135 TII->get(ARM::PHI), ABSDstReg)
9136 .addReg(NewRsbDstReg).addMBB(RSBBB)
9137 .addReg(ABSSrcReg).addMBB(BB);
9139 // remove ABS instruction
9140 MI.eraseFromParent();
9142 // return last added BB
9145 case ARM::COPY_STRUCT_BYVAL_I32:
9147 return EmitStructByval(MI, BB);
9148 case ARM::WIN__CHKSTK:
9149 return EmitLowered__chkstk(MI, BB);
9150 case ARM::WIN__DBZCHK:
9151 return EmitLowered__dbzchk(MI, BB);
9155 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
9156 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
9157 /// instead of as a custom inserter because we need the use list from the SDNode.
9158 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
9159 MachineInstr &MI, const SDNode *Node) {
9160 bool isThumb1 = Subtarget->isThumb1Only();
9162 DebugLoc DL = MI.getDebugLoc();
9163 MachineFunction *MF = MI.getParent()->getParent();
9164 MachineRegisterInfo &MRI = MF->getRegInfo();
9165 MachineInstrBuilder MIB(*MF, MI);
9167 // If the new dst/src is unused mark it as dead.
9168 if (!Node->hasAnyUseOfValue(0)) {
9169 MI.getOperand(0).setIsDead(true);
9171 if (!Node->hasAnyUseOfValue(1)) {
9172 MI.getOperand(1).setIsDead(true);
9175 // The MEMCPY both defines and kills the scratch registers.
9176 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
9177 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
9178 : &ARM::GPRRegClass);
9179 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
9183 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9184 SDNode *Node) const {
9185 if (MI.getOpcode() == ARM::MEMCPY) {
9186 attachMEMCPYScratchRegs(Subtarget, MI, Node);
9190 const MCInstrDesc *MCID = &MI.getDesc();
9191 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
9192 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
9193 // operand is still set to noreg. If needed, set the optional operand's
9194 // register to CPSR, and remove the redundant implicit def.
9196 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
9198 // Rename pseudo opcodes.
9199 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
9202 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
9203 MCID = &TII->get(NewOpc);
9205 assert(MCID->getNumOperands() ==
9206 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
9207 && "converted opcode should be the same except for cc_out"
9208 " (and, on Thumb1, pred)");
9212 // Add the optional cc_out operand
9213 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
9215 // On Thumb1, move all input operands to the end, then add the predicate
9216 if (Subtarget->isThumb1Only()) {
9217 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
9218 MI.addOperand(MI.getOperand(1));
9219 MI.RemoveOperand(1);
9223 for (unsigned i = MI.getNumOperands(); i--;) {
9224 const MachineOperand& op = MI.getOperand(i);
9225 if (op.isReg() && op.isUse()) {
9226 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
9228 MI.tieOperands(DefIdx, i);
9232 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
9233 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
9236 ccOutIdx = MCID->getNumOperands() - 1;
9238 ccOutIdx = MCID->getNumOperands() - 1;
9240 // Any ARM instruction that sets the 's' bit should specify an optional
9241 // "cc_out" operand in the last operand position.
9242 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
9243 assert(!NewOpc && "Optional cc_out operand required");
9246 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
9247 // since we already have an optional CPSR def.
9248 bool definesCPSR = false;
9249 bool deadCPSR = false;
9250 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
9252 const MachineOperand &MO = MI.getOperand(i);
9253 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
9257 MI.RemoveOperand(i);
9262 assert(!NewOpc && "Optional cc_out operand required");
9265 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
9267 assert(!MI.getOperand(ccOutIdx).getReg() &&
9268 "expect uninitialized optional cc_out operand");
9269 // Thumb1 instructions must have the S bit even if the CPSR is dead.
9270 if (!Subtarget->isThumb1Only())
9274 // If this instruction was defined with an optional CPSR def and its dag node
9275 // had a live implicit CPSR def, then activate the optional CPSR def.
9276 MachineOperand &MO = MI.getOperand(ccOutIdx);
9277 MO.setReg(ARM::CPSR);
9281 //===----------------------------------------------------------------------===//
9282 // ARM Optimization Hooks
9283 //===----------------------------------------------------------------------===//
9285 // Helper function that checks if N is a null or all ones constant.
9286 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
9287 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
9290 // Return true if N is conditionally 0 or all ones.
9291 // Detects these expressions where cc is an i1 value:
9293 // (select cc 0, y) [AllOnes=0]
9294 // (select cc y, 0) [AllOnes=0]
9295 // (zext cc) [AllOnes=0]
9296 // (sext cc) [AllOnes=0/1]
9297 // (select cc -1, y) [AllOnes=1]
9298 // (select cc y, -1) [AllOnes=1]
9300 // Invert is set when N is the null/all ones constant when CC is false.
9301 // OtherOp is set to the alternative value of N.
9302 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9303 SDValue &CC, bool &Invert,
9305 SelectionDAG &DAG) {
9306 switch (N->getOpcode()) {
9307 default: return false;
9309 CC = N->getOperand(0);
9310 SDValue N1 = N->getOperand(1);
9311 SDValue N2 = N->getOperand(2);
9312 if (isZeroOrAllOnes(N1, AllOnes)) {
9317 if (isZeroOrAllOnes(N2, AllOnes)) {
9324 case ISD::ZERO_EXTEND:
9325 // (zext cc) can never be the all ones value.
9329 case ISD::SIGN_EXTEND: {
9331 EVT VT = N->getValueType(0);
9332 CC = N->getOperand(0);
9333 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
9337 // When looking for an AllOnes constant, N is an sext, and the 'other'
9339 OtherOp = DAG.getConstant(0, dl, VT);
9340 else if (N->getOpcode() == ISD::ZERO_EXTEND)
9341 // When looking for a 0 constant, N can be zext or sext.
9342 OtherOp = DAG.getConstant(1, dl, VT);
9344 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
9351 // Combine a constant select operand into its use:
9353 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
9354 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
9355 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
9356 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
9357 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
9359 // The transform is rejected if the select doesn't have a constant operand that
9360 // is null, or all ones when AllOnes is set.
9362 // Also recognize sext/zext from i1:
9364 // (add (zext cc), x) -> (select cc (add x, 1), x)
9365 // (add (sext cc), x) -> (select cc (add x, -1), x)
9367 // These transformations eventually create predicated instructions.
9369 // @param N The node to transform.
9370 // @param Slct The N operand that is a select.
9371 // @param OtherOp The other N operand (x above).
9372 // @param DCI Context.
9373 // @param AllOnes Require the select constant to be all ones instead of null.
9374 // @returns The new node, or SDValue() on failure.
9376 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
9377 TargetLowering::DAGCombinerInfo &DCI,
9378 bool AllOnes = false) {
9379 SelectionDAG &DAG = DCI.DAG;
9380 EVT VT = N->getValueType(0);
9381 SDValue NonConstantVal;
9384 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
9385 NonConstantVal, DAG))
9388 // Slct is now know to be the desired identity constant when CC is true.
9389 SDValue TrueVal = OtherOp;
9390 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
9391 OtherOp, NonConstantVal);
9392 // Unless SwapSelectOps says CC should be false.
9394 std::swap(TrueVal, FalseVal);
9396 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
9397 CCOp, TrueVal, FalseVal);
9400 // Attempt combineSelectAndUse on each operand of a commutative operator N.
9402 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
9403 TargetLowering::DAGCombinerInfo &DCI) {
9404 SDValue N0 = N->getOperand(0);
9405 SDValue N1 = N->getOperand(1);
9406 if (N0.getNode()->hasOneUse())
9407 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
9409 if (N1.getNode()->hasOneUse())
9410 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
9415 static bool IsVUZPShuffleNode(SDNode *N) {
9416 // VUZP shuffle node.
9417 if (N->getOpcode() == ARMISD::VUZP)
9420 // "VUZP" on i32 is an alias for VTRN.
9421 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
9427 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
9428 TargetLowering::DAGCombinerInfo &DCI,
9429 const ARMSubtarget *Subtarget) {
9430 // Look for ADD(VUZP.0, VUZP.1).
9431 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
9435 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
9436 if (!N->getValueType(0).is64BitVector())
9440 SelectionDAG &DAG = DCI.DAG;
9441 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9443 SDNode *Unzip = N0.getNode();
9444 EVT VT = N->getValueType(0);
9446 SmallVector<SDValue, 8> Ops;
9447 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
9448 TLI.getPointerTy(DAG.getDataLayout())));
9449 Ops.push_back(Unzip->getOperand(0));
9450 Ops.push_back(Unzip->getOperand(1));
9452 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9455 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9456 TargetLowering::DAGCombinerInfo &DCI,
9457 const ARMSubtarget *Subtarget) {
9458 // Check for two extended operands.
9459 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
9460 N1.getOpcode() == ISD::SIGN_EXTEND) &&
9461 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
9462 N1.getOpcode() == ISD::ZERO_EXTEND))
9465 SDValue N00 = N0.getOperand(0);
9466 SDValue N10 = N1.getOperand(0);
9468 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
9469 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
9473 // We only recognize Q register paddl here; this can't be reached until
9474 // after type legalization.
9475 if (!N00.getValueType().is64BitVector() ||
9476 !N0.getValueType().is128BitVector())
9480 SelectionDAG &DAG = DCI.DAG;
9481 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9483 EVT VT = N->getValueType(0);
9485 SmallVector<SDValue, 8> Ops;
9486 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
9488 if (N0.getOpcode() == ISD::SIGN_EXTEND)
9489 Opcode = Intrinsic::arm_neon_vpaddls;
9491 Opcode = Intrinsic::arm_neon_vpaddlu;
9492 Ops.push_back(DAG.getConstant(Opcode, dl,
9493 TLI.getPointerTy(DAG.getDataLayout())));
9494 EVT ElemTy = N00.getValueType().getVectorElementType();
9495 unsigned NumElts = VT.getVectorNumElements();
9496 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
9497 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
9498 N00.getOperand(0), N00.getOperand(1));
9499 Ops.push_back(Concat);
9501 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9504 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
9505 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
9506 // much easier to match.
9508 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9509 TargetLowering::DAGCombinerInfo &DCI,
9510 const ARMSubtarget *Subtarget) {
9511 // Only perform optimization if after legalize, and if NEON is available. We
9512 // also expected both operands to be BUILD_VECTORs.
9513 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
9514 || N0.getOpcode() != ISD::BUILD_VECTOR
9515 || N1.getOpcode() != ISD::BUILD_VECTOR)
9518 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
9519 EVT VT = N->getValueType(0);
9520 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
9523 // Check that the vector operands are of the right form.
9524 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
9525 // operands, where N is the size of the formed vector.
9526 // Each EXTRACT_VECTOR should have the same input vector and odd or even
9527 // index such that we have a pair wise add pattern.
9529 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
9530 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9532 SDValue Vec = N0->getOperand(0)->getOperand(0);
9533 SDNode *V = Vec.getNode();
9534 unsigned nextIndex = 0;
9536 // For each operands to the ADD which are BUILD_VECTORs,
9537 // check to see if each of their operands are an EXTRACT_VECTOR with
9538 // the same vector and appropriate index.
9539 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
9540 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
9541 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9543 SDValue ExtVec0 = N0->getOperand(i);
9544 SDValue ExtVec1 = N1->getOperand(i);
9546 // First operand is the vector, verify its the same.
9547 if (V != ExtVec0->getOperand(0).getNode() ||
9548 V != ExtVec1->getOperand(0).getNode())
9551 // Second is the constant, verify its correct.
9552 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
9553 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
9555 // For the constant, we want to see all the even or all the odd.
9556 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
9557 || C1->getZExtValue() != nextIndex+1)
9566 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
9567 // we're using the entire input vector, otherwise there's a size/legality
9568 // mismatch somewhere.
9569 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
9570 Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
9573 // Create VPADDL node.
9574 SelectionDAG &DAG = DCI.DAG;
9575 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9579 // Build operand list.
9580 SmallVector<SDValue, 8> Ops;
9581 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
9582 TLI.getPointerTy(DAG.getDataLayout())));
9584 // Input is the vector.
9587 // Get widened type and narrowed type.
9589 unsigned numElem = VT.getVectorNumElements();
9591 EVT inputLaneType = Vec.getValueType().getVectorElementType();
9592 switch (inputLaneType.getSimpleVT().SimpleTy) {
9593 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
9594 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
9595 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
9597 llvm_unreachable("Invalid vector element type for padd optimization.");
9600 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
9601 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
9602 return DAG.getNode(ExtOp, dl, VT, tmp);
9605 static SDValue findMUL_LOHI(SDValue V) {
9606 if (V->getOpcode() == ISD::UMUL_LOHI ||
9607 V->getOpcode() == ISD::SMUL_LOHI)
9612 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
9613 TargetLowering::DAGCombinerInfo &DCI,
9614 const ARMSubtarget *Subtarget) {
9616 if (Subtarget->isThumb()) {
9617 if (!Subtarget->hasDSP())
9619 } else if (!Subtarget->hasV5TEOps())
9622 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
9623 // accumulates the product into a 64-bit value. The 16-bit values will
9624 // be sign extended somehow or SRA'd into 32-bit values
9625 // (addc (adde (mul 16bit, 16bit), lo), hi)
9626 SDValue Mul = AddcNode->getOperand(0);
9627 SDValue Lo = AddcNode->getOperand(1);
9628 if (Mul.getOpcode() != ISD::MUL) {
9629 Lo = AddcNode->getOperand(0);
9630 Mul = AddcNode->getOperand(1);
9631 if (Mul.getOpcode() != ISD::MUL)
9635 SDValue SRA = AddeNode->getOperand(0);
9636 SDValue Hi = AddeNode->getOperand(1);
9637 if (SRA.getOpcode() != ISD::SRA) {
9638 SRA = AddeNode->getOperand(1);
9639 Hi = AddeNode->getOperand(0);
9640 if (SRA.getOpcode() != ISD::SRA)
9643 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
9644 if (Const->getZExtValue() != 31)
9649 if (SRA.getOperand(0) != Mul)
9652 SelectionDAG &DAG = DCI.DAG;
9654 unsigned Opcode = 0;
9658 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
9659 Opcode = ARMISD::SMLALBB;
9660 Op0 = Mul.getOperand(0);
9661 Op1 = Mul.getOperand(1);
9662 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
9663 Opcode = ARMISD::SMLALBT;
9664 Op0 = Mul.getOperand(0);
9665 Op1 = Mul.getOperand(1).getOperand(0);
9666 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
9667 Opcode = ARMISD::SMLALTB;
9668 Op0 = Mul.getOperand(0).getOperand(0);
9669 Op1 = Mul.getOperand(1);
9670 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
9671 Opcode = ARMISD::SMLALTT;
9672 Op0 = Mul->getOperand(0).getOperand(0);
9673 Op1 = Mul->getOperand(1).getOperand(0);
9679 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
9681 // Replace the ADDs' nodes uses by the MLA node's values.
9682 SDValue HiMLALResult(SMLAL.getNode(), 1);
9683 SDValue LoMLALResult(SMLAL.getNode(), 0);
9685 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9686 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9688 // Return original node to notify the driver to stop replacing.
9689 SDValue resNode(AddcNode, 0);
9693 static SDValue AddCombineTo64bitMLAL(SDNode *AddeNode,
9694 TargetLowering::DAGCombinerInfo &DCI,
9695 const ARMSubtarget *Subtarget) {
9696 // Look for multiply add opportunities.
9697 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
9698 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
9699 // a glue link from the first add to the second add.
9700 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
9701 // a S/UMLAL instruction.
9704 // / \ [no multiline comment]
9710 assert(AddeNode->getOpcode() == ARMISD::ADDE && "Expect an ADDE");
9712 assert(AddeNode->getNumOperands() == 3 &&
9713 AddeNode->getOperand(2).getValueType() == MVT::i32 &&
9714 "ADDE node has the wrong inputs");
9716 // Check that we have a glued ADDC node.
9717 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
9718 if (AddcNode->getOpcode() != ARMISD::ADDC)
9721 SDValue AddcOp0 = AddcNode->getOperand(0);
9722 SDValue AddcOp1 = AddcNode->getOperand(1);
9724 // Check if the two operands are from the same mul_lohi node.
9725 if (AddcOp0.getNode() == AddcOp1.getNode())
9728 assert(AddcNode->getNumValues() == 2 &&
9729 AddcNode->getValueType(0) == MVT::i32 &&
9730 "Expect ADDC with two result values. First: i32");
9732 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
9733 // maybe a SMLAL which multiplies two 16-bit values.
9734 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
9735 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
9736 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
9737 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
9738 return AddCombineTo64BitSMLAL16(AddcNode, AddeNode, DCI, Subtarget);
9740 // Check for the triangle shape.
9741 SDValue AddeOp0 = AddeNode->getOperand(0);
9742 SDValue AddeOp1 = AddeNode->getOperand(1);
9744 // Make sure that the ADDE operands are not coming from the same node.
9745 if (AddeOp0.getNode() == AddeOp1.getNode())
9748 // Find the MUL_LOHI node walking up ADDE's operands.
9749 bool IsLeftOperandMUL = false;
9750 SDValue MULOp = findMUL_LOHI(AddeOp0);
9751 if (MULOp == SDValue())
9752 MULOp = findMUL_LOHI(AddeOp1);
9754 IsLeftOperandMUL = true;
9755 if (MULOp == SDValue())
9758 // Figure out the right opcode.
9759 unsigned Opc = MULOp->getOpcode();
9760 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
9762 // Figure out the high and low input values to the MLAL node.
9763 SDValue* HiAdd = nullptr;
9764 SDValue* LoMul = nullptr;
9765 SDValue* LowAdd = nullptr;
9767 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
9768 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
9771 if (IsLeftOperandMUL)
9777 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
9778 // whose low result is fed to the ADDC we are checking.
9780 if (AddcOp0 == MULOp.getValue(0)) {
9784 if (AddcOp1 == MULOp.getValue(0)) {
9792 // Create the merged node.
9793 SelectionDAG &DAG = DCI.DAG;
9795 // Build operand list.
9796 SmallVector<SDValue, 8> Ops;
9797 Ops.push_back(LoMul->getOperand(0));
9798 Ops.push_back(LoMul->getOperand(1));
9799 Ops.push_back(*LowAdd);
9800 Ops.push_back(*HiAdd);
9802 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
9803 DAG.getVTList(MVT::i32, MVT::i32), Ops);
9805 // Replace the ADDs' nodes uses by the MLA node's values.
9806 SDValue HiMLALResult(MLALNode.getNode(), 1);
9807 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9809 SDValue LoMLALResult(MLALNode.getNode(), 0);
9810 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9812 // Return original node to notify the driver to stop replacing.
9813 return SDValue(AddeNode, 0);
9816 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
9817 TargetLowering::DAGCombinerInfo &DCI,
9818 const ARMSubtarget *Subtarget) {
9819 // UMAAL is similar to UMLAL except that it adds two unsigned values.
9820 // While trying to combine for the other MLAL nodes, first search for the
9821 // chance to use UMAAL. Check if Addc uses a node which has already
9822 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
9823 // as the addend, and it's handled in PerformUMLALCombine.
9825 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
9826 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
9828 // Check that we have a glued ADDC node.
9829 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
9830 if (AddcNode->getOpcode() != ARMISD::ADDC)
9833 // Find the converted UMAAL or quit if it doesn't exist.
9834 SDNode *UmlalNode = nullptr;
9836 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
9837 UmlalNode = AddcNode->getOperand(0).getNode();
9838 AddHi = AddcNode->getOperand(1);
9839 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
9840 UmlalNode = AddcNode->getOperand(1).getNode();
9841 AddHi = AddcNode->getOperand(0);
9843 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
9846 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
9847 // the ADDC as well as Zero.
9848 if (!isNullConstant(UmlalNode->getOperand(3)))
9851 if ((isNullConstant(AddeNode->getOperand(0)) &&
9852 AddeNode->getOperand(1).getNode() == UmlalNode) ||
9853 (AddeNode->getOperand(0).getNode() == UmlalNode &&
9854 isNullConstant(AddeNode->getOperand(1)))) {
9856 SelectionDAG &DAG = DCI.DAG;
9857 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
9858 UmlalNode->getOperand(2), AddHi };
9859 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
9860 DAG.getVTList(MVT::i32, MVT::i32), Ops);
9862 // Replace the ADDs' nodes uses by the UMAAL node's values.
9863 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
9864 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
9866 // Return original node to notify the driver to stop replacing.
9867 return SDValue(AddeNode, 0);
9872 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
9873 const ARMSubtarget *Subtarget) {
9874 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
9877 // Check that we have a pair of ADDC and ADDE as operands.
9878 // Both addends of the ADDE must be zero.
9879 SDNode* AddcNode = N->getOperand(2).getNode();
9880 SDNode* AddeNode = N->getOperand(3).getNode();
9881 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
9882 (AddeNode->getOpcode() == ARMISD::ADDE) &&
9883 isNullConstant(AddeNode->getOperand(0)) &&
9884 isNullConstant(AddeNode->getOperand(1)) &&
9885 (AddeNode->getOperand(2).getNode() == AddcNode))
9886 return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
9887 DAG.getVTList(MVT::i32, MVT::i32),
9888 {N->getOperand(0), N->getOperand(1),
9889 AddcNode->getOperand(0), AddcNode->getOperand(1)});
9894 static SDValue PerformAddcSubcCombine(SDNode *N, SelectionDAG &DAG,
9895 const ARMSubtarget *Subtarget) {
9896 if (Subtarget->isThumb1Only()) {
9897 SDValue RHS = N->getOperand(1);
9898 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
9899 int32_t imm = C->getSExtValue();
9900 if (imm < 0 && imm > INT_MIN) {
9902 RHS = DAG.getConstant(-imm, DL, MVT::i32);
9903 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
9905 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
9912 static SDValue PerformAddeSubeCombine(SDNode *N, SelectionDAG &DAG,
9913 const ARMSubtarget *Subtarget) {
9914 if (Subtarget->isThumb1Only()) {
9915 SDValue RHS = N->getOperand(1);
9916 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
9917 int64_t imm = C->getSExtValue();
9921 // The with-carry-in form matches bitwise not instead of the negation.
9922 // Effectively, the inverse interpretation of the carry flag already
9923 // accounts for part of the negation.
9924 RHS = DAG.getConstant(~imm, DL, MVT::i32);
9926 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
9928 return DAG.getNode(Opcode, DL, N->getVTList(),
9929 N->getOperand(0), RHS, N->getOperand(2));
9936 /// PerformADDECombine - Target-specific dag combine transform from
9937 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
9938 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
9939 static SDValue PerformADDECombine(SDNode *N,
9940 TargetLowering::DAGCombinerInfo &DCI,
9941 const ARMSubtarget *Subtarget) {
9942 // Only ARM and Thumb2 support UMLAL/SMLAL.
9943 if (Subtarget->isThumb1Only())
9944 return PerformAddeSubeCombine(N, DCI.DAG, Subtarget);
9946 // Only perform the checks after legalize when the pattern is available.
9947 if (DCI.isBeforeLegalize()) return SDValue();
9949 return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
9952 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
9953 /// operands N0 and N1. This is a helper for PerformADDCombine that is
9954 /// called with the default operands, and if that fails, with commuted
9956 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
9957 TargetLowering::DAGCombinerInfo &DCI,
9958 const ARMSubtarget *Subtarget){
9959 // Attempt to create vpadd for this add.
9960 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
9963 // Attempt to create vpaddl for this add.
9964 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
9966 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
9970 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
9971 if (N0.getNode()->hasOneUse())
9972 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
9977 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
9979 static SDValue PerformADDCombine(SDNode *N,
9980 TargetLowering::DAGCombinerInfo &DCI,
9981 const ARMSubtarget *Subtarget) {
9982 SDValue N0 = N->getOperand(0);
9983 SDValue N1 = N->getOperand(1);
9985 // First try with the default operand order.
9986 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
9989 // If that didn't work, try again with the operands commuted.
9990 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
9993 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
9995 static SDValue PerformSUBCombine(SDNode *N,
9996 TargetLowering::DAGCombinerInfo &DCI) {
9997 SDValue N0 = N->getOperand(0);
9998 SDValue N1 = N->getOperand(1);
10000 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10001 if (N1.getNode()->hasOneUse())
10002 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
10008 /// PerformVMULCombine
10009 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
10010 /// special multiplier accumulator forwarding.
10011 /// vmul d3, d0, d2
10012 /// vmla d3, d1, d2
10014 /// vadd d3, d0, d1
10015 /// vmul d3, d3, d2
10016 // However, for (A + B) * (A + B),
10023 static SDValue PerformVMULCombine(SDNode *N,
10024 TargetLowering::DAGCombinerInfo &DCI,
10025 const ARMSubtarget *Subtarget) {
10026 if (!Subtarget->hasVMLxForwarding())
10029 SelectionDAG &DAG = DCI.DAG;
10030 SDValue N0 = N->getOperand(0);
10031 SDValue N1 = N->getOperand(1);
10032 unsigned Opcode = N0.getOpcode();
10033 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10034 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
10035 Opcode = N1.getOpcode();
10036 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10037 Opcode != ISD::FADD && Opcode != ISD::FSUB)
10045 EVT VT = N->getValueType(0);
10047 SDValue N00 = N0->getOperand(0);
10048 SDValue N01 = N0->getOperand(1);
10049 return DAG.getNode(Opcode, DL, VT,
10050 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
10051 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
10054 static SDValue PerformMULCombine(SDNode *N,
10055 TargetLowering::DAGCombinerInfo &DCI,
10056 const ARMSubtarget *Subtarget) {
10057 SelectionDAG &DAG = DCI.DAG;
10059 if (Subtarget->isThumb1Only())
10062 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10065 EVT VT = N->getValueType(0);
10066 if (VT.is64BitVector() || VT.is128BitVector())
10067 return PerformVMULCombine(N, DCI, Subtarget);
10068 if (VT != MVT::i32)
10071 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10075 int64_t MulAmt = C->getSExtValue();
10076 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
10078 ShiftAmt = ShiftAmt & (32 - 1);
10079 SDValue V = N->getOperand(0);
10083 MulAmt >>= ShiftAmt;
10086 if (isPowerOf2_32(MulAmt - 1)) {
10087 // (mul x, 2^N + 1) => (add (shl x, N), x)
10088 Res = DAG.getNode(ISD::ADD, DL, VT,
10090 DAG.getNode(ISD::SHL, DL, VT,
10092 DAG.getConstant(Log2_32(MulAmt - 1), DL,
10094 } else if (isPowerOf2_32(MulAmt + 1)) {
10095 // (mul x, 2^N - 1) => (sub (shl x, N), x)
10096 Res = DAG.getNode(ISD::SUB, DL, VT,
10097 DAG.getNode(ISD::SHL, DL, VT,
10099 DAG.getConstant(Log2_32(MulAmt + 1), DL,
10105 uint64_t MulAmtAbs = -MulAmt;
10106 if (isPowerOf2_32(MulAmtAbs + 1)) {
10107 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10108 Res = DAG.getNode(ISD::SUB, DL, VT,
10110 DAG.getNode(ISD::SHL, DL, VT,
10112 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
10114 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
10115 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10116 Res = DAG.getNode(ISD::ADD, DL, VT,
10118 DAG.getNode(ISD::SHL, DL, VT,
10120 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
10122 Res = DAG.getNode(ISD::SUB, DL, VT,
10123 DAG.getConstant(0, DL, MVT::i32), Res);
10130 Res = DAG.getNode(ISD::SHL, DL, VT,
10131 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
10133 // Do not add new nodes to DAG combiner worklist.
10134 DCI.CombineTo(N, Res, false);
10138 static SDValue PerformANDCombine(SDNode *N,
10139 TargetLowering::DAGCombinerInfo &DCI,
10140 const ARMSubtarget *Subtarget) {
10141 // Attempt to use immediate-form VBIC
10142 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10144 EVT VT = N->getValueType(0);
10145 SelectionDAG &DAG = DCI.DAG;
10147 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10150 APInt SplatBits, SplatUndef;
10151 unsigned SplatBitSize;
10154 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10155 if (SplatBitSize <= 64) {
10157 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
10158 SplatUndef.getZExtValue(), SplatBitSize,
10159 DAG, dl, VbicVT, VT.is128BitVector(),
10161 if (Val.getNode()) {
10163 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
10164 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
10165 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
10170 if (!Subtarget->isThumb1Only()) {
10171 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
10172 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
10179 // Try combining OR nodes to SMULWB, SMULWT.
10180 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
10181 TargetLowering::DAGCombinerInfo &DCI,
10182 const ARMSubtarget *Subtarget) {
10183 if (!Subtarget->hasV6Ops() ||
10184 (Subtarget->isThumb() &&
10185 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
10188 SDValue SRL = OR->getOperand(0);
10189 SDValue SHL = OR->getOperand(1);
10191 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
10192 SRL = OR->getOperand(1);
10193 SHL = OR->getOperand(0);
10195 if (!isSRL16(SRL) || !isSHL16(SHL))
10198 // The first operands to the shifts need to be the two results from the
10199 // same smul_lohi node.
10200 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
10201 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
10204 SDNode *SMULLOHI = SRL.getOperand(0).getNode();
10205 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
10206 SHL.getOperand(0) != SDValue(SMULLOHI, 1))
10210 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
10211 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
10212 // For SMUWB the 16-bit value will signed extended somehow.
10213 // For SMULWT only the SRA is required.
10214 // Check both sides of SMUL_LOHI
10215 SDValue OpS16 = SMULLOHI->getOperand(0);
10216 SDValue OpS32 = SMULLOHI->getOperand(1);
10218 SelectionDAG &DAG = DCI.DAG;
10219 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
10221 OpS32 = SMULLOHI->getOperand(0);
10225 unsigned Opcode = 0;
10226 if (isS16(OpS16, DAG))
10227 Opcode = ARMISD::SMULWB;
10228 else if (isSRA16(OpS16)) {
10229 Opcode = ARMISD::SMULWT;
10230 OpS16 = OpS16->getOperand(0);
10235 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
10236 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
10237 return SDValue(OR, 0);
10240 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
10241 static SDValue PerformORCombine(SDNode *N,
10242 TargetLowering::DAGCombinerInfo &DCI,
10243 const ARMSubtarget *Subtarget) {
10244 // Attempt to use immediate-form VORR
10245 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10247 EVT VT = N->getValueType(0);
10248 SelectionDAG &DAG = DCI.DAG;
10250 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10253 APInt SplatBits, SplatUndef;
10254 unsigned SplatBitSize;
10256 if (BVN && Subtarget->hasNEON() &&
10257 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10258 if (SplatBitSize <= 64) {
10260 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
10261 SplatUndef.getZExtValue(), SplatBitSize,
10262 DAG, dl, VorrVT, VT.is128BitVector(),
10264 if (Val.getNode()) {
10266 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
10267 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
10268 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
10273 if (!Subtarget->isThumb1Only()) {
10274 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10275 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10277 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
10281 // The code below optimizes (or (and X, Y), Z).
10282 // The AND operand needs to have a single user to make these optimizations
10284 SDValue N0 = N->getOperand(0);
10285 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
10287 SDValue N1 = N->getOperand(1);
10289 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
10290 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
10291 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10293 unsigned SplatBitSize;
10296 APInt SplatBits0, SplatBits1;
10297 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
10298 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
10299 // Ensure that the second operand of both ands are constants
10300 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
10301 HasAnyUndefs) && !HasAnyUndefs) {
10302 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
10303 HasAnyUndefs) && !HasAnyUndefs) {
10304 // Ensure that the bit width of the constants are the same and that
10305 // the splat arguments are logical inverses as per the pattern we
10306 // are trying to simplify.
10307 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
10308 SplatBits0 == ~SplatBits1) {
10309 // Canonicalize the vector type to make instruction selection
10311 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
10312 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
10315 N1->getOperand(0));
10316 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10322 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
10325 // BFI is only available on V6T2+
10326 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
10330 // 1) or (and A, mask), val => ARMbfi A, val, mask
10331 // iff (val & mask) == val
10333 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10334 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
10335 // && mask == ~mask2
10336 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
10337 // && ~mask == mask2
10338 // (i.e., copy a bitfield value into another bitfield of the same width)
10340 if (VT != MVT::i32)
10343 SDValue N00 = N0.getOperand(0);
10345 // The value and the mask need to be constants so we can verify this is
10346 // actually a bitfield set. If the mask is 0xffff, we can do better
10347 // via a movt instruction, so don't use BFI in that case.
10348 SDValue MaskOp = N0.getOperand(1);
10349 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
10352 unsigned Mask = MaskC->getZExtValue();
10353 if (Mask == 0xffff)
10356 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
10357 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10359 unsigned Val = N1C->getZExtValue();
10360 if ((Val & ~Mask) != Val)
10363 if (ARM::isBitFieldInvertedMask(Mask)) {
10364 Val >>= countTrailingZeros(~Mask);
10366 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
10367 DAG.getConstant(Val, DL, MVT::i32),
10368 DAG.getConstant(Mask, DL, MVT::i32));
10370 // Do not add new nodes to DAG combiner worklist.
10371 DCI.CombineTo(N, Res, false);
10374 } else if (N1.getOpcode() == ISD::AND) {
10375 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10376 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10379 unsigned Mask2 = N11C->getZExtValue();
10381 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
10383 if (ARM::isBitFieldInvertedMask(Mask) &&
10384 (Mask == ~Mask2)) {
10385 // The pack halfword instruction works better for masks that fit it,
10386 // so use that when it's available.
10387 if (Subtarget->hasDSP() &&
10388 (Mask == 0xffff || Mask == 0xffff0000))
10391 unsigned amt = countTrailingZeros(Mask2);
10392 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
10393 DAG.getConstant(amt, DL, MVT::i32));
10394 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
10395 DAG.getConstant(Mask, DL, MVT::i32));
10396 // Do not add new nodes to DAG combiner worklist.
10397 DCI.CombineTo(N, Res, false);
10399 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
10400 (~Mask == Mask2)) {
10401 // The pack halfword instruction works better for masks that fit it,
10402 // so use that when it's available.
10403 if (Subtarget->hasDSP() &&
10404 (Mask2 == 0xffff || Mask2 == 0xffff0000))
10407 unsigned lsb = countTrailingZeros(Mask);
10408 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
10409 DAG.getConstant(lsb, DL, MVT::i32));
10410 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
10411 DAG.getConstant(Mask2, DL, MVT::i32));
10412 // Do not add new nodes to DAG combiner worklist.
10413 DCI.CombineTo(N, Res, false);
10418 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
10419 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
10420 ARM::isBitFieldInvertedMask(~Mask)) {
10421 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
10422 // where lsb(mask) == #shamt and masked bits of B are known zero.
10423 SDValue ShAmt = N00.getOperand(1);
10424 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10425 unsigned LSB = countTrailingZeros(Mask);
10429 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
10430 DAG.getConstant(~Mask, DL, MVT::i32));
10432 // Do not add new nodes to DAG combiner worklist.
10433 DCI.CombineTo(N, Res, false);
10439 static SDValue PerformXORCombine(SDNode *N,
10440 TargetLowering::DAGCombinerInfo &DCI,
10441 const ARMSubtarget *Subtarget) {
10442 EVT VT = N->getValueType(0);
10443 SelectionDAG &DAG = DCI.DAG;
10445 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10448 if (!Subtarget->isThumb1Only()) {
10449 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10450 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10457 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
10458 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
10459 // their position in "to" (Rd).
10460 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
10461 assert(N->getOpcode() == ARMISD::BFI);
10463 SDValue From = N->getOperand(1);
10464 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
10465 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
10467 // If the Base came from a SHR #C, we can deduce that it is really testing bit
10468 // #C in the base of the SHR.
10469 if (From->getOpcode() == ISD::SRL &&
10470 isa<ConstantSDNode>(From->getOperand(1))) {
10471 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
10472 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
10473 FromMask <<= Shift.getLimitedValue(31);
10474 From = From->getOperand(0);
10480 // If A and B contain one contiguous set of bits, does A | B == A . B?
10482 // Neither A nor B must be zero.
10483 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
10484 unsigned LastActiveBitInA = A.countTrailingZeros();
10485 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
10486 return LastActiveBitInA - 1 == FirstActiveBitInB;
10489 static SDValue FindBFIToCombineWith(SDNode *N) {
10490 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
10492 APInt ToMask, FromMask;
10493 SDValue From = ParseBFI(N, ToMask, FromMask);
10494 SDValue To = N->getOperand(0);
10496 // Now check for a compatible BFI to merge with. We can pass through BFIs that
10497 // aren't compatible, but not if they set the same bit in their destination as
10498 // we do (or that of any BFI we're going to combine with).
10500 APInt CombinedToMask = ToMask;
10501 while (V.getOpcode() == ARMISD::BFI) {
10502 APInt NewToMask, NewFromMask;
10503 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
10504 if (NewFrom != From) {
10505 // This BFI has a different base. Keep going.
10506 CombinedToMask |= NewToMask;
10507 V = V.getOperand(0);
10511 // Do the written bits conflict with any we've seen so far?
10512 if ((NewToMask & CombinedToMask).getBoolValue())
10513 // Conflicting bits - bail out because going further is unsafe.
10516 // Are the new bits contiguous when combined with the old bits?
10517 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
10518 BitsProperlyConcatenate(FromMask, NewFromMask))
10520 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
10521 BitsProperlyConcatenate(NewFromMask, FromMask))
10524 // We've seen a write to some bits, so track it.
10525 CombinedToMask |= NewToMask;
10527 V = V.getOperand(0);
10533 static SDValue PerformBFICombine(SDNode *N,
10534 TargetLowering::DAGCombinerInfo &DCI) {
10535 SDValue N1 = N->getOperand(1);
10536 if (N1.getOpcode() == ISD::AND) {
10537 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
10538 // the bits being cleared by the AND are not demanded by the BFI.
10539 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10542 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10543 unsigned LSB = countTrailingZeros(~InvMask);
10544 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
10546 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
10547 "undefined behavior");
10548 unsigned Mask = (1u << Width) - 1;
10549 unsigned Mask2 = N11C->getZExtValue();
10550 if ((Mask & (~Mask2)) == 0)
10551 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
10552 N->getOperand(0), N1.getOperand(0),
10554 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
10555 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
10556 // Keep track of any consecutive bits set that all come from the same base
10557 // value. We can combine these together into a single BFI.
10558 SDValue CombineBFI = FindBFIToCombineWith(N);
10559 if (CombineBFI == SDValue())
10562 // We've found a BFI.
10563 APInt ToMask1, FromMask1;
10564 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
10566 APInt ToMask2, FromMask2;
10567 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
10568 assert(From1 == From2);
10571 // First, unlink CombineBFI.
10572 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
10573 // Then create a new BFI, combining the two together.
10574 APInt NewFromMask = FromMask1 | FromMask2;
10575 APInt NewToMask = ToMask1 | ToMask2;
10577 EVT VT = N->getValueType(0);
10580 if (NewFromMask[0] == 0)
10581 From1 = DCI.DAG.getNode(
10582 ISD::SRL, dl, VT, From1,
10583 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
10584 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
10585 DCI.DAG.getConstant(~NewToMask, dl, VT));
10590 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
10591 /// ARMISD::VMOVRRD.
10592 static SDValue PerformVMOVRRDCombine(SDNode *N,
10593 TargetLowering::DAGCombinerInfo &DCI,
10594 const ARMSubtarget *Subtarget) {
10595 // vmovrrd(vmovdrr x, y) -> x,y
10596 SDValue InDouble = N->getOperand(0);
10597 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
10598 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
10600 // vmovrrd(load f64) -> (load i32), (load i32)
10601 SDNode *InNode = InDouble.getNode();
10602 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
10603 InNode->getValueType(0) == MVT::f64 &&
10604 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
10605 !cast<LoadSDNode>(InNode)->isVolatile()) {
10606 // TODO: Should this be done for non-FrameIndex operands?
10607 LoadSDNode *LD = cast<LoadSDNode>(InNode);
10609 SelectionDAG &DAG = DCI.DAG;
10611 SDValue BasePtr = LD->getBasePtr();
10613 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
10614 LD->getAlignment(), LD->getMemOperand()->getFlags());
10616 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10617 DAG.getConstant(4, DL, MVT::i32));
10618 SDValue NewLD2 = DAG.getLoad(
10619 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
10620 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
10622 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
10623 if (DCI.DAG.getDataLayout().isBigEndian())
10624 std::swap (NewLD1, NewLD2);
10625 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
10632 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
10633 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
10634 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
10635 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
10636 SDValue Op0 = N->getOperand(0);
10637 SDValue Op1 = N->getOperand(1);
10638 if (Op0.getOpcode() == ISD::BITCAST)
10639 Op0 = Op0.getOperand(0);
10640 if (Op1.getOpcode() == ISD::BITCAST)
10641 Op1 = Op1.getOperand(0);
10642 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
10643 Op0.getNode() == Op1.getNode() &&
10644 Op0.getResNo() == 0 && Op1.getResNo() == 1)
10645 return DAG.getNode(ISD::BITCAST, SDLoc(N),
10646 N->getValueType(0), Op0.getOperand(0));
10650 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
10651 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
10652 /// i64 vector to have f64 elements, since the value can then be loaded
10653 /// directly into a VFP register.
10654 static bool hasNormalLoadOperand(SDNode *N) {
10655 unsigned NumElts = N->getValueType(0).getVectorNumElements();
10656 for (unsigned i = 0; i < NumElts; ++i) {
10657 SDNode *Elt = N->getOperand(i).getNode();
10658 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
10664 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
10665 /// ISD::BUILD_VECTOR.
10666 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
10667 TargetLowering::DAGCombinerInfo &DCI,
10668 const ARMSubtarget *Subtarget) {
10669 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
10670 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
10671 // into a pair of GPRs, which is fine when the value is used as a scalar,
10672 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
10673 SelectionDAG &DAG = DCI.DAG;
10674 if (N->getNumOperands() == 2)
10675 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
10678 // Load i64 elements as f64 values so that type legalization does not split
10679 // them up into i32 values.
10680 EVT VT = N->getValueType(0);
10681 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
10684 SmallVector<SDValue, 8> Ops;
10685 unsigned NumElts = VT.getVectorNumElements();
10686 for (unsigned i = 0; i < NumElts; ++i) {
10687 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
10689 // Make the DAGCombiner fold the bitcast.
10690 DCI.AddToWorklist(V.getNode());
10692 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
10693 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
10694 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10697 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
10699 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
10700 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
10701 // At that time, we may have inserted bitcasts from integer to float.
10702 // If these bitcasts have survived DAGCombine, change the lowering of this
10703 // BUILD_VECTOR in something more vector friendly, i.e., that does not
10704 // force to use floating point types.
10706 // Make sure we can change the type of the vector.
10707 // This is possible iff:
10708 // 1. The vector is only used in a bitcast to a integer type. I.e.,
10709 // 1.1. Vector is used only once.
10710 // 1.2. Use is a bit convert to an integer type.
10711 // 2. The size of its operands are 32-bits (64-bits are not legal).
10712 EVT VT = N->getValueType(0);
10713 EVT EltVT = VT.getVectorElementType();
10715 // Check 1.1. and 2.
10716 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
10719 // By construction, the input type must be float.
10720 assert(EltVT == MVT::f32 && "Unexpected type!");
10723 SDNode *Use = *N->use_begin();
10724 if (Use->getOpcode() != ISD::BITCAST ||
10725 Use->getValueType(0).isFloatingPoint())
10728 // Check profitability.
10729 // Model is, if more than half of the relevant operands are bitcast from
10730 // i32, turn the build_vector into a sequence of insert_vector_elt.
10731 // Relevant operands are everything that is not statically
10732 // (i.e., at compile time) bitcasted.
10733 unsigned NumOfBitCastedElts = 0;
10734 unsigned NumElts = VT.getVectorNumElements();
10735 unsigned NumOfRelevantElts = NumElts;
10736 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
10737 SDValue Elt = N->getOperand(Idx);
10738 if (Elt->getOpcode() == ISD::BITCAST) {
10739 // Assume only bit cast to i32 will go away.
10740 if (Elt->getOperand(0).getValueType() == MVT::i32)
10741 ++NumOfBitCastedElts;
10742 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
10743 // Constants are statically casted, thus do not count them as
10744 // relevant operands.
10745 --NumOfRelevantElts;
10748 // Check if more than half of the elements require a non-free bitcast.
10749 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
10752 SelectionDAG &DAG = DCI.DAG;
10753 // Create the new vector type.
10754 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
10755 // Check if the type is legal.
10756 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10757 if (!TLI.isTypeLegal(VecVT))
10761 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
10762 // => BITCAST INSERT_VECTOR_ELT
10763 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
10764 // (BITCAST EN), N.
10765 SDValue Vec = DAG.getUNDEF(VecVT);
10767 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
10768 SDValue V = N->getOperand(Idx);
10771 if (V.getOpcode() == ISD::BITCAST &&
10772 V->getOperand(0).getValueType() == MVT::i32)
10773 // Fold obvious case.
10774 V = V.getOperand(0);
10776 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
10777 // Make the DAGCombiner fold the bitcasts.
10778 DCI.AddToWorklist(V.getNode());
10780 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
10781 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
10783 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
10784 // Make the DAGCombiner fold the bitcasts.
10785 DCI.AddToWorklist(Vec.getNode());
10789 /// PerformInsertEltCombine - Target-specific dag combine xforms for
10790 /// ISD::INSERT_VECTOR_ELT.
10791 static SDValue PerformInsertEltCombine(SDNode *N,
10792 TargetLowering::DAGCombinerInfo &DCI) {
10793 // Bitcast an i64 load inserted into a vector to f64.
10794 // Otherwise, the i64 value will be legalized to a pair of i32 values.
10795 EVT VT = N->getValueType(0);
10796 SDNode *Elt = N->getOperand(1).getNode();
10797 if (VT.getVectorElementType() != MVT::i64 ||
10798 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
10801 SelectionDAG &DAG = DCI.DAG;
10803 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10804 VT.getVectorNumElements());
10805 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
10806 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
10807 // Make the DAGCombiner fold the bitcasts.
10808 DCI.AddToWorklist(Vec.getNode());
10809 DCI.AddToWorklist(V.getNode());
10810 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
10811 Vec, V, N->getOperand(2));
10812 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
10815 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
10816 /// ISD::VECTOR_SHUFFLE.
10817 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
10818 // The LLVM shufflevector instruction does not require the shuffle mask
10819 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
10820 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
10821 // operands do not match the mask length, they are extended by concatenating
10822 // them with undef vectors. That is probably the right thing for other
10823 // targets, but for NEON it is better to concatenate two double-register
10824 // size vector operands into a single quad-register size vector. Do that
10825 // transformation here:
10826 // shuffle(concat(v1, undef), concat(v2, undef)) ->
10827 // shuffle(concat(v1, v2), undef)
10828 SDValue Op0 = N->getOperand(0);
10829 SDValue Op1 = N->getOperand(1);
10830 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
10831 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
10832 Op0.getNumOperands() != 2 ||
10833 Op1.getNumOperands() != 2)
10835 SDValue Concat0Op1 = Op0.getOperand(1);
10836 SDValue Concat1Op1 = Op1.getOperand(1);
10837 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
10839 // Skip the transformation if any of the types are illegal.
10840 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10841 EVT VT = N->getValueType(0);
10842 if (!TLI.isTypeLegal(VT) ||
10843 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
10844 !TLI.isTypeLegal(Concat1Op1.getValueType()))
10847 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10848 Op0.getOperand(0), Op1.getOperand(0));
10849 // Translate the shuffle mask.
10850 SmallVector<int, 16> NewMask;
10851 unsigned NumElts = VT.getVectorNumElements();
10852 unsigned HalfElts = NumElts/2;
10853 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10854 for (unsigned n = 0; n < NumElts; ++n) {
10855 int MaskElt = SVN->getMaskElt(n);
10857 if (MaskElt < (int)HalfElts)
10859 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
10860 NewElt = HalfElts + MaskElt - NumElts;
10861 NewMask.push_back(NewElt);
10863 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
10864 DAG.getUNDEF(VT), NewMask);
10867 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
10868 /// NEON load/store intrinsics, and generic vector load/stores, to merge
10869 /// base address updates.
10870 /// For generic load/stores, the memory type is assumed to be a vector.
10871 /// The caller is assumed to have checked legality.
10872 static SDValue CombineBaseUpdate(SDNode *N,
10873 TargetLowering::DAGCombinerInfo &DCI) {
10874 SelectionDAG &DAG = DCI.DAG;
10875 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
10876 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
10877 const bool isStore = N->getOpcode() == ISD::STORE;
10878 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
10879 SDValue Addr = N->getOperand(AddrOpIdx);
10880 MemSDNode *MemN = cast<MemSDNode>(N);
10883 // Search for a use of the address operand that is an increment.
10884 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10885 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10886 SDNode *User = *UI;
10887 if (User->getOpcode() != ISD::ADD ||
10888 UI.getUse().getResNo() != Addr.getResNo())
10891 // Check that the add is independent of the load/store. Otherwise, folding
10892 // it would create a cycle.
10893 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
10896 // Find the new opcode for the updating load/store.
10897 bool isLoadOp = true;
10898 bool isLaneOp = false;
10899 unsigned NewOpc = 0;
10900 unsigned NumVecs = 0;
10902 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10904 default: llvm_unreachable("unexpected intrinsic for Neon base update");
10905 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
10906 NumVecs = 1; break;
10907 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
10908 NumVecs = 2; break;
10909 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
10910 NumVecs = 3; break;
10911 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
10912 NumVecs = 4; break;
10913 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
10914 NumVecs = 2; isLaneOp = true; break;
10915 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
10916 NumVecs = 3; isLaneOp = true; break;
10917 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
10918 NumVecs = 4; isLaneOp = true; break;
10919 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
10920 NumVecs = 1; isLoadOp = false; break;
10921 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
10922 NumVecs = 2; isLoadOp = false; break;
10923 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
10924 NumVecs = 3; isLoadOp = false; break;
10925 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
10926 NumVecs = 4; isLoadOp = false; break;
10927 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
10928 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
10929 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
10930 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
10931 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
10932 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
10936 switch (N->getOpcode()) {
10937 default: llvm_unreachable("unexpected opcode for Neon base update");
10938 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
10939 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
10940 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
10941 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
10942 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
10943 NumVecs = 1; isLaneOp = false; break;
10944 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
10945 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
10949 // Find the size of memory referenced by the load/store.
10952 VecTy = N->getValueType(0);
10953 } else if (isIntrinsic) {
10954 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
10956 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
10957 VecTy = N->getOperand(1).getValueType();
10960 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10962 NumBytes /= VecTy.getVectorNumElements();
10964 // If the increment is a constant, it must match the memory ref size.
10965 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10966 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
10967 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
10968 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
10969 // separate instructions that make it harder to use a non-constant update.
10973 // OK, we found an ADD we can fold into the base update.
10974 // Now, create a _UPD node, taking care of not breaking alignment.
10976 EVT AlignedVecTy = VecTy;
10977 unsigned Alignment = MemN->getAlignment();
10979 // If this is a less-than-standard-aligned load/store, change the type to
10980 // match the standard alignment.
10981 // The alignment is overlooked when selecting _UPD variants; and it's
10982 // easier to introduce bitcasts here than fix that.
10983 // There are 3 ways to get to this base-update combine:
10984 // - intrinsics: they are assumed to be properly aligned (to the standard
10985 // alignment of the memory type), so we don't need to do anything.
10986 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
10987 // intrinsics, so, likewise, there's nothing to do.
10988 // - generic load/store instructions: the alignment is specified as an
10989 // explicit operand, rather than implicitly as the standard alignment
10990 // of the memory type (like the intrisics). We need to change the
10991 // memory type to match the explicit alignment. That way, we don't
10992 // generate non-standard-aligned ARMISD::VLDx nodes.
10993 if (isa<LSBaseSDNode>(N)) {
10994 if (Alignment == 0)
10996 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
10997 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
10998 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
10999 assert(!isLaneOp && "Unexpected generic load/store lane.");
11000 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
11001 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
11003 // Don't set an explicit alignment on regular load/stores that we want
11004 // to transform to VLD/VST 1_UPD nodes.
11005 // This matches the behavior of regular load/stores, which only get an
11006 // explicit alignment if the MMO alignment is larger than the standard
11007 // alignment of the memory type.
11008 // Intrinsics, however, always get an explicit alignment, set to the
11009 // alignment of the MMO.
11013 // Create the new updating load/store node.
11014 // First, create an SDVTList for the new updating node's results.
11016 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
11018 for (n = 0; n < NumResultVecs; ++n)
11019 Tys[n] = AlignedVecTy;
11020 Tys[n++] = MVT::i32;
11021 Tys[n] = MVT::Other;
11022 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
11024 // Then, gather the new node's operands.
11025 SmallVector<SDValue, 8> Ops;
11026 Ops.push_back(N->getOperand(0)); // incoming chain
11027 Ops.push_back(N->getOperand(AddrOpIdx));
11028 Ops.push_back(Inc);
11030 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
11031 // Try to match the intrinsic's signature
11032 Ops.push_back(StN->getValue());
11034 // Loads (and of course intrinsics) match the intrinsics' signature,
11035 // so just add all but the alignment operand.
11036 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
11037 Ops.push_back(N->getOperand(i));
11040 // For all node types, the alignment operand is always the last one.
11041 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
11043 // If this is a non-standard-aligned STORE, the penultimate operand is the
11044 // stored value. Bitcast it to the aligned type.
11045 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
11046 SDValue &StVal = Ops[Ops.size()-2];
11047 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
11050 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
11051 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
11052 MemN->getMemOperand());
11054 // Update the uses.
11055 SmallVector<SDValue, 5> NewResults;
11056 for (unsigned i = 0; i < NumResultVecs; ++i)
11057 NewResults.push_back(SDValue(UpdN.getNode(), i));
11059 // If this is an non-standard-aligned LOAD, the first result is the loaded
11060 // value. Bitcast it to the expected result type.
11061 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
11062 SDValue &LdVal = NewResults[0];
11063 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
11066 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
11067 DCI.CombineTo(N, NewResults);
11068 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11075 static SDValue PerformVLDCombine(SDNode *N,
11076 TargetLowering::DAGCombinerInfo &DCI) {
11077 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11080 return CombineBaseUpdate(N, DCI);
11083 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
11084 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
11085 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
11087 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11088 SelectionDAG &DAG = DCI.DAG;
11089 EVT VT = N->getValueType(0);
11090 // vldN-dup instructions only support 64-bit vectors for N > 1.
11091 if (!VT.is64BitVector())
11094 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
11095 SDNode *VLD = N->getOperand(0).getNode();
11096 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
11098 unsigned NumVecs = 0;
11099 unsigned NewOpc = 0;
11100 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
11101 if (IntNo == Intrinsic::arm_neon_vld2lane) {
11103 NewOpc = ARMISD::VLD2DUP;
11104 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
11106 NewOpc = ARMISD::VLD3DUP;
11107 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
11109 NewOpc = ARMISD::VLD4DUP;
11114 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
11115 // numbers match the load.
11116 unsigned VLDLaneNo =
11117 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
11118 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11120 // Ignore uses of the chain result.
11121 if (UI.getUse().getResNo() == NumVecs)
11123 SDNode *User = *UI;
11124 if (User->getOpcode() != ARMISD::VDUPLANE ||
11125 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
11129 // Create the vldN-dup node.
11132 for (n = 0; n < NumVecs; ++n)
11134 Tys[n] = MVT::Other;
11135 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
11136 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
11137 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
11138 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
11139 Ops, VLDMemInt->getMemoryVT(),
11140 VLDMemInt->getMemOperand());
11142 // Update the uses.
11143 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11145 unsigned ResNo = UI.getUse().getResNo();
11146 // Ignore uses of the chain result.
11147 if (ResNo == NumVecs)
11149 SDNode *User = *UI;
11150 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
11153 // Now the vldN-lane intrinsic is dead except for its chain result.
11154 // Update uses of the chain.
11155 std::vector<SDValue> VLDDupResults;
11156 for (unsigned n = 0; n < NumVecs; ++n)
11157 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
11158 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
11159 DCI.CombineTo(VLD, VLDDupResults);
11164 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
11165 /// ARMISD::VDUPLANE.
11166 static SDValue PerformVDUPLANECombine(SDNode *N,
11167 TargetLowering::DAGCombinerInfo &DCI) {
11168 SDValue Op = N->getOperand(0);
11170 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
11171 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
11172 if (CombineVLDDUP(N, DCI))
11173 return SDValue(N, 0);
11175 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
11176 // redundant. Ignore bit_converts for now; element sizes are checked below.
11177 while (Op.getOpcode() == ISD::BITCAST)
11178 Op = Op.getOperand(0);
11179 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
11182 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
11183 unsigned EltSize = Op.getScalarValueSizeInBits();
11184 // The canonical VMOV for a zero vector uses a 32-bit element size.
11185 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11187 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
11189 EVT VT = N->getValueType(0);
11190 if (EltSize > VT.getScalarSizeInBits())
11193 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
11196 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
11197 static SDValue PerformVDUPCombine(SDNode *N,
11198 TargetLowering::DAGCombinerInfo &DCI) {
11199 SelectionDAG &DAG = DCI.DAG;
11200 SDValue Op = N->getOperand(0);
11202 // Match VDUP(LOAD) -> VLD1DUP.
11203 // We match this pattern here rather than waiting for isel because the
11204 // transform is only legal for unindexed loads.
11205 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
11206 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
11207 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
11208 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
11209 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
11210 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
11211 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
11212 Ops, LD->getMemoryVT(),
11213 LD->getMemOperand());
11214 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
11221 static SDValue PerformLOADCombine(SDNode *N,
11222 TargetLowering::DAGCombinerInfo &DCI) {
11223 EVT VT = N->getValueType(0);
11225 // If this is a legal vector load, try to combine it into a VLD1_UPD.
11226 if (ISD::isNormalLoad(N) && VT.isVector() &&
11227 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11228 return CombineBaseUpdate(N, DCI);
11233 /// PerformSTORECombine - Target-specific dag combine xforms for
11235 static SDValue PerformSTORECombine(SDNode *N,
11236 TargetLowering::DAGCombinerInfo &DCI) {
11237 StoreSDNode *St = cast<StoreSDNode>(N);
11238 if (St->isVolatile())
11241 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
11242 // pack all of the elements in one place. Next, store to memory in fewer
11244 SDValue StVal = St->getValue();
11245 EVT VT = StVal.getValueType();
11246 if (St->isTruncatingStore() && VT.isVector()) {
11247 SelectionDAG &DAG = DCI.DAG;
11248 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11249 EVT StVT = St->getMemoryVT();
11250 unsigned NumElems = VT.getVectorNumElements();
11251 assert(StVT != VT && "Cannot truncate to the same type");
11252 unsigned FromEltSz = VT.getScalarSizeInBits();
11253 unsigned ToEltSz = StVT.getScalarSizeInBits();
11255 // From, To sizes and ElemCount must be pow of two
11256 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
11258 // We are going to use the original vector elt for storing.
11259 // Accumulated smaller vector elements must be a multiple of the store size.
11260 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
11262 unsigned SizeRatio = FromEltSz / ToEltSz;
11263 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
11265 // Create a type on which we perform the shuffle.
11266 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
11267 NumElems*SizeRatio);
11268 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
11271 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
11272 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
11273 for (unsigned i = 0; i < NumElems; ++i)
11274 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
11275 ? (i + 1) * SizeRatio - 1
11278 // Can't shuffle using an illegal type.
11279 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
11281 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
11282 DAG.getUNDEF(WideVec.getValueType()),
11284 // At this point all of the data is stored at the bottom of the
11285 // register. We now need to save it to mem.
11287 // Find the largest store unit
11288 MVT StoreType = MVT::i8;
11289 for (MVT Tp : MVT::integer_valuetypes()) {
11290 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
11293 // Didn't find a legal store type.
11294 if (!TLI.isTypeLegal(StoreType))
11297 // Bitcast the original vector into a vector of store-size units
11298 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
11299 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
11300 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
11301 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
11302 SmallVector<SDValue, 8> Chains;
11303 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
11304 TLI.getPointerTy(DAG.getDataLayout()));
11305 SDValue BasePtr = St->getBasePtr();
11307 // Perform one or more big stores into memory.
11308 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
11309 for (unsigned I = 0; I < E; I++) {
11310 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
11311 StoreType, ShuffWide,
11312 DAG.getIntPtrConstant(I, DL));
11313 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
11314 St->getPointerInfo(), St->getAlignment(),
11315 St->getMemOperand()->getFlags());
11316 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
11318 Chains.push_back(Ch);
11320 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11323 if (!ISD::isNormalStore(St))
11326 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
11327 // ARM stores of arguments in the same cache line.
11328 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
11329 StVal.getNode()->hasOneUse()) {
11330 SelectionDAG &DAG = DCI.DAG;
11331 bool isBigEndian = DAG.getDataLayout().isBigEndian();
11333 SDValue BasePtr = St->getBasePtr();
11334 SDValue NewST1 = DAG.getStore(
11335 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
11336 BasePtr, St->getPointerInfo(), St->getAlignment(),
11337 St->getMemOperand()->getFlags());
11339 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11340 DAG.getConstant(4, DL, MVT::i32));
11341 return DAG.getStore(NewST1.getValue(0), DL,
11342 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
11343 OffsetPtr, St->getPointerInfo(),
11344 std::min(4U, St->getAlignment() / 2),
11345 St->getMemOperand()->getFlags());
11348 if (StVal.getValueType() == MVT::i64 &&
11349 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11351 // Bitcast an i64 store extracted from a vector to f64.
11352 // Otherwise, the i64 value will be legalized to a pair of i32 values.
11353 SelectionDAG &DAG = DCI.DAG;
11355 SDValue IntVec = StVal.getOperand(0);
11356 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11357 IntVec.getValueType().getVectorNumElements());
11358 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
11359 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11360 Vec, StVal.getOperand(1));
11362 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
11363 // Make the DAGCombiner fold the bitcasts.
11364 DCI.AddToWorklist(Vec.getNode());
11365 DCI.AddToWorklist(ExtElt.getNode());
11366 DCI.AddToWorklist(V.getNode());
11367 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
11368 St->getPointerInfo(), St->getAlignment(),
11369 St->getMemOperand()->getFlags(), St->getAAInfo());
11372 // If this is a legal vector store, try to combine it into a VST1_UPD.
11373 if (ISD::isNormalStore(N) && VT.isVector() &&
11374 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11375 return CombineBaseUpdate(N, DCI);
11380 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
11381 /// can replace combinations of VMUL and VCVT (floating-point to integer)
11382 /// when the VMUL has a constant operand that is a power of 2.
11384 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11385 /// vmul.f32 d16, d17, d16
11386 /// vcvt.s32.f32 d16, d16
11388 /// vcvt.s32.f32 d16, d16, #3
11389 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
11390 const ARMSubtarget *Subtarget) {
11391 if (!Subtarget->hasNEON())
11394 SDValue Op = N->getOperand(0);
11395 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
11396 Op.getOpcode() != ISD::FMUL)
11399 SDValue ConstVec = Op->getOperand(1);
11400 if (!isa<BuildVectorSDNode>(ConstVec))
11403 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
11404 uint32_t FloatBits = FloatTy.getSizeInBits();
11405 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
11406 uint32_t IntBits = IntTy.getSizeInBits();
11407 unsigned NumLanes = Op.getValueType().getVectorNumElements();
11408 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11409 // These instructions only exist converting from f32 to i32. We can handle
11410 // smaller integers by generating an extra truncate, but larger ones would
11411 // be lossy. We also can't handle more then 4 lanes, since these intructions
11412 // only support v2i32/v4i32 types.
11416 BitVector UndefElements;
11417 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11418 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11419 if (C == -1 || C == 0 || C > 32)
11423 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
11424 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
11425 Intrinsic::arm_neon_vcvtfp2fxu;
11426 SDValue FixConv = DAG.getNode(
11427 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11428 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
11429 DAG.getConstant(C, dl, MVT::i32));
11431 if (IntBits < FloatBits)
11432 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
11437 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
11438 /// can replace combinations of VCVT (integer to floating-point) and VDIV
11439 /// when the VDIV has a constant operand that is a power of 2.
11441 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11442 /// vcvt.f32.s32 d16, d16
11443 /// vdiv.f32 d16, d17, d16
11445 /// vcvt.f32.s32 d16, d16, #3
11446 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
11447 const ARMSubtarget *Subtarget) {
11448 if (!Subtarget->hasNEON())
11451 SDValue Op = N->getOperand(0);
11452 unsigned OpOpcode = Op.getNode()->getOpcode();
11453 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
11454 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
11457 SDValue ConstVec = N->getOperand(1);
11458 if (!isa<BuildVectorSDNode>(ConstVec))
11461 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
11462 uint32_t FloatBits = FloatTy.getSizeInBits();
11463 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
11464 uint32_t IntBits = IntTy.getSizeInBits();
11465 unsigned NumLanes = Op.getValueType().getVectorNumElements();
11466 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11467 // These instructions only exist converting from i32 to f32. We can handle
11468 // smaller integers by generating an extra extend, but larger ones would
11469 // be lossy. We also can't handle more then 4 lanes, since these intructions
11470 // only support v2i32/v4i32 types.
11474 BitVector UndefElements;
11475 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11476 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11477 if (C == -1 || C == 0 || C > 32)
11481 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
11482 SDValue ConvInput = Op.getOperand(0);
11483 if (IntBits < FloatBits)
11484 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
11485 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11488 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
11489 Intrinsic::arm_neon_vcvtfxu2fp;
11490 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
11492 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
11493 ConvInput, DAG.getConstant(C, dl, MVT::i32));
11496 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
11497 /// operand of a vector shift operation, where all the elements of the
11498 /// build_vector must have the same constant integer value.
11499 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
11500 // Ignore bit_converts.
11501 while (Op.getOpcode() == ISD::BITCAST)
11502 Op = Op.getOperand(0);
11503 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
11504 APInt SplatBits, SplatUndef;
11505 unsigned SplatBitSize;
11507 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
11508 HasAnyUndefs, ElementBits) ||
11509 SplatBitSize > ElementBits)
11511 Cnt = SplatBits.getSExtValue();
11515 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
11516 /// operand of a vector shift left operation. That value must be in the range:
11517 /// 0 <= Value < ElementBits for a left shift; or
11518 /// 0 <= Value <= ElementBits for a long left shift.
11519 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
11520 assert(VT.isVector() && "vector shift count is not a vector type");
11521 int64_t ElementBits = VT.getScalarSizeInBits();
11522 if (! getVShiftImm(Op, ElementBits, Cnt))
11524 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
11527 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
11528 /// operand of a vector shift right operation. For a shift opcode, the value
11529 /// is positive, but for an intrinsic the value count must be negative. The
11530 /// absolute value must be in the range:
11531 /// 1 <= |Value| <= ElementBits for a right shift; or
11532 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
11533 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
11535 assert(VT.isVector() && "vector shift count is not a vector type");
11536 int64_t ElementBits = VT.getScalarSizeInBits();
11537 if (! getVShiftImm(Op, ElementBits, Cnt))
11540 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
11541 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
11548 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
11549 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
11550 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11553 // Don't do anything for most intrinsics.
11556 // Vector shifts: check for immediate versions and lower them.
11557 // Note: This is done during DAG combining instead of DAG legalizing because
11558 // the build_vectors for 64-bit vector element shift counts are generally
11559 // not legal, and it is hard to see their values after they get legalized to
11560 // loads from a constant pool.
11561 case Intrinsic::arm_neon_vshifts:
11562 case Intrinsic::arm_neon_vshiftu:
11563 case Intrinsic::arm_neon_vrshifts:
11564 case Intrinsic::arm_neon_vrshiftu:
11565 case Intrinsic::arm_neon_vrshiftn:
11566 case Intrinsic::arm_neon_vqshifts:
11567 case Intrinsic::arm_neon_vqshiftu:
11568 case Intrinsic::arm_neon_vqshiftsu:
11569 case Intrinsic::arm_neon_vqshiftns:
11570 case Intrinsic::arm_neon_vqshiftnu:
11571 case Intrinsic::arm_neon_vqshiftnsu:
11572 case Intrinsic::arm_neon_vqrshiftns:
11573 case Intrinsic::arm_neon_vqrshiftnu:
11574 case Intrinsic::arm_neon_vqrshiftnsu: {
11575 EVT VT = N->getOperand(1).getValueType();
11577 unsigned VShiftOpc = 0;
11580 case Intrinsic::arm_neon_vshifts:
11581 case Intrinsic::arm_neon_vshiftu:
11582 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
11583 VShiftOpc = ARMISD::VSHL;
11586 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
11587 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
11588 ARMISD::VSHRs : ARMISD::VSHRu);
11593 case Intrinsic::arm_neon_vrshifts:
11594 case Intrinsic::arm_neon_vrshiftu:
11595 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
11599 case Intrinsic::arm_neon_vqshifts:
11600 case Intrinsic::arm_neon_vqshiftu:
11601 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11605 case Intrinsic::arm_neon_vqshiftsu:
11606 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11608 llvm_unreachable("invalid shift count for vqshlu intrinsic");
11610 case Intrinsic::arm_neon_vrshiftn:
11611 case Intrinsic::arm_neon_vqshiftns:
11612 case Intrinsic::arm_neon_vqshiftnu:
11613 case Intrinsic::arm_neon_vqshiftnsu:
11614 case Intrinsic::arm_neon_vqrshiftns:
11615 case Intrinsic::arm_neon_vqrshiftnu:
11616 case Intrinsic::arm_neon_vqrshiftnsu:
11617 // Narrowing shifts require an immediate right shift.
11618 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
11620 llvm_unreachable("invalid shift count for narrowing vector shift "
11624 llvm_unreachable("unhandled vector shift");
11628 case Intrinsic::arm_neon_vshifts:
11629 case Intrinsic::arm_neon_vshiftu:
11630 // Opcode already set above.
11632 case Intrinsic::arm_neon_vrshifts:
11633 VShiftOpc = ARMISD::VRSHRs; break;
11634 case Intrinsic::arm_neon_vrshiftu:
11635 VShiftOpc = ARMISD::VRSHRu; break;
11636 case Intrinsic::arm_neon_vrshiftn:
11637 VShiftOpc = ARMISD::VRSHRN; break;
11638 case Intrinsic::arm_neon_vqshifts:
11639 VShiftOpc = ARMISD::VQSHLs; break;
11640 case Intrinsic::arm_neon_vqshiftu:
11641 VShiftOpc = ARMISD::VQSHLu; break;
11642 case Intrinsic::arm_neon_vqshiftsu:
11643 VShiftOpc = ARMISD::VQSHLsu; break;
11644 case Intrinsic::arm_neon_vqshiftns:
11645 VShiftOpc = ARMISD::VQSHRNs; break;
11646 case Intrinsic::arm_neon_vqshiftnu:
11647 VShiftOpc = ARMISD::VQSHRNu; break;
11648 case Intrinsic::arm_neon_vqshiftnsu:
11649 VShiftOpc = ARMISD::VQSHRNsu; break;
11650 case Intrinsic::arm_neon_vqrshiftns:
11651 VShiftOpc = ARMISD::VQRSHRNs; break;
11652 case Intrinsic::arm_neon_vqrshiftnu:
11653 VShiftOpc = ARMISD::VQRSHRNu; break;
11654 case Intrinsic::arm_neon_vqrshiftnsu:
11655 VShiftOpc = ARMISD::VQRSHRNsu; break;
11659 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11660 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
11663 case Intrinsic::arm_neon_vshiftins: {
11664 EVT VT = N->getOperand(1).getValueType();
11666 unsigned VShiftOpc = 0;
11668 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
11669 VShiftOpc = ARMISD::VSLI;
11670 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
11671 VShiftOpc = ARMISD::VSRI;
11673 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
11677 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11678 N->getOperand(1), N->getOperand(2),
11679 DAG.getConstant(Cnt, dl, MVT::i32));
11682 case Intrinsic::arm_neon_vqrshifts:
11683 case Intrinsic::arm_neon_vqrshiftu:
11684 // No immediate versions of these to check for.
11691 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
11692 /// lowers them. As with the vector shift intrinsics, this is done during DAG
11693 /// combining instead of DAG legalizing because the build_vectors for 64-bit
11694 /// vector element shift counts are generally not legal, and it is hard to see
11695 /// their values after they get legalized to loads from a constant pool.
11696 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
11697 const ARMSubtarget *ST) {
11698 EVT VT = N->getValueType(0);
11699 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
11700 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
11701 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
11702 SDValue N1 = N->getOperand(1);
11703 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
11704 SDValue N0 = N->getOperand(0);
11705 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
11706 DAG.MaskedValueIsZero(N0.getOperand(0),
11707 APInt::getHighBitsSet(32, 16)))
11708 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
11712 // Nothing to be done for scalar shifts.
11713 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11714 if (!VT.isVector() || !TLI.isTypeLegal(VT))
11717 assert(ST->hasNEON() && "unexpected vector shift");
11720 switch (N->getOpcode()) {
11721 default: llvm_unreachable("unexpected shift opcode");
11724 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
11726 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
11727 DAG.getConstant(Cnt, dl, MVT::i32));
11733 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
11734 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
11735 ARMISD::VSHRs : ARMISD::VSHRu);
11737 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
11738 DAG.getConstant(Cnt, dl, MVT::i32));
11744 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
11745 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
11746 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
11747 const ARMSubtarget *ST) {
11748 SDValue N0 = N->getOperand(0);
11750 // Check for sign- and zero-extensions of vector extract operations of 8-
11751 // and 16-bit vector elements. NEON supports these directly. They are
11752 // handled during DAG combining because type legalization will promote them
11753 // to 32-bit types and it is messy to recognize the operations after that.
11754 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11755 SDValue Vec = N0.getOperand(0);
11756 SDValue Lane = N0.getOperand(1);
11757 EVT VT = N->getValueType(0);
11758 EVT EltVT = N0.getValueType();
11759 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11761 if (VT == MVT::i32 &&
11762 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
11763 TLI.isTypeLegal(Vec.getValueType()) &&
11764 isa<ConstantSDNode>(Lane)) {
11767 switch (N->getOpcode()) {
11768 default: llvm_unreachable("unexpected opcode");
11769 case ISD::SIGN_EXTEND:
11770 Opc = ARMISD::VGETLANEs;
11772 case ISD::ZERO_EXTEND:
11773 case ISD::ANY_EXTEND:
11774 Opc = ARMISD::VGETLANEu;
11777 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
11784 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
11785 // If we have a CMOV, OR and AND combination such as:
11790 // * CN is a single bit;
11791 // * All bits covered by CM are known zero in y
11793 // Then we can convert this into a sequence of BFI instructions. This will
11794 // always be a win if CM is a single bit, will always be no worse than the
11795 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
11796 // three bits (due to the extra IT instruction).
11798 SDValue Op0 = CMOV->getOperand(0);
11799 SDValue Op1 = CMOV->getOperand(1);
11800 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
11801 auto CC = CCNode->getAPIntValue().getLimitedValue();
11802 SDValue CmpZ = CMOV->getOperand(4);
11804 // The compare must be against zero.
11805 if (!isNullConstant(CmpZ->getOperand(1)))
11808 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
11809 SDValue And = CmpZ->getOperand(0);
11810 if (And->getOpcode() != ISD::AND)
11812 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
11813 if (!AndC || !AndC->getAPIntValue().isPowerOf2())
11815 SDValue X = And->getOperand(0);
11817 if (CC == ARMCC::EQ) {
11818 // We're performing an "equal to zero" compare. Swap the operands so we
11819 // canonicalize on a "not equal to zero" compare.
11820 std::swap(Op0, Op1);
11822 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
11825 if (Op1->getOpcode() != ISD::OR)
11828 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
11831 SDValue Y = Op1->getOperand(0);
11836 // Now, is it profitable to continue?
11837 APInt OrCI = OrC->getAPIntValue();
11838 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
11839 if (OrCI.countPopulation() > Heuristic)
11842 // Lastly, can we determine that the bits defined by OrCI
11845 DAG.computeKnownBits(Y, Known);
11846 if ((OrCI & Known.Zero) != OrCI)
11849 // OK, we can do the combine.
11852 EVT VT = X.getValueType();
11853 unsigned BitInX = AndC->getAPIntValue().logBase2();
11856 // We must shift X first.
11857 X = DAG.getNode(ISD::SRL, dl, VT, X,
11858 DAG.getConstant(BitInX, dl, VT));
11861 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
11862 BitInY < NumActiveBits; ++BitInY) {
11863 if (OrCI[BitInY] == 0)
11865 APInt Mask(VT.getSizeInBits(), 0);
11866 Mask.setBit(BitInY);
11867 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
11868 // Confusingly, the operand is an *inverted* mask.
11869 DAG.getConstant(~Mask, dl, VT));
11875 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
11877 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
11878 SDValue Cmp = N->getOperand(4);
11879 if (Cmp.getOpcode() != ARMISD::CMPZ)
11880 // Only looking at NE cases.
11883 EVT VT = N->getValueType(0);
11885 SDValue LHS = Cmp.getOperand(0);
11886 SDValue RHS = Cmp.getOperand(1);
11887 SDValue Chain = N->getOperand(0);
11888 SDValue BB = N->getOperand(1);
11889 SDValue ARMcc = N->getOperand(2);
11890 ARMCC::CondCodes CC =
11891 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
11893 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
11894 // -> (brcond Chain BB CC CPSR Cmp)
11895 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
11896 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
11897 LHS->getOperand(0)->hasOneUse()) {
11898 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
11899 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
11900 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
11901 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
11902 if ((LHS00C && LHS00C->getZExtValue() == 0) &&
11903 (LHS01C && LHS01C->getZExtValue() == 1) &&
11904 (LHS1C && LHS1C->getZExtValue() == 1) &&
11905 (RHSC && RHSC->getZExtValue() == 0)) {
11906 return DAG.getNode(
11907 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
11908 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
11915 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
11917 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
11918 SDValue Cmp = N->getOperand(4);
11919 if (Cmp.getOpcode() != ARMISD::CMPZ)
11920 // Only looking at EQ and NE cases.
11923 EVT VT = N->getValueType(0);
11925 SDValue LHS = Cmp.getOperand(0);
11926 SDValue RHS = Cmp.getOperand(1);
11927 SDValue FalseVal = N->getOperand(0);
11928 SDValue TrueVal = N->getOperand(1);
11929 SDValue ARMcc = N->getOperand(2);
11930 ARMCC::CondCodes CC =
11931 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
11933 // BFI is only available on V6T2+.
11934 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
11935 SDValue R = PerformCMOVToBFICombine(N, DAG);
11956 /// FIXME: Turn this into a target neutral optimization?
11958 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
11959 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
11960 N->getOperand(3), Cmp);
11961 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
11963 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
11964 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
11965 N->getOperand(3), NewCmp);
11968 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
11969 // -> (cmov F T CC CPSR Cmp)
11970 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
11971 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
11972 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
11973 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
11974 if ((LHS0C && LHS0C->getZExtValue() == 0) &&
11975 (LHS1C && LHS1C->getZExtValue() == 1) &&
11976 (RHSC && RHSC->getZExtValue() == 0)) {
11977 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
11978 LHS->getOperand(2), LHS->getOperand(3),
11979 LHS->getOperand(4));
11983 if (Res.getNode()) {
11985 DAG.computeKnownBits(SDValue(N,0), Known);
11986 // Capture demanded bits information that would be otherwise lost.
11987 if (Known.Zero == 0xfffffffe)
11988 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11989 DAG.getValueType(MVT::i1));
11990 else if (Known.Zero == 0xffffff00)
11991 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11992 DAG.getValueType(MVT::i8));
11993 else if (Known.Zero == 0xffff0000)
11994 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11995 DAG.getValueType(MVT::i16));
12001 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
12002 DAGCombinerInfo &DCI) const {
12003 switch (N->getOpcode()) {
12005 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
12006 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget);
12007 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
12008 case ISD::SUB: return PerformSUBCombine(N, DCI);
12009 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
12010 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
12011 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
12012 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
12014 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI.DAG, Subtarget);
12015 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI.DAG, Subtarget);
12016 case ARMISD::BFI: return PerformBFICombine(N, DCI);
12017 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
12018 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
12019 case ISD::STORE: return PerformSTORECombine(N, DCI);
12020 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
12021 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
12022 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
12023 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
12024 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI);
12025 case ISD::FP_TO_SINT:
12026 case ISD::FP_TO_UINT:
12027 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
12029 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
12030 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
12033 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
12034 case ISD::SIGN_EXTEND:
12035 case ISD::ZERO_EXTEND:
12036 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
12037 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
12038 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
12039 case ISD::LOAD: return PerformLOADCombine(N, DCI);
12040 case ARMISD::VLD1DUP:
12041 case ARMISD::VLD2DUP:
12042 case ARMISD::VLD3DUP:
12043 case ARMISD::VLD4DUP:
12044 return PerformVLDCombine(N, DCI);
12045 case ARMISD::BUILD_VECTOR:
12046 return PerformARMBUILD_VECTORCombine(N, DCI);
12047 case ARMISD::SMULWB: {
12048 unsigned BitWidth = N->getValueType(0).getSizeInBits();
12049 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12050 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12054 case ARMISD::SMULWT: {
12055 unsigned BitWidth = N->getValueType(0).getSizeInBits();
12056 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12057 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12061 case ARMISD::SMLALBB: {
12062 unsigned BitWidth = N->getValueType(0).getSizeInBits();
12063 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12064 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12065 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12069 case ARMISD::SMLALBT: {
12070 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
12071 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12072 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
12073 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12074 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
12075 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
12079 case ARMISD::SMLALTB: {
12080 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
12081 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12082 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
12083 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12084 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
12085 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
12089 case ARMISD::SMLALTT: {
12090 unsigned BitWidth = N->getValueType(0).getSizeInBits();
12091 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12092 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12093 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12097 case ISD::INTRINSIC_VOID:
12098 case ISD::INTRINSIC_W_CHAIN:
12099 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12100 case Intrinsic::arm_neon_vld1:
12101 case Intrinsic::arm_neon_vld2:
12102 case Intrinsic::arm_neon_vld3:
12103 case Intrinsic::arm_neon_vld4:
12104 case Intrinsic::arm_neon_vld2lane:
12105 case Intrinsic::arm_neon_vld3lane:
12106 case Intrinsic::arm_neon_vld4lane:
12107 case Intrinsic::arm_neon_vst1:
12108 case Intrinsic::arm_neon_vst2:
12109 case Intrinsic::arm_neon_vst3:
12110 case Intrinsic::arm_neon_vst4:
12111 case Intrinsic::arm_neon_vst2lane:
12112 case Intrinsic::arm_neon_vst3lane:
12113 case Intrinsic::arm_neon_vst4lane:
12114 return PerformVLDCombine(N, DCI);
12122 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
12124 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
12127 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12130 bool *Fast) const {
12131 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
12132 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
12134 switch (VT.getSimpleVT().SimpleTy) {
12140 // Unaligned access can use (for example) LRDB, LRDH, LDR
12141 if (AllowsUnaligned) {
12143 *Fast = Subtarget->hasV7Ops();
12150 // For any little-endian targets with neon, we can support unaligned ld/st
12151 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
12152 // A big-endian target may also explicitly support unaligned accesses
12153 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
12163 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
12164 unsigned AlignCheck) {
12165 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
12166 (DstAlign == 0 || DstAlign % AlignCheck == 0));
12169 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
12170 unsigned DstAlign, unsigned SrcAlign,
12171 bool IsMemset, bool ZeroMemset,
12173 MachineFunction &MF) const {
12174 const Function *F = MF.getFunction();
12176 // See if we can use NEON instructions for this...
12177 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
12178 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
12181 (memOpAlign(SrcAlign, DstAlign, 16) ||
12182 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
12184 } else if (Size >= 8 &&
12185 (memOpAlign(SrcAlign, DstAlign, 8) ||
12186 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
12192 // Let the target-independent logic figure it out.
12196 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12197 if (Val.getOpcode() != ISD::LOAD)
12200 EVT VT1 = Val.getValueType();
12201 if (!VT1.isSimple() || !VT1.isInteger() ||
12202 !VT2.isSimple() || !VT2.isInteger())
12205 switch (VT1.getSimpleVT().SimpleTy) {
12210 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
12217 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
12218 EVT VT = ExtVal.getValueType();
12220 if (!isTypeLegal(VT))
12223 // Don't create a loadext if we can fold the extension into a wide/long
12225 // If there's more than one user instruction, the loadext is desirable no
12226 // matter what. There can be two uses by the same instruction.
12227 if (ExtVal->use_empty() ||
12228 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
12231 SDNode *U = *ExtVal->use_begin();
12232 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
12233 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
12239 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
12240 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12243 if (!isTypeLegal(EVT::getEVT(Ty1)))
12246 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
12248 // Assuming the caller doesn't have a zeroext or signext return parameter,
12249 // truncation all the way down to i1 is valid.
12253 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
12254 const AddrMode &AM, Type *Ty,
12255 unsigned AS) const {
12256 if (isLegalAddressingMode(DL, AM, Ty, AS)) {
12257 if (Subtarget->hasFPAO())
12258 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
12265 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
12269 unsigned Scale = 1;
12270 switch (VT.getSimpleVT().SimpleTy) {
12271 default: return false;
12286 if ((V & (Scale - 1)) != 0)
12289 return V == (V & ((1LL << 5) - 1));
12292 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
12293 const ARMSubtarget *Subtarget) {
12294 bool isNeg = false;
12300 switch (VT.getSimpleVT().SimpleTy) {
12301 default: return false;
12306 // + imm12 or - imm8
12308 return V == (V & ((1LL << 8) - 1));
12309 return V == (V & ((1LL << 12) - 1));
12312 // Same as ARM mode. FIXME: NEON?
12313 if (!Subtarget->hasVFP2())
12318 return V == (V & ((1LL << 8) - 1));
12322 /// isLegalAddressImmediate - Return true if the integer value can be used
12323 /// as the offset of the target addressing mode for load / store of the
12325 static bool isLegalAddressImmediate(int64_t V, EVT VT,
12326 const ARMSubtarget *Subtarget) {
12330 if (!VT.isSimple())
12333 if (Subtarget->isThumb1Only())
12334 return isLegalT1AddressImmediate(V, VT);
12335 else if (Subtarget->isThumb2())
12336 return isLegalT2AddressImmediate(V, VT, Subtarget);
12341 switch (VT.getSimpleVT().SimpleTy) {
12342 default: return false;
12347 return V == (V & ((1LL << 12) - 1));
12350 return V == (V & ((1LL << 8) - 1));
12353 if (!Subtarget->hasVFP2()) // FIXME: NEON?
12358 return V == (V & ((1LL << 8) - 1));
12362 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
12364 int Scale = AM.Scale;
12368 switch (VT.getSimpleVT().SimpleTy) {
12369 default: return false;
12377 Scale = Scale & ~1;
12378 return Scale == 2 || Scale == 4 || Scale == 8;
12381 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
12385 // Note, we allow "void" uses (basically, uses that aren't loads or
12386 // stores), because arm allows folding a scale into many arithmetic
12387 // operations. This should be made more precise and revisited later.
12389 // Allow r << imm, but the imm has to be a multiple of two.
12390 if (Scale & 1) return false;
12391 return isPowerOf2_32(Scale);
12395 /// isLegalAddressingMode - Return true if the addressing mode represented
12396 /// by AM is legal for this target, for a load/store of the specified type.
12397 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12398 const AddrMode &AM, Type *Ty,
12399 unsigned AS) const {
12400 EVT VT = getValueType(DL, Ty, true);
12401 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
12404 // Can never fold addr of global into load/store.
12408 switch (AM.Scale) {
12409 case 0: // no scale reg, must be "r+i" or "r", or "i".
12412 if (Subtarget->isThumb1Only())
12416 // ARM doesn't support any R+R*scale+imm addr modes.
12420 if (!VT.isSimple())
12423 if (Subtarget->isThumb2())
12424 return isLegalT2ScaledAddressingMode(AM, VT);
12426 int Scale = AM.Scale;
12427 switch (VT.getSimpleVT().SimpleTy) {
12428 default: return false;
12432 if (Scale < 0) Scale = -Scale;
12436 return isPowerOf2_32(Scale & ~1);
12440 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
12445 // Note, we allow "void" uses (basically, uses that aren't loads or
12446 // stores), because arm allows folding a scale into many arithmetic
12447 // operations. This should be made more precise and revisited later.
12449 // Allow r << imm, but the imm has to be a multiple of two.
12450 if (Scale & 1) return false;
12451 return isPowerOf2_32(Scale);
12457 /// isLegalICmpImmediate - Return true if the specified immediate is legal
12458 /// icmp immediate, that is the target has icmp instructions which can compare
12459 /// a register against the immediate without having to materialize the
12460 /// immediate into a register.
12461 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12462 // Thumb2 and ARM modes can use cmn for negative immediates.
12463 if (!Subtarget->isThumb())
12464 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
12465 if (Subtarget->isThumb2())
12466 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
12467 // Thumb1 doesn't have cmn, and only 8-bit immediates.
12468 return Imm >= 0 && Imm <= 255;
12471 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
12472 /// *or sub* immediate, that is the target has add or sub instructions which can
12473 /// add a register with the immediate without having to materialize the
12474 /// immediate into a register.
12475 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12476 // Same encoding for add/sub, just flip the sign.
12477 int64_t AbsImm = std::abs(Imm);
12478 if (!Subtarget->isThumb())
12479 return ARM_AM::getSOImmVal(AbsImm) != -1;
12480 if (Subtarget->isThumb2())
12481 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
12482 // Thumb1 only has 8-bit unsigned immediate.
12483 return AbsImm >= 0 && AbsImm <= 255;
12486 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
12487 bool isSEXTLoad, SDValue &Base,
12488 SDValue &Offset, bool &isInc,
12489 SelectionDAG &DAG) {
12490 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12493 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
12494 // AddressingMode 3
12495 Base = Ptr->getOperand(0);
12496 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12497 int RHSC = (int)RHS->getZExtValue();
12498 if (RHSC < 0 && RHSC > -256) {
12499 assert(Ptr->getOpcode() == ISD::ADD);
12501 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12505 isInc = (Ptr->getOpcode() == ISD::ADD);
12506 Offset = Ptr->getOperand(1);
12508 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
12509 // AddressingMode 2
12510 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12511 int RHSC = (int)RHS->getZExtValue();
12512 if (RHSC < 0 && RHSC > -0x1000) {
12513 assert(Ptr->getOpcode() == ISD::ADD);
12515 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12516 Base = Ptr->getOperand(0);
12521 if (Ptr->getOpcode() == ISD::ADD) {
12523 ARM_AM::ShiftOpc ShOpcVal=
12524 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
12525 if (ShOpcVal != ARM_AM::no_shift) {
12526 Base = Ptr->getOperand(1);
12527 Offset = Ptr->getOperand(0);
12529 Base = Ptr->getOperand(0);
12530 Offset = Ptr->getOperand(1);
12535 isInc = (Ptr->getOpcode() == ISD::ADD);
12536 Base = Ptr->getOperand(0);
12537 Offset = Ptr->getOperand(1);
12541 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
12545 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
12546 bool isSEXTLoad, SDValue &Base,
12547 SDValue &Offset, bool &isInc,
12548 SelectionDAG &DAG) {
12549 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12552 Base = Ptr->getOperand(0);
12553 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12554 int RHSC = (int)RHS->getZExtValue();
12555 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
12556 assert(Ptr->getOpcode() == ISD::ADD);
12558 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12560 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
12561 isInc = Ptr->getOpcode() == ISD::ADD;
12562 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
12570 /// getPreIndexedAddressParts - returns true by value, base pointer and
12571 /// offset pointer and addressing mode by reference if the node's address
12572 /// can be legally represented as pre-indexed load / store address.
12574 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
12576 ISD::MemIndexedMode &AM,
12577 SelectionDAG &DAG) const {
12578 if (Subtarget->isThumb1Only())
12583 bool isSEXTLoad = false;
12584 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12585 Ptr = LD->getBasePtr();
12586 VT = LD->getMemoryVT();
12587 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12588 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12589 Ptr = ST->getBasePtr();
12590 VT = ST->getMemoryVT();
12595 bool isLegal = false;
12596 if (Subtarget->isThumb2())
12597 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
12598 Offset, isInc, DAG);
12600 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
12601 Offset, isInc, DAG);
12605 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
12609 /// getPostIndexedAddressParts - returns true by value, base pointer and
12610 /// offset pointer and addressing mode by reference if this node can be
12611 /// combined with a load / store to form a post-indexed load / store.
12612 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
12615 ISD::MemIndexedMode &AM,
12616 SelectionDAG &DAG) const {
12619 bool isSEXTLoad = false, isNonExt;
12620 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12621 VT = LD->getMemoryVT();
12622 Ptr = LD->getBasePtr();
12623 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12624 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
12625 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12626 VT = ST->getMemoryVT();
12627 Ptr = ST->getBasePtr();
12628 isNonExt = !ST->isTruncatingStore();
12632 if (Subtarget->isThumb1Only()) {
12633 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
12634 // must be non-extending/truncating, i32, with an offset of 4.
12635 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
12636 if (Op->getOpcode() != ISD::ADD || !isNonExt)
12638 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
12639 if (!RHS || RHS->getZExtValue() != 4)
12642 Offset = Op->getOperand(1);
12643 Base = Op->getOperand(0);
12644 AM = ISD::POST_INC;
12649 bool isLegal = false;
12650 if (Subtarget->isThumb2())
12651 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12654 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12660 // Swap base ptr and offset to catch more post-index load / store when
12661 // it's legal. In Thumb2 mode, offset must be an immediate.
12662 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
12663 !Subtarget->isThumb2())
12664 std::swap(Base, Offset);
12666 // Post-indexed load / store update the base pointer.
12671 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
12675 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12677 const APInt &DemandedElts,
12678 const SelectionDAG &DAG,
12679 unsigned Depth) const {
12680 unsigned BitWidth = Known.getBitWidth();
12682 switch (Op.getOpcode()) {
12688 // These nodes' second result is a boolean
12689 if (Op.getResNo() == 0)
12691 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12693 case ARMISD::CMOV: {
12694 // Bits are known zero/one if known on the LHS and RHS.
12695 DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1);
12696 if (Known.isUnknown())
12699 KnownBits KnownRHS;
12700 DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1);
12701 Known.Zero &= KnownRHS.Zero;
12702 Known.One &= KnownRHS.One;
12705 case ISD::INTRINSIC_W_CHAIN: {
12706 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
12707 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
12710 case Intrinsic::arm_ldaex:
12711 case Intrinsic::arm_ldrex: {
12712 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
12713 unsigned MemBits = VT.getScalarSizeInBits();
12714 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
12719 case ARMISD::BFI: {
12720 // Conservatively, we can recurse down the first operand
12721 // and just mask out all affected bits.
12722 DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1);
12724 // The operand to BFI is already a mask suitable for removing the bits it
12726 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
12727 const APInt &Mask = CI->getAPIntValue();
12728 Known.Zero &= Mask;
12735 //===----------------------------------------------------------------------===//
12736 // ARM Inline Assembly Support
12737 //===----------------------------------------------------------------------===//
12739 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
12740 // Looking for "rev" which is V6+.
12741 if (!Subtarget->hasV6Ops())
12744 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12745 std::string AsmStr = IA->getAsmString();
12746 SmallVector<StringRef, 4> AsmPieces;
12747 SplitString(AsmStr, AsmPieces, ";\n");
12749 switch (AsmPieces.size()) {
12750 default: return false;
12752 AsmStr = AsmPieces[0];
12754 SplitString(AsmStr, AsmPieces, " \t,");
12757 if (AsmPieces.size() == 3 &&
12758 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
12759 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
12760 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12761 if (Ty && Ty->getBitWidth() == 32)
12762 return IntrinsicLowering::LowerToByteSwap(CI);
12770 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
12771 // At this point, we have to lower this constraint to something else, so we
12772 // lower it to an "r" or "w". However, by doing this we will force the result
12773 // to be in register, while the X constraint is much more permissive.
12775 // Although we are correct (we are free to emit anything, without
12776 // constraints), we might break use cases that would expect us to be more
12777 // efficient and emit something else.
12778 if (!Subtarget->hasVFP2())
12780 if (ConstraintVT.isFloatingPoint())
12782 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
12783 (ConstraintVT.getSizeInBits() == 64 ||
12784 ConstraintVT.getSizeInBits() == 128))
12790 /// getConstraintType - Given a constraint letter, return the type of
12791 /// constraint it is for this target.
12792 ARMTargetLowering::ConstraintType
12793 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
12794 if (Constraint.size() == 1) {
12795 switch (Constraint[0]) {
12797 case 'l': return C_RegisterClass;
12798 case 'w': return C_RegisterClass;
12799 case 'h': return C_RegisterClass;
12800 case 'x': return C_RegisterClass;
12801 case 't': return C_RegisterClass;
12802 case 'j': return C_Other; // Constant for movw.
12803 // An address with a single base register. Due to the way we
12804 // currently handle addresses it is the same as an 'r' memory constraint.
12805 case 'Q': return C_Memory;
12807 } else if (Constraint.size() == 2) {
12808 switch (Constraint[0]) {
12810 // All 'U+' constraints are addresses.
12811 case 'U': return C_Memory;
12814 return TargetLowering::getConstraintType(Constraint);
12817 /// Examine constraint type and operand type and determine a weight value.
12818 /// This object must already have been set up with the operand type
12819 /// and the current alternative constraint selected.
12820 TargetLowering::ConstraintWeight
12821 ARMTargetLowering::getSingleConstraintMatchWeight(
12822 AsmOperandInfo &info, const char *constraint) const {
12823 ConstraintWeight weight = CW_Invalid;
12824 Value *CallOperandVal = info.CallOperandVal;
12825 // If we don't have a value, we can't do a match,
12826 // but allow it at the lowest weight.
12827 if (!CallOperandVal)
12829 Type *type = CallOperandVal->getType();
12830 // Look at the constraint type.
12831 switch (*constraint) {
12833 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12836 if (type->isIntegerTy()) {
12837 if (Subtarget->isThumb())
12838 weight = CW_SpecificReg;
12840 weight = CW_Register;
12844 if (type->isFloatingPointTy())
12845 weight = CW_Register;
12851 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
12852 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
12853 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
12854 if (Constraint.size() == 1) {
12855 // GCC ARM Constraint Letters
12856 switch (Constraint[0]) {
12857 case 'l': // Low regs or general regs.
12858 if (Subtarget->isThumb())
12859 return RCPair(0U, &ARM::tGPRRegClass);
12860 return RCPair(0U, &ARM::GPRRegClass);
12861 case 'h': // High regs or no regs.
12862 if (Subtarget->isThumb())
12863 return RCPair(0U, &ARM::hGPRRegClass);
12866 if (Subtarget->isThumb1Only())
12867 return RCPair(0U, &ARM::tGPRRegClass);
12868 return RCPair(0U, &ARM::GPRRegClass);
12870 if (VT == MVT::Other)
12872 if (VT == MVT::f32)
12873 return RCPair(0U, &ARM::SPRRegClass);
12874 if (VT.getSizeInBits() == 64)
12875 return RCPair(0U, &ARM::DPRRegClass);
12876 if (VT.getSizeInBits() == 128)
12877 return RCPair(0U, &ARM::QPRRegClass);
12880 if (VT == MVT::Other)
12882 if (VT == MVT::f32)
12883 return RCPair(0U, &ARM::SPR_8RegClass);
12884 if (VT.getSizeInBits() == 64)
12885 return RCPair(0U, &ARM::DPR_8RegClass);
12886 if (VT.getSizeInBits() == 128)
12887 return RCPair(0U, &ARM::QPR_8RegClass);
12890 if (VT == MVT::f32)
12891 return RCPair(0U, &ARM::SPRRegClass);
12895 if (StringRef("{cc}").equals_lower(Constraint))
12896 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
12898 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12901 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12902 /// vector. If it is invalid, don't add anything to Ops.
12903 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12904 std::string &Constraint,
12905 std::vector<SDValue>&Ops,
12906 SelectionDAG &DAG) const {
12909 // Currently only support length 1 constraints.
12910 if (Constraint.length() != 1) return;
12912 char ConstraintLetter = Constraint[0];
12913 switch (ConstraintLetter) {
12916 case 'I': case 'J': case 'K': case 'L':
12917 case 'M': case 'N': case 'O':
12918 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
12922 int64_t CVal64 = C->getSExtValue();
12923 int CVal = (int) CVal64;
12924 // None of these constraints allow values larger than 32 bits. Check
12925 // that the value fits in an int.
12926 if (CVal != CVal64)
12929 switch (ConstraintLetter) {
12931 // Constant suitable for movw, must be between 0 and
12933 if (Subtarget->hasV6T2Ops())
12934 if (CVal >= 0 && CVal <= 65535)
12938 if (Subtarget->isThumb1Only()) {
12939 // This must be a constant between 0 and 255, for ADD
12941 if (CVal >= 0 && CVal <= 255)
12943 } else if (Subtarget->isThumb2()) {
12944 // A constant that can be used as an immediate value in a
12945 // data-processing instruction.
12946 if (ARM_AM::getT2SOImmVal(CVal) != -1)
12949 // A constant that can be used as an immediate value in a
12950 // data-processing instruction.
12951 if (ARM_AM::getSOImmVal(CVal) != -1)
12957 if (Subtarget->isThumb1Only()) {
12958 // This must be a constant between -255 and -1, for negated ADD
12959 // immediates. This can be used in GCC with an "n" modifier that
12960 // prints the negated value, for use with SUB instructions. It is
12961 // not useful otherwise but is implemented for compatibility.
12962 if (CVal >= -255 && CVal <= -1)
12965 // This must be a constant between -4095 and 4095. It is not clear
12966 // what this constraint is intended for. Implemented for
12967 // compatibility with GCC.
12968 if (CVal >= -4095 && CVal <= 4095)
12974 if (Subtarget->isThumb1Only()) {
12975 // A 32-bit value where only one byte has a nonzero value. Exclude
12976 // zero to match GCC. This constraint is used by GCC internally for
12977 // constants that can be loaded with a move/shift combination.
12978 // It is not useful otherwise but is implemented for compatibility.
12979 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
12981 } else if (Subtarget->isThumb2()) {
12982 // A constant whose bitwise inverse can be used as an immediate
12983 // value in a data-processing instruction. This can be used in GCC
12984 // with a "B" modifier that prints the inverted value, for use with
12985 // BIC and MVN instructions. It is not useful otherwise but is
12986 // implemented for compatibility.
12987 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
12990 // A constant whose bitwise inverse can be used as an immediate
12991 // value in a data-processing instruction. This can be used in GCC
12992 // with a "B" modifier that prints the inverted value, for use with
12993 // BIC and MVN instructions. It is not useful otherwise but is
12994 // implemented for compatibility.
12995 if (ARM_AM::getSOImmVal(~CVal) != -1)
13001 if (Subtarget->isThumb1Only()) {
13002 // This must be a constant between -7 and 7,
13003 // for 3-operand ADD/SUB immediate instructions.
13004 if (CVal >= -7 && CVal < 7)
13006 } else if (Subtarget->isThumb2()) {
13007 // A constant whose negation can be used as an immediate value in a
13008 // data-processing instruction. This can be used in GCC with an "n"
13009 // modifier that prints the negated value, for use with SUB
13010 // instructions. It is not useful otherwise but is implemented for
13012 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
13015 // A constant whose negation can be used as an immediate value in a
13016 // data-processing instruction. This can be used in GCC with an "n"
13017 // modifier that prints the negated value, for use with SUB
13018 // instructions. It is not useful otherwise but is implemented for
13020 if (ARM_AM::getSOImmVal(-CVal) != -1)
13026 if (Subtarget->isThumb1Only()) {
13027 // This must be a multiple of 4 between 0 and 1020, for
13028 // ADD sp + immediate.
13029 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
13032 // A power of two or a constant between 0 and 32. This is used in
13033 // GCC for the shift amount on shifted register operands, but it is
13034 // useful in general for any shift amounts.
13035 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
13041 if (Subtarget->isThumb()) { // FIXME thumb2
13042 // This must be a constant between 0 and 31, for shift amounts.
13043 if (CVal >= 0 && CVal <= 31)
13049 if (Subtarget->isThumb()) { // FIXME thumb2
13050 // This must be a multiple of 4 between -508 and 508, for
13051 // ADD/SUB sp = sp + immediate.
13052 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
13057 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
13061 if (Result.getNode()) {
13062 Ops.push_back(Result);
13065 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13068 static RTLIB::Libcall getDivRemLibcall(
13069 const SDNode *N, MVT::SimpleValueType SVT) {
13070 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13071 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
13072 "Unhandled Opcode in getDivRemLibcall");
13073 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13074 N->getOpcode() == ISD::SREM;
13077 default: llvm_unreachable("Unexpected request for libcall!");
13078 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
13079 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
13080 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
13081 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
13086 static TargetLowering::ArgListTy getDivRemArgList(
13087 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
13088 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13089 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
13090 "Unhandled Opcode in getDivRemArgList");
13091 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13092 N->getOpcode() == ISD::SREM;
13093 TargetLowering::ArgListTy Args;
13094 TargetLowering::ArgListEntry Entry;
13095 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13096 EVT ArgVT = N->getOperand(i).getValueType();
13097 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
13098 Entry.Node = N->getOperand(i);
13100 Entry.IsSExt = isSigned;
13101 Entry.IsZExt = !isSigned;
13102 Args.push_back(Entry);
13104 if (Subtarget->isTargetWindows() && Args.size() >= 2)
13105 std::swap(Args[0], Args[1]);
13109 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
13110 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
13111 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
13112 Subtarget->isTargetWindows()) &&
13113 "Register-based DivRem lowering only");
13114 unsigned Opcode = Op->getOpcode();
13115 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
13116 "Invalid opcode for Div/Rem lowering");
13117 bool isSigned = (Opcode == ISD::SDIVREM);
13118 EVT VT = Op->getValueType(0);
13119 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
13122 // If the target has hardware divide, use divide + multiply + subtract:
13124 // rem = a - b * div
13125 // return {div, rem}
13126 // This should be lowered into UDIV/SDIV + MLS later on.
13127 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
13128 : Subtarget->hasDivideInARMMode();
13129 if (hasDivide && Op->getValueType(0).isSimple() &&
13130 Op->getSimpleValueType(0) == MVT::i32) {
13131 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
13132 const SDValue Dividend = Op->getOperand(0);
13133 const SDValue Divisor = Op->getOperand(1);
13134 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
13135 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
13136 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13138 SDValue Values[2] = {Div, Rem};
13139 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
13142 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
13143 VT.getSimpleVT().SimpleTy);
13144 SDValue InChain = DAG.getEntryNode();
13146 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
13150 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13151 getPointerTy(DAG.getDataLayout()));
13153 Type *RetTy = StructType::get(Ty, Ty);
13155 if (Subtarget->isTargetWindows())
13156 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
13158 TargetLowering::CallLoweringInfo CLI(DAG);
13159 CLI.setDebugLoc(dl).setChain(InChain)
13160 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
13161 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13163 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13164 return CallInfo.first;
13167 // Lowers REM using divmod helpers
13168 // see RTABI section 4.2/4.3
13169 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
13170 // Build return types (div and rem)
13171 std::vector<Type*> RetTyParams;
13172 Type *RetTyElement;
13174 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
13175 default: llvm_unreachable("Unexpected request for libcall!");
13176 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
13177 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
13178 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
13179 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
13182 RetTyParams.push_back(RetTyElement);
13183 RetTyParams.push_back(RetTyElement);
13184 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
13185 Type *RetTy = StructType::get(*DAG.getContext(), ret);
13187 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
13189 SDValue InChain = DAG.getEntryNode();
13190 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
13192 bool isSigned = N->getOpcode() == ISD::SREM;
13193 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13194 getPointerTy(DAG.getDataLayout()));
13196 if (Subtarget->isTargetWindows())
13197 InChain = WinDBZCheckDenominator(DAG, N, InChain);
13200 CallLoweringInfo CLI(DAG);
13201 CLI.setChain(InChain)
13202 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
13203 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
13204 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
13206 // Return second (rem) result operand (first contains div)
13207 SDNode *ResNode = CallResult.first.getNode();
13208 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
13209 return ResNode->getOperand(1);
13213 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
13214 assert(Subtarget->isTargetWindows() && "unsupported target platform");
13218 SDValue Chain = Op.getOperand(0);
13219 SDValue Size = Op.getOperand(1);
13221 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
13222 DAG.getConstant(2, DL, MVT::i32));
13225 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
13226 Flag = Chain.getValue(1);
13228 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13229 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
13231 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
13232 Chain = NewSP.getValue(1);
13234 SDValue Ops[2] = { NewSP, Chain };
13235 return DAG.getMergeValues(Ops, DL);
13238 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
13239 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
13240 "Unexpected type for custom-lowering FP_EXTEND");
13243 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
13245 SDValue SrcVal = Op.getOperand(0);
13246 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13250 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
13251 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
13252 Subtarget->isFPOnlySP() &&
13253 "Unexpected type for custom-lowering FP_ROUND");
13256 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
13258 SDValue SrcVal = Op.getOperand(0);
13259 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13264 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
13265 // The ARM target isn't yet aware of offsets.
13269 bool ARM::isBitFieldInvertedMask(unsigned v) {
13270 if (v == 0xffffffff)
13273 // there can be 1's on either or both "outsides", all the "inside"
13274 // bits must be 0's
13275 return isShiftedMask_32(~v);
13278 /// isFPImmLegal - Returns true if the target can instruction select the
13279 /// specified FP immediate natively. If false, the legalizer will
13280 /// materialize the FP immediate as a load from a constant pool.
13281 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
13282 if (!Subtarget->hasVFP3())
13284 if (VT == MVT::f32)
13285 return ARM_AM::getFP32Imm(Imm) != -1;
13286 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
13287 return ARM_AM::getFP64Imm(Imm) != -1;
13291 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
13292 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
13293 /// specified in the intrinsic calls.
13294 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
13296 unsigned Intrinsic) const {
13297 switch (Intrinsic) {
13298 case Intrinsic::arm_neon_vld1:
13299 case Intrinsic::arm_neon_vld2:
13300 case Intrinsic::arm_neon_vld3:
13301 case Intrinsic::arm_neon_vld4:
13302 case Intrinsic::arm_neon_vld2lane:
13303 case Intrinsic::arm_neon_vld3lane:
13304 case Intrinsic::arm_neon_vld4lane: {
13305 Info.opc = ISD::INTRINSIC_W_CHAIN;
13306 // Conservatively set memVT to the entire set of vectors loaded.
13307 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13308 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
13309 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13310 Info.ptrVal = I.getArgOperand(0);
13312 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13313 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13314 Info.vol = false; // volatile loads with NEON intrinsics not supported
13315 Info.readMem = true;
13316 Info.writeMem = false;
13319 case Intrinsic::arm_neon_vst1:
13320 case Intrinsic::arm_neon_vst2:
13321 case Intrinsic::arm_neon_vst3:
13322 case Intrinsic::arm_neon_vst4:
13323 case Intrinsic::arm_neon_vst2lane:
13324 case Intrinsic::arm_neon_vst3lane:
13325 case Intrinsic::arm_neon_vst4lane: {
13326 Info.opc = ISD::INTRINSIC_VOID;
13327 // Conservatively set memVT to the entire set of vectors stored.
13328 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13329 unsigned NumElts = 0;
13330 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
13331 Type *ArgTy = I.getArgOperand(ArgI)->getType();
13332 if (!ArgTy->isVectorTy())
13334 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
13336 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13337 Info.ptrVal = I.getArgOperand(0);
13339 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13340 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13341 Info.vol = false; // volatile stores with NEON intrinsics not supported
13342 Info.readMem = false;
13343 Info.writeMem = true;
13346 case Intrinsic::arm_ldaex:
13347 case Intrinsic::arm_ldrex: {
13348 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13349 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
13350 Info.opc = ISD::INTRINSIC_W_CHAIN;
13351 Info.memVT = MVT::getVT(PtrTy->getElementType());
13352 Info.ptrVal = I.getArgOperand(0);
13354 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13356 Info.readMem = true;
13357 Info.writeMem = false;
13360 case Intrinsic::arm_stlex:
13361 case Intrinsic::arm_strex: {
13362 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13363 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
13364 Info.opc = ISD::INTRINSIC_W_CHAIN;
13365 Info.memVT = MVT::getVT(PtrTy->getElementType());
13366 Info.ptrVal = I.getArgOperand(1);
13368 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13370 Info.readMem = false;
13371 Info.writeMem = true;
13374 case Intrinsic::arm_stlexd:
13375 case Intrinsic::arm_strexd:
13376 Info.opc = ISD::INTRINSIC_W_CHAIN;
13377 Info.memVT = MVT::i64;
13378 Info.ptrVal = I.getArgOperand(2);
13382 Info.readMem = false;
13383 Info.writeMem = true;
13386 case Intrinsic::arm_ldaexd:
13387 case Intrinsic::arm_ldrexd:
13388 Info.opc = ISD::INTRINSIC_W_CHAIN;
13389 Info.memVT = MVT::i64;
13390 Info.ptrVal = I.getArgOperand(0);
13394 Info.readMem = true;
13395 Info.writeMem = false;
13405 /// \brief Returns true if it is beneficial to convert a load of a constant
13406 /// to just the constant itself.
13407 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
13409 assert(Ty->isIntegerTy());
13411 unsigned Bits = Ty->getPrimitiveSizeInBits();
13412 if (Bits == 0 || Bits > 32)
13417 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT,
13418 unsigned Index) const {
13419 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
13422 return (Index == 0 || Index == ResVT.getVectorNumElements());
13425 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
13426 ARM_MB::MemBOpt Domain) const {
13427 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13429 // First, if the target has no DMB, see what fallback we can use.
13430 if (!Subtarget->hasDataBarrier()) {
13431 // Some ARMv6 cpus can support data barriers with an mcr instruction.
13432 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
13434 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
13435 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
13436 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
13437 Builder.getInt32(0), Builder.getInt32(7),
13438 Builder.getInt32(10), Builder.getInt32(5)};
13439 return Builder.CreateCall(MCR, args);
13441 // Instead of using barriers, atomic accesses on these subtargets use
13443 llvm_unreachable("makeDMB on a target so old that it has no barriers");
13446 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
13447 // Only a full system barrier exists in the M-class architectures.
13448 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
13449 Constant *CDomain = Builder.getInt32(Domain);
13450 return Builder.CreateCall(DMB, CDomain);
13454 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
13455 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
13457 AtomicOrdering Ord) const {
13459 case AtomicOrdering::NotAtomic:
13460 case AtomicOrdering::Unordered:
13461 llvm_unreachable("Invalid fence: unordered/non-atomic");
13462 case AtomicOrdering::Monotonic:
13463 case AtomicOrdering::Acquire:
13464 return nullptr; // Nothing to do
13465 case AtomicOrdering::SequentiallyConsistent:
13466 if (!Inst->hasAtomicStore())
13467 return nullptr; // Nothing to do
13469 case AtomicOrdering::Release:
13470 case AtomicOrdering::AcquireRelease:
13471 if (Subtarget->preferISHSTBarriers())
13472 return makeDMB(Builder, ARM_MB::ISHST);
13473 // FIXME: add a comment with a link to documentation justifying this.
13475 return makeDMB(Builder, ARM_MB::ISH);
13477 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
13480 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
13482 AtomicOrdering Ord) const {
13484 case AtomicOrdering::NotAtomic:
13485 case AtomicOrdering::Unordered:
13486 llvm_unreachable("Invalid fence: unordered/not-atomic");
13487 case AtomicOrdering::Monotonic:
13488 case AtomicOrdering::Release:
13489 return nullptr; // Nothing to do
13490 case AtomicOrdering::Acquire:
13491 case AtomicOrdering::AcquireRelease:
13492 case AtomicOrdering::SequentiallyConsistent:
13493 return makeDMB(Builder, ARM_MB::ISH);
13495 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
13498 // Loads and stores less than 64-bits are already atomic; ones above that
13499 // are doomed anyway, so defer to the default libcall and blame the OS when
13500 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13501 // anything for those.
13502 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
13503 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
13504 return (Size == 64) && !Subtarget->isMClass();
13507 // Loads and stores less than 64-bits are already atomic; ones above that
13508 // are doomed anyway, so defer to the default libcall and blame the OS when
13509 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13510 // anything for those.
13511 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
13512 // guarantee, see DDI0406C ARM architecture reference manual,
13513 // sections A8.8.72-74 LDRD)
13514 TargetLowering::AtomicExpansionKind
13515 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
13516 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
13517 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
13518 : AtomicExpansionKind::None;
13521 // For the real atomic operations, we have ldrex/strex up to 32 bits,
13522 // and up to 64 bits on the non-M profiles
13523 TargetLowering::AtomicExpansionKind
13524 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
13525 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
13526 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13527 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
13528 ? AtomicExpansionKind::LLSC
13529 : AtomicExpansionKind::None;
13532 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
13533 AtomicCmpXchgInst *AI) const {
13534 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
13535 // implement cmpxchg without spilling. If the address being exchanged is also
13536 // on the stack and close enough to the spill slot, this can lead to a
13537 // situation where the monitor always gets cleared and the atomic operation
13538 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
13539 bool hasAtomicCmpXchg =
13540 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13541 return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg;
13544 bool ARMTargetLowering::shouldInsertFencesForAtomic(
13545 const Instruction *I) const {
13546 return InsertFencesForAtomic;
13549 // This has so far only been implemented for MachO.
13550 bool ARMTargetLowering::useLoadStackGuardNode() const {
13551 return Subtarget->isTargetMachO();
13554 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
13555 unsigned &Cost) const {
13556 // If we do not have NEON, vector types are not natively supported.
13557 if (!Subtarget->hasNEON())
13560 // Floating point values and vector values map to the same register file.
13561 // Therefore, although we could do a store extract of a vector type, this is
13562 // better to leave at float as we have more freedom in the addressing mode for
13564 if (VectorTy->isFPOrFPVectorTy())
13567 // If the index is unknown at compile time, this is very expensive to lower
13568 // and it is not possible to combine the store with the extract.
13569 if (!isa<ConstantInt>(Idx))
13572 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
13573 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
13574 // We can do a store + vector extract on any vector that fits perfectly in a D
13576 if (BitWidth == 64 || BitWidth == 128) {
13583 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
13584 return Subtarget->hasV6T2Ops();
13587 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
13588 return Subtarget->hasV6T2Ops();
13591 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
13592 AtomicOrdering Ord) const {
13593 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13594 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
13595 bool IsAcquire = isAcquireOrStronger(Ord);
13597 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
13598 // intrinsic must return {i32, i32} and we have to recombine them into a
13599 // single i64 here.
13600 if (ValTy->getPrimitiveSizeInBits() == 64) {
13601 Intrinsic::ID Int =
13602 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
13603 Function *Ldrex = Intrinsic::getDeclaration(M, Int);
13605 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13606 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
13608 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
13609 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
13610 if (!Subtarget->isLittle())
13611 std::swap (Lo, Hi);
13612 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
13613 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
13614 return Builder.CreateOr(
13615 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
13618 Type *Tys[] = { Addr->getType() };
13619 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
13620 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
13622 return Builder.CreateTruncOrBitCast(
13623 Builder.CreateCall(Ldrex, Addr),
13624 cast<PointerType>(Addr->getType())->getElementType());
13627 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
13628 IRBuilder<> &Builder) const {
13629 if (!Subtarget->hasV7Ops())
13631 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13632 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
13635 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
13637 AtomicOrdering Ord) const {
13638 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13639 bool IsRelease = isReleaseOrStronger(Ord);
13641 // Since the intrinsics must have legal type, the i64 intrinsics take two
13642 // parameters: "i32, i32". We must marshal Val into the appropriate form
13643 // before the call.
13644 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
13645 Intrinsic::ID Int =
13646 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
13647 Function *Strex = Intrinsic::getDeclaration(M, Int);
13648 Type *Int32Ty = Type::getInt32Ty(M->getContext());
13650 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
13651 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
13652 if (!Subtarget->isLittle())
13653 std::swap (Lo, Hi);
13654 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13655 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
13658 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
13659 Type *Tys[] = { Addr->getType() };
13660 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
13662 return Builder.CreateCall(
13663 Strex, {Builder.CreateZExtOrBitCast(
13664 Val, Strex->getFunctionType()->getParamType(0)),
13668 /// A helper function for determining the number of interleaved accesses we
13669 /// will generate when lowering accesses of the given type.
13671 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
13672 const DataLayout &DL) const {
13673 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
13676 bool ARMTargetLowering::isLegalInterleavedAccessType(
13677 VectorType *VecTy, const DataLayout &DL) const {
13679 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
13680 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
13682 // Ensure the vector doesn't have f16 elements. Even though we could do an
13683 // i16 vldN, we can't hold the f16 vectors and will end up converting via
13685 if (VecTy->getElementType()->isHalfTy())
13688 // Ensure the number of vector elements is greater than 1.
13689 if (VecTy->getNumElements() < 2)
13692 // Ensure the element type is legal.
13693 if (ElSize != 8 && ElSize != 16 && ElSize != 32)
13696 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
13697 // 128 will be split into multiple interleaved accesses.
13698 return VecSize == 64 || VecSize % 128 == 0;
13701 /// \brief Lower an interleaved load into a vldN intrinsic.
13703 /// E.g. Lower an interleaved load (Factor = 2):
13704 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
13705 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
13706 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
13709 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
13710 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
13711 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
13712 bool ARMTargetLowering::lowerInterleavedLoad(
13713 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
13714 ArrayRef<unsigned> Indices, unsigned Factor) const {
13715 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
13716 "Invalid interleave factor");
13717 assert(!Shuffles.empty() && "Empty shufflevector input");
13718 assert(Shuffles.size() == Indices.size() &&
13719 "Unmatched number of shufflevectors and indices");
13721 VectorType *VecTy = Shuffles[0]->getType();
13722 Type *EltTy = VecTy->getVectorElementType();
13724 const DataLayout &DL = LI->getModule()->getDataLayout();
13726 // Skip if we do not have NEON and skip illegal vector types. We can
13727 // "legalize" wide vector types into multiple interleaved accesses as long as
13728 // the vector types are divisible by 128.
13729 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
13732 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
13734 // A pointer vector can not be the return type of the ldN intrinsics. Need to
13735 // load integer vectors first and then convert to pointer vectors.
13736 if (EltTy->isPointerTy())
13738 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
13740 IRBuilder<> Builder(LI);
13742 // The base address of the load.
13743 Value *BaseAddr = LI->getPointerOperand();
13745 if (NumLoads > 1) {
13746 // If we're going to generate more than one load, reset the sub-vector type
13747 // to something legal.
13748 VecTy = VectorType::get(VecTy->getVectorElementType(),
13749 VecTy->getVectorNumElements() / NumLoads);
13751 // We will compute the pointer operand of each load from the original base
13752 // address using GEPs. Cast the base address to a pointer to the scalar
13754 BaseAddr = Builder.CreateBitCast(
13755 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
13756 LI->getPointerAddressSpace()));
13759 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
13761 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
13762 Type *Tys[] = {VecTy, Int8Ptr};
13763 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
13764 Intrinsic::arm_neon_vld3,
13765 Intrinsic::arm_neon_vld4};
13766 Function *VldnFunc =
13767 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
13769 // Holds sub-vectors extracted from the load intrinsic return values. The
13770 // sub-vectors are associated with the shufflevector instructions they will
13772 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
13774 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
13776 // If we're generating more than one load, compute the base address of
13777 // subsequent loads as an offset from the previous.
13779 BaseAddr = Builder.CreateConstGEP1_32(
13780 BaseAddr, VecTy->getVectorNumElements() * Factor);
13782 SmallVector<Value *, 2> Ops;
13783 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
13784 Ops.push_back(Builder.getInt32(LI->getAlignment()));
13786 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
13788 // Replace uses of each shufflevector with the corresponding vector loaded
13790 for (unsigned i = 0; i < Shuffles.size(); i++) {
13791 ShuffleVectorInst *SV = Shuffles[i];
13792 unsigned Index = Indices[i];
13794 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
13796 // Convert the integer vector to pointer vector if the element is pointer.
13797 if (EltTy->isPointerTy())
13798 SubVec = Builder.CreateIntToPtr(
13799 SubVec, VectorType::get(SV->getType()->getVectorElementType(),
13800 VecTy->getVectorNumElements()));
13802 SubVecs[SV].push_back(SubVec);
13806 // Replace uses of the shufflevector instructions with the sub-vectors
13807 // returned by the load intrinsic. If a shufflevector instruction is
13808 // associated with more than one sub-vector, those sub-vectors will be
13809 // concatenated into a single wide vector.
13810 for (ShuffleVectorInst *SVI : Shuffles) {
13811 auto &SubVec = SubVecs[SVI];
13813 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
13814 SVI->replaceAllUsesWith(WideVec);
13820 /// \brief Lower an interleaved store into a vstN intrinsic.
13822 /// E.g. Lower an interleaved store (Factor = 3):
13823 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
13824 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
13825 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
13828 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
13829 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
13830 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
13831 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
13833 /// Note that the new shufflevectors will be removed and we'll only generate one
13834 /// vst3 instruction in CodeGen.
13836 /// Example for a more general valid mask (Factor 3). Lower:
13837 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
13838 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
13839 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
13842 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
13843 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
13844 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
13845 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
13846 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
13847 ShuffleVectorInst *SVI,
13848 unsigned Factor) const {
13849 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
13850 "Invalid interleave factor");
13852 VectorType *VecTy = SVI->getType();
13853 assert(VecTy->getVectorNumElements() % Factor == 0 &&
13854 "Invalid interleaved store");
13856 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
13857 Type *EltTy = VecTy->getVectorElementType();
13858 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
13860 const DataLayout &DL = SI->getModule()->getDataLayout();
13862 // Skip if we do not have NEON and skip illegal vector types. We can
13863 // "legalize" wide vector types into multiple interleaved accesses as long as
13864 // the vector types are divisible by 128.
13865 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
13868 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
13870 Value *Op0 = SVI->getOperand(0);
13871 Value *Op1 = SVI->getOperand(1);
13872 IRBuilder<> Builder(SI);
13874 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
13875 // vectors to integer vectors.
13876 if (EltTy->isPointerTy()) {
13877 Type *IntTy = DL.getIntPtrType(EltTy);
13879 // Convert to the corresponding integer vector.
13881 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
13882 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
13883 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
13885 SubVecTy = VectorType::get(IntTy, LaneLen);
13888 // The base address of the store.
13889 Value *BaseAddr = SI->getPointerOperand();
13891 if (NumStores > 1) {
13892 // If we're going to generate more than one store, reset the lane length
13893 // and sub-vector type to something legal.
13894 LaneLen /= NumStores;
13895 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
13897 // We will compute the pointer operand of each store from the original base
13898 // address using GEPs. Cast the base address to a pointer to the scalar
13900 BaseAddr = Builder.CreateBitCast(
13901 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
13902 SI->getPointerAddressSpace()));
13905 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
13907 auto Mask = SVI->getShuffleMask();
13909 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
13910 Type *Tys[] = {Int8Ptr, SubVecTy};
13911 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
13912 Intrinsic::arm_neon_vst3,
13913 Intrinsic::arm_neon_vst4};
13915 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
13917 // If we generating more than one store, we compute the base address of
13918 // subsequent stores as an offset from the previous.
13919 if (StoreCount > 0)
13920 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
13922 SmallVector<Value *, 6> Ops;
13923 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
13925 Function *VstNFunc =
13926 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
13928 // Split the shufflevector operands into sub vectors for the new vstN call.
13929 for (unsigned i = 0; i < Factor; i++) {
13930 unsigned IdxI = StoreCount * LaneLen * Factor + i;
13931 if (Mask[IdxI] >= 0) {
13932 Ops.push_back(Builder.CreateShuffleVector(
13933 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
13935 unsigned StartMask = 0;
13936 for (unsigned j = 1; j < LaneLen; j++) {
13937 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
13938 if (Mask[IdxJ * Factor + IdxI] >= 0) {
13939 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
13943 // Note: If all elements in a chunk are undefs, StartMask=0!
13944 // Note: Filling undef gaps with random elements is ok, since
13945 // those elements were being written anyway (with undefs).
13946 // In the case of all undefs we're defaulting to using elems from 0
13947 // Note: StartMask cannot be negative, it's checked in
13948 // isReInterleaveMask
13949 Ops.push_back(Builder.CreateShuffleVector(
13950 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
13954 Ops.push_back(Builder.getInt32(SI->getAlignment()));
13955 Builder.CreateCall(VstNFunc, Ops);
13968 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
13969 uint64_t &Members) {
13970 if (auto *ST = dyn_cast<StructType>(Ty)) {
13971 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
13972 uint64_t SubMembers = 0;
13973 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
13975 Members += SubMembers;
13977 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
13978 uint64_t SubMembers = 0;
13979 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
13981 Members += SubMembers * AT->getNumElements();
13982 } else if (Ty->isFloatTy()) {
13983 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
13987 } else if (Ty->isDoubleTy()) {
13988 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
13992 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
13999 return VT->getBitWidth() == 64;
14001 return VT->getBitWidth() == 128;
14003 switch (VT->getBitWidth()) {
14016 return (Members > 0 && Members <= 4);
14019 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
14020 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
14021 /// passing according to AAPCS rules.
14022 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
14023 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
14024 if (getEffectiveCallingConv(CallConv, isVarArg) !=
14025 CallingConv::ARM_AAPCS_VFP)
14028 HABaseType Base = HA_UNKNOWN;
14029 uint64_t Members = 0;
14030 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
14031 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
14033 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
14034 return IsHA || IsIntArray;
14037 unsigned ARMTargetLowering::getExceptionPointerRegister(
14038 const Constant *PersonalityFn) const {
14039 // Platforms which do not use SjLj EH may return values in these registers
14040 // via the personality function.
14041 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
14044 unsigned ARMTargetLowering::getExceptionSelectorRegister(
14045 const Constant *PersonalityFn) const {
14046 // Platforms which do not use SjLj EH may return values in these registers
14047 // via the personality function.
14048 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
14051 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
14052 // Update IsSplitCSR in ARMFunctionInfo.
14053 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
14054 AFI->setIsSplitCSR(true);
14057 void ARMTargetLowering::insertCopiesSplitCSR(
14058 MachineBasicBlock *Entry,
14059 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
14060 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
14061 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14065 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
14066 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14067 MachineBasicBlock::iterator MBBI = Entry->begin();
14068 for (const MCPhysReg *I = IStart; *I; ++I) {
14069 const TargetRegisterClass *RC = nullptr;
14070 if (ARM::GPRRegClass.contains(*I))
14071 RC = &ARM::GPRRegClass;
14072 else if (ARM::DPRRegClass.contains(*I))
14073 RC = &ARM::DPRRegClass;
14075 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14077 unsigned NewVR = MRI->createVirtualRegister(RC);
14078 // Create copy from CSR to a virtual register.
14079 // FIXME: this currently does not emit CFI pseudo-instructions, it works
14080 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14081 // nounwind. If we want to generalize this later, we may need to emit
14082 // CFI pseudo-instructions.
14083 assert(Entry->getParent()->getFunction()->hasFnAttribute(
14084 Attribute::NoUnwind) &&
14085 "Function should be nounwind in insertCopiesSplitCSR!");
14086 Entry->addLiveIn(*I);
14087 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14090 // Insert the copy-back instructions right before the terminator.
14091 for (auto *Exit : Exits)
14092 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14093 TII->get(TargetOpcode::COPY), *I)
14098 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
14099 MF.getFrameInfo().computeMaxCallFrameSize(MF);
14100 TargetLoweringBase::finalizeLowering(MF);