[ARM] MVE integer min and max
[llvm-complete.git] / lib / Target / ARM / ARMISelLowering.cpp
blobe538353fc7669804982139e2982a59f0f6e56d9d
1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that ARM uses to lower LLVM code into a
10 // selection DAG.
12 //===----------------------------------------------------------------------===//
14 #include "ARMISelLowering.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMPerfectShuffle.h"
21 #include "ARMRegisterInfo.h"
22 #include "ARMSelectionDAGInfo.h"
23 #include "ARMSubtarget.h"
24 #include "MCTargetDesc/ARMAddressingModes.h"
25 #include "MCTargetDesc/ARMBaseInfo.h"
26 #include "Utils/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/RuntimeLibcalls.h"
56 #include "llvm/CodeGen/SelectionDAG.h"
57 #include "llvm/CodeGen/SelectionDAGNodes.h"
58 #include "llvm/CodeGen/TargetInstrInfo.h"
59 #include "llvm/CodeGen/TargetLowering.h"
60 #include "llvm/CodeGen/TargetOpcodes.h"
61 #include "llvm/CodeGen/TargetRegisterInfo.h"
62 #include "llvm/CodeGen/TargetSubtargetInfo.h"
63 #include "llvm/CodeGen/ValueTypes.h"
64 #include "llvm/IR/Attributes.h"
65 #include "llvm/IR/CallingConv.h"
66 #include "llvm/IR/Constant.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DebugLoc.h"
70 #include "llvm/IR/DerivedTypes.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/IR/GlobalAlias.h"
73 #include "llvm/IR/GlobalValue.h"
74 #include "llvm/IR/GlobalVariable.h"
75 #include "llvm/IR/IRBuilder.h"
76 #include "llvm/IR/InlineAsm.h"
77 #include "llvm/IR/Instruction.h"
78 #include "llvm/IR/Instructions.h"
79 #include "llvm/IR/IntrinsicInst.h"
80 #include "llvm/IR/Intrinsics.h"
81 #include "llvm/IR/Module.h"
82 #include "llvm/IR/PatternMatch.h"
83 #include "llvm/IR/Type.h"
84 #include "llvm/IR/User.h"
85 #include "llvm/IR/Value.h"
86 #include "llvm/MC/MCInstrDesc.h"
87 #include "llvm/MC/MCInstrItineraries.h"
88 #include "llvm/MC/MCRegisterInfo.h"
89 #include "llvm/MC/MCSchedule.h"
90 #include "llvm/Support/AtomicOrdering.h"
91 #include "llvm/Support/BranchProbability.h"
92 #include "llvm/Support/Casting.h"
93 #include "llvm/Support/CodeGen.h"
94 #include "llvm/Support/CommandLine.h"
95 #include "llvm/Support/Compiler.h"
96 #include "llvm/Support/Debug.h"
97 #include "llvm/Support/ErrorHandling.h"
98 #include "llvm/Support/KnownBits.h"
99 #include "llvm/Support/MachineValueType.h"
100 #include "llvm/Support/MathExtras.h"
101 #include "llvm/Support/raw_ostream.h"
102 #include "llvm/Target/TargetMachine.h"
103 #include "llvm/Target/TargetOptions.h"
104 #include <algorithm>
105 #include <cassert>
106 #include <cstdint>
107 #include <cstdlib>
108 #include <iterator>
109 #include <limits>
110 #include <string>
111 #include <tuple>
112 #include <utility>
113 #include <vector>
115 using namespace llvm;
116 using namespace llvm::PatternMatch;
118 #define DEBUG_TYPE "arm-isel"
120 STATISTIC(NumTailCalls, "Number of tail calls");
121 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
122 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
123 STATISTIC(NumConstpoolPromoted,
124 "Number of constants with their storage promoted into constant pools");
126 static cl::opt<bool>
127 ARMInterworking("arm-interworking", cl::Hidden,
128 cl::desc("Enable / disable ARM interworking (for debugging only)"),
129 cl::init(true));
131 static cl::opt<bool> EnableConstpoolPromotion(
132 "arm-promote-constant", cl::Hidden,
133 cl::desc("Enable / disable promotion of unnamed_addr constants into "
134 "constant pools"),
135 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
136 static cl::opt<unsigned> ConstpoolPromotionMaxSize(
137 "arm-promote-constant-max-size", cl::Hidden,
138 cl::desc("Maximum size of constant to promote into a constant pool"),
139 cl::init(64));
140 static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
141 "arm-promote-constant-max-total", cl::Hidden,
142 cl::desc("Maximum size of ALL constants to promote into a constant pool"),
143 cl::init(128));
145 // The APCS parameter registers.
146 static const MCPhysReg GPRArgRegs[] = {
147 ARM::R0, ARM::R1, ARM::R2, ARM::R3
150 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
151 MVT PromotedBitwiseVT) {
152 if (VT != PromotedLdStVT) {
153 setOperationAction(ISD::LOAD, VT, Promote);
154 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
156 setOperationAction(ISD::STORE, VT, Promote);
157 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
160 MVT ElemTy = VT.getVectorElementType();
161 if (ElemTy != MVT::f64)
162 setOperationAction(ISD::SETCC, VT, Custom);
163 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
164 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
165 if (ElemTy == MVT::i32) {
166 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
167 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
168 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
169 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
170 } else {
171 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
172 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
173 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
174 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
176 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
177 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
178 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
179 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
180 setOperationAction(ISD::SELECT, VT, Expand);
181 setOperationAction(ISD::SELECT_CC, VT, Expand);
182 setOperationAction(ISD::VSELECT, VT, Expand);
183 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
184 if (VT.isInteger()) {
185 setOperationAction(ISD::SHL, VT, Custom);
186 setOperationAction(ISD::SRA, VT, Custom);
187 setOperationAction(ISD::SRL, VT, Custom);
190 // Promote all bit-wise operations.
191 if (VT.isInteger() && VT != PromotedBitwiseVT) {
192 setOperationAction(ISD::AND, VT, Promote);
193 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
194 setOperationAction(ISD::OR, VT, Promote);
195 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
196 setOperationAction(ISD::XOR, VT, Promote);
197 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
200 // Neon does not support vector divide/remainder operations.
201 setOperationAction(ISD::SDIV, VT, Expand);
202 setOperationAction(ISD::UDIV, VT, Expand);
203 setOperationAction(ISD::FDIV, VT, Expand);
204 setOperationAction(ISD::SREM, VT, Expand);
205 setOperationAction(ISD::UREM, VT, Expand);
206 setOperationAction(ISD::FREM, VT, Expand);
208 if (!VT.isFloatingPoint() &&
209 VT != MVT::v2i64 && VT != MVT::v1i64)
210 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
211 setOperationAction(Opcode, VT, Legal);
214 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
215 addRegisterClass(VT, &ARM::DPRRegClass);
216 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
219 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
220 addRegisterClass(VT, &ARM::DPairRegClass);
221 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
224 void ARMTargetLowering::setAllExpand(MVT VT) {
225 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
226 setOperationAction(Opc, VT, Expand);
228 // We support these really simple operations even on types where all
229 // the actual arithmetic has to be broken down into simpler
230 // operations or turned into library calls.
231 setOperationAction(ISD::BITCAST, VT, Legal);
232 setOperationAction(ISD::LOAD, VT, Legal);
233 setOperationAction(ISD::STORE, VT, Legal);
234 setOperationAction(ISD::UNDEF, VT, Legal);
237 void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To,
238 LegalizeAction Action) {
239 setLoadExtAction(ISD::EXTLOAD, From, To, Action);
240 setLoadExtAction(ISD::ZEXTLOAD, From, To, Action);
241 setLoadExtAction(ISD::SEXTLOAD, From, To, Action);
244 void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) {
245 const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 };
247 for (auto VT : IntTypes) {
248 addRegisterClass(VT, &ARM::QPRRegClass);
249 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
250 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
251 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
252 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
253 setOperationAction(ISD::SMIN, VT, Legal);
254 setOperationAction(ISD::SMAX, VT, Legal);
255 setOperationAction(ISD::UMIN, VT, Legal);
256 setOperationAction(ISD::UMAX, VT, Legal);
258 // No native support for these.
259 setOperationAction(ISD::UDIV, VT, Expand);
260 setOperationAction(ISD::SDIV, VT, Expand);
261 setOperationAction(ISD::UREM, VT, Expand);
262 setOperationAction(ISD::SREM, VT, Expand);
264 if (!HasMVEFP) {
265 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
266 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
267 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
268 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
272 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
273 for (auto VT : FloatTypes) {
274 addRegisterClass(VT, &ARM::QPRRegClass);
275 if (!HasMVEFP)
276 setAllExpand(VT);
278 // These are legal or custom whether we have MVE.fp or not
279 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
280 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
281 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom);
282 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
283 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
284 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom);
285 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal);
287 if (HasMVEFP) {
288 setOperationAction(ISD::FMINNUM, VT, Legal);
289 setOperationAction(ISD::FMAXNUM, VT, Legal);
290 setOperationAction(ISD::FROUND, VT, Legal);
292 // No native support for these.
293 setOperationAction(ISD::FDIV, VT, Expand);
294 setOperationAction(ISD::FREM, VT, Expand);
295 setOperationAction(ISD::FSQRT, VT, Expand);
296 setOperationAction(ISD::FSIN, VT, Expand);
297 setOperationAction(ISD::FCOS, VT, Expand);
298 setOperationAction(ISD::FPOW, VT, Expand);
299 setOperationAction(ISD::FLOG, VT, Expand);
300 setOperationAction(ISD::FLOG2, VT, Expand);
301 setOperationAction(ISD::FLOG10, VT, Expand);
302 setOperationAction(ISD::FEXP, VT, Expand);
303 setOperationAction(ISD::FEXP2, VT, Expand);
304 setOperationAction(ISD::FNEARBYINT, VT, Expand);
308 // We 'support' these types up to bitcast/load/store level, regardless of
309 // MVE integer-only / float support. Only doing FP data processing on the FP
310 // vector types is inhibited at integer-only level.
311 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
312 for (auto VT : LongTypes) {
313 addRegisterClass(VT, &ARM::QPRRegClass);
314 setAllExpand(VT);
315 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
316 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
317 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
320 // It is legal to extload from v4i8 to v4i16 or v4i32.
321 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
322 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
323 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
325 // Some truncating stores are legal too.
326 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
327 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
328 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
331 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
332 const ARMSubtarget &STI)
333 : TargetLowering(TM), Subtarget(&STI) {
334 RegInfo = Subtarget->getRegisterInfo();
335 Itins = Subtarget->getInstrItineraryData();
337 setBooleanContents(ZeroOrOneBooleanContent);
338 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
340 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
341 !Subtarget->isTargetWatchOS()) {
342 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
343 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
344 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
345 IsHFTarget ? CallingConv::ARM_AAPCS_VFP
346 : CallingConv::ARM_AAPCS);
349 if (Subtarget->isTargetMachO()) {
350 // Uses VFP for Thumb libfuncs if available.
351 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
352 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
353 static const struct {
354 const RTLIB::Libcall Op;
355 const char * const Name;
356 const ISD::CondCode Cond;
357 } LibraryCalls[] = {
358 // Single-precision floating-point arithmetic.
359 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
360 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
361 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
362 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
364 // Double-precision floating-point arithmetic.
365 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
366 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
367 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
368 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
370 // Single-precision comparisons.
371 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
372 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
373 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
374 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
375 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
376 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
377 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
378 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
380 // Double-precision comparisons.
381 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
382 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
383 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
384 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
385 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
386 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
387 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
388 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
390 // Floating-point to integer conversions.
391 // i64 conversions are done via library routines even when generating VFP
392 // instructions, so use the same ones.
393 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
394 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
395 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
396 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
398 // Conversions between floating types.
399 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
400 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
402 // Integer to floating-point conversions.
403 // i64 conversions are done via library routines even when generating VFP
404 // instructions, so use the same ones.
405 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
406 // e.g., __floatunsidf vs. __floatunssidfvfp.
407 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
408 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
409 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
410 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
413 for (const auto &LC : LibraryCalls) {
414 setLibcallName(LC.Op, LC.Name);
415 if (LC.Cond != ISD::SETCC_INVALID)
416 setCmpLibcallCC(LC.Op, LC.Cond);
421 // These libcalls are not available in 32-bit.
422 setLibcallName(RTLIB::SHL_I128, nullptr);
423 setLibcallName(RTLIB::SRL_I128, nullptr);
424 setLibcallName(RTLIB::SRA_I128, nullptr);
426 // RTLIB
427 if (Subtarget->isAAPCS_ABI() &&
428 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
429 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
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 } LibraryCalls[] = {
436 // Double-precision floating-point arithmetic helper functions
437 // RTABI chapter 4.1.2, Table 2
438 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
439 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
440 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
441 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
443 // Double-precision floating-point comparison helper functions
444 // RTABI chapter 4.1.2, Table 3
445 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
446 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
447 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
448 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
449 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
450 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
451 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
452 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
454 // Single-precision floating-point arithmetic helper functions
455 // RTABI chapter 4.1.2, Table 4
456 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
457 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
458 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
459 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
461 // Single-precision floating-point comparison helper functions
462 // RTABI chapter 4.1.2, Table 5
463 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
464 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
465 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
466 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
467 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
468 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
469 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
470 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
472 // Floating-point to integer conversions.
473 // RTABI chapter 4.1.2, Table 6
474 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
475 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
476 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
477 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
478 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
479 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
480 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
481 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
483 // Conversions between floating types.
484 // RTABI chapter 4.1.2, Table 7
485 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
486 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
487 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
489 // Integer to floating-point conversions.
490 // RTABI chapter 4.1.2, Table 8
491 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
492 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
493 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
494 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
495 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
496 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
497 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
498 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
500 // Long long helper functions
501 // RTABI chapter 4.2, Table 9
502 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
503 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
504 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
505 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
507 // Integer division functions
508 // RTABI chapter 4.3.1
509 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
510 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
511 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
512 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
513 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
514 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
515 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
516 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
519 for (const auto &LC : LibraryCalls) {
520 setLibcallName(LC.Op, LC.Name);
521 setLibcallCallingConv(LC.Op, LC.CC);
522 if (LC.Cond != ISD::SETCC_INVALID)
523 setCmpLibcallCC(LC.Op, LC.Cond);
526 // EABI dependent RTLIB
527 if (TM.Options.EABIVersion == EABI::EABI4 ||
528 TM.Options.EABIVersion == EABI::EABI5) {
529 static const struct {
530 const RTLIB::Libcall Op;
531 const char *const Name;
532 const CallingConv::ID CC;
533 const ISD::CondCode Cond;
534 } MemOpsLibraryCalls[] = {
535 // Memory operations
536 // RTABI chapter 4.3.4
537 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
538 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
539 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
542 for (const auto &LC : MemOpsLibraryCalls) {
543 setLibcallName(LC.Op, LC.Name);
544 setLibcallCallingConv(LC.Op, LC.CC);
545 if (LC.Cond != ISD::SETCC_INVALID)
546 setCmpLibcallCC(LC.Op, LC.Cond);
551 if (Subtarget->isTargetWindows()) {
552 static const struct {
553 const RTLIB::Libcall Op;
554 const char * const Name;
555 const CallingConv::ID CC;
556 } LibraryCalls[] = {
557 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
558 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
559 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
560 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
561 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
562 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
563 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
564 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
567 for (const auto &LC : LibraryCalls) {
568 setLibcallName(LC.Op, LC.Name);
569 setLibcallCallingConv(LC.Op, LC.CC);
573 // Use divmod compiler-rt calls for iOS 5.0 and later.
574 if (Subtarget->isTargetMachO() &&
575 !(Subtarget->isTargetIOS() &&
576 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
577 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
578 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
581 // The half <-> float conversion functions are always soft-float on
582 // non-watchos platforms, but are needed for some targets which use a
583 // hard-float calling convention by default.
584 if (!Subtarget->isTargetWatchABI()) {
585 if (Subtarget->isAAPCS_ABI()) {
586 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
587 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
588 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
589 } else {
590 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
591 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
592 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
596 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
597 // a __gnu_ prefix (which is the default).
598 if (Subtarget->isTargetAEABI()) {
599 static const struct {
600 const RTLIB::Libcall Op;
601 const char * const Name;
602 const CallingConv::ID CC;
603 } LibraryCalls[] = {
604 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
605 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
606 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
609 for (const auto &LC : LibraryCalls) {
610 setLibcallName(LC.Op, LC.Name);
611 setLibcallCallingConv(LC.Op, LC.CC);
615 if (Subtarget->isThumb1Only())
616 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
617 else
618 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
620 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
621 Subtarget->hasFPRegs()) {
622 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
623 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
624 if (!Subtarget->hasVFP2Base())
625 setAllExpand(MVT::f32);
626 if (!Subtarget->hasFP64())
627 setAllExpand(MVT::f64);
630 if (Subtarget->hasFullFP16()) {
631 addRegisterClass(MVT::f16, &ARM::HPRRegClass);
632 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
633 setOperationAction(ISD::BITCAST, MVT::i32, Custom);
634 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
636 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
637 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
640 for (MVT VT : MVT::vector_valuetypes()) {
641 for (MVT InnerVT : MVT::vector_valuetypes()) {
642 setTruncStoreAction(VT, InnerVT, Expand);
643 addAllExtLoads(VT, InnerVT, Expand);
646 setOperationAction(ISD::MULHS, VT, Expand);
647 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
648 setOperationAction(ISD::MULHU, VT, Expand);
649 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
651 setOperationAction(ISD::BSWAP, VT, Expand);
654 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
655 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
657 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
658 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
660 if (Subtarget->hasMVEIntegerOps())
661 addMVEVectorTypes(Subtarget->hasMVEFloatOps());
663 // Combine low-overhead loop intrinsics so that we can lower i1 types.
664 if (Subtarget->hasLOB())
665 setTargetDAGCombine(ISD::BRCOND);
667 if (Subtarget->hasNEON()) {
668 addDRTypeForNEON(MVT::v2f32);
669 addDRTypeForNEON(MVT::v8i8);
670 addDRTypeForNEON(MVT::v4i16);
671 addDRTypeForNEON(MVT::v2i32);
672 addDRTypeForNEON(MVT::v1i64);
674 addQRTypeForNEON(MVT::v4f32);
675 addQRTypeForNEON(MVT::v2f64);
676 addQRTypeForNEON(MVT::v16i8);
677 addQRTypeForNEON(MVT::v8i16);
678 addQRTypeForNEON(MVT::v4i32);
679 addQRTypeForNEON(MVT::v2i64);
681 if (Subtarget->hasFullFP16()) {
682 addQRTypeForNEON(MVT::v8f16);
683 addDRTypeForNEON(MVT::v4f16);
687 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
688 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
689 // none of Neon, MVE or VFP supports any arithmetic operations on it.
690 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
691 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
692 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
693 // FIXME: Code duplication: FDIV and FREM are expanded always, see
694 // ARMTargetLowering::addTypeForNEON method for details.
695 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
696 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
697 // FIXME: Create unittest.
698 // In another words, find a way when "copysign" appears in DAG with vector
699 // operands.
700 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
701 // FIXME: Code duplication: SETCC has custom operation action, see
702 // ARMTargetLowering::addTypeForNEON method for details.
703 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
704 // FIXME: Create unittest for FNEG and for FABS.
705 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
706 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
707 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
708 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
709 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
710 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
711 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
712 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
713 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
714 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
715 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
716 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
717 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
718 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
719 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
720 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
721 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
722 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
725 if (Subtarget->hasNEON()) {
726 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
727 // supported for v4f32.
728 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
729 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
730 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
731 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
732 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
733 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
734 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
735 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
736 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
737 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
738 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
739 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
740 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
741 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
743 // Mark v2f32 intrinsics.
744 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
745 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
746 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
747 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
748 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
749 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
750 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
751 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
752 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
753 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
754 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
755 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
756 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
757 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
759 // Neon does not support some operations on v1i64 and v2i64 types.
760 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
761 // Custom handling for some quad-vector types to detect VMULL.
762 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
763 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
764 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
765 // Custom handling for some vector types to avoid expensive expansions
766 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
767 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
768 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
769 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
770 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
771 // a destination type that is wider than the source, and nor does
772 // it have a FP_TO_[SU]INT instruction with a narrower destination than
773 // source.
774 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
775 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
776 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
777 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
778 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
779 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
780 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
781 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
783 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
784 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
786 // NEON does not have single instruction CTPOP for vectors with element
787 // types wider than 8-bits. However, custom lowering can leverage the
788 // v8i8/v16i8 vcnt instruction.
789 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
790 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
791 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
792 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
793 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom);
794 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
796 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
797 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
799 // NEON does not have single instruction CTTZ for vectors.
800 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
801 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
802 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
803 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
805 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
806 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
807 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
808 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
810 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
811 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
812 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
813 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
815 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
816 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
817 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
818 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
820 // NEON only has FMA instructions as of VFP4.
821 if (!Subtarget->hasVFP4Base()) {
822 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
823 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
826 setTargetDAGCombine(ISD::INTRINSIC_VOID);
827 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
828 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
829 setTargetDAGCombine(ISD::SHL);
830 setTargetDAGCombine(ISD::SRL);
831 setTargetDAGCombine(ISD::SRA);
832 setTargetDAGCombine(ISD::SIGN_EXTEND);
833 setTargetDAGCombine(ISD::ZERO_EXTEND);
834 setTargetDAGCombine(ISD::ANY_EXTEND);
835 setTargetDAGCombine(ISD::STORE);
836 setTargetDAGCombine(ISD::FP_TO_SINT);
837 setTargetDAGCombine(ISD::FP_TO_UINT);
838 setTargetDAGCombine(ISD::FDIV);
839 setTargetDAGCombine(ISD::LOAD);
841 // It is legal to extload from v4i8 to v4i16 or v4i32.
842 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
843 MVT::v2i32}) {
844 for (MVT VT : MVT::integer_vector_valuetypes()) {
845 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
846 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
847 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
852 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
853 setTargetDAGCombine(ISD::BUILD_VECTOR);
854 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
855 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
858 if (!Subtarget->hasFP64()) {
859 // When targeting a floating-point unit with only single-precision
860 // operations, f64 is legal for the few double-precision instructions which
861 // are present However, no double-precision operations other than moves,
862 // loads and stores are provided by the hardware.
863 setOperationAction(ISD::FADD, MVT::f64, Expand);
864 setOperationAction(ISD::FSUB, MVT::f64, Expand);
865 setOperationAction(ISD::FMUL, MVT::f64, Expand);
866 setOperationAction(ISD::FMA, MVT::f64, Expand);
867 setOperationAction(ISD::FDIV, MVT::f64, Expand);
868 setOperationAction(ISD::FREM, MVT::f64, Expand);
869 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
870 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
871 setOperationAction(ISD::FNEG, MVT::f64, Expand);
872 setOperationAction(ISD::FABS, MVT::f64, Expand);
873 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
874 setOperationAction(ISD::FSIN, MVT::f64, Expand);
875 setOperationAction(ISD::FCOS, MVT::f64, Expand);
876 setOperationAction(ISD::FPOW, MVT::f64, Expand);
877 setOperationAction(ISD::FLOG, MVT::f64, Expand);
878 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
879 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
880 setOperationAction(ISD::FEXP, MVT::f64, Expand);
881 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
882 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
883 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
884 setOperationAction(ISD::FRINT, MVT::f64, Expand);
885 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
886 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
887 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
888 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
889 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
890 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
891 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
892 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
893 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
896 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()){
897 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
898 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
901 if (!Subtarget->hasFP16())
902 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom);
904 if (!Subtarget->hasFP64())
905 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
907 computeRegisterProperties(Subtarget->getRegisterInfo());
909 // ARM does not have floating-point extending loads.
910 for (MVT VT : MVT::fp_valuetypes()) {
911 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
912 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
915 // ... or truncating stores
916 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
917 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
918 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
920 // ARM does not have i1 sign extending load.
921 for (MVT VT : MVT::integer_valuetypes())
922 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
924 // ARM supports all 4 flavors of integer indexed load / store.
925 if (!Subtarget->isThumb1Only()) {
926 for (unsigned im = (unsigned)ISD::PRE_INC;
927 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
928 setIndexedLoadAction(im, MVT::i1, Legal);
929 setIndexedLoadAction(im, MVT::i8, Legal);
930 setIndexedLoadAction(im, MVT::i16, Legal);
931 setIndexedLoadAction(im, MVT::i32, Legal);
932 setIndexedStoreAction(im, MVT::i1, Legal);
933 setIndexedStoreAction(im, MVT::i8, Legal);
934 setIndexedStoreAction(im, MVT::i16, Legal);
935 setIndexedStoreAction(im, MVT::i32, Legal);
937 } else {
938 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
939 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal);
940 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal);
943 setOperationAction(ISD::SADDO, MVT::i32, Custom);
944 setOperationAction(ISD::UADDO, MVT::i32, Custom);
945 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
946 setOperationAction(ISD::USUBO, MVT::i32, Custom);
948 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
949 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
951 // i64 operation support.
952 setOperationAction(ISD::MUL, MVT::i64, Expand);
953 setOperationAction(ISD::MULHU, MVT::i32, Expand);
954 if (Subtarget->isThumb1Only()) {
955 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
956 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
958 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
959 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
960 setOperationAction(ISD::MULHS, MVT::i32, Expand);
962 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
963 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
964 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
965 setOperationAction(ISD::SRL, MVT::i64, Custom);
966 setOperationAction(ISD::SRA, MVT::i64, Custom);
967 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
969 // MVE lowers 64 bit shifts to lsll and lsrl
970 // assuming that ISD::SRL and SRA of i64 are already marked custom
971 if (Subtarget->hasMVEIntegerOps())
972 setOperationAction(ISD::SHL, MVT::i64, Custom);
974 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
975 if (Subtarget->isThumb1Only()) {
976 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
977 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
978 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
981 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
982 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
984 // ARM does not have ROTL.
985 setOperationAction(ISD::ROTL, MVT::i32, Expand);
986 for (MVT VT : MVT::vector_valuetypes()) {
987 setOperationAction(ISD::ROTL, VT, Expand);
988 setOperationAction(ISD::ROTR, VT, Expand);
990 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
991 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
992 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
993 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
994 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
997 // @llvm.readcyclecounter requires the Performance Monitors extension.
998 // Default to the 0 expansion on unsupported platforms.
999 // FIXME: Technically there are older ARM CPUs that have
1000 // implementation-specific ways of obtaining this information.
1001 if (Subtarget->hasPerfMon())
1002 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1004 // Only ARMv6 has BSWAP.
1005 if (!Subtarget->hasV6Ops())
1006 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1008 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1009 : Subtarget->hasDivideInARMMode();
1010 if (!hasDivide) {
1011 // These are expanded into libcalls if the cpu doesn't have HW divider.
1012 setOperationAction(ISD::SDIV, MVT::i32, LibCall);
1013 setOperationAction(ISD::UDIV, MVT::i32, LibCall);
1016 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
1017 setOperationAction(ISD::SDIV, MVT::i32, Custom);
1018 setOperationAction(ISD::UDIV, MVT::i32, Custom);
1020 setOperationAction(ISD::SDIV, MVT::i64, Custom);
1021 setOperationAction(ISD::UDIV, MVT::i64, Custom);
1024 setOperationAction(ISD::SREM, MVT::i32, Expand);
1025 setOperationAction(ISD::UREM, MVT::i32, Expand);
1027 // Register based DivRem for AEABI (RTABI 4.2)
1028 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
1029 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
1030 Subtarget->isTargetWindows()) {
1031 setOperationAction(ISD::SREM, MVT::i64, Custom);
1032 setOperationAction(ISD::UREM, MVT::i64, Custom);
1033 HasStandaloneRem = false;
1035 if (Subtarget->isTargetWindows()) {
1036 const struct {
1037 const RTLIB::Libcall Op;
1038 const char * const Name;
1039 const CallingConv::ID CC;
1040 } LibraryCalls[] = {
1041 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
1042 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
1043 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
1044 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
1046 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
1047 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
1048 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
1049 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
1052 for (const auto &LC : LibraryCalls) {
1053 setLibcallName(LC.Op, LC.Name);
1054 setLibcallCallingConv(LC.Op, LC.CC);
1056 } else {
1057 const struct {
1058 const RTLIB::Libcall Op;
1059 const char * const Name;
1060 const CallingConv::ID CC;
1061 } LibraryCalls[] = {
1062 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1063 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1064 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1065 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
1067 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1068 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1069 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1070 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
1073 for (const auto &LC : LibraryCalls) {
1074 setLibcallName(LC.Op, LC.Name);
1075 setLibcallCallingConv(LC.Op, LC.CC);
1079 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1080 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1081 setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1082 setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1083 } else {
1084 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1085 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1088 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
1089 for (auto &VT : {MVT::f32, MVT::f64})
1090 setOperationAction(ISD::FPOWI, VT, Custom);
1092 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1093 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
1094 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1095 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1097 setOperationAction(ISD::TRAP, MVT::Other, Legal);
1098 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1100 // Use the default implementation.
1101 setOperationAction(ISD::VASTART, MVT::Other, Custom);
1102 setOperationAction(ISD::VAARG, MVT::Other, Expand);
1103 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
1104 setOperationAction(ISD::VAEND, MVT::Other, Expand);
1105 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
1106 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
1108 if (Subtarget->isTargetWindows())
1109 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1110 else
1111 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1113 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1114 // the default expansion.
1115 InsertFencesForAtomic = false;
1116 if (Subtarget->hasAnyDataBarrier() &&
1117 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1118 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1119 // to ldrex/strex loops already.
1120 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
1121 if (!Subtarget->isThumb() || !Subtarget->isMClass())
1122 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
1124 // On v8, we have particularly efficient implementations of atomic fences
1125 // if they can be combined with nearby atomic loads and stores.
1126 if (!Subtarget->hasAcquireRelease() ||
1127 getTargetMachine().getOptLevel() == 0) {
1128 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1129 InsertFencesForAtomic = true;
1131 } else {
1132 // If there's anything we can use as a barrier, go through custom lowering
1133 // for ATOMIC_FENCE.
1134 // If target has DMB in thumb, Fences can be inserted.
1135 if (Subtarget->hasDataBarrier())
1136 InsertFencesForAtomic = true;
1138 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
1139 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1141 // Set them all for expansion, which will force libcalls.
1142 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
1143 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
1144 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
1145 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
1146 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
1147 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
1148 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
1149 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1150 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1151 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1152 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1153 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1154 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1155 // Unordered/Monotonic case.
1156 if (!InsertFencesForAtomic) {
1157 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1158 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1162 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
1164 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1165 if (!Subtarget->hasV6Ops()) {
1166 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1167 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
1169 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1171 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1172 !Subtarget->isThumb1Only()) {
1173 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1174 // iff target supports vfp2.
1175 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1176 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1179 // We want to custom lower some of our intrinsics.
1180 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1181 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1182 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1183 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1184 if (Subtarget->useSjLjEH())
1185 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1187 setOperationAction(ISD::SETCC, MVT::i32, Expand);
1188 setOperationAction(ISD::SETCC, MVT::f32, Expand);
1189 setOperationAction(ISD::SETCC, MVT::f64, Expand);
1190 setOperationAction(ISD::SELECT, MVT::i32, Custom);
1191 setOperationAction(ISD::SELECT, MVT::f32, Custom);
1192 setOperationAction(ISD::SELECT, MVT::f64, Custom);
1193 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1194 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1195 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1196 if (Subtarget->hasFullFP16()) {
1197 setOperationAction(ISD::SETCC, MVT::f16, Expand);
1198 setOperationAction(ISD::SELECT, MVT::f16, Custom);
1199 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1202 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1204 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
1205 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
1206 if (Subtarget->hasFullFP16())
1207 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
1208 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
1209 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
1210 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1212 // We don't support sin/cos/fmod/copysign/pow
1213 setOperationAction(ISD::FSIN, MVT::f64, Expand);
1214 setOperationAction(ISD::FSIN, MVT::f32, Expand);
1215 setOperationAction(ISD::FCOS, MVT::f32, Expand);
1216 setOperationAction(ISD::FCOS, MVT::f64, Expand);
1217 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1218 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1219 setOperationAction(ISD::FREM, MVT::f64, Expand);
1220 setOperationAction(ISD::FREM, MVT::f32, Expand);
1221 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1222 !Subtarget->isThumb1Only()) {
1223 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1224 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1226 setOperationAction(ISD::FPOW, MVT::f64, Expand);
1227 setOperationAction(ISD::FPOW, MVT::f32, Expand);
1229 if (!Subtarget->hasVFP4Base()) {
1230 setOperationAction(ISD::FMA, MVT::f64, Expand);
1231 setOperationAction(ISD::FMA, MVT::f32, Expand);
1234 // Various VFP goodness
1235 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1236 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1237 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1238 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1239 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1242 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1243 if (!Subtarget->hasFP16()) {
1244 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1245 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1249 // Use __sincos_stret if available.
1250 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1251 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1252 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1253 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1256 // FP-ARMv8 implements a lot of rounding-like FP operations.
1257 if (Subtarget->hasFPARMv8Base()) {
1258 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1259 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1260 setOperationAction(ISD::FROUND, MVT::f32, Legal);
1261 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1262 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1263 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1264 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1265 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1266 if (Subtarget->hasNEON()) {
1267 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1268 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1269 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1270 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1273 if (Subtarget->hasFP64()) {
1274 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1275 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1276 setOperationAction(ISD::FROUND, MVT::f64, Legal);
1277 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1278 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1279 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1280 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1281 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1285 // FP16 often need to be promoted to call lib functions
1286 if (Subtarget->hasFullFP16()) {
1287 setOperationAction(ISD::FREM, MVT::f16, Promote);
1288 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1289 setOperationAction(ISD::FSIN, MVT::f16, Promote);
1290 setOperationAction(ISD::FCOS, MVT::f16, Promote);
1291 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1292 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1293 setOperationAction(ISD::FPOW, MVT::f16, Promote);
1294 setOperationAction(ISD::FEXP, MVT::f16, Promote);
1295 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1296 setOperationAction(ISD::FLOG, MVT::f16, Promote);
1297 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1298 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1300 setOperationAction(ISD::FROUND, MVT::f16, Legal);
1303 if (Subtarget->hasNEON()) {
1304 // vmin and vmax aren't available in a scalar form, so we use
1305 // a NEON instruction with an undef lane instead.
1306 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1307 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1308 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1309 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1310 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1311 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1312 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1313 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1315 if (Subtarget->hasFullFP16()) {
1316 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1317 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1318 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1319 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1321 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1322 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1323 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1324 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1328 // We have target-specific dag combine patterns for the following nodes:
1329 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1330 setTargetDAGCombine(ISD::ADD);
1331 setTargetDAGCombine(ISD::SUB);
1332 setTargetDAGCombine(ISD::MUL);
1333 setTargetDAGCombine(ISD::AND);
1334 setTargetDAGCombine(ISD::OR);
1335 setTargetDAGCombine(ISD::XOR);
1337 if (Subtarget->hasV6Ops())
1338 setTargetDAGCombine(ISD::SRL);
1339 if (Subtarget->isThumb1Only())
1340 setTargetDAGCombine(ISD::SHL);
1342 setStackPointerRegisterToSaveRestore(ARM::SP);
1344 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1345 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1346 setSchedulingPreference(Sched::RegPressure);
1347 else
1348 setSchedulingPreference(Sched::Hybrid);
1350 //// temporary - rewrite interface to use type
1351 MaxStoresPerMemset = 8;
1352 MaxStoresPerMemsetOptSize = 4;
1353 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1354 MaxStoresPerMemcpyOptSize = 2;
1355 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1356 MaxStoresPerMemmoveOptSize = 2;
1358 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1359 // are at least 4 bytes aligned.
1360 setMinStackArgumentAlignment(4);
1362 // Prefer likely predicted branches to selects on out-of-order cores.
1363 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1365 setPrefLoopAlignment(Subtarget->getPrefLoopAlignment());
1367 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1369 if (Subtarget->isThumb() || Subtarget->isThumb2())
1370 setTargetDAGCombine(ISD::ABS);
1373 bool ARMTargetLowering::useSoftFloat() const {
1374 return Subtarget->useSoftFloat();
1377 // FIXME: It might make sense to define the representative register class as the
1378 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1379 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1380 // SPR's representative would be DPR_VFP2. This should work well if register
1381 // pressure tracking were modified such that a register use would increment the
1382 // pressure of the register class's representative and all of it's super
1383 // classes' representatives transitively. We have not implemented this because
1384 // of the difficulty prior to coalescing of modeling operand register classes
1385 // due to the common occurrence of cross class copies and subregister insertions
1386 // and extractions.
1387 std::pair<const TargetRegisterClass *, uint8_t>
1388 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1389 MVT VT) const {
1390 const TargetRegisterClass *RRC = nullptr;
1391 uint8_t Cost = 1;
1392 switch (VT.SimpleTy) {
1393 default:
1394 return TargetLowering::findRepresentativeClass(TRI, VT);
1395 // Use DPR as representative register class for all floating point
1396 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1397 // the cost is 1 for both f32 and f64.
1398 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1399 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1400 RRC = &ARM::DPRRegClass;
1401 // When NEON is used for SP, only half of the register file is available
1402 // because operations that define both SP and DP results will be constrained
1403 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1404 // coalescing by double-counting the SP regs. See the FIXME above.
1405 if (Subtarget->useNEONForSinglePrecisionFP())
1406 Cost = 2;
1407 break;
1408 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1409 case MVT::v4f32: case MVT::v2f64:
1410 RRC = &ARM::DPRRegClass;
1411 Cost = 2;
1412 break;
1413 case MVT::v4i64:
1414 RRC = &ARM::DPRRegClass;
1415 Cost = 4;
1416 break;
1417 case MVT::v8i64:
1418 RRC = &ARM::DPRRegClass;
1419 Cost = 8;
1420 break;
1422 return std::make_pair(RRC, Cost);
1425 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1426 switch ((ARMISD::NodeType)Opcode) {
1427 case ARMISD::FIRST_NUMBER: break;
1428 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1429 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1430 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1431 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1432 case ARMISD::CALL: return "ARMISD::CALL";
1433 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1434 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1435 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1436 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1437 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1438 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1439 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1440 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1441 case ARMISD::CMP: return "ARMISD::CMP";
1442 case ARMISD::CMN: return "ARMISD::CMN";
1443 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1444 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1445 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1446 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1447 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1449 case ARMISD::CMOV: return "ARMISD::CMOV";
1450 case ARMISD::SUBS: return "ARMISD::SUBS";
1452 case ARMISD::SSAT: return "ARMISD::SSAT";
1453 case ARMISD::USAT: return "ARMISD::USAT";
1455 case ARMISD::ASRL: return "ARMISD::ASRL";
1456 case ARMISD::LSRL: return "ARMISD::LSRL";
1457 case ARMISD::LSLL: return "ARMISD::LSLL";
1459 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1460 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1461 case ARMISD::RRX: return "ARMISD::RRX";
1463 case ARMISD::ADDC: return "ARMISD::ADDC";
1464 case ARMISD::ADDE: return "ARMISD::ADDE";
1465 case ARMISD::SUBC: return "ARMISD::SUBC";
1466 case ARMISD::SUBE: return "ARMISD::SUBE";
1468 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1469 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1470 case ARMISD::VMOVhr: return "ARMISD::VMOVhr";
1471 case ARMISD::VMOVrh: return "ARMISD::VMOVrh";
1472 case ARMISD::VMOVSR: return "ARMISD::VMOVSR";
1474 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1475 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1476 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1478 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1480 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1482 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1484 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1486 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1488 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK";
1489 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1491 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1492 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1493 case ARMISD::VCGE: return "ARMISD::VCGE";
1494 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1495 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1496 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1497 case ARMISD::VCGT: return "ARMISD::VCGT";
1498 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1499 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1500 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1501 case ARMISD::VTST: return "ARMISD::VTST";
1503 case ARMISD::VSHL: return "ARMISD::VSHL";
1504 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1505 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1506 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1507 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1508 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1509 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1510 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1511 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1512 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1513 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1514 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1515 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1516 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1517 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1518 case ARMISD::VSLI: return "ARMISD::VSLI";
1519 case ARMISD::VSRI: return "ARMISD::VSRI";
1520 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1521 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1522 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1523 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1524 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1525 case ARMISD::VDUP: return "ARMISD::VDUP";
1526 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1527 case ARMISD::VEXT: return "ARMISD::VEXT";
1528 case ARMISD::VREV64: return "ARMISD::VREV64";
1529 case ARMISD::VREV32: return "ARMISD::VREV32";
1530 case ARMISD::VREV16: return "ARMISD::VREV16";
1531 case ARMISD::VZIP: return "ARMISD::VZIP";
1532 case ARMISD::VUZP: return "ARMISD::VUZP";
1533 case ARMISD::VTRN: return "ARMISD::VTRN";
1534 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1535 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1536 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1537 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1538 case ARMISD::UMAAL: return "ARMISD::UMAAL";
1539 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1540 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1541 case ARMISD::SMLALBB: return "ARMISD::SMLALBB";
1542 case ARMISD::SMLALBT: return "ARMISD::SMLALBT";
1543 case ARMISD::SMLALTB: return "ARMISD::SMLALTB";
1544 case ARMISD::SMLALTT: return "ARMISD::SMLALTT";
1545 case ARMISD::SMULWB: return "ARMISD::SMULWB";
1546 case ARMISD::SMULWT: return "ARMISD::SMULWT";
1547 case ARMISD::SMLALD: return "ARMISD::SMLALD";
1548 case ARMISD::SMLALDX: return "ARMISD::SMLALDX";
1549 case ARMISD::SMLSLD: return "ARMISD::SMLSLD";
1550 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX";
1551 case ARMISD::SMMLAR: return "ARMISD::SMMLAR";
1552 case ARMISD::SMMLSR: return "ARMISD::SMMLSR";
1553 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1554 case ARMISD::BFI: return "ARMISD::BFI";
1555 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1556 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1557 case ARMISD::VBSL: return "ARMISD::VBSL";
1558 case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1559 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP";
1560 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1561 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1562 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1563 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1564 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1565 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1566 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1567 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1568 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1569 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1570 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD";
1571 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1572 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1573 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1574 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1575 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1576 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1577 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1578 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1579 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1580 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1581 case ARMISD::WLS: return "ARMISD::WLS";
1583 return nullptr;
1586 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1587 EVT VT) const {
1588 if (!VT.isVector())
1589 return getPointerTy(DL);
1590 return VT.changeVectorElementTypeToInteger();
1593 /// getRegClassFor - Return the register class that should be used for the
1594 /// specified value type.
1595 const TargetRegisterClass *
1596 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1597 (void)isDivergent;
1598 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1599 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1600 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1601 // MVE Q registers.
1602 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1603 if (VT == MVT::v4i64)
1604 return &ARM::QQPRRegClass;
1605 if (VT == MVT::v8i64)
1606 return &ARM::QQQQPRRegClass;
1608 return TargetLowering::getRegClassFor(VT);
1611 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1612 // source/dest is aligned and the copy size is large enough. We therefore want
1613 // to align such objects passed to memory intrinsics.
1614 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1615 unsigned &PrefAlign) const {
1616 if (!isa<MemIntrinsic>(CI))
1617 return false;
1618 MinSize = 8;
1619 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1620 // cycle faster than 4-byte aligned LDM.
1621 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1622 return true;
1625 // Create a fast isel object.
1626 FastISel *
1627 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1628 const TargetLibraryInfo *libInfo) const {
1629 return ARM::createFastISel(funcInfo, libInfo);
1632 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1633 unsigned NumVals = N->getNumValues();
1634 if (!NumVals)
1635 return Sched::RegPressure;
1637 for (unsigned i = 0; i != NumVals; ++i) {
1638 EVT VT = N->getValueType(i);
1639 if (VT == MVT::Glue || VT == MVT::Other)
1640 continue;
1641 if (VT.isFloatingPoint() || VT.isVector())
1642 return Sched::ILP;
1645 if (!N->isMachineOpcode())
1646 return Sched::RegPressure;
1648 // Load are scheduled for latency even if there instruction itinerary
1649 // is not available.
1650 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1651 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1653 if (MCID.getNumDefs() == 0)
1654 return Sched::RegPressure;
1655 if (!Itins->isEmpty() &&
1656 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1657 return Sched::ILP;
1659 return Sched::RegPressure;
1662 //===----------------------------------------------------------------------===//
1663 // Lowering Code
1664 //===----------------------------------------------------------------------===//
1666 static bool isSRL16(const SDValue &Op) {
1667 if (Op.getOpcode() != ISD::SRL)
1668 return false;
1669 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1670 return Const->getZExtValue() == 16;
1671 return false;
1674 static bool isSRA16(const SDValue &Op) {
1675 if (Op.getOpcode() != ISD::SRA)
1676 return false;
1677 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1678 return Const->getZExtValue() == 16;
1679 return false;
1682 static bool isSHL16(const SDValue &Op) {
1683 if (Op.getOpcode() != ISD::SHL)
1684 return false;
1685 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1686 return Const->getZExtValue() == 16;
1687 return false;
1690 // Check for a signed 16-bit value. We special case SRA because it makes it
1691 // more simple when also looking for SRAs that aren't sign extending a
1692 // smaller value. Without the check, we'd need to take extra care with
1693 // checking order for some operations.
1694 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1695 if (isSRA16(Op))
1696 return isSHL16(Op.getOperand(0));
1697 return DAG.ComputeNumSignBits(Op) == 17;
1700 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1701 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1702 switch (CC) {
1703 default: llvm_unreachable("Unknown condition code!");
1704 case ISD::SETNE: return ARMCC::NE;
1705 case ISD::SETEQ: return ARMCC::EQ;
1706 case ISD::SETGT: return ARMCC::GT;
1707 case ISD::SETGE: return ARMCC::GE;
1708 case ISD::SETLT: return ARMCC::LT;
1709 case ISD::SETLE: return ARMCC::LE;
1710 case ISD::SETUGT: return ARMCC::HI;
1711 case ISD::SETUGE: return ARMCC::HS;
1712 case ISD::SETULT: return ARMCC::LO;
1713 case ISD::SETULE: return ARMCC::LS;
1717 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1718 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1719 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1720 CondCode2 = ARMCC::AL;
1721 InvalidOnQNaN = true;
1722 switch (CC) {
1723 default: llvm_unreachable("Unknown FP condition!");
1724 case ISD::SETEQ:
1725 case ISD::SETOEQ:
1726 CondCode = ARMCC::EQ;
1727 InvalidOnQNaN = false;
1728 break;
1729 case ISD::SETGT:
1730 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1731 case ISD::SETGE:
1732 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1733 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1734 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1735 case ISD::SETONE:
1736 CondCode = ARMCC::MI;
1737 CondCode2 = ARMCC::GT;
1738 InvalidOnQNaN = false;
1739 break;
1740 case ISD::SETO: CondCode = ARMCC::VC; break;
1741 case ISD::SETUO: CondCode = ARMCC::VS; break;
1742 case ISD::SETUEQ:
1743 CondCode = ARMCC::EQ;
1744 CondCode2 = ARMCC::VS;
1745 InvalidOnQNaN = false;
1746 break;
1747 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1748 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1749 case ISD::SETLT:
1750 case ISD::SETULT: CondCode = ARMCC::LT; break;
1751 case ISD::SETLE:
1752 case ISD::SETULE: CondCode = ARMCC::LE; break;
1753 case ISD::SETNE:
1754 case ISD::SETUNE:
1755 CondCode = ARMCC::NE;
1756 InvalidOnQNaN = false;
1757 break;
1761 //===----------------------------------------------------------------------===//
1762 // Calling Convention Implementation
1763 //===----------------------------------------------------------------------===//
1765 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1766 /// account presence of floating point hardware and calling convention
1767 /// limitations, such as support for variadic functions.
1768 CallingConv::ID
1769 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1770 bool isVarArg) const {
1771 switch (CC) {
1772 default:
1773 report_fatal_error("Unsupported calling convention");
1774 case CallingConv::ARM_AAPCS:
1775 case CallingConv::ARM_APCS:
1776 case CallingConv::GHC:
1777 return CC;
1778 case CallingConv::PreserveMost:
1779 return CallingConv::PreserveMost;
1780 case CallingConv::ARM_AAPCS_VFP:
1781 case CallingConv::Swift:
1782 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1783 case CallingConv::C:
1784 if (!Subtarget->isAAPCS_ABI())
1785 return CallingConv::ARM_APCS;
1786 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
1787 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1788 !isVarArg)
1789 return CallingConv::ARM_AAPCS_VFP;
1790 else
1791 return CallingConv::ARM_AAPCS;
1792 case CallingConv::Fast:
1793 case CallingConv::CXX_FAST_TLS:
1794 if (!Subtarget->isAAPCS_ABI()) {
1795 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
1796 return CallingConv::Fast;
1797 return CallingConv::ARM_APCS;
1798 } else if (Subtarget->hasVFP2Base() &&
1799 !Subtarget->isThumb1Only() && !isVarArg)
1800 return CallingConv::ARM_AAPCS_VFP;
1801 else
1802 return CallingConv::ARM_AAPCS;
1806 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1807 bool isVarArg) const {
1808 return CCAssignFnForNode(CC, false, isVarArg);
1811 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1812 bool isVarArg) const {
1813 return CCAssignFnForNode(CC, true, isVarArg);
1816 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1817 /// CallingConvention.
1818 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1819 bool Return,
1820 bool isVarArg) const {
1821 switch (getEffectiveCallingConv(CC, isVarArg)) {
1822 default:
1823 report_fatal_error("Unsupported calling convention");
1824 case CallingConv::ARM_APCS:
1825 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1826 case CallingConv::ARM_AAPCS:
1827 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1828 case CallingConv::ARM_AAPCS_VFP:
1829 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1830 case CallingConv::Fast:
1831 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1832 case CallingConv::GHC:
1833 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1834 case CallingConv::PreserveMost:
1835 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1839 /// LowerCallResult - Lower the result values of a call into the
1840 /// appropriate copies out of appropriate physical registers.
1841 SDValue ARMTargetLowering::LowerCallResult(
1842 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1843 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1844 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1845 SDValue ThisVal) const {
1846 // Assign locations to each value returned by this call.
1847 SmallVector<CCValAssign, 16> RVLocs;
1848 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1849 *DAG.getContext());
1850 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1852 // Copy all of the result registers out of their specified physreg.
1853 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1854 CCValAssign VA = RVLocs[i];
1856 // Pass 'this' value directly from the argument to return value, to avoid
1857 // reg unit interference
1858 if (i == 0 && isThisReturn) {
1859 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1860 "unexpected return calling convention register assignment");
1861 InVals.push_back(ThisVal);
1862 continue;
1865 SDValue Val;
1866 if (VA.needsCustom()) {
1867 // Handle f64 or half of a v2f64.
1868 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1869 InFlag);
1870 Chain = Lo.getValue(1);
1871 InFlag = Lo.getValue(2);
1872 VA = RVLocs[++i]; // skip ahead to next loc
1873 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1874 InFlag);
1875 Chain = Hi.getValue(1);
1876 InFlag = Hi.getValue(2);
1877 if (!Subtarget->isLittle())
1878 std::swap (Lo, Hi);
1879 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1881 if (VA.getLocVT() == MVT::v2f64) {
1882 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1883 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1884 DAG.getConstant(0, dl, MVT::i32));
1886 VA = RVLocs[++i]; // skip ahead to next loc
1887 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1888 Chain = Lo.getValue(1);
1889 InFlag = Lo.getValue(2);
1890 VA = RVLocs[++i]; // skip ahead to next loc
1891 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1892 Chain = Hi.getValue(1);
1893 InFlag = Hi.getValue(2);
1894 if (!Subtarget->isLittle())
1895 std::swap (Lo, Hi);
1896 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1897 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1898 DAG.getConstant(1, dl, MVT::i32));
1900 } else {
1901 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1902 InFlag);
1903 Chain = Val.getValue(1);
1904 InFlag = Val.getValue(2);
1907 switch (VA.getLocInfo()) {
1908 default: llvm_unreachable("Unknown loc info!");
1909 case CCValAssign::Full: break;
1910 case CCValAssign::BCvt:
1911 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1912 break;
1915 InVals.push_back(Val);
1918 return Chain;
1921 /// LowerMemOpCallTo - Store the argument to the stack.
1922 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1923 SDValue Arg, const SDLoc &dl,
1924 SelectionDAG &DAG,
1925 const CCValAssign &VA,
1926 ISD::ArgFlagsTy Flags) const {
1927 unsigned LocMemOffset = VA.getLocMemOffset();
1928 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1929 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1930 StackPtr, PtrOff);
1931 return DAG.getStore(
1932 Chain, dl, Arg, PtrOff,
1933 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1936 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1937 SDValue Chain, SDValue &Arg,
1938 RegsToPassVector &RegsToPass,
1939 CCValAssign &VA, CCValAssign &NextVA,
1940 SDValue &StackPtr,
1941 SmallVectorImpl<SDValue> &MemOpChains,
1942 ISD::ArgFlagsTy Flags) const {
1943 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1944 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1945 unsigned id = Subtarget->isLittle() ? 0 : 1;
1946 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1948 if (NextVA.isRegLoc())
1949 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1950 else {
1951 assert(NextVA.isMemLoc());
1952 if (!StackPtr.getNode())
1953 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1954 getPointerTy(DAG.getDataLayout()));
1956 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1957 dl, DAG, NextVA,
1958 Flags));
1962 /// LowerCall - Lowering a call into a callseq_start <-
1963 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1964 /// nodes.
1965 SDValue
1966 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1967 SmallVectorImpl<SDValue> &InVals) const {
1968 SelectionDAG &DAG = CLI.DAG;
1969 SDLoc &dl = CLI.DL;
1970 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1971 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1972 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1973 SDValue Chain = CLI.Chain;
1974 SDValue Callee = CLI.Callee;
1975 bool &isTailCall = CLI.IsTailCall;
1976 CallingConv::ID CallConv = CLI.CallConv;
1977 bool doesNotRet = CLI.DoesNotReturn;
1978 bool isVarArg = CLI.IsVarArg;
1980 MachineFunction &MF = DAG.getMachineFunction();
1981 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1982 bool isThisReturn = false;
1983 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
1984 bool PreferIndirect = false;
1986 // Disable tail calls if they're not supported.
1987 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1988 isTailCall = false;
1990 if (isa<GlobalAddressSDNode>(Callee)) {
1991 // If we're optimizing for minimum size and the function is called three or
1992 // more times in this block, we can improve codesize by calling indirectly
1993 // as BLXr has a 16-bit encoding.
1994 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
1995 if (CLI.CS) {
1996 auto *BB = CLI.CS.getParent();
1997 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
1998 count_if(GV->users(), [&BB](const User *U) {
1999 return isa<Instruction>(U) &&
2000 cast<Instruction>(U)->getParent() == BB;
2001 }) > 2;
2004 if (isTailCall) {
2005 // Check if it's really possible to do a tail call.
2006 isTailCall = IsEligibleForTailCallOptimization(
2007 Callee, CallConv, isVarArg, isStructRet,
2008 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2009 PreferIndirect);
2010 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
2011 report_fatal_error("failed to perform tail call elimination on a call "
2012 "site marked musttail");
2013 // We don't support GuaranteedTailCallOpt for ARM, only automatically
2014 // detected sibcalls.
2015 if (isTailCall)
2016 ++NumTailCalls;
2019 // Analyze operands of the call, assigning locations to each operand.
2020 SmallVector<CCValAssign, 16> ArgLocs;
2021 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2022 *DAG.getContext());
2023 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2025 // Get a count of how many bytes are to be pushed on the stack.
2026 unsigned NumBytes = CCInfo.getNextStackOffset();
2028 if (isTailCall) {
2029 // For tail calls, memory operands are available in our caller's stack.
2030 NumBytes = 0;
2031 } else {
2032 // Adjust the stack pointer for the new arguments...
2033 // These operations are automatically eliminated by the prolog/epilog pass
2034 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
2037 SDValue StackPtr =
2038 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2040 RegsToPassVector RegsToPass;
2041 SmallVector<SDValue, 8> MemOpChains;
2043 // Walk the register/memloc assignments, inserting copies/loads. In the case
2044 // of tail call optimization, arguments are handled later.
2045 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2046 i != e;
2047 ++i, ++realArgIdx) {
2048 CCValAssign &VA = ArgLocs[i];
2049 SDValue Arg = OutVals[realArgIdx];
2050 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2051 bool isByVal = Flags.isByVal();
2053 // Promote the value if needed.
2054 switch (VA.getLocInfo()) {
2055 default: llvm_unreachable("Unknown loc info!");
2056 case CCValAssign::Full: break;
2057 case CCValAssign::SExt:
2058 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2059 break;
2060 case CCValAssign::ZExt:
2061 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2062 break;
2063 case CCValAssign::AExt:
2064 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2065 break;
2066 case CCValAssign::BCvt:
2067 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2068 break;
2071 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2072 if (VA.needsCustom()) {
2073 if (VA.getLocVT() == MVT::v2f64) {
2074 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2075 DAG.getConstant(0, dl, MVT::i32));
2076 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2077 DAG.getConstant(1, dl, MVT::i32));
2079 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
2080 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2082 VA = ArgLocs[++i]; // skip ahead to next loc
2083 if (VA.isRegLoc()) {
2084 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
2085 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2086 } else {
2087 assert(VA.isMemLoc());
2089 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
2090 dl, DAG, VA, Flags));
2092 } else {
2093 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2094 StackPtr, MemOpChains, Flags);
2096 } else if (VA.isRegLoc()) {
2097 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2098 Outs[0].VT == MVT::i32) {
2099 assert(VA.getLocVT() == MVT::i32 &&
2100 "unexpected calling convention register assignment");
2101 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2102 "unexpected use of 'returned'");
2103 isThisReturn = true;
2105 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2106 } else if (isByVal) {
2107 assert(VA.isMemLoc());
2108 unsigned offset = 0;
2110 // True if this byval aggregate will be split between registers
2111 // and memory.
2112 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2113 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2115 if (CurByValIdx < ByValArgsCount) {
2117 unsigned RegBegin, RegEnd;
2118 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2120 EVT PtrVT =
2121 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2122 unsigned int i, j;
2123 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2124 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2125 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2126 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
2127 MachinePointerInfo(),
2128 DAG.InferPtrAlignment(AddArg));
2129 MemOpChains.push_back(Load.getValue(1));
2130 RegsToPass.push_back(std::make_pair(j, Load));
2133 // If parameter size outsides register area, "offset" value
2134 // helps us to calculate stack slot for remained part properly.
2135 offset = RegEnd - RegBegin;
2137 CCInfo.nextInRegsParam();
2140 if (Flags.getByValSize() > 4*offset) {
2141 auto PtrVT = getPointerTy(DAG.getDataLayout());
2142 unsigned LocMemOffset = VA.getLocMemOffset();
2143 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2144 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
2145 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2146 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2147 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2148 MVT::i32);
2149 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
2150 MVT::i32);
2152 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2153 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2154 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2155 Ops));
2157 } else if (!isTailCall) {
2158 assert(VA.isMemLoc());
2160 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2161 dl, DAG, VA, Flags));
2165 if (!MemOpChains.empty())
2166 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2168 // Build a sequence of copy-to-reg nodes chained together with token chain
2169 // and flag operands which copy the outgoing args into the appropriate regs.
2170 SDValue InFlag;
2171 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2172 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2173 RegsToPass[i].second, InFlag);
2174 InFlag = Chain.getValue(1);
2177 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2178 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2179 // node so that legalize doesn't hack it.
2180 bool isDirect = false;
2182 const TargetMachine &TM = getTargetMachine();
2183 const Module *Mod = MF.getFunction().getParent();
2184 const GlobalValue *GV = nullptr;
2185 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2186 GV = G->getGlobal();
2187 bool isStub =
2188 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2190 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2191 bool isLocalARMFunc = false;
2192 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2193 auto PtrVt = getPointerTy(DAG.getDataLayout());
2195 if (Subtarget->genLongCalls()) {
2196 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2197 "long-calls codegen is not position independent!");
2198 // Handle a global address or an external symbol. If it's not one of
2199 // those, the target's already in a register, so we don't need to do
2200 // anything extra.
2201 if (isa<GlobalAddressSDNode>(Callee)) {
2202 // Create a constant pool entry for the callee address
2203 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2204 ARMConstantPoolValue *CPV =
2205 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2207 // Get the address of the callee into a register
2208 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2209 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2210 Callee = DAG.getLoad(
2211 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2212 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2213 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2214 const char *Sym = S->getSymbol();
2216 // Create a constant pool entry for the callee address
2217 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2218 ARMConstantPoolValue *CPV =
2219 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2220 ARMPCLabelIndex, 0);
2221 // Get the address of the callee into a register
2222 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2223 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2224 Callee = DAG.getLoad(
2225 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2226 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2228 } else if (isa<GlobalAddressSDNode>(Callee)) {
2229 if (!PreferIndirect) {
2230 isDirect = true;
2231 bool isDef = GV->isStrongDefinitionForLinker();
2233 // ARM call to a local ARM function is predicable.
2234 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2235 // tBX takes a register source operand.
2236 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2237 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2238 Callee = DAG.getNode(
2239 ARMISD::WrapperPIC, dl, PtrVt,
2240 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2241 Callee = DAG.getLoad(
2242 PtrVt, dl, DAG.getEntryNode(), Callee,
2243 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2244 /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2245 MachineMemOperand::MOInvariant);
2246 } else if (Subtarget->isTargetCOFF()) {
2247 assert(Subtarget->isTargetWindows() &&
2248 "Windows is the only supported COFF target");
2249 unsigned TargetFlags = GV->hasDLLImportStorageClass()
2250 ? ARMII::MO_DLLIMPORT
2251 : ARMII::MO_NO_FLAG;
2252 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2253 TargetFlags);
2254 if (GV->hasDLLImportStorageClass())
2255 Callee =
2256 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2257 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2258 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2259 } else {
2260 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2263 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2264 isDirect = true;
2265 // tBX takes a register source operand.
2266 const char *Sym = S->getSymbol();
2267 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2268 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2269 ARMConstantPoolValue *CPV =
2270 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2271 ARMPCLabelIndex, 4);
2272 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2273 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2274 Callee = DAG.getLoad(
2275 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2276 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2277 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2278 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2279 } else {
2280 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2284 // FIXME: handle tail calls differently.
2285 unsigned CallOpc;
2286 if (Subtarget->isThumb()) {
2287 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2288 CallOpc = ARMISD::CALL_NOLINK;
2289 else
2290 CallOpc = ARMISD::CALL;
2291 } else {
2292 if (!isDirect && !Subtarget->hasV5TOps())
2293 CallOpc = ARMISD::CALL_NOLINK;
2294 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2295 // Emit regular call when code size is the priority
2296 !Subtarget->hasMinSize())
2297 // "mov lr, pc; b _foo" to avoid confusing the RSP
2298 CallOpc = ARMISD::CALL_NOLINK;
2299 else
2300 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2303 std::vector<SDValue> Ops;
2304 Ops.push_back(Chain);
2305 Ops.push_back(Callee);
2307 // Add argument registers to the end of the list so that they are known live
2308 // into the call.
2309 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2310 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2311 RegsToPass[i].second.getValueType()));
2313 // Add a register mask operand representing the call-preserved registers.
2314 if (!isTailCall) {
2315 const uint32_t *Mask;
2316 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2317 if (isThisReturn) {
2318 // For 'this' returns, use the R0-preserving mask if applicable
2319 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2320 if (!Mask) {
2321 // Set isThisReturn to false if the calling convention is not one that
2322 // allows 'returned' to be modeled in this way, so LowerCallResult does
2323 // not try to pass 'this' straight through
2324 isThisReturn = false;
2325 Mask = ARI->getCallPreservedMask(MF, CallConv);
2327 } else
2328 Mask = ARI->getCallPreservedMask(MF, CallConv);
2330 assert(Mask && "Missing call preserved mask for calling convention");
2331 Ops.push_back(DAG.getRegisterMask(Mask));
2334 if (InFlag.getNode())
2335 Ops.push_back(InFlag);
2337 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2338 if (isTailCall) {
2339 MF.getFrameInfo().setHasTailCall();
2340 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2343 // Returns a chain and a flag for retval copy to use.
2344 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2345 InFlag = Chain.getValue(1);
2347 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2348 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2349 if (!Ins.empty())
2350 InFlag = Chain.getValue(1);
2352 // Handle result values, copying them out of physregs into vregs that we
2353 // return.
2354 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2355 InVals, isThisReturn,
2356 isThisReturn ? OutVals[0] : SDValue());
2359 /// HandleByVal - Every parameter *after* a byval parameter is passed
2360 /// on the stack. Remember the next parameter register to allocate,
2361 /// and then confiscate the rest of the parameter registers to insure
2362 /// this.
2363 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2364 unsigned Align) const {
2365 // Byval (as with any stack) slots are always at least 4 byte aligned.
2366 Align = std::max(Align, 4U);
2368 unsigned Reg = State->AllocateReg(GPRArgRegs);
2369 if (!Reg)
2370 return;
2372 unsigned AlignInRegs = Align / 4;
2373 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2374 for (unsigned i = 0; i < Waste; ++i)
2375 Reg = State->AllocateReg(GPRArgRegs);
2377 if (!Reg)
2378 return;
2380 unsigned Excess = 4 * (ARM::R4 - Reg);
2382 // Special case when NSAA != SP and parameter size greater than size of
2383 // all remained GPR regs. In that case we can't split parameter, we must
2384 // send it to stack. We also must set NCRN to R4, so waste all
2385 // remained registers.
2386 const unsigned NSAAOffset = State->getNextStackOffset();
2387 if (NSAAOffset != 0 && Size > Excess) {
2388 while (State->AllocateReg(GPRArgRegs))
2390 return;
2393 // First register for byval parameter is the first register that wasn't
2394 // allocated before this method call, so it would be "reg".
2395 // If parameter is small enough to be saved in range [reg, r4), then
2396 // the end (first after last) register would be reg + param-size-in-regs,
2397 // else parameter would be splitted between registers and stack,
2398 // end register would be r4 in this case.
2399 unsigned ByValRegBegin = Reg;
2400 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2401 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2402 // Note, first register is allocated in the beginning of function already,
2403 // allocate remained amount of registers we need.
2404 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2405 State->AllocateReg(GPRArgRegs);
2406 // A byval parameter that is split between registers and memory needs its
2407 // size truncated here.
2408 // In the case where the entire structure fits in registers, we set the
2409 // size in memory to zero.
2410 Size = std::max<int>(Size - Excess, 0);
2413 /// MatchingStackOffset - Return true if the given stack call argument is
2414 /// already available in the same position (relatively) of the caller's
2415 /// incoming argument stack.
2416 static
2417 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2418 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2419 const TargetInstrInfo *TII) {
2420 unsigned Bytes = Arg.getValueSizeInBits() / 8;
2421 int FI = std::numeric_limits<int>::max();
2422 if (Arg.getOpcode() == ISD::CopyFromReg) {
2423 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2424 if (!TargetRegisterInfo::isVirtualRegister(VR))
2425 return false;
2426 MachineInstr *Def = MRI->getVRegDef(VR);
2427 if (!Def)
2428 return false;
2429 if (!Flags.isByVal()) {
2430 if (!TII->isLoadFromStackSlot(*Def, FI))
2431 return false;
2432 } else {
2433 return false;
2435 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2436 if (Flags.isByVal())
2437 // ByVal argument is passed in as a pointer but it's now being
2438 // dereferenced. e.g.
2439 // define @foo(%struct.X* %A) {
2440 // tail call @bar(%struct.X* byval %A)
2441 // }
2442 return false;
2443 SDValue Ptr = Ld->getBasePtr();
2444 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2445 if (!FINode)
2446 return false;
2447 FI = FINode->getIndex();
2448 } else
2449 return false;
2451 assert(FI != std::numeric_limits<int>::max());
2452 if (!MFI.isFixedObjectIndex(FI))
2453 return false;
2454 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2457 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2458 /// for tail call optimization. Targets which want to do tail call
2459 /// optimization should implement this function.
2460 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2461 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2462 bool isCalleeStructRet, bool isCallerStructRet,
2463 const SmallVectorImpl<ISD::OutputArg> &Outs,
2464 const SmallVectorImpl<SDValue> &OutVals,
2465 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2466 const bool isIndirect) const {
2467 MachineFunction &MF = DAG.getMachineFunction();
2468 const Function &CallerF = MF.getFunction();
2469 CallingConv::ID CallerCC = CallerF.getCallingConv();
2471 assert(Subtarget->supportsTailCall());
2473 // Indirect tail calls cannot be optimized for Thumb1 if the args
2474 // to the call take up r0-r3. The reason is that there are no legal registers
2475 // left to hold the pointer to the function to be called.
2476 if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2477 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2478 return false;
2480 // Look for obvious safe cases to perform tail call optimization that do not
2481 // require ABI changes. This is what gcc calls sibcall.
2483 // Exception-handling functions need a special set of instructions to indicate
2484 // a return to the hardware. Tail-calling another function would probably
2485 // break this.
2486 if (CallerF.hasFnAttribute("interrupt"))
2487 return false;
2489 // Also avoid sibcall optimization if either caller or callee uses struct
2490 // return semantics.
2491 if (isCalleeStructRet || isCallerStructRet)
2492 return false;
2494 // Externally-defined functions with weak linkage should not be
2495 // tail-called on ARM when the OS does not support dynamic
2496 // pre-emption of symbols, as the AAELF spec requires normal calls
2497 // to undefined weak functions to be replaced with a NOP or jump to the
2498 // next instruction. The behaviour of branch instructions in this
2499 // situation (as used for tail calls) is implementation-defined, so we
2500 // cannot rely on the linker replacing the tail call with a return.
2501 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2502 const GlobalValue *GV = G->getGlobal();
2503 const Triple &TT = getTargetMachine().getTargetTriple();
2504 if (GV->hasExternalWeakLinkage() &&
2505 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2506 return false;
2509 // Check that the call results are passed in the same way.
2510 LLVMContext &C = *DAG.getContext();
2511 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2512 CCAssignFnForReturn(CalleeCC, isVarArg),
2513 CCAssignFnForReturn(CallerCC, isVarArg)))
2514 return false;
2515 // The callee has to preserve all registers the caller needs to preserve.
2516 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2517 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2518 if (CalleeCC != CallerCC) {
2519 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2520 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2521 return false;
2524 // If Caller's vararg or byval argument has been split between registers and
2525 // stack, do not perform tail call, since part of the argument is in caller's
2526 // local frame.
2527 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2528 if (AFI_Caller->getArgRegsSaveSize())
2529 return false;
2531 // If the callee takes no arguments then go on to check the results of the
2532 // call.
2533 if (!Outs.empty()) {
2534 // Check if stack adjustment is needed. For now, do not do this if any
2535 // argument is passed on the stack.
2536 SmallVector<CCValAssign, 16> ArgLocs;
2537 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2538 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2539 if (CCInfo.getNextStackOffset()) {
2540 // Check if the arguments are already laid out in the right way as
2541 // the caller's fixed stack objects.
2542 MachineFrameInfo &MFI = MF.getFrameInfo();
2543 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2544 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2545 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2546 i != e;
2547 ++i, ++realArgIdx) {
2548 CCValAssign &VA = ArgLocs[i];
2549 EVT RegVT = VA.getLocVT();
2550 SDValue Arg = OutVals[realArgIdx];
2551 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2552 if (VA.getLocInfo() == CCValAssign::Indirect)
2553 return false;
2554 if (VA.needsCustom()) {
2555 // f64 and vector types are split into multiple registers or
2556 // register/stack-slot combinations. The types will not match
2557 // the registers; give up on memory f64 refs until we figure
2558 // out what to do about this.
2559 if (!VA.isRegLoc())
2560 return false;
2561 if (!ArgLocs[++i].isRegLoc())
2562 return false;
2563 if (RegVT == MVT::v2f64) {
2564 if (!ArgLocs[++i].isRegLoc())
2565 return false;
2566 if (!ArgLocs[++i].isRegLoc())
2567 return false;
2569 } else if (!VA.isRegLoc()) {
2570 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2571 MFI, MRI, TII))
2572 return false;
2577 const MachineRegisterInfo &MRI = MF.getRegInfo();
2578 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2579 return false;
2582 return true;
2585 bool
2586 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2587 MachineFunction &MF, bool isVarArg,
2588 const SmallVectorImpl<ISD::OutputArg> &Outs,
2589 LLVMContext &Context) const {
2590 SmallVector<CCValAssign, 16> RVLocs;
2591 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2592 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2595 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2596 const SDLoc &DL, SelectionDAG &DAG) {
2597 const MachineFunction &MF = DAG.getMachineFunction();
2598 const Function &F = MF.getFunction();
2600 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2602 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2603 // version of the "preferred return address". These offsets affect the return
2604 // instruction if this is a return from PL1 without hypervisor extensions.
2605 // IRQ/FIQ: +4 "subs pc, lr, #4"
2606 // SWI: 0 "subs pc, lr, #0"
2607 // ABORT: +4 "subs pc, lr, #4"
2608 // UNDEF: +4/+2 "subs pc, lr, #0"
2609 // UNDEF varies depending on where the exception came from ARM or Thumb
2610 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2612 int64_t LROffset;
2613 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2614 IntKind == "ABORT")
2615 LROffset = 4;
2616 else if (IntKind == "SWI" || IntKind == "UNDEF")
2617 LROffset = 0;
2618 else
2619 report_fatal_error("Unsupported interrupt attribute. If present, value "
2620 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2622 RetOps.insert(RetOps.begin() + 1,
2623 DAG.getConstant(LROffset, DL, MVT::i32, false));
2625 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2628 SDValue
2629 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2630 bool isVarArg,
2631 const SmallVectorImpl<ISD::OutputArg> &Outs,
2632 const SmallVectorImpl<SDValue> &OutVals,
2633 const SDLoc &dl, SelectionDAG &DAG) const {
2634 // CCValAssign - represent the assignment of the return value to a location.
2635 SmallVector<CCValAssign, 16> RVLocs;
2637 // CCState - Info about the registers and stack slots.
2638 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2639 *DAG.getContext());
2641 // Analyze outgoing return values.
2642 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2644 SDValue Flag;
2645 SmallVector<SDValue, 4> RetOps;
2646 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2647 bool isLittleEndian = Subtarget->isLittle();
2649 MachineFunction &MF = DAG.getMachineFunction();
2650 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2651 AFI->setReturnRegsCount(RVLocs.size());
2653 // Copy the result values into the output registers.
2654 for (unsigned i = 0, realRVLocIdx = 0;
2655 i != RVLocs.size();
2656 ++i, ++realRVLocIdx) {
2657 CCValAssign &VA = RVLocs[i];
2658 assert(VA.isRegLoc() && "Can only return in registers!");
2660 SDValue Arg = OutVals[realRVLocIdx];
2661 bool ReturnF16 = false;
2663 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2664 // Half-precision return values can be returned like this:
2666 // t11 f16 = fadd ...
2667 // t12: i16 = bitcast t11
2668 // t13: i32 = zero_extend t12
2669 // t14: f32 = bitcast t13 <~~~~~~~ Arg
2671 // to avoid code generation for bitcasts, we simply set Arg to the node
2672 // that produces the f16 value, t11 in this case.
2674 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2675 SDValue ZE = Arg.getOperand(0);
2676 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2677 SDValue BC = ZE.getOperand(0);
2678 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2679 Arg = BC.getOperand(0);
2680 ReturnF16 = true;
2686 switch (VA.getLocInfo()) {
2687 default: llvm_unreachable("Unknown loc info!");
2688 case CCValAssign::Full: break;
2689 case CCValAssign::BCvt:
2690 if (!ReturnF16)
2691 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2692 break;
2695 if (VA.needsCustom()) {
2696 if (VA.getLocVT() == MVT::v2f64) {
2697 // Extract the first half and return it in two registers.
2698 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2699 DAG.getConstant(0, dl, MVT::i32));
2700 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2701 DAG.getVTList(MVT::i32, MVT::i32), Half);
2703 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2704 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2705 Flag);
2706 Flag = Chain.getValue(1);
2707 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2708 VA = RVLocs[++i]; // skip ahead to next loc
2709 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2710 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2711 Flag);
2712 Flag = Chain.getValue(1);
2713 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2714 VA = RVLocs[++i]; // skip ahead to next loc
2716 // Extract the 2nd half and fall through to handle it as an f64 value.
2717 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2718 DAG.getConstant(1, dl, MVT::i32));
2720 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2721 // available.
2722 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2723 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2724 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2725 fmrrd.getValue(isLittleEndian ? 0 : 1),
2726 Flag);
2727 Flag = Chain.getValue(1);
2728 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2729 VA = RVLocs[++i]; // skip ahead to next loc
2730 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2731 fmrrd.getValue(isLittleEndian ? 1 : 0),
2732 Flag);
2733 } else
2734 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2736 // Guarantee that all emitted copies are
2737 // stuck together, avoiding something bad.
2738 Flag = Chain.getValue(1);
2739 RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2740 ReturnF16 ? MVT::f16 : VA.getLocVT()));
2742 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2743 const MCPhysReg *I =
2744 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2745 if (I) {
2746 for (; *I; ++I) {
2747 if (ARM::GPRRegClass.contains(*I))
2748 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2749 else if (ARM::DPRRegClass.contains(*I))
2750 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2751 else
2752 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2756 // Update chain and glue.
2757 RetOps[0] = Chain;
2758 if (Flag.getNode())
2759 RetOps.push_back(Flag);
2761 // CPUs which aren't M-class use a special sequence to return from
2762 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2763 // though we use "subs pc, lr, #N").
2765 // M-class CPUs actually use a normal return sequence with a special
2766 // (hardware-provided) value in LR, so the normal code path works.
2767 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2768 !Subtarget->isMClass()) {
2769 if (Subtarget->isThumb1Only())
2770 report_fatal_error("interrupt attribute is not supported in Thumb1");
2771 return LowerInterruptReturn(RetOps, dl, DAG);
2774 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2777 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2778 if (N->getNumValues() != 1)
2779 return false;
2780 if (!N->hasNUsesOfValue(1, 0))
2781 return false;
2783 SDValue TCChain = Chain;
2784 SDNode *Copy = *N->use_begin();
2785 if (Copy->getOpcode() == ISD::CopyToReg) {
2786 // If the copy has a glue operand, we conservatively assume it isn't safe to
2787 // perform a tail call.
2788 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2789 return false;
2790 TCChain = Copy->getOperand(0);
2791 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2792 SDNode *VMov = Copy;
2793 // f64 returned in a pair of GPRs.
2794 SmallPtrSet<SDNode*, 2> Copies;
2795 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2796 UI != UE; ++UI) {
2797 if (UI->getOpcode() != ISD::CopyToReg)
2798 return false;
2799 Copies.insert(*UI);
2801 if (Copies.size() > 2)
2802 return false;
2804 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2805 UI != UE; ++UI) {
2806 SDValue UseChain = UI->getOperand(0);
2807 if (Copies.count(UseChain.getNode()))
2808 // Second CopyToReg
2809 Copy = *UI;
2810 else {
2811 // We are at the top of this chain.
2812 // If the copy has a glue operand, we conservatively assume it
2813 // isn't safe to perform a tail call.
2814 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2815 return false;
2816 // First CopyToReg
2817 TCChain = UseChain;
2820 } else if (Copy->getOpcode() == ISD::BITCAST) {
2821 // f32 returned in a single GPR.
2822 if (!Copy->hasOneUse())
2823 return false;
2824 Copy = *Copy->use_begin();
2825 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2826 return false;
2827 // If the copy has a glue operand, we conservatively assume it isn't safe to
2828 // perform a tail call.
2829 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2830 return false;
2831 TCChain = Copy->getOperand(0);
2832 } else {
2833 return false;
2836 bool HasRet = false;
2837 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2838 UI != UE; ++UI) {
2839 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2840 UI->getOpcode() != ARMISD::INTRET_FLAG)
2841 return false;
2842 HasRet = true;
2845 if (!HasRet)
2846 return false;
2848 Chain = TCChain;
2849 return true;
2852 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2853 if (!Subtarget->supportsTailCall())
2854 return false;
2856 auto Attr =
2857 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2858 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2859 return false;
2861 return true;
2864 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2865 // and pass the lower and high parts through.
2866 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2867 SDLoc DL(Op);
2868 SDValue WriteValue = Op->getOperand(2);
2870 // This function is only supposed to be called for i64 type argument.
2871 assert(WriteValue.getValueType() == MVT::i64
2872 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2874 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2875 DAG.getConstant(0, DL, MVT::i32));
2876 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2877 DAG.getConstant(1, DL, MVT::i32));
2878 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2879 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2882 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2883 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2884 // one of the above mentioned nodes. It has to be wrapped because otherwise
2885 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2886 // be used to form addressing mode. These wrapped nodes will be selected
2887 // into MOVi.
2888 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2889 SelectionDAG &DAG) const {
2890 EVT PtrVT = Op.getValueType();
2891 // FIXME there is no actual debug info here
2892 SDLoc dl(Op);
2893 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2894 SDValue Res;
2896 // When generating execute-only code Constant Pools must be promoted to the
2897 // global data section. It's a bit ugly that we can't share them across basic
2898 // blocks, but this way we guarantee that execute-only behaves correct with
2899 // position-independent addressing modes.
2900 if (Subtarget->genExecuteOnly()) {
2901 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2902 auto T = const_cast<Type*>(CP->getType());
2903 auto C = const_cast<Constant*>(CP->getConstVal());
2904 auto M = const_cast<Module*>(DAG.getMachineFunction().
2905 getFunction().getParent());
2906 auto GV = new GlobalVariable(
2907 *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C,
2908 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2909 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2910 Twine(AFI->createPICLabelUId())
2912 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2913 dl, PtrVT);
2914 return LowerGlobalAddress(GA, DAG);
2917 if (CP->isMachineConstantPoolEntry())
2918 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2919 CP->getAlignment());
2920 else
2921 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2922 CP->getAlignment());
2923 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2926 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2927 return MachineJumpTableInfo::EK_Inline;
2930 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2931 SelectionDAG &DAG) const {
2932 MachineFunction &MF = DAG.getMachineFunction();
2933 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2934 unsigned ARMPCLabelIndex = 0;
2935 SDLoc DL(Op);
2936 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2937 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2938 SDValue CPAddr;
2939 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2940 if (!IsPositionIndependent) {
2941 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2942 } else {
2943 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2944 ARMPCLabelIndex = AFI->createPICLabelUId();
2945 ARMConstantPoolValue *CPV =
2946 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2947 ARMCP::CPBlockAddress, PCAdj);
2948 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2950 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2951 SDValue Result = DAG.getLoad(
2952 PtrVT, DL, DAG.getEntryNode(), CPAddr,
2953 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2954 if (!IsPositionIndependent)
2955 return Result;
2956 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2957 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2960 /// Convert a TLS address reference into the correct sequence of loads
2961 /// and calls to compute the variable's address for Darwin, and return an
2962 /// SDValue containing the final node.
2964 /// Darwin only has one TLS scheme which must be capable of dealing with the
2965 /// fully general situation, in the worst case. This means:
2966 /// + "extern __thread" declaration.
2967 /// + Defined in a possibly unknown dynamic library.
2969 /// The general system is that each __thread variable has a [3 x i32] descriptor
2970 /// which contains information used by the runtime to calculate the address. The
2971 /// only part of this the compiler needs to know about is the first word, which
2972 /// contains a function pointer that must be called with the address of the
2973 /// entire descriptor in "r0".
2975 /// Since this descriptor may be in a different unit, in general access must
2976 /// proceed along the usual ARM rules. A common sequence to produce is:
2978 /// movw rT1, :lower16:_var$non_lazy_ptr
2979 /// movt rT1, :upper16:_var$non_lazy_ptr
2980 /// ldr r0, [rT1]
2981 /// ldr rT2, [r0]
2982 /// blx rT2
2983 /// [...address now in r0...]
2984 SDValue
2985 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2986 SelectionDAG &DAG) const {
2987 assert(Subtarget->isTargetDarwin() &&
2988 "This function expects a Darwin target");
2989 SDLoc DL(Op);
2991 // First step is to get the address of the actua global symbol. This is where
2992 // the TLS descriptor lives.
2993 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2995 // The first entry in the descriptor is a function pointer that we must call
2996 // to obtain the address of the variable.
2997 SDValue Chain = DAG.getEntryNode();
2998 SDValue FuncTLVGet = DAG.getLoad(
2999 MVT::i32, DL, Chain, DescAddr,
3000 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3001 /* Alignment = */ 4,
3002 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3003 MachineMemOperand::MOInvariant);
3004 Chain = FuncTLVGet.getValue(1);
3006 MachineFunction &F = DAG.getMachineFunction();
3007 MachineFrameInfo &MFI = F.getFrameInfo();
3008 MFI.setAdjustsStack(true);
3010 // TLS calls preserve all registers except those that absolutely must be
3011 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3012 // silly).
3013 auto TRI =
3014 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3015 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3016 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3018 // Finally, we can make the call. This is just a degenerate version of a
3019 // normal AArch64 call node: r0 takes the address of the descriptor, and
3020 // returns the address of the variable in this thread.
3021 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3022 Chain =
3023 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3024 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3025 DAG.getRegisterMask(Mask), Chain.getValue(1));
3026 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3029 SDValue
3030 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3031 SelectionDAG &DAG) const {
3032 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
3034 SDValue Chain = DAG.getEntryNode();
3035 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3036 SDLoc DL(Op);
3038 // Load the current TEB (thread environment block)
3039 SDValue Ops[] = {Chain,
3040 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3041 DAG.getConstant(15, DL, MVT::i32),
3042 DAG.getConstant(0, DL, MVT::i32),
3043 DAG.getConstant(13, DL, MVT::i32),
3044 DAG.getConstant(0, DL, MVT::i32),
3045 DAG.getConstant(2, DL, MVT::i32)};
3046 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3047 DAG.getVTList(MVT::i32, MVT::Other), Ops);
3049 SDValue TEB = CurrentTEB.getValue(0);
3050 Chain = CurrentTEB.getValue(1);
3052 // Load the ThreadLocalStoragePointer from the TEB
3053 // A pointer to the TLS array is located at offset 0x2c from the TEB.
3054 SDValue TLSArray =
3055 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3056 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3058 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3059 // offset into the TLSArray.
3061 // Load the TLS index from the C runtime
3062 SDValue TLSIndex =
3063 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3064 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3065 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3067 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3068 DAG.getConstant(2, DL, MVT::i32));
3069 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3070 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3071 MachinePointerInfo());
3073 // Get the offset of the start of the .tls section (section base)
3074 const auto *GA = cast<GlobalAddressSDNode>(Op);
3075 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3076 SDValue Offset = DAG.getLoad(
3077 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3078 DAG.getTargetConstantPool(CPV, PtrVT, 4)),
3079 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3081 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3084 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3085 SDValue
3086 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3087 SelectionDAG &DAG) const {
3088 SDLoc dl(GA);
3089 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3090 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3091 MachineFunction &MF = DAG.getMachineFunction();
3092 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3093 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3094 ARMConstantPoolValue *CPV =
3095 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3096 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3097 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3098 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3099 Argument = DAG.getLoad(
3100 PtrVT, dl, DAG.getEntryNode(), Argument,
3101 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3102 SDValue Chain = Argument.getValue(1);
3104 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3105 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3107 // call __tls_get_addr.
3108 ArgListTy Args;
3109 ArgListEntry Entry;
3110 Entry.Node = Argument;
3111 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3112 Args.push_back(Entry);
3114 // FIXME: is there useful debug info available here?
3115 TargetLowering::CallLoweringInfo CLI(DAG);
3116 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3117 CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3118 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3120 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3121 return CallResult.first;
3124 // Lower ISD::GlobalTLSAddress using the "initial exec" or
3125 // "local exec" model.
3126 SDValue
3127 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3128 SelectionDAG &DAG,
3129 TLSModel::Model model) const {
3130 const GlobalValue *GV = GA->getGlobal();
3131 SDLoc dl(GA);
3132 SDValue Offset;
3133 SDValue Chain = DAG.getEntryNode();
3134 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3135 // Get the Thread Pointer
3136 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3138 if (model == TLSModel::InitialExec) {
3139 MachineFunction &MF = DAG.getMachineFunction();
3140 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3141 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3142 // Initial exec model.
3143 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3144 ARMConstantPoolValue *CPV =
3145 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3146 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3147 true);
3148 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3149 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3150 Offset = DAG.getLoad(
3151 PtrVT, dl, Chain, Offset,
3152 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3153 Chain = Offset.getValue(1);
3155 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3156 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3158 Offset = DAG.getLoad(
3159 PtrVT, dl, Chain, Offset,
3160 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3161 } else {
3162 // local exec model
3163 assert(model == TLSModel::LocalExec);
3164 ARMConstantPoolValue *CPV =
3165 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3166 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3167 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3168 Offset = DAG.getLoad(
3169 PtrVT, dl, Chain, Offset,
3170 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3173 // The address of the thread local variable is the add of the thread
3174 // pointer with the offset of the variable.
3175 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3178 SDValue
3179 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3180 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3181 if (DAG.getTarget().useEmulatedTLS())
3182 return LowerToTLSEmulatedModel(GA, DAG);
3184 if (Subtarget->isTargetDarwin())
3185 return LowerGlobalTLSAddressDarwin(Op, DAG);
3187 if (Subtarget->isTargetWindows())
3188 return LowerGlobalTLSAddressWindows(Op, DAG);
3190 // TODO: implement the "local dynamic" model
3191 assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3192 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3194 switch (model) {
3195 case TLSModel::GeneralDynamic:
3196 case TLSModel::LocalDynamic:
3197 return LowerToTLSGeneralDynamicModel(GA, DAG);
3198 case TLSModel::InitialExec:
3199 case TLSModel::LocalExec:
3200 return LowerToTLSExecModels(GA, DAG, model);
3202 llvm_unreachable("bogus TLS model");
3205 /// Return true if all users of V are within function F, looking through
3206 /// ConstantExprs.
3207 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3208 SmallVector<const User*,4> Worklist;
3209 for (auto *U : V->users())
3210 Worklist.push_back(U);
3211 while (!Worklist.empty()) {
3212 auto *U = Worklist.pop_back_val();
3213 if (isa<ConstantExpr>(U)) {
3214 for (auto *UU : U->users())
3215 Worklist.push_back(UU);
3216 continue;
3219 auto *I = dyn_cast<Instruction>(U);
3220 if (!I || I->getParent()->getParent() != F)
3221 return false;
3223 return true;
3226 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3227 const GlobalValue *GV, SelectionDAG &DAG,
3228 EVT PtrVT, const SDLoc &dl) {
3229 // If we're creating a pool entry for a constant global with unnamed address,
3230 // and the global is small enough, we can emit it inline into the constant pool
3231 // to save ourselves an indirection.
3233 // This is a win if the constant is only used in one function (so it doesn't
3234 // need to be duplicated) or duplicating the constant wouldn't increase code
3235 // size (implying the constant is no larger than 4 bytes).
3236 const Function &F = DAG.getMachineFunction().getFunction();
3238 // We rely on this decision to inline being idemopotent and unrelated to the
3239 // use-site. We know that if we inline a variable at one use site, we'll
3240 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3241 // doesn't know about this optimization, so bail out if it's enabled else
3242 // we could decide to inline here (and thus never emit the GV) but require
3243 // the GV from fast-isel generated code.
3244 if (!EnableConstpoolPromotion ||
3245 DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3246 return SDValue();
3248 auto *GVar = dyn_cast<GlobalVariable>(GV);
3249 if (!GVar || !GVar->hasInitializer() ||
3250 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3251 !GVar->hasLocalLinkage())
3252 return SDValue();
3254 // If we inline a value that contains relocations, we move the relocations
3255 // from .data to .text. This is not allowed in position-independent code.
3256 auto *Init = GVar->getInitializer();
3257 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3258 Init->needsRelocation())
3259 return SDValue();
3261 // The constant islands pass can only really deal with alignment requests
3262 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3263 // any type wanting greater alignment requirements than 4 bytes. We also
3264 // can only promote constants that are multiples of 4 bytes in size or
3265 // are paddable to a multiple of 4. Currently we only try and pad constants
3266 // that are strings for simplicity.
3267 auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3268 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3269 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar);
3270 unsigned RequiredPadding = 4 - (Size % 4);
3271 bool PaddingPossible =
3272 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3273 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3274 Size == 0)
3275 return SDValue();
3277 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3278 MachineFunction &MF = DAG.getMachineFunction();
3279 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3281 // We can't bloat the constant pool too much, else the ConstantIslands pass
3282 // may fail to converge. If we haven't promoted this global yet (it may have
3283 // multiple uses), and promoting it would increase the constant pool size (Sz
3284 // > 4), ensure we have space to do so up to MaxTotal.
3285 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3286 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3287 ConstpoolPromotionMaxTotal)
3288 return SDValue();
3290 // This is only valid if all users are in a single function; we can't clone
3291 // the constant in general. The LLVM IR unnamed_addr allows merging
3292 // constants, but not cloning them.
3294 // We could potentially allow cloning if we could prove all uses of the
3295 // constant in the current function don't care about the address, like
3296 // printf format strings. But that isn't implemented for now.
3297 if (!allUsersAreInFunction(GVar, &F))
3298 return SDValue();
3300 // We're going to inline this global. Pad it out if needed.
3301 if (RequiredPadding != 4) {
3302 StringRef S = CDAInit->getAsString();
3304 SmallVector<uint8_t,16> V(S.size());
3305 std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3306 while (RequiredPadding--)
3307 V.push_back(0);
3308 Init = ConstantDataArray::get(*DAG.getContext(), V);
3311 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3312 SDValue CPAddr =
3313 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3314 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3315 AFI->markGlobalAsPromotedToConstantPool(GVar);
3316 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3317 PaddedSize - 4);
3319 ++NumConstpoolPromoted;
3320 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3323 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3324 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3325 if (!(GV = GA->getBaseObject()))
3326 return false;
3327 if (const auto *V = dyn_cast<GlobalVariable>(GV))
3328 return V->isConstant();
3329 return isa<Function>(GV);
3332 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3333 SelectionDAG &DAG) const {
3334 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3335 default: llvm_unreachable("unknown object format");
3336 case Triple::COFF:
3337 return LowerGlobalAddressWindows(Op, DAG);
3338 case Triple::ELF:
3339 return LowerGlobalAddressELF(Op, DAG);
3340 case Triple::MachO:
3341 return LowerGlobalAddressDarwin(Op, DAG);
3345 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3346 SelectionDAG &DAG) const {
3347 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3348 SDLoc dl(Op);
3349 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3350 const TargetMachine &TM = getTargetMachine();
3351 bool IsRO = isReadOnly(GV);
3353 // promoteToConstantPool only if not generating XO text section
3354 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3355 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3356 return V;
3358 if (isPositionIndependent()) {
3359 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3360 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3361 UseGOT_PREL ? ARMII::MO_GOT : 0);
3362 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3363 if (UseGOT_PREL)
3364 Result =
3365 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3366 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3367 return Result;
3368 } else if (Subtarget->isROPI() && IsRO) {
3369 // PC-relative.
3370 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3371 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3372 return Result;
3373 } else if (Subtarget->isRWPI() && !IsRO) {
3374 // SB-relative.
3375 SDValue RelAddr;
3376 if (Subtarget->useMovt()) {
3377 ++NumMovwMovt;
3378 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3379 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3380 } else { // use literal pool for address constant
3381 ARMConstantPoolValue *CPV =
3382 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3383 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3384 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3385 RelAddr = DAG.getLoad(
3386 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3387 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3389 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3390 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3391 return Result;
3394 // If we have T2 ops, we can materialize the address directly via movt/movw
3395 // pair. This is always cheaper.
3396 if (Subtarget->useMovt()) {
3397 ++NumMovwMovt;
3398 // FIXME: Once remat is capable of dealing with instructions with register
3399 // operands, expand this into two nodes.
3400 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3401 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3402 } else {
3403 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3404 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3405 return DAG.getLoad(
3406 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3407 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3411 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3412 SelectionDAG &DAG) const {
3413 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3414 "ROPI/RWPI not currently supported for Darwin");
3415 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3416 SDLoc dl(Op);
3417 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3419 if (Subtarget->useMovt())
3420 ++NumMovwMovt;
3422 // FIXME: Once remat is capable of dealing with instructions with register
3423 // operands, expand this into multiple nodes
3424 unsigned Wrapper =
3425 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3427 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3428 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3430 if (Subtarget->isGVIndirectSymbol(GV))
3431 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3432 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3433 return Result;
3436 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3437 SelectionDAG &DAG) const {
3438 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3439 assert(Subtarget->useMovt() &&
3440 "Windows on ARM expects to use movw/movt");
3441 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3442 "ROPI/RWPI not currently supported for Windows");
3444 const TargetMachine &TM = getTargetMachine();
3445 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3446 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3447 if (GV->hasDLLImportStorageClass())
3448 TargetFlags = ARMII::MO_DLLIMPORT;
3449 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3450 TargetFlags = ARMII::MO_COFFSTUB;
3451 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3452 SDValue Result;
3453 SDLoc DL(Op);
3455 ++NumMovwMovt;
3457 // FIXME: Once remat is capable of dealing with instructions with register
3458 // operands, expand this into two nodes.
3459 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3460 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3461 TargetFlags));
3462 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3463 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3464 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3465 return Result;
3468 SDValue
3469 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3470 SDLoc dl(Op);
3471 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3472 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3473 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3474 Op.getOperand(1), Val);
3477 SDValue
3478 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3479 SDLoc dl(Op);
3480 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3481 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3484 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3485 SelectionDAG &DAG) const {
3486 SDLoc dl(Op);
3487 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3488 Op.getOperand(0));
3491 SDValue
3492 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3493 const ARMSubtarget *Subtarget) const {
3494 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3495 SDLoc dl(Op);
3496 switch (IntNo) {
3497 default: return SDValue(); // Don't custom lower most intrinsics.
3498 case Intrinsic::thread_pointer: {
3499 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3500 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3502 case Intrinsic::eh_sjlj_lsda: {
3503 MachineFunction &MF = DAG.getMachineFunction();
3504 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3505 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3506 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3507 SDValue CPAddr;
3508 bool IsPositionIndependent = isPositionIndependent();
3509 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3510 ARMConstantPoolValue *CPV =
3511 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3512 ARMCP::CPLSDA, PCAdj);
3513 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3514 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3515 SDValue Result = DAG.getLoad(
3516 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3517 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3519 if (IsPositionIndependent) {
3520 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3521 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3523 return Result;
3525 case Intrinsic::arm_neon_vabs:
3526 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3527 Op.getOperand(1));
3528 case Intrinsic::arm_neon_vmulls:
3529 case Intrinsic::arm_neon_vmullu: {
3530 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3531 ? ARMISD::VMULLs : ARMISD::VMULLu;
3532 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3533 Op.getOperand(1), Op.getOperand(2));
3535 case Intrinsic::arm_neon_vminnm:
3536 case Intrinsic::arm_neon_vmaxnm: {
3537 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3538 ? ISD::FMINNUM : ISD::FMAXNUM;
3539 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3540 Op.getOperand(1), Op.getOperand(2));
3542 case Intrinsic::arm_neon_vminu:
3543 case Intrinsic::arm_neon_vmaxu: {
3544 if (Op.getValueType().isFloatingPoint())
3545 return SDValue();
3546 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3547 ? ISD::UMIN : ISD::UMAX;
3548 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3549 Op.getOperand(1), Op.getOperand(2));
3551 case Intrinsic::arm_neon_vmins:
3552 case Intrinsic::arm_neon_vmaxs: {
3553 // v{min,max}s is overloaded between signed integers and floats.
3554 if (!Op.getValueType().isFloatingPoint()) {
3555 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3556 ? ISD::SMIN : ISD::SMAX;
3557 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3558 Op.getOperand(1), Op.getOperand(2));
3560 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3561 ? ISD::FMINIMUM : ISD::FMAXIMUM;
3562 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3563 Op.getOperand(1), Op.getOperand(2));
3565 case Intrinsic::arm_neon_vtbl1:
3566 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3567 Op.getOperand(1), Op.getOperand(2));
3568 case Intrinsic::arm_neon_vtbl2:
3569 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3570 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3574 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3575 const ARMSubtarget *Subtarget) {
3576 SDLoc dl(Op);
3577 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3578 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3579 if (SSID == SyncScope::SingleThread)
3580 return Op;
3582 if (!Subtarget->hasDataBarrier()) {
3583 // Some ARMv6 cpus can support data barriers with an mcr instruction.
3584 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3585 // here.
3586 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3587 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3588 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3589 DAG.getConstant(0, dl, MVT::i32));
3592 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3593 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3594 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3595 if (Subtarget->isMClass()) {
3596 // Only a full system barrier exists in the M-class architectures.
3597 Domain = ARM_MB::SY;
3598 } else if (Subtarget->preferISHSTBarriers() &&
3599 Ord == AtomicOrdering::Release) {
3600 // Swift happens to implement ISHST barriers in a way that's compatible with
3601 // Release semantics but weaker than ISH so we'd be fools not to use
3602 // it. Beware: other processors probably don't!
3603 Domain = ARM_MB::ISHST;
3606 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3607 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3608 DAG.getConstant(Domain, dl, MVT::i32));
3611 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3612 const ARMSubtarget *Subtarget) {
3613 // ARM pre v5TE and Thumb1 does not have preload instructions.
3614 if (!(Subtarget->isThumb2() ||
3615 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3616 // Just preserve the chain.
3617 return Op.getOperand(0);
3619 SDLoc dl(Op);
3620 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3621 if (!isRead &&
3622 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3623 // ARMv7 with MP extension has PLDW.
3624 return Op.getOperand(0);
3626 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3627 if (Subtarget->isThumb()) {
3628 // Invert the bits.
3629 isRead = ~isRead & 1;
3630 isData = ~isData & 1;
3633 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3634 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3635 DAG.getConstant(isData, dl, MVT::i32));
3638 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3639 MachineFunction &MF = DAG.getMachineFunction();
3640 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3642 // vastart just stores the address of the VarArgsFrameIndex slot into the
3643 // memory location argument.
3644 SDLoc dl(Op);
3645 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3646 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3647 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3648 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3649 MachinePointerInfo(SV));
3652 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3653 CCValAssign &NextVA,
3654 SDValue &Root,
3655 SelectionDAG &DAG,
3656 const SDLoc &dl) const {
3657 MachineFunction &MF = DAG.getMachineFunction();
3658 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3660 const TargetRegisterClass *RC;
3661 if (AFI->isThumb1OnlyFunction())
3662 RC = &ARM::tGPRRegClass;
3663 else
3664 RC = &ARM::GPRRegClass;
3666 // Transform the arguments stored in physical registers into virtual ones.
3667 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3668 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3670 SDValue ArgValue2;
3671 if (NextVA.isMemLoc()) {
3672 MachineFrameInfo &MFI = MF.getFrameInfo();
3673 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3675 // Create load node to retrieve arguments from the stack.
3676 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3677 ArgValue2 = DAG.getLoad(
3678 MVT::i32, dl, Root, FIN,
3679 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3680 } else {
3681 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3682 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3684 if (!Subtarget->isLittle())
3685 std::swap (ArgValue, ArgValue2);
3686 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3689 // The remaining GPRs hold either the beginning of variable-argument
3690 // data, or the beginning of an aggregate passed by value (usually
3691 // byval). Either way, we allocate stack slots adjacent to the data
3692 // provided by our caller, and store the unallocated registers there.
3693 // If this is a variadic function, the va_list pointer will begin with
3694 // these values; otherwise, this reassembles a (byval) structure that
3695 // was split between registers and memory.
3696 // Return: The frame index registers were stored into.
3697 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3698 const SDLoc &dl, SDValue &Chain,
3699 const Value *OrigArg,
3700 unsigned InRegsParamRecordIdx,
3701 int ArgOffset, unsigned ArgSize) const {
3702 // Currently, two use-cases possible:
3703 // Case #1. Non-var-args function, and we meet first byval parameter.
3704 // Setup first unallocated register as first byval register;
3705 // eat all remained registers
3706 // (these two actions are performed by HandleByVal method).
3707 // Then, here, we initialize stack frame with
3708 // "store-reg" instructions.
3709 // Case #2. Var-args function, that doesn't contain byval parameters.
3710 // The same: eat all remained unallocated registers,
3711 // initialize stack frame.
3713 MachineFunction &MF = DAG.getMachineFunction();
3714 MachineFrameInfo &MFI = MF.getFrameInfo();
3715 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3716 unsigned RBegin, REnd;
3717 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3718 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3719 } else {
3720 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3721 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3722 REnd = ARM::R4;
3725 if (REnd != RBegin)
3726 ArgOffset = -4 * (ARM::R4 - RBegin);
3728 auto PtrVT = getPointerTy(DAG.getDataLayout());
3729 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3730 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3732 SmallVector<SDValue, 4> MemOps;
3733 const TargetRegisterClass *RC =
3734 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3736 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3737 unsigned VReg = MF.addLiveIn(Reg, RC);
3738 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3739 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3740 MachinePointerInfo(OrigArg, 4 * i));
3741 MemOps.push_back(Store);
3742 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3745 if (!MemOps.empty())
3746 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3747 return FrameIndex;
3750 // Setup stack frame, the va_list pointer will start from.
3751 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3752 const SDLoc &dl, SDValue &Chain,
3753 unsigned ArgOffset,
3754 unsigned TotalArgRegsSaveSize,
3755 bool ForceMutable) const {
3756 MachineFunction &MF = DAG.getMachineFunction();
3757 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3759 // Try to store any remaining integer argument regs
3760 // to their spots on the stack so that they may be loaded by dereferencing
3761 // the result of va_next.
3762 // If there is no regs to be stored, just point address after last
3763 // argument passed via stack.
3764 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3765 CCInfo.getInRegsParamsCount(),
3766 CCInfo.getNextStackOffset(),
3767 std::max(4U, TotalArgRegsSaveSize));
3768 AFI->setVarArgsFrameIndex(FrameIndex);
3771 SDValue ARMTargetLowering::LowerFormalArguments(
3772 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3773 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3774 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3775 MachineFunction &MF = DAG.getMachineFunction();
3776 MachineFrameInfo &MFI = MF.getFrameInfo();
3778 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3780 // Assign locations to all of the incoming arguments.
3781 SmallVector<CCValAssign, 16> ArgLocs;
3782 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3783 *DAG.getContext());
3784 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3786 SmallVector<SDValue, 16> ArgValues;
3787 SDValue ArgValue;
3788 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3789 unsigned CurArgIdx = 0;
3791 // Initially ArgRegsSaveSize is zero.
3792 // Then we increase this value each time we meet byval parameter.
3793 // We also increase this value in case of varargs function.
3794 AFI->setArgRegsSaveSize(0);
3796 // Calculate the amount of stack space that we need to allocate to store
3797 // byval and variadic arguments that are passed in registers.
3798 // We need to know this before we allocate the first byval or variadic
3799 // argument, as they will be allocated a stack slot below the CFA (Canonical
3800 // Frame Address, the stack pointer at entry to the function).
3801 unsigned ArgRegBegin = ARM::R4;
3802 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3803 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3804 break;
3806 CCValAssign &VA = ArgLocs[i];
3807 unsigned Index = VA.getValNo();
3808 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3809 if (!Flags.isByVal())
3810 continue;
3812 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3813 unsigned RBegin, REnd;
3814 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3815 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3817 CCInfo.nextInRegsParam();
3819 CCInfo.rewindByValRegsInfo();
3821 int lastInsIndex = -1;
3822 if (isVarArg && MFI.hasVAStart()) {
3823 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3824 if (RegIdx != array_lengthof(GPRArgRegs))
3825 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3828 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3829 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3830 auto PtrVT = getPointerTy(DAG.getDataLayout());
3832 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3833 CCValAssign &VA = ArgLocs[i];
3834 if (Ins[VA.getValNo()].isOrigArg()) {
3835 std::advance(CurOrigArg,
3836 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3837 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3839 // Arguments stored in registers.
3840 if (VA.isRegLoc()) {
3841 EVT RegVT = VA.getLocVT();
3843 if (VA.needsCustom()) {
3844 // f64 and vector types are split up into multiple registers or
3845 // combinations of registers and stack slots.
3846 if (VA.getLocVT() == MVT::v2f64) {
3847 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3848 Chain, DAG, dl);
3849 VA = ArgLocs[++i]; // skip ahead to next loc
3850 SDValue ArgValue2;
3851 if (VA.isMemLoc()) {
3852 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3853 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3854 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3855 MachinePointerInfo::getFixedStack(
3856 DAG.getMachineFunction(), FI));
3857 } else {
3858 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3859 Chain, DAG, dl);
3861 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3862 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3863 ArgValue, ArgValue1,
3864 DAG.getIntPtrConstant(0, dl));
3865 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3866 ArgValue, ArgValue2,
3867 DAG.getIntPtrConstant(1, dl));
3868 } else
3869 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3870 } else {
3871 const TargetRegisterClass *RC;
3874 if (RegVT == MVT::f16)
3875 RC = &ARM::HPRRegClass;
3876 else if (RegVT == MVT::f32)
3877 RC = &ARM::SPRRegClass;
3878 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
3879 RC = &ARM::DPRRegClass;
3880 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
3881 RC = &ARM::QPRRegClass;
3882 else if (RegVT == MVT::i32)
3883 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3884 : &ARM::GPRRegClass;
3885 else
3886 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3888 // Transform the arguments in physical registers into virtual ones.
3889 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3890 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3893 // If this is an 8 or 16-bit value, it is really passed promoted
3894 // to 32 bits. Insert an assert[sz]ext to capture this, then
3895 // truncate to the right size.
3896 switch (VA.getLocInfo()) {
3897 default: llvm_unreachable("Unknown loc info!");
3898 case CCValAssign::Full: break;
3899 case CCValAssign::BCvt:
3900 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3901 break;
3902 case CCValAssign::SExt:
3903 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3904 DAG.getValueType(VA.getValVT()));
3905 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3906 break;
3907 case CCValAssign::ZExt:
3908 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3909 DAG.getValueType(VA.getValVT()));
3910 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3911 break;
3914 InVals.push_back(ArgValue);
3915 } else { // VA.isRegLoc()
3916 // sanity check
3917 assert(VA.isMemLoc());
3918 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3920 int index = VA.getValNo();
3922 // Some Ins[] entries become multiple ArgLoc[] entries.
3923 // Process them only once.
3924 if (index != lastInsIndex)
3926 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3927 // FIXME: For now, all byval parameter objects are marked mutable.
3928 // This can be changed with more analysis.
3929 // In case of tail call optimization mark all arguments mutable.
3930 // Since they could be overwritten by lowering of arguments in case of
3931 // a tail call.
3932 if (Flags.isByVal()) {
3933 assert(Ins[index].isOrigArg() &&
3934 "Byval arguments cannot be implicit");
3935 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3937 int FrameIndex = StoreByValRegs(
3938 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3939 VA.getLocMemOffset(), Flags.getByValSize());
3940 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3941 CCInfo.nextInRegsParam();
3942 } else {
3943 unsigned FIOffset = VA.getLocMemOffset();
3944 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3945 FIOffset, true);
3947 // Create load nodes to retrieve arguments from the stack.
3948 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3949 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3950 MachinePointerInfo::getFixedStack(
3951 DAG.getMachineFunction(), FI)));
3953 lastInsIndex = index;
3958 // varargs
3959 if (isVarArg && MFI.hasVAStart())
3960 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3961 CCInfo.getNextStackOffset(),
3962 TotalArgRegsSaveSize);
3964 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3966 return Chain;
3969 /// isFloatingPointZero - Return true if this is +0.0.
3970 static bool isFloatingPointZero(SDValue Op) {
3971 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3972 return CFP->getValueAPF().isPosZero();
3973 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3974 // Maybe this has already been legalized into the constant pool?
3975 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3976 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3977 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3978 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3979 return CFP->getValueAPF().isPosZero();
3981 } else if (Op->getOpcode() == ISD::BITCAST &&
3982 Op->getValueType(0) == MVT::f64) {
3983 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3984 // created by LowerConstantFP().
3985 SDValue BitcastOp = Op->getOperand(0);
3986 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3987 isNullConstant(BitcastOp->getOperand(0)))
3988 return true;
3990 return false;
3993 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3994 /// the given operands.
3995 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3996 SDValue &ARMcc, SelectionDAG &DAG,
3997 const SDLoc &dl) const {
3998 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3999 unsigned C = RHSC->getZExtValue();
4000 if (!isLegalICmpImmediate((int32_t)C)) {
4001 // Constant does not fit, try adjusting it by one.
4002 switch (CC) {
4003 default: break;
4004 case ISD::SETLT:
4005 case ISD::SETGE:
4006 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4007 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4008 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4010 break;
4011 case ISD::SETULT:
4012 case ISD::SETUGE:
4013 if (C != 0 && isLegalICmpImmediate(C-1)) {
4014 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4015 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4017 break;
4018 case ISD::SETLE:
4019 case ISD::SETGT:
4020 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4021 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4022 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4024 break;
4025 case ISD::SETULE:
4026 case ISD::SETUGT:
4027 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4028 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4029 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4031 break;
4034 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4035 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4036 // In ARM and Thumb-2, the compare instructions can shift their second
4037 // operand.
4038 CC = ISD::getSetCCSwappedOperands(CC);
4039 std::swap(LHS, RHS);
4042 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4044 // If the RHS is a constant zero then the V (overflow) flag will never be
4045 // set. This can allow us to simplify GE to PL or LT to MI, which can be
4046 // simpler for other passes (like the peephole optimiser) to deal with.
4047 if (isNullConstant(RHS)) {
4048 switch (CondCode) {
4049 default: break;
4050 case ARMCC::GE:
4051 CondCode = ARMCC::PL;
4052 break;
4053 case ARMCC::LT:
4054 CondCode = ARMCC::MI;
4055 break;
4059 ARMISD::NodeType CompareType;
4060 switch (CondCode) {
4061 default:
4062 CompareType = ARMISD::CMP;
4063 break;
4064 case ARMCC::EQ:
4065 case ARMCC::NE:
4066 // Uses only Z Flag
4067 CompareType = ARMISD::CMPZ;
4068 break;
4070 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4071 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4074 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4075 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4076 SelectionDAG &DAG, const SDLoc &dl,
4077 bool InvalidOnQNaN) const {
4078 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4079 SDValue Cmp;
4080 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
4081 if (!isFloatingPointZero(RHS))
4082 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
4083 else
4084 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
4085 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4088 /// duplicateCmp - Glue values can have only one use, so this function
4089 /// duplicates a comparison node.
4090 SDValue
4091 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4092 unsigned Opc = Cmp.getOpcode();
4093 SDLoc DL(Cmp);
4094 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4095 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4097 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
4098 Cmp = Cmp.getOperand(0);
4099 Opc = Cmp.getOpcode();
4100 if (Opc == ARMISD::CMPFP)
4101 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
4102 Cmp.getOperand(1), Cmp.getOperand(2));
4103 else {
4104 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
4105 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
4106 Cmp.getOperand(1));
4108 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4111 // This function returns three things: the arithmetic computation itself
4112 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
4113 // comparison and the condition code define the case in which the arithmetic
4114 // computation *does not* overflow.
4115 std::pair<SDValue, SDValue>
4116 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4117 SDValue &ARMcc) const {
4118 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
4120 SDValue Value, OverflowCmp;
4121 SDValue LHS = Op.getOperand(0);
4122 SDValue RHS = Op.getOperand(1);
4123 SDLoc dl(Op);
4125 // FIXME: We are currently always generating CMPs because we don't support
4126 // generating CMN through the backend. This is not as good as the natural
4127 // CMP case because it causes a register dependency and cannot be folded
4128 // later.
4130 switch (Op.getOpcode()) {
4131 default:
4132 llvm_unreachable("Unknown overflow instruction!");
4133 case ISD::SADDO:
4134 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4135 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4136 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4137 break;
4138 case ISD::UADDO:
4139 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4140 // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4141 // We do not use it in the USUBO case as Value may not be used.
4142 Value = DAG.getNode(ARMISD::ADDC, dl,
4143 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4144 .getValue(0);
4145 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4146 break;
4147 case ISD::SSUBO:
4148 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4149 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4150 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4151 break;
4152 case ISD::USUBO:
4153 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4154 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4155 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4156 break;
4157 case ISD::UMULO:
4158 // We generate a UMUL_LOHI and then check if the high word is 0.
4159 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4160 Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4161 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4162 LHS, RHS);
4163 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4164 DAG.getConstant(0, dl, MVT::i32));
4165 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4166 break;
4167 case ISD::SMULO:
4168 // We generate a SMUL_LOHI and then check if all the bits of the high word
4169 // are the same as the sign bit of the low word.
4170 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4171 Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4172 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4173 LHS, RHS);
4174 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4175 DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4176 Value.getValue(0),
4177 DAG.getConstant(31, dl, MVT::i32)));
4178 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4179 break;
4180 } // switch (...)
4182 return std::make_pair(Value, OverflowCmp);
4185 SDValue
4186 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4187 // Let legalize expand this if it isn't a legal type yet.
4188 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4189 return SDValue();
4191 SDValue Value, OverflowCmp;
4192 SDValue ARMcc;
4193 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4194 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4195 SDLoc dl(Op);
4196 // We use 0 and 1 as false and true values.
4197 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4198 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4199 EVT VT = Op.getValueType();
4201 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4202 ARMcc, CCR, OverflowCmp);
4204 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4205 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4208 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4209 SelectionDAG &DAG) {
4210 SDLoc DL(BoolCarry);
4211 EVT CarryVT = BoolCarry.getValueType();
4213 // This converts the boolean value carry into the carry flag by doing
4214 // ARMISD::SUBC Carry, 1
4215 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4216 DAG.getVTList(CarryVT, MVT::i32),
4217 BoolCarry, DAG.getConstant(1, DL, CarryVT));
4218 return Carry.getValue(1);
4221 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4222 SelectionDAG &DAG) {
4223 SDLoc DL(Flags);
4225 // Now convert the carry flag into a boolean carry. We do this
4226 // using ARMISD:ADDE 0, 0, Carry
4227 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4228 DAG.getConstant(0, DL, MVT::i32),
4229 DAG.getConstant(0, DL, MVT::i32), Flags);
4232 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4233 SelectionDAG &DAG) const {
4234 // Let legalize expand this if it isn't a legal type yet.
4235 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4236 return SDValue();
4238 SDValue LHS = Op.getOperand(0);
4239 SDValue RHS = Op.getOperand(1);
4240 SDLoc dl(Op);
4242 EVT VT = Op.getValueType();
4243 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4244 SDValue Value;
4245 SDValue Overflow;
4246 switch (Op.getOpcode()) {
4247 default:
4248 llvm_unreachable("Unknown overflow instruction!");
4249 case ISD::UADDO:
4250 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4251 // Convert the carry flag into a boolean value.
4252 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4253 break;
4254 case ISD::USUBO: {
4255 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4256 // Convert the carry flag into a boolean value.
4257 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4258 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4259 // value. So compute 1 - C.
4260 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4261 DAG.getConstant(1, dl, MVT::i32), Overflow);
4262 break;
4266 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4269 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4270 SDValue Cond = Op.getOperand(0);
4271 SDValue SelectTrue = Op.getOperand(1);
4272 SDValue SelectFalse = Op.getOperand(2);
4273 SDLoc dl(Op);
4274 unsigned Opc = Cond.getOpcode();
4276 if (Cond.getResNo() == 1 &&
4277 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4278 Opc == ISD::USUBO)) {
4279 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4280 return SDValue();
4282 SDValue Value, OverflowCmp;
4283 SDValue ARMcc;
4284 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4285 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4286 EVT VT = Op.getValueType();
4288 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4289 OverflowCmp, DAG);
4292 // Convert:
4294 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4295 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4297 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4298 const ConstantSDNode *CMOVTrue =
4299 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4300 const ConstantSDNode *CMOVFalse =
4301 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4303 if (CMOVTrue && CMOVFalse) {
4304 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4305 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4307 SDValue True;
4308 SDValue False;
4309 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4310 True = SelectTrue;
4311 False = SelectFalse;
4312 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4313 True = SelectFalse;
4314 False = SelectTrue;
4317 if (True.getNode() && False.getNode()) {
4318 EVT VT = Op.getValueType();
4319 SDValue ARMcc = Cond.getOperand(2);
4320 SDValue CCR = Cond.getOperand(3);
4321 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4322 assert(True.getValueType() == VT);
4323 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4328 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4329 // undefined bits before doing a full-word comparison with zero.
4330 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4331 DAG.getConstant(1, dl, Cond.getValueType()));
4333 return DAG.getSelectCC(dl, Cond,
4334 DAG.getConstant(0, dl, Cond.getValueType()),
4335 SelectTrue, SelectFalse, ISD::SETNE);
4338 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4339 bool &swpCmpOps, bool &swpVselOps) {
4340 // Start by selecting the GE condition code for opcodes that return true for
4341 // 'equality'
4342 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4343 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE)
4344 CondCode = ARMCC::GE;
4346 // and GT for opcodes that return false for 'equality'.
4347 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4348 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT)
4349 CondCode = ARMCC::GT;
4351 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4352 // to swap the compare operands.
4353 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4354 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT)
4355 swpCmpOps = true;
4357 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4358 // If we have an unordered opcode, we need to swap the operands to the VSEL
4359 // instruction (effectively negating the condition).
4361 // This also has the effect of swapping which one of 'less' or 'greater'
4362 // returns true, so we also swap the compare operands. It also switches
4363 // whether we return true for 'equality', so we compensate by picking the
4364 // opposite condition code to our original choice.
4365 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4366 CC == ISD::SETUGT) {
4367 swpCmpOps = !swpCmpOps;
4368 swpVselOps = !swpVselOps;
4369 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4372 // 'ordered' is 'anything but unordered', so use the VS condition code and
4373 // swap the VSEL operands.
4374 if (CC == ISD::SETO) {
4375 CondCode = ARMCC::VS;
4376 swpVselOps = true;
4379 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4380 // code and swap the VSEL operands. Also do this if we don't care about the
4381 // unordered case.
4382 if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4383 CondCode = ARMCC::EQ;
4384 swpVselOps = true;
4388 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4389 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4390 SDValue Cmp, SelectionDAG &DAG) const {
4391 if (!Subtarget->hasFP64() && VT == MVT::f64) {
4392 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4393 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4394 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4395 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4397 SDValue TrueLow = TrueVal.getValue(0);
4398 SDValue TrueHigh = TrueVal.getValue(1);
4399 SDValue FalseLow = FalseVal.getValue(0);
4400 SDValue FalseHigh = FalseVal.getValue(1);
4402 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4403 ARMcc, CCR, Cmp);
4404 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4405 ARMcc, CCR, duplicateCmp(Cmp, DAG));
4407 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4408 } else {
4409 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4410 Cmp);
4414 static bool isGTorGE(ISD::CondCode CC) {
4415 return CC == ISD::SETGT || CC == ISD::SETGE;
4418 static bool isLTorLE(ISD::CondCode CC) {
4419 return CC == ISD::SETLT || CC == ISD::SETLE;
4422 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4423 // All of these conditions (and their <= and >= counterparts) will do:
4424 // x < k ? k : x
4425 // x > k ? x : k
4426 // k < x ? x : k
4427 // k > x ? k : x
4428 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4429 const SDValue TrueVal, const SDValue FalseVal,
4430 const ISD::CondCode CC, const SDValue K) {
4431 return (isGTorGE(CC) &&
4432 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4433 (isLTorLE(CC) &&
4434 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4437 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4438 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4439 const SDValue TrueVal, const SDValue FalseVal,
4440 const ISD::CondCode CC, const SDValue K) {
4441 return (isGTorGE(CC) &&
4442 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4443 (isLTorLE(CC) &&
4444 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4447 // Check if two chained conditionals could be converted into SSAT or USAT.
4449 // SSAT can replace a set of two conditional selectors that bound a number to an
4450 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4452 // x < -k ? -k : (x > k ? k : x)
4453 // x < -k ? -k : (x < k ? x : k)
4454 // x > -k ? (x > k ? k : x) : -k
4455 // x < k ? (x < -k ? -k : x) : k
4456 // etc.
4458 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4459 // a power of 2.
4461 // It returns true if the conversion can be done, false otherwise.
4462 // Additionally, the variable is returned in parameter V, the constant in K and
4463 // usat is set to true if the conditional represents an unsigned saturation
4464 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4465 uint64_t &K, bool &usat) {
4466 SDValue LHS1 = Op.getOperand(0);
4467 SDValue RHS1 = Op.getOperand(1);
4468 SDValue TrueVal1 = Op.getOperand(2);
4469 SDValue FalseVal1 = Op.getOperand(3);
4470 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4472 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4473 if (Op2.getOpcode() != ISD::SELECT_CC)
4474 return false;
4476 SDValue LHS2 = Op2.getOperand(0);
4477 SDValue RHS2 = Op2.getOperand(1);
4478 SDValue TrueVal2 = Op2.getOperand(2);
4479 SDValue FalseVal2 = Op2.getOperand(3);
4480 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4482 // Find out which are the constants and which are the variables
4483 // in each conditional
4484 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4485 ? &RHS1
4486 : nullptr;
4487 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4488 ? &RHS2
4489 : nullptr;
4490 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4491 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4492 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4493 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4495 // We must detect cases where the original operations worked with 16- or
4496 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4497 // must work with sign-extended values but the select operations return
4498 // the original non-extended value.
4499 SDValue V2TmpReg = V2Tmp;
4500 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4501 V2TmpReg = V2Tmp->getOperand(0);
4503 // Check that the registers and the constants have the correct values
4504 // in both conditionals
4505 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4506 V2TmpReg != V2)
4507 return false;
4509 // Figure out which conditional is saturating the lower/upper bound.
4510 const SDValue *LowerCheckOp =
4511 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4512 ? &Op
4513 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4514 ? &Op2
4515 : nullptr;
4516 const SDValue *UpperCheckOp =
4517 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4518 ? &Op
4519 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4520 ? &Op2
4521 : nullptr;
4523 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4524 return false;
4526 // Check that the constant in the lower-bound check is
4527 // the opposite of the constant in the upper-bound check
4528 // in 1's complement.
4529 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4530 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4531 int64_t PosVal = std::max(Val1, Val2);
4532 int64_t NegVal = std::min(Val1, Val2);
4534 if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4535 (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4536 isPowerOf2_64(PosVal + 1)) {
4538 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4539 if (Val1 == ~Val2)
4540 usat = false;
4541 else if (NegVal == 0)
4542 usat = true;
4543 else
4544 return false;
4546 V = V2;
4547 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4549 return true;
4552 return false;
4555 // Check if a condition of the type x < k ? k : x can be converted into a
4556 // bit operation instead of conditional moves.
4557 // Currently this is allowed given:
4558 // - The conditions and values match up
4559 // - k is 0 or -1 (all ones)
4560 // This function will not check the last condition, thats up to the caller
4561 // It returns true if the transformation can be made, and in such case
4562 // returns x in V, and k in SatK.
4563 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
4564 SDValue &SatK)
4566 SDValue LHS = Op.getOperand(0);
4567 SDValue RHS = Op.getOperand(1);
4568 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4569 SDValue TrueVal = Op.getOperand(2);
4570 SDValue FalseVal = Op.getOperand(3);
4572 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
4573 ? &RHS
4574 : nullptr;
4576 // No constant operation in comparison, early out
4577 if (!K)
4578 return false;
4580 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
4581 V = (KTmp == TrueVal) ? FalseVal : TrueVal;
4582 SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
4584 // If the constant on left and right side, or variable on left and right,
4585 // does not match, early out
4586 if (*K != KTmp || V != VTmp)
4587 return false;
4589 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
4590 SatK = *K;
4591 return true;
4594 return false;
4597 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
4598 if (VT == MVT::f32)
4599 return !Subtarget->hasVFP2Base();
4600 if (VT == MVT::f64)
4601 return !Subtarget->hasFP64();
4602 if (VT == MVT::f16)
4603 return !Subtarget->hasFullFP16();
4604 return false;
4607 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4608 EVT VT = Op.getValueType();
4609 SDLoc dl(Op);
4611 // Try to convert two saturating conditional selects into a single SSAT
4612 SDValue SatValue;
4613 uint64_t SatConstant;
4614 bool SatUSat;
4615 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4616 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4617 if (SatUSat)
4618 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4619 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4620 else
4621 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4622 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4625 // Try to convert expressions of the form x < k ? k : x (and similar forms)
4626 // into more efficient bit operations, which is possible when k is 0 or -1
4627 // On ARM and Thumb-2 which have flexible operand 2 this will result in
4628 // single instructions. On Thumb the shift and the bit operation will be two
4629 // instructions.
4630 // Only allow this transformation on full-width (32-bit) operations
4631 SDValue LowerSatConstant;
4632 if (VT == MVT::i32 &&
4633 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
4634 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
4635 DAG.getConstant(31, dl, VT));
4636 if (isNullConstant(LowerSatConstant)) {
4637 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
4638 DAG.getAllOnesConstant(dl, VT));
4639 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
4640 } else if (isAllOnesConstant(LowerSatConstant))
4641 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
4644 SDValue LHS = Op.getOperand(0);
4645 SDValue RHS = Op.getOperand(1);
4646 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4647 SDValue TrueVal = Op.getOperand(2);
4648 SDValue FalseVal = Op.getOperand(3);
4650 if (isUnsupportedFloatingType(LHS.getValueType())) {
4651 DAG.getTargetLoweringInfo().softenSetCCOperands(
4652 DAG, LHS.getValueType(), LHS, RHS, CC, dl);
4654 // If softenSetCCOperands only returned one value, we should compare it to
4655 // zero.
4656 if (!RHS.getNode()) {
4657 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4658 CC = ISD::SETNE;
4662 if (LHS.getValueType() == MVT::i32) {
4663 // Try to generate VSEL on ARMv8.
4664 // The VSEL instruction can't use all the usual ARM condition
4665 // codes: it only has two bits to select the condition code, so it's
4666 // constrained to use only GE, GT, VS and EQ.
4668 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4669 // swap the operands of the previous compare instruction (effectively
4670 // inverting the compare condition, swapping 'less' and 'greater') and
4671 // sometimes need to swap the operands to the VSEL (which inverts the
4672 // condition in the sense of firing whenever the previous condition didn't)
4673 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
4674 TrueVal.getValueType() == MVT::f32 ||
4675 TrueVal.getValueType() == MVT::f64)) {
4676 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4677 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4678 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4679 CC = ISD::getSetCCInverse(CC, true);
4680 std::swap(TrueVal, FalseVal);
4684 SDValue ARMcc;
4685 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4686 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4687 // Choose GE over PL, which vsel does now support
4688 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
4689 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
4690 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4693 ARMCC::CondCodes CondCode, CondCode2;
4694 bool InvalidOnQNaN;
4695 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4697 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
4698 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
4699 // must use VSEL (limited condition codes), due to not having conditional f16
4700 // moves.
4701 if (Subtarget->hasFPARMv8Base() &&
4702 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
4703 (TrueVal.getValueType() == MVT::f16 ||
4704 TrueVal.getValueType() == MVT::f32 ||
4705 TrueVal.getValueType() == MVT::f64)) {
4706 bool swpCmpOps = false;
4707 bool swpVselOps = false;
4708 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4710 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4711 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4712 if (swpCmpOps)
4713 std::swap(LHS, RHS);
4714 if (swpVselOps)
4715 std::swap(TrueVal, FalseVal);
4719 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4720 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4721 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4722 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4723 if (CondCode2 != ARMCC::AL) {
4724 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4725 // FIXME: Needs another CMP because flag can have but one use.
4726 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4727 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4729 return Result;
4732 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4733 /// to morph to an integer compare sequence.
4734 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4735 const ARMSubtarget *Subtarget) {
4736 SDNode *N = Op.getNode();
4737 if (!N->hasOneUse())
4738 // Otherwise it requires moving the value from fp to integer registers.
4739 return false;
4740 if (!N->getNumValues())
4741 return false;
4742 EVT VT = Op.getValueType();
4743 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4744 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4745 // vmrs are very slow, e.g. cortex-a8.
4746 return false;
4748 if (isFloatingPointZero(Op)) {
4749 SeenZero = true;
4750 return true;
4752 return ISD::isNormalLoad(N);
4755 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4756 if (isFloatingPointZero(Op))
4757 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4759 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4760 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4761 Ld->getPointerInfo(), Ld->getAlignment(),
4762 Ld->getMemOperand()->getFlags());
4764 llvm_unreachable("Unknown VFP cmp argument!");
4767 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4768 SDValue &RetVal1, SDValue &RetVal2) {
4769 SDLoc dl(Op);
4771 if (isFloatingPointZero(Op)) {
4772 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4773 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4774 return;
4777 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4778 SDValue Ptr = Ld->getBasePtr();
4779 RetVal1 =
4780 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4781 Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4783 EVT PtrType = Ptr.getValueType();
4784 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4785 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4786 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4787 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4788 Ld->getPointerInfo().getWithOffset(4), NewAlign,
4789 Ld->getMemOperand()->getFlags());
4790 return;
4793 llvm_unreachable("Unknown VFP cmp argument!");
4796 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4797 /// f32 and even f64 comparisons to integer ones.
4798 SDValue
4799 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4800 SDValue Chain = Op.getOperand(0);
4801 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4802 SDValue LHS = Op.getOperand(2);
4803 SDValue RHS = Op.getOperand(3);
4804 SDValue Dest = Op.getOperand(4);
4805 SDLoc dl(Op);
4807 bool LHSSeenZero = false;
4808 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4809 bool RHSSeenZero = false;
4810 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4811 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4812 // If unsafe fp math optimization is enabled and there are no other uses of
4813 // the CMP operands, and the condition code is EQ or NE, we can optimize it
4814 // to an integer comparison.
4815 if (CC == ISD::SETOEQ)
4816 CC = ISD::SETEQ;
4817 else if (CC == ISD::SETUNE)
4818 CC = ISD::SETNE;
4820 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4821 SDValue ARMcc;
4822 if (LHS.getValueType() == MVT::f32) {
4823 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4824 bitcastf32Toi32(LHS, DAG), Mask);
4825 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4826 bitcastf32Toi32(RHS, DAG), Mask);
4827 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4828 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4829 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4830 Chain, Dest, ARMcc, CCR, Cmp);
4833 SDValue LHS1, LHS2;
4834 SDValue RHS1, RHS2;
4835 expandf64Toi32(LHS, DAG, LHS1, LHS2);
4836 expandf64Toi32(RHS, DAG, RHS1, RHS2);
4837 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4838 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4839 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4840 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4841 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4842 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4843 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4846 return SDValue();
4849 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
4850 SDValue Chain = Op.getOperand(0);
4851 SDValue Cond = Op.getOperand(1);
4852 SDValue Dest = Op.getOperand(2);
4853 SDLoc dl(Op);
4855 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4856 // instruction.
4857 unsigned Opc = Cond.getOpcode();
4858 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
4859 !Subtarget->isThumb1Only();
4860 if (Cond.getResNo() == 1 &&
4861 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4862 Opc == ISD::USUBO || OptimizeMul)) {
4863 // Only lower legal XALUO ops.
4864 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4865 return SDValue();
4867 // The actual operation with overflow check.
4868 SDValue Value, OverflowCmp;
4869 SDValue ARMcc;
4870 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4872 // Reverse the condition code.
4873 ARMCC::CondCodes CondCode =
4874 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4875 CondCode = ARMCC::getOppositeCondition(CondCode);
4876 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4877 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4879 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4880 OverflowCmp);
4883 return SDValue();
4886 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4887 SDValue Chain = Op.getOperand(0);
4888 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4889 SDValue LHS = Op.getOperand(2);
4890 SDValue RHS = Op.getOperand(3);
4891 SDValue Dest = Op.getOperand(4);
4892 SDLoc dl(Op);
4894 if (isUnsupportedFloatingType(LHS.getValueType())) {
4895 DAG.getTargetLoweringInfo().softenSetCCOperands(
4896 DAG, LHS.getValueType(), LHS, RHS, CC, dl);
4898 // If softenSetCCOperands only returned one value, we should compare it to
4899 // zero.
4900 if (!RHS.getNode()) {
4901 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4902 CC = ISD::SETNE;
4906 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4907 // instruction.
4908 unsigned Opc = LHS.getOpcode();
4909 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
4910 !Subtarget->isThumb1Only();
4911 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
4912 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4913 Opc == ISD::USUBO || OptimizeMul) &&
4914 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4915 // Only lower legal XALUO ops.
4916 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4917 return SDValue();
4919 // The actual operation with overflow check.
4920 SDValue Value, OverflowCmp;
4921 SDValue ARMcc;
4922 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
4924 if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
4925 // Reverse the condition code.
4926 ARMCC::CondCodes CondCode =
4927 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4928 CondCode = ARMCC::getOppositeCondition(CondCode);
4929 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4931 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4933 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4934 OverflowCmp);
4937 if (LHS.getValueType() == MVT::i32) {
4938 SDValue ARMcc;
4939 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4940 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4941 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4942 Chain, Dest, ARMcc, CCR, Cmp);
4945 if (getTargetMachine().Options.UnsafeFPMath &&
4946 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4947 CC == ISD::SETNE || CC == ISD::SETUNE)) {
4948 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4949 return Result;
4952 ARMCC::CondCodes CondCode, CondCode2;
4953 bool InvalidOnQNaN;
4954 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4956 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4957 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4958 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4959 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4960 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4961 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4962 if (CondCode2 != ARMCC::AL) {
4963 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4964 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4965 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4967 return Res;
4970 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4971 SDValue Chain = Op.getOperand(0);
4972 SDValue Table = Op.getOperand(1);
4973 SDValue Index = Op.getOperand(2);
4974 SDLoc dl(Op);
4976 EVT PTy = getPointerTy(DAG.getDataLayout());
4977 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4978 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4979 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4980 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4981 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
4982 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
4983 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
4984 // which does another jump to the destination. This also makes it easier
4985 // to translate it to TBB / TBH later (Thumb2 only).
4986 // FIXME: This might not work if the function is extremely large.
4987 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4988 Addr, Op.getOperand(2), JTI);
4990 if (isPositionIndependent() || Subtarget->isROPI()) {
4991 Addr =
4992 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4993 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4994 Chain = Addr.getValue(1);
4995 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
4996 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4997 } else {
4998 Addr =
4999 DAG.getLoad(PTy, dl, Chain, Addr,
5000 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5001 Chain = Addr.getValue(1);
5002 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5006 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5007 EVT VT = Op.getValueType();
5008 SDLoc dl(Op);
5010 if (Op.getValueType().getVectorElementType() == MVT::i32) {
5011 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5012 return Op;
5013 return DAG.UnrollVectorOp(Op.getNode());
5016 const bool HasFullFP16 =
5017 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5019 EVT NewTy;
5020 const EVT OpTy = Op.getOperand(0).getValueType();
5021 if (OpTy == MVT::v4f32)
5022 NewTy = MVT::v4i32;
5023 else if (OpTy == MVT::v4f16 && HasFullFP16)
5024 NewTy = MVT::v4i16;
5025 else if (OpTy == MVT::v8f16 && HasFullFP16)
5026 NewTy = MVT::v8i16;
5027 else
5028 llvm_unreachable("Invalid type for custom lowering!");
5030 if (VT != MVT::v4i16 && VT != MVT::v8i16)
5031 return DAG.UnrollVectorOp(Op.getNode());
5033 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5034 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5037 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5038 EVT VT = Op.getValueType();
5039 if (VT.isVector())
5040 return LowerVectorFP_TO_INT(Op, DAG);
5041 if (isUnsupportedFloatingType(Op.getOperand(0).getValueType())) {
5042 RTLIB::Libcall LC;
5043 if (Op.getOpcode() == ISD::FP_TO_SINT)
5044 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
5045 Op.getValueType());
5046 else
5047 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
5048 Op.getValueType());
5049 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5050 /*isSigned*/ false, SDLoc(Op)).first;
5053 return Op;
5056 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5057 EVT VT = Op.getValueType();
5058 SDLoc dl(Op);
5060 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5061 if (VT.getVectorElementType() == MVT::f32)
5062 return Op;
5063 return DAG.UnrollVectorOp(Op.getNode());
5066 assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5067 Op.getOperand(0).getValueType() == MVT::v8i16) &&
5068 "Invalid type for custom lowering!");
5070 const bool HasFullFP16 =
5071 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5073 EVT DestVecType;
5074 if (VT == MVT::v4f32)
5075 DestVecType = MVT::v4i32;
5076 else if (VT == MVT::v4f16 && HasFullFP16)
5077 DestVecType = MVT::v4i16;
5078 else if (VT == MVT::v8f16 && HasFullFP16)
5079 DestVecType = MVT::v8i16;
5080 else
5081 return DAG.UnrollVectorOp(Op.getNode());
5083 unsigned CastOpc;
5084 unsigned Opc;
5085 switch (Op.getOpcode()) {
5086 default: llvm_unreachable("Invalid opcode!");
5087 case ISD::SINT_TO_FP:
5088 CastOpc = ISD::SIGN_EXTEND;
5089 Opc = ISD::SINT_TO_FP;
5090 break;
5091 case ISD::UINT_TO_FP:
5092 CastOpc = ISD::ZERO_EXTEND;
5093 Opc = ISD::UINT_TO_FP;
5094 break;
5097 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5098 return DAG.getNode(Opc, dl, VT, Op);
5101 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5102 EVT VT = Op.getValueType();
5103 if (VT.isVector())
5104 return LowerVectorINT_TO_FP(Op, DAG);
5105 if (isUnsupportedFloatingType(VT)) {
5106 RTLIB::Libcall LC;
5107 if (Op.getOpcode() == ISD::SINT_TO_FP)
5108 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5109 Op.getValueType());
5110 else
5111 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5112 Op.getValueType());
5113 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5114 /*isSigned*/ false, SDLoc(Op)).first;
5117 return Op;
5120 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5121 // Implement fcopysign with a fabs and a conditional fneg.
5122 SDValue Tmp0 = Op.getOperand(0);
5123 SDValue Tmp1 = Op.getOperand(1);
5124 SDLoc dl(Op);
5125 EVT VT = Op.getValueType();
5126 EVT SrcVT = Tmp1.getValueType();
5127 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5128 Tmp0.getOpcode() == ARMISD::VMOVDRR;
5129 bool UseNEON = !InGPR && Subtarget->hasNEON();
5131 if (UseNEON) {
5132 // Use VBSL to copy the sign bit.
5133 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
5134 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5135 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5136 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5137 if (VT == MVT::f64)
5138 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
5139 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5140 DAG.getConstant(32, dl, MVT::i32));
5141 else /*if (VT == MVT::f32)*/
5142 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5143 if (SrcVT == MVT::f32) {
5144 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5145 if (VT == MVT::f64)
5146 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
5147 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5148 DAG.getConstant(32, dl, MVT::i32));
5149 } else if (VT == MVT::f32)
5150 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
5151 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5152 DAG.getConstant(32, dl, MVT::i32));
5153 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5154 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5156 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
5157 dl, MVT::i32);
5158 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5159 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5160 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5162 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5163 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5164 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5165 if (VT == MVT::f32) {
5166 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5167 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5168 DAG.getConstant(0, dl, MVT::i32));
5169 } else {
5170 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5173 return Res;
5176 // Bitcast operand 1 to i32.
5177 if (SrcVT == MVT::f64)
5178 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5179 Tmp1).getValue(1);
5180 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5182 // Or in the signbit with integer operations.
5183 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5184 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5185 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5186 if (VT == MVT::f32) {
5187 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5188 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5189 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5190 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5193 // f64: Or the high part with signbit and then combine two parts.
5194 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5195 Tmp0);
5196 SDValue Lo = Tmp0.getValue(0);
5197 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5198 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5199 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5202 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5203 MachineFunction &MF = DAG.getMachineFunction();
5204 MachineFrameInfo &MFI = MF.getFrameInfo();
5205 MFI.setReturnAddressIsTaken(true);
5207 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5208 return SDValue();
5210 EVT VT = Op.getValueType();
5211 SDLoc dl(Op);
5212 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5213 if (Depth) {
5214 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5215 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5216 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5217 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5218 MachinePointerInfo());
5221 // Return LR, which contains the return address. Mark it an implicit live-in.
5222 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5223 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5226 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5227 const ARMBaseRegisterInfo &ARI =
5228 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5229 MachineFunction &MF = DAG.getMachineFunction();
5230 MachineFrameInfo &MFI = MF.getFrameInfo();
5231 MFI.setFrameAddressIsTaken(true);
5233 EVT VT = Op.getValueType();
5234 SDLoc dl(Op); // FIXME probably not meaningful
5235 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5236 unsigned FrameReg = ARI.getFrameRegister(MF);
5237 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5238 while (Depth--)
5239 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5240 MachinePointerInfo());
5241 return FrameAddr;
5244 // FIXME? Maybe this could be a TableGen attribute on some registers and
5245 // this table could be generated automatically from RegInfo.
5246 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
5247 SelectionDAG &DAG) const {
5248 unsigned Reg = StringSwitch<unsigned>(RegName)
5249 .Case("sp", ARM::SP)
5250 .Default(0);
5251 if (Reg)
5252 return Reg;
5253 report_fatal_error(Twine("Invalid register name \""
5254 + StringRef(RegName) + "\"."));
5257 // Result is 64 bit value so split into two 32 bit values and return as a
5258 // pair of values.
5259 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5260 SelectionDAG &DAG) {
5261 SDLoc DL(N);
5263 // This function is only supposed to be called for i64 type destination.
5264 assert(N->getValueType(0) == MVT::i64
5265 && "ExpandREAD_REGISTER called for non-i64 type result.");
5267 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5268 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5269 N->getOperand(0),
5270 N->getOperand(1));
5272 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5273 Read.getValue(1)));
5274 Results.push_back(Read.getOperand(0));
5277 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5278 /// When \p DstVT, the destination type of \p BC, is on the vector
5279 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5280 /// it might be possible to combine them, such that everything stays on the
5281 /// vector register bank.
5282 /// \p return The node that would replace \p BT, if the combine
5283 /// is possible.
5284 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5285 SelectionDAG &DAG) {
5286 SDValue Op = BC->getOperand(0);
5287 EVT DstVT = BC->getValueType(0);
5289 // The only vector instruction that can produce a scalar (remember,
5290 // since the bitcast was about to be turned into VMOVDRR, the source
5291 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5292 // Moreover, we can do this combine only if there is one use.
5293 // Finally, if the destination type is not a vector, there is not
5294 // much point on forcing everything on the vector bank.
5295 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5296 !Op.hasOneUse())
5297 return SDValue();
5299 // If the index is not constant, we will introduce an additional
5300 // multiply that will stick.
5301 // Give up in that case.
5302 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5303 if (!Index)
5304 return SDValue();
5305 unsigned DstNumElt = DstVT.getVectorNumElements();
5307 // Compute the new index.
5308 const APInt &APIntIndex = Index->getAPIntValue();
5309 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5310 NewIndex *= APIntIndex;
5311 // Check if the new constant index fits into i32.
5312 if (NewIndex.getBitWidth() > 32)
5313 return SDValue();
5315 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5316 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5317 SDLoc dl(Op);
5318 SDValue ExtractSrc = Op.getOperand(0);
5319 EVT VecVT = EVT::getVectorVT(
5320 *DAG.getContext(), DstVT.getScalarType(),
5321 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5322 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5323 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5324 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5327 /// ExpandBITCAST - If the target supports VFP, this function is called to
5328 /// expand a bit convert where either the source or destination type is i64 to
5329 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
5330 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5331 /// vectors), since the legalizer won't know what to do with that.
5332 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5333 const ARMSubtarget *Subtarget) {
5334 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5335 SDLoc dl(N);
5336 SDValue Op = N->getOperand(0);
5338 // This function is only supposed to be called for i64 types, either as the
5339 // source or destination of the bit convert.
5340 EVT SrcVT = Op.getValueType();
5341 EVT DstVT = N->getValueType(0);
5342 const bool HasFullFP16 = Subtarget->hasFullFP16();
5344 if (SrcVT == MVT::f32 && DstVT == MVT::i32) {
5345 // FullFP16: half values are passed in S-registers, and we don't
5346 // need any of the bitcast and moves:
5348 // t2: f32,ch = CopyFromReg t0, Register:f32 %0
5349 // t5: i32 = bitcast t2
5350 // t18: f16 = ARMISD::VMOVhr t5
5351 if (Op.getOpcode() != ISD::CopyFromReg ||
5352 Op.getValueType() != MVT::f32)
5353 return SDValue();
5355 auto Move = N->use_begin();
5356 if (Move->getOpcode() != ARMISD::VMOVhr)
5357 return SDValue();
5359 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
5360 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops);
5361 DAG.ReplaceAllUsesWith(*Move, &Copy);
5362 return Copy;
5365 if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5366 if (!HasFullFP16)
5367 return SDValue();
5368 // SoftFP: read half-precision arguments:
5370 // t2: i32,ch = ...
5371 // t7: i16 = truncate t2 <~~~~ Op
5372 // t8: f16 = bitcast t7 <~~~~ N
5374 if (Op.getOperand(0).getValueType() == MVT::i32)
5375 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op),
5376 MVT::f16, Op.getOperand(0));
5378 return SDValue();
5381 // Half-precision return values
5382 if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5383 if (!HasFullFP16)
5384 return SDValue();
5386 // t11: f16 = fadd t8, t10
5387 // t12: i16 = bitcast t11 <~~~ SDNode N
5388 // t13: i32 = zero_extend t12
5389 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13
5390 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1
5392 // transform this into:
5394 // t20: i32 = ARMISD::VMOVrh t11
5395 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20
5397 auto ZeroExtend = N->use_begin();
5398 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND ||
5399 ZeroExtend->getValueType(0) != MVT::i32)
5400 return SDValue();
5402 auto Copy = ZeroExtend->use_begin();
5403 if (Copy->getOpcode() == ISD::CopyToReg &&
5404 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) {
5405 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op);
5406 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt);
5407 return Cvt;
5409 return SDValue();
5412 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5413 return SDValue();
5415 // Turn i64->f64 into VMOVDRR.
5416 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5417 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5418 // if we can combine the bitcast with its source.
5419 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5420 return Val;
5422 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5423 DAG.getConstant(0, dl, MVT::i32));
5424 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5425 DAG.getConstant(1, dl, MVT::i32));
5426 return DAG.getNode(ISD::BITCAST, dl, DstVT,
5427 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5430 // Turn f64->i64 into VMOVRRD.
5431 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5432 SDValue Cvt;
5433 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5434 SrcVT.getVectorNumElements() > 1)
5435 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5436 DAG.getVTList(MVT::i32, MVT::i32),
5437 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5438 else
5439 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5440 DAG.getVTList(MVT::i32, MVT::i32), Op);
5441 // Merge the pieces into a single i64 value.
5442 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5445 return SDValue();
5448 /// getZeroVector - Returns a vector of specified type with all zero elements.
5449 /// Zero vectors are used to represent vector negation and in those cases
5450 /// will be implemented with the NEON VNEG instruction. However, VNEG does
5451 /// not support i64 elements, so sometimes the zero vectors will need to be
5452 /// explicitly constructed. Regardless, use a canonical VMOV to create the
5453 /// zero vector.
5454 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5455 assert(VT.isVector() && "Expected a vector type");
5456 // The canonical modified immediate encoding of a zero vector is....0!
5457 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5458 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5459 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5460 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5463 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5464 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5465 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5466 SelectionDAG &DAG) const {
5467 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5468 EVT VT = Op.getValueType();
5469 unsigned VTBits = VT.getSizeInBits();
5470 SDLoc dl(Op);
5471 SDValue ShOpLo = Op.getOperand(0);
5472 SDValue ShOpHi = Op.getOperand(1);
5473 SDValue ShAmt = Op.getOperand(2);
5474 SDValue ARMcc;
5475 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5476 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5478 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5480 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5481 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5482 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5483 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5484 DAG.getConstant(VTBits, dl, MVT::i32));
5485 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5486 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5487 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5488 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5489 ISD::SETGE, ARMcc, DAG, dl);
5490 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5491 ARMcc, CCR, CmpLo);
5493 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5494 SDValue HiBigShift = Opc == ISD::SRA
5495 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5496 DAG.getConstant(VTBits - 1, dl, VT))
5497 : DAG.getConstant(0, dl, VT);
5498 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5499 ISD::SETGE, ARMcc, DAG, dl);
5500 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5501 ARMcc, CCR, CmpHi);
5503 SDValue Ops[2] = { Lo, Hi };
5504 return DAG.getMergeValues(Ops, dl);
5507 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5508 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5509 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5510 SelectionDAG &DAG) const {
5511 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5512 EVT VT = Op.getValueType();
5513 unsigned VTBits = VT.getSizeInBits();
5514 SDLoc dl(Op);
5515 SDValue ShOpLo = Op.getOperand(0);
5516 SDValue ShOpHi = Op.getOperand(1);
5517 SDValue ShAmt = Op.getOperand(2);
5518 SDValue ARMcc;
5519 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5521 assert(Op.getOpcode() == ISD::SHL_PARTS);
5522 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5523 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5524 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5525 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5526 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5528 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5529 DAG.getConstant(VTBits, dl, MVT::i32));
5530 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5531 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5532 ISD::SETGE, ARMcc, DAG, dl);
5533 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5534 ARMcc, CCR, CmpHi);
5536 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5537 ISD::SETGE, ARMcc, DAG, dl);
5538 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5539 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5540 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5542 SDValue Ops[2] = { Lo, Hi };
5543 return DAG.getMergeValues(Ops, dl);
5546 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5547 SelectionDAG &DAG) const {
5548 // The rounding mode is in bits 23:22 of the FPSCR.
5549 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5550 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5551 // so that the shift + and get folded into a bitfield extract.
5552 SDLoc dl(Op);
5553 SDValue Ops[] = { DAG.getEntryNode(),
5554 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5556 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5557 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5558 DAG.getConstant(1U << 22, dl, MVT::i32));
5559 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5560 DAG.getConstant(22, dl, MVT::i32));
5561 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5562 DAG.getConstant(3, dl, MVT::i32));
5565 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5566 const ARMSubtarget *ST) {
5567 SDLoc dl(N);
5568 EVT VT = N->getValueType(0);
5569 if (VT.isVector()) {
5570 assert(ST->hasNEON());
5572 // Compute the least significant set bit: LSB = X & -X
5573 SDValue X = N->getOperand(0);
5574 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5575 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5577 EVT ElemTy = VT.getVectorElementType();
5579 if (ElemTy == MVT::i8) {
5580 // Compute with: cttz(x) = ctpop(lsb - 1)
5581 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5582 DAG.getTargetConstant(1, dl, ElemTy));
5583 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5584 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5587 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5588 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5589 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5590 unsigned NumBits = ElemTy.getSizeInBits();
5591 SDValue WidthMinus1 =
5592 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5593 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5594 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5595 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5598 // Compute with: cttz(x) = ctpop(lsb - 1)
5600 // Compute LSB - 1.
5601 SDValue Bits;
5602 if (ElemTy == MVT::i64) {
5603 // Load constant 0xffff'ffff'ffff'ffff to register.
5604 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5605 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5606 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5607 } else {
5608 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5609 DAG.getTargetConstant(1, dl, ElemTy));
5610 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5612 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5615 if (!ST->hasV6T2Ops())
5616 return SDValue();
5618 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5619 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5622 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5623 const ARMSubtarget *ST) {
5624 EVT VT = N->getValueType(0);
5625 SDLoc DL(N);
5627 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5628 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5629 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5630 "Unexpected type for custom ctpop lowering");
5632 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5633 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5634 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
5635 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
5637 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5638 unsigned EltSize = 8;
5639 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5640 while (EltSize != VT.getScalarSizeInBits()) {
5641 SmallVector<SDValue, 8> Ops;
5642 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
5643 TLI.getPointerTy(DAG.getDataLayout())));
5644 Ops.push_back(Res);
5646 EltSize *= 2;
5647 NumElts /= 2;
5648 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5649 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
5652 return Res;
5655 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5656 const ARMSubtarget *ST) {
5657 EVT VT = N->getValueType(0);
5658 SDLoc dl(N);
5660 if (!VT.isVector())
5661 return SDValue();
5663 // Lower vector shifts on NEON to use VSHL.
5664 assert(ST->hasNEON() && "unexpected vector shift");
5666 // Left shifts translate directly to the vshiftu intrinsic.
5667 if (N->getOpcode() == ISD::SHL)
5668 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5669 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5670 MVT::i32),
5671 N->getOperand(0), N->getOperand(1));
5673 assert((N->getOpcode() == ISD::SRA ||
5674 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5676 // NEON uses the same intrinsics for both left and right shifts. For
5677 // right shifts, the shift amounts are negative, so negate the vector of
5678 // shift amounts.
5679 EVT ShiftVT = N->getOperand(1).getValueType();
5680 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5681 getZeroVector(ShiftVT, DAG, dl),
5682 N->getOperand(1));
5683 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5684 Intrinsic::arm_neon_vshifts :
5685 Intrinsic::arm_neon_vshiftu);
5686 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5687 DAG.getConstant(vshiftInt, dl, MVT::i32),
5688 N->getOperand(0), NegatedCount);
5691 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5692 const ARMSubtarget *ST) {
5693 EVT VT = N->getValueType(0);
5694 SDLoc dl(N);
5696 // We can get here for a node like i32 = ISD::SHL i32, i64
5697 if (VT != MVT::i64)
5698 return SDValue();
5700 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
5701 N->getOpcode() == ISD::SHL) &&
5702 "Unknown shift to lower!");
5704 unsigned ShOpc = N->getOpcode();
5705 if (ST->hasMVEIntegerOps()) {
5706 SDValue ShAmt = N->getOperand(1);
5707 unsigned ShPartsOpc = ARMISD::LSLL;
5708 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
5710 // If the shift amount is greater than 32 then do the default optimisation
5711 if (Con && Con->getZExtValue() > 32)
5712 return SDValue();
5714 // Extract the lower 32 bits of the shift amount if it's an i64
5715 if (ShAmt->getValueType(0) == MVT::i64)
5716 ShAmt = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, ShAmt,
5717 DAG.getConstant(0, dl, MVT::i32));
5719 if (ShOpc == ISD::SRL) {
5720 if (!Con)
5721 // There is no t2LSRLr instruction so negate and perform an lsll if the
5722 // shift amount is in a register, emulating a right shift.
5723 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5724 DAG.getConstant(0, dl, MVT::i32), ShAmt);
5725 else
5726 // Else generate an lsrl on the immediate shift amount
5727 ShPartsOpc = ARMISD::LSRL;
5728 } else if (ShOpc == ISD::SRA)
5729 ShPartsOpc = ARMISD::ASRL;
5731 // Lower 32 bits of the destination/source
5732 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5733 DAG.getConstant(0, dl, MVT::i32));
5734 // Upper 32 bits of the destination/source
5735 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5736 DAG.getConstant(1, dl, MVT::i32));
5738 // Generate the shift operation as computed above
5739 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
5740 ShAmt);
5741 // The upper 32 bits come from the second return value of lsll
5742 Hi = SDValue(Lo.getNode(), 1);
5743 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5746 // We only lower SRA, SRL of 1 here, all others use generic lowering.
5747 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
5748 return SDValue();
5750 // If we are in thumb mode, we don't have RRX.
5751 if (ST->isThumb1Only())
5752 return SDValue();
5754 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
5755 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5756 DAG.getConstant(0, dl, MVT::i32));
5757 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5758 DAG.getConstant(1, dl, MVT::i32));
5760 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5761 // captures the result into a carry flag.
5762 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5763 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5765 // The low part is an ARMISD::RRX operand, which shifts the carry in.
5766 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5768 // Merge the pieces into a single i64 value.
5769 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5772 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5773 SDValue TmpOp0, TmpOp1;
5774 bool Invert = false;
5775 bool Swap = false;
5776 unsigned Opc = 0;
5778 SDValue Op0 = Op.getOperand(0);
5779 SDValue Op1 = Op.getOperand(1);
5780 SDValue CC = Op.getOperand(2);
5781 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5782 EVT VT = Op.getValueType();
5783 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5784 SDLoc dl(Op);
5786 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5787 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5788 // Special-case integer 64-bit equality comparisons. They aren't legal,
5789 // but they can be lowered with a few vector instructions.
5790 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5791 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5792 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5793 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5794 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5795 DAG.getCondCode(ISD::SETEQ));
5796 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5797 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5798 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5799 if (SetCCOpcode == ISD::SETNE)
5800 Merged = DAG.getNOT(dl, Merged, CmpVT);
5801 Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5802 return Merged;
5805 if (CmpVT.getVectorElementType() == MVT::i64)
5806 // 64-bit comparisons are not legal in general.
5807 return SDValue();
5809 if (Op1.getValueType().isFloatingPoint()) {
5810 switch (SetCCOpcode) {
5811 default: llvm_unreachable("Illegal FP comparison");
5812 case ISD::SETUNE:
5813 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH;
5814 case ISD::SETOEQ:
5815 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
5816 case ISD::SETOLT:
5817 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5818 case ISD::SETOGT:
5819 case ISD::SETGT: Opc = ARMISD::VCGT; break;
5820 case ISD::SETOLE:
5821 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
5822 case ISD::SETOGE:
5823 case ISD::SETGE: Opc = ARMISD::VCGE; break;
5824 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5825 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5826 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5827 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5828 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5829 case ISD::SETONE:
5830 // Expand this to (OLT | OGT).
5831 TmpOp0 = Op0;
5832 TmpOp1 = Op1;
5833 Opc = ISD::OR;
5834 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5835 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5836 break;
5837 case ISD::SETUO:
5838 Invert = true;
5839 LLVM_FALLTHROUGH;
5840 case ISD::SETO:
5841 // Expand this to (OLT | OGE).
5842 TmpOp0 = Op0;
5843 TmpOp1 = Op1;
5844 Opc = ISD::OR;
5845 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5846 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5847 break;
5849 } else {
5850 // Integer comparisons.
5851 switch (SetCCOpcode) {
5852 default: llvm_unreachable("Illegal integer comparison");
5853 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH;
5854 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
5855 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5856 case ISD::SETGT: Opc = ARMISD::VCGT; break;
5857 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
5858 case ISD::SETGE: Opc = ARMISD::VCGE; break;
5859 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
5860 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5861 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
5862 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5865 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5866 if (Opc == ARMISD::VCEQ) {
5867 SDValue AndOp;
5868 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5869 AndOp = Op0;
5870 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5871 AndOp = Op1;
5873 // Ignore bitconvert.
5874 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5875 AndOp = AndOp.getOperand(0);
5877 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5878 Opc = ARMISD::VTST;
5879 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5880 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5881 Invert = !Invert;
5886 if (Swap)
5887 std::swap(Op0, Op1);
5889 // If one of the operands is a constant vector zero, attempt to fold the
5890 // comparison to a specialized compare-against-zero form.
5891 SDValue SingleOp;
5892 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5893 SingleOp = Op0;
5894 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5895 if (Opc == ARMISD::VCGE)
5896 Opc = ARMISD::VCLEZ;
5897 else if (Opc == ARMISD::VCGT)
5898 Opc = ARMISD::VCLTZ;
5899 SingleOp = Op1;
5902 SDValue Result;
5903 if (SingleOp.getNode()) {
5904 switch (Opc) {
5905 case ARMISD::VCEQ:
5906 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5907 case ARMISD::VCGE:
5908 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5909 case ARMISD::VCLEZ:
5910 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5911 case ARMISD::VCGT:
5912 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5913 case ARMISD::VCLTZ:
5914 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5915 default:
5916 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5918 } else {
5919 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5922 Result = DAG.getSExtOrTrunc(Result, dl, VT);
5924 if (Invert)
5925 Result = DAG.getNOT(dl, Result, VT);
5927 return Result;
5930 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
5931 SDValue LHS = Op.getOperand(0);
5932 SDValue RHS = Op.getOperand(1);
5933 SDValue Carry = Op.getOperand(2);
5934 SDValue Cond = Op.getOperand(3);
5935 SDLoc DL(Op);
5937 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
5939 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
5940 // have to invert the carry first.
5941 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
5942 DAG.getConstant(1, DL, MVT::i32), Carry);
5943 // This converts the boolean value carry into the carry flag.
5944 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
5946 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5947 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5949 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5950 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5951 SDValue ARMcc = DAG.getConstant(
5952 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5953 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5954 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5955 Cmp.getValue(1), SDValue());
5956 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5957 CCR, Chain.getValue(1));
5960 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5961 /// valid vector constant for a NEON or MVE instruction with a "modified immediate"
5962 /// operand (e.g., VMOV). If so, return the encoded value.
5963 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5964 unsigned SplatBitSize, SelectionDAG &DAG,
5965 const SDLoc &dl, EVT &VT, bool is128Bits,
5966 NEONModImmType type) {
5967 unsigned OpCmode, Imm;
5969 // SplatBitSize is set to the smallest size that splats the vector, so a
5970 // zero vector will always have SplatBitSize == 8. However, NEON modified
5971 // immediate instructions others than VMOV do not support the 8-bit encoding
5972 // of a zero vector, and the default encoding of zero is supposed to be the
5973 // 32-bit version.
5974 if (SplatBits == 0)
5975 SplatBitSize = 32;
5977 switch (SplatBitSize) {
5978 case 8:
5979 if (type != VMOVModImm)
5980 return SDValue();
5981 // Any 1-byte value is OK. Op=0, Cmode=1110.
5982 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5983 OpCmode = 0xe;
5984 Imm = SplatBits;
5985 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5986 break;
5988 case 16:
5989 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5990 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5991 if ((SplatBits & ~0xff) == 0) {
5992 // Value = 0x00nn: Op=x, Cmode=100x.
5993 OpCmode = 0x8;
5994 Imm = SplatBits;
5995 break;
5997 if ((SplatBits & ~0xff00) == 0) {
5998 // Value = 0xnn00: Op=x, Cmode=101x.
5999 OpCmode = 0xa;
6000 Imm = SplatBits >> 8;
6001 break;
6003 return SDValue();
6005 case 32:
6006 // NEON's 32-bit VMOV supports splat values where:
6007 // * only one byte is nonzero, or
6008 // * the least significant byte is 0xff and the second byte is nonzero, or
6009 // * the least significant 2 bytes are 0xff and the third is nonzero.
6010 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6011 if ((SplatBits & ~0xff) == 0) {
6012 // Value = 0x000000nn: Op=x, Cmode=000x.
6013 OpCmode = 0;
6014 Imm = SplatBits;
6015 break;
6017 if ((SplatBits & ~0xff00) == 0) {
6018 // Value = 0x0000nn00: Op=x, Cmode=001x.
6019 OpCmode = 0x2;
6020 Imm = SplatBits >> 8;
6021 break;
6023 if ((SplatBits & ~0xff0000) == 0) {
6024 // Value = 0x00nn0000: Op=x, Cmode=010x.
6025 OpCmode = 0x4;
6026 Imm = SplatBits >> 16;
6027 break;
6029 if ((SplatBits & ~0xff000000) == 0) {
6030 // Value = 0xnn000000: Op=x, Cmode=011x.
6031 OpCmode = 0x6;
6032 Imm = SplatBits >> 24;
6033 break;
6036 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6037 if (type == OtherModImm) return SDValue();
6039 if ((SplatBits & ~0xffff) == 0 &&
6040 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6041 // Value = 0x0000nnff: Op=x, Cmode=1100.
6042 OpCmode = 0xc;
6043 Imm = SplatBits >> 8;
6044 break;
6047 // cmode == 0b1101 is not supported for MVE VMVN
6048 if (type == MVEVMVNModImm)
6049 return SDValue();
6051 if ((SplatBits & ~0xffffff) == 0 &&
6052 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6053 // Value = 0x00nnffff: Op=x, Cmode=1101.
6054 OpCmode = 0xd;
6055 Imm = SplatBits >> 16;
6056 break;
6059 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6060 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6061 // VMOV.I32. A (very) minor optimization would be to replicate the value
6062 // and fall through here to test for a valid 64-bit splat. But, then the
6063 // caller would also need to check and handle the change in size.
6064 return SDValue();
6066 case 64: {
6067 if (type != VMOVModImm)
6068 return SDValue();
6069 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6070 uint64_t BitMask = 0xff;
6071 uint64_t Val = 0;
6072 unsigned ImmMask = 1;
6073 Imm = 0;
6074 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6075 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6076 Val |= BitMask;
6077 Imm |= ImmMask;
6078 } else if ((SplatBits & BitMask) != 0) {
6079 return SDValue();
6081 BitMask <<= 8;
6082 ImmMask <<= 1;
6085 if (DAG.getDataLayout().isBigEndian())
6086 // swap higher and lower 32 bit word
6087 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
6089 // Op=1, Cmode=1110.
6090 OpCmode = 0x1e;
6091 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6092 break;
6095 default:
6096 llvm_unreachable("unexpected size for isNEONModifiedImm");
6099 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
6100 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6103 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6104 const ARMSubtarget *ST) const {
6105 EVT VT = Op.getValueType();
6106 bool IsDouble = (VT == MVT::f64);
6107 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6108 const APFloat &FPVal = CFP->getValueAPF();
6110 // Prevent floating-point constants from using literal loads
6111 // when execute-only is enabled.
6112 if (ST->genExecuteOnly()) {
6113 // If we can represent the constant as an immediate, don't lower it
6114 if (isFPImmLegal(FPVal, VT))
6115 return Op;
6116 // Otherwise, construct as integer, and move to float register
6117 APInt INTVal = FPVal.bitcastToAPInt();
6118 SDLoc DL(CFP);
6119 switch (VT.getSimpleVT().SimpleTy) {
6120 default:
6121 llvm_unreachable("Unknown floating point type!");
6122 break;
6123 case MVT::f64: {
6124 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6125 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6126 if (!ST->isLittle())
6127 std::swap(Lo, Hi);
6128 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
6130 case MVT::f32:
6131 return DAG.getNode(ARMISD::VMOVSR, DL, VT,
6132 DAG.getConstant(INTVal, DL, MVT::i32));
6136 if (!ST->hasVFP3Base())
6137 return SDValue();
6139 // Use the default (constant pool) lowering for double constants when we have
6140 // an SP-only FPU
6141 if (IsDouble && !Subtarget->hasFP64())
6142 return SDValue();
6144 // Try splatting with a VMOV.f32...
6145 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
6147 if (ImmVal != -1) {
6148 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6149 // We have code in place to select a valid ConstantFP already, no need to
6150 // do any mangling.
6151 return Op;
6154 // It's a float and we are trying to use NEON operations where
6155 // possible. Lower it to a splat followed by an extract.
6156 SDLoc DL(Op);
6157 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
6158 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
6159 NewVal);
6160 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
6161 DAG.getConstant(0, DL, MVT::i32));
6164 // The rest of our options are NEON only, make sure that's allowed before
6165 // proceeding..
6166 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6167 return SDValue();
6169 EVT VMovVT;
6170 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6172 // It wouldn't really be worth bothering for doubles except for one very
6173 // important value, which does happen to match: 0.0. So make sure we don't do
6174 // anything stupid.
6175 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6176 return SDValue();
6178 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6179 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
6180 VMovVT, false, VMOVModImm);
6181 if (NewVal != SDValue()) {
6182 SDLoc DL(Op);
6183 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
6184 NewVal);
6185 if (IsDouble)
6186 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6188 // It's a float: cast and extract a vector element.
6189 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6190 VecConstant);
6191 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6192 DAG.getConstant(0, DL, MVT::i32));
6195 // Finally, try a VMVN.i32
6196 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6197 false, VMVNModImm);
6198 if (NewVal != SDValue()) {
6199 SDLoc DL(Op);
6200 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6202 if (IsDouble)
6203 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6205 // It's a float: cast and extract a vector element.
6206 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6207 VecConstant);
6208 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6209 DAG.getConstant(0, DL, MVT::i32));
6212 return SDValue();
6215 // check if an VEXT instruction can handle the shuffle mask when the
6216 // vector sources of the shuffle are the same.
6217 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6218 unsigned NumElts = VT.getVectorNumElements();
6220 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6221 if (M[0] < 0)
6222 return false;
6224 Imm = M[0];
6226 // If this is a VEXT shuffle, the immediate value is the index of the first
6227 // element. The other shuffle indices must be the successive elements after
6228 // the first one.
6229 unsigned ExpectedElt = Imm;
6230 for (unsigned i = 1; i < NumElts; ++i) {
6231 // Increment the expected index. If it wraps around, just follow it
6232 // back to index zero and keep going.
6233 ++ExpectedElt;
6234 if (ExpectedElt == NumElts)
6235 ExpectedElt = 0;
6237 if (M[i] < 0) continue; // ignore UNDEF indices
6238 if (ExpectedElt != static_cast<unsigned>(M[i]))
6239 return false;
6242 return true;
6245 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6246 bool &ReverseVEXT, unsigned &Imm) {
6247 unsigned NumElts = VT.getVectorNumElements();
6248 ReverseVEXT = false;
6250 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6251 if (M[0] < 0)
6252 return false;
6254 Imm = M[0];
6256 // If this is a VEXT shuffle, the immediate value is the index of the first
6257 // element. The other shuffle indices must be the successive elements after
6258 // the first one.
6259 unsigned ExpectedElt = Imm;
6260 for (unsigned i = 1; i < NumElts; ++i) {
6261 // Increment the expected index. If it wraps around, it may still be
6262 // a VEXT but the source vectors must be swapped.
6263 ExpectedElt += 1;
6264 if (ExpectedElt == NumElts * 2) {
6265 ExpectedElt = 0;
6266 ReverseVEXT = true;
6269 if (M[i] < 0) continue; // ignore UNDEF indices
6270 if (ExpectedElt != static_cast<unsigned>(M[i]))
6271 return false;
6274 // Adjust the index value if the source operands will be swapped.
6275 if (ReverseVEXT)
6276 Imm -= NumElts;
6278 return true;
6281 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6282 /// instruction with the specified blocksize. (The order of the elements
6283 /// within each block of the vector is reversed.)
6284 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6285 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6286 "Only possible block sizes for VREV are: 16, 32, 64");
6288 unsigned EltSz = VT.getScalarSizeInBits();
6289 if (EltSz == 64)
6290 return false;
6292 unsigned NumElts = VT.getVectorNumElements();
6293 unsigned BlockElts = M[0] + 1;
6294 // If the first shuffle index is UNDEF, be optimistic.
6295 if (M[0] < 0)
6296 BlockElts = BlockSize / EltSz;
6298 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6299 return false;
6301 for (unsigned i = 0; i < NumElts; ++i) {
6302 if (M[i] < 0) continue; // ignore UNDEF indices
6303 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6304 return false;
6307 return true;
6310 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6311 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6312 // range, then 0 is placed into the resulting vector. So pretty much any mask
6313 // of 8 elements can work here.
6314 return VT == MVT::v8i8 && M.size() == 8;
6317 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6318 unsigned Index) {
6319 if (Mask.size() == Elements * 2)
6320 return Index / Elements;
6321 return Mask[Index] == 0 ? 0 : 1;
6324 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6325 // checking that pairs of elements in the shuffle mask represent the same index
6326 // in each vector, incrementing the expected index by 2 at each step.
6327 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6328 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6329 // v2={e,f,g,h}
6330 // WhichResult gives the offset for each element in the mask based on which
6331 // of the two results it belongs to.
6333 // The transpose can be represented either as:
6334 // result1 = shufflevector v1, v2, result1_shuffle_mask
6335 // result2 = shufflevector v1, v2, result2_shuffle_mask
6336 // where v1/v2 and the shuffle masks have the same number of elements
6337 // (here WhichResult (see below) indicates which result is being checked)
6339 // or as:
6340 // results = shufflevector v1, v2, shuffle_mask
6341 // where both results are returned in one vector and the shuffle mask has twice
6342 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6343 // want to check the low half and high half of the shuffle mask as if it were
6344 // the other case
6345 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6346 unsigned EltSz = VT.getScalarSizeInBits();
6347 if (EltSz == 64)
6348 return false;
6350 unsigned NumElts = VT.getVectorNumElements();
6351 if (M.size() != NumElts && M.size() != NumElts*2)
6352 return false;
6354 // If the mask is twice as long as the input vector then we need to check the
6355 // upper and lower parts of the mask with a matching value for WhichResult
6356 // FIXME: A mask with only even values will be rejected in case the first
6357 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6358 // M[0] is used to determine WhichResult
6359 for (unsigned i = 0; i < M.size(); i += NumElts) {
6360 WhichResult = SelectPairHalf(NumElts, M, i);
6361 for (unsigned j = 0; j < NumElts; j += 2) {
6362 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6363 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6364 return false;
6368 if (M.size() == NumElts*2)
6369 WhichResult = 0;
6371 return true;
6374 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6375 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6376 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6377 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6378 unsigned EltSz = VT.getScalarSizeInBits();
6379 if (EltSz == 64)
6380 return false;
6382 unsigned NumElts = VT.getVectorNumElements();
6383 if (M.size() != NumElts && M.size() != NumElts*2)
6384 return false;
6386 for (unsigned i = 0; i < M.size(); i += NumElts) {
6387 WhichResult = SelectPairHalf(NumElts, M, i);
6388 for (unsigned j = 0; j < NumElts; j += 2) {
6389 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6390 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6391 return false;
6395 if (M.size() == NumElts*2)
6396 WhichResult = 0;
6398 return true;
6401 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6402 // that the mask elements are either all even and in steps of size 2 or all odd
6403 // and in steps of size 2.
6404 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6405 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6406 // v2={e,f,g,h}
6407 // Requires similar checks to that of isVTRNMask with
6408 // respect the how results are returned.
6409 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6410 unsigned EltSz = VT.getScalarSizeInBits();
6411 if (EltSz == 64)
6412 return false;
6414 unsigned NumElts = VT.getVectorNumElements();
6415 if (M.size() != NumElts && M.size() != NumElts*2)
6416 return false;
6418 for (unsigned i = 0; i < M.size(); i += NumElts) {
6419 WhichResult = SelectPairHalf(NumElts, M, i);
6420 for (unsigned j = 0; j < NumElts; ++j) {
6421 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6422 return false;
6426 if (M.size() == NumElts*2)
6427 WhichResult = 0;
6429 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6430 if (VT.is64BitVector() && EltSz == 32)
6431 return false;
6433 return true;
6436 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6437 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6438 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6439 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6440 unsigned EltSz = VT.getScalarSizeInBits();
6441 if (EltSz == 64)
6442 return false;
6444 unsigned NumElts = VT.getVectorNumElements();
6445 if (M.size() != NumElts && M.size() != NumElts*2)
6446 return false;
6448 unsigned Half = NumElts / 2;
6449 for (unsigned i = 0; i < M.size(); i += NumElts) {
6450 WhichResult = SelectPairHalf(NumElts, M, i);
6451 for (unsigned j = 0; j < NumElts; j += Half) {
6452 unsigned Idx = WhichResult;
6453 for (unsigned k = 0; k < Half; ++k) {
6454 int MIdx = M[i + j + k];
6455 if (MIdx >= 0 && (unsigned) MIdx != Idx)
6456 return false;
6457 Idx += 2;
6462 if (M.size() == NumElts*2)
6463 WhichResult = 0;
6465 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6466 if (VT.is64BitVector() && EltSz == 32)
6467 return false;
6469 return true;
6472 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6473 // that pairs of elements of the shufflemask represent the same index in each
6474 // vector incrementing sequentially through the vectors.
6475 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6476 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6477 // v2={e,f,g,h}
6478 // Requires similar checks to that of isVTRNMask with respect the how results
6479 // are returned.
6480 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6481 unsigned EltSz = VT.getScalarSizeInBits();
6482 if (EltSz == 64)
6483 return false;
6485 unsigned NumElts = VT.getVectorNumElements();
6486 if (M.size() != NumElts && M.size() != NumElts*2)
6487 return false;
6489 for (unsigned i = 0; i < M.size(); i += NumElts) {
6490 WhichResult = SelectPairHalf(NumElts, M, i);
6491 unsigned Idx = WhichResult * NumElts / 2;
6492 for (unsigned j = 0; j < NumElts; j += 2) {
6493 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6494 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6495 return false;
6496 Idx += 1;
6500 if (M.size() == NumElts*2)
6501 WhichResult = 0;
6503 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6504 if (VT.is64BitVector() && EltSz == 32)
6505 return false;
6507 return true;
6510 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6511 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6512 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6513 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6514 unsigned EltSz = VT.getScalarSizeInBits();
6515 if (EltSz == 64)
6516 return false;
6518 unsigned NumElts = VT.getVectorNumElements();
6519 if (M.size() != NumElts && M.size() != NumElts*2)
6520 return false;
6522 for (unsigned i = 0; i < M.size(); i += NumElts) {
6523 WhichResult = SelectPairHalf(NumElts, M, i);
6524 unsigned Idx = WhichResult * NumElts / 2;
6525 for (unsigned j = 0; j < NumElts; j += 2) {
6526 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6527 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6528 return false;
6529 Idx += 1;
6533 if (M.size() == NumElts*2)
6534 WhichResult = 0;
6536 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6537 if (VT.is64BitVector() && EltSz == 32)
6538 return false;
6540 return true;
6543 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6544 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6545 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6546 unsigned &WhichResult,
6547 bool &isV_UNDEF) {
6548 isV_UNDEF = false;
6549 if (isVTRNMask(ShuffleMask, VT, WhichResult))
6550 return ARMISD::VTRN;
6551 if (isVUZPMask(ShuffleMask, VT, WhichResult))
6552 return ARMISD::VUZP;
6553 if (isVZIPMask(ShuffleMask, VT, WhichResult))
6554 return ARMISD::VZIP;
6556 isV_UNDEF = true;
6557 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6558 return ARMISD::VTRN;
6559 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6560 return ARMISD::VUZP;
6561 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6562 return ARMISD::VZIP;
6564 return 0;
6567 /// \return true if this is a reverse operation on an vector.
6568 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6569 unsigned NumElts = VT.getVectorNumElements();
6570 // Make sure the mask has the right size.
6571 if (NumElts != M.size())
6572 return false;
6574 // Look for <15, ..., 3, -1, 1, 0>.
6575 for (unsigned i = 0; i != NumElts; ++i)
6576 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6577 return false;
6579 return true;
6582 // If N is an integer constant that can be moved into a register in one
6583 // instruction, return an SDValue of such a constant (will become a MOV
6584 // instruction). Otherwise return null.
6585 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6586 const ARMSubtarget *ST, const SDLoc &dl) {
6587 uint64_t Val;
6588 if (!isa<ConstantSDNode>(N))
6589 return SDValue();
6590 Val = cast<ConstantSDNode>(N)->getZExtValue();
6592 if (ST->isThumb1Only()) {
6593 if (Val <= 255 || ~Val <= 255)
6594 return DAG.getConstant(Val, dl, MVT::i32);
6595 } else {
6596 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6597 return DAG.getConstant(Val, dl, MVT::i32);
6599 return SDValue();
6602 // If this is a case we can't handle, return null and let the default
6603 // expansion code take care of it.
6604 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6605 const ARMSubtarget *ST) const {
6606 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6607 SDLoc dl(Op);
6608 EVT VT = Op.getValueType();
6610 APInt SplatBits, SplatUndef;
6611 unsigned SplatBitSize;
6612 bool HasAnyUndefs;
6613 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6614 if (SplatUndef.isAllOnesValue())
6615 return DAG.getUNDEF(VT);
6617 if ((ST->hasNEON() && SplatBitSize <= 64) ||
6618 (ST->hasMVEIntegerOps() && SplatBitSize <= 32)) {
6619 // Check if an immediate VMOV works.
6620 EVT VmovVT;
6621 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6622 SplatUndef.getZExtValue(), SplatBitSize,
6623 DAG, dl, VmovVT, VT.is128BitVector(),
6624 VMOVModImm);
6626 if (Val.getNode()) {
6627 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6628 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6631 // Try an immediate VMVN.
6632 uint64_t NegatedImm = (~SplatBits).getZExtValue();
6633 Val = isNEONModifiedImm(
6634 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize,
6635 DAG, dl, VmovVT, VT.is128BitVector(),
6636 ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
6637 if (Val.getNode()) {
6638 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6639 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6642 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6643 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6644 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6645 if (ImmVal != -1) {
6646 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6647 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6653 // Scan through the operands to see if only one value is used.
6655 // As an optimisation, even if more than one value is used it may be more
6656 // profitable to splat with one value then change some lanes.
6658 // Heuristically we decide to do this if the vector has a "dominant" value,
6659 // defined as splatted to more than half of the lanes.
6660 unsigned NumElts = VT.getVectorNumElements();
6661 bool isOnlyLowElement = true;
6662 bool usesOnlyOneValue = true;
6663 bool hasDominantValue = false;
6664 bool isConstant = true;
6666 // Map of the number of times a particular SDValue appears in the
6667 // element list.
6668 DenseMap<SDValue, unsigned> ValueCounts;
6669 SDValue Value;
6670 for (unsigned i = 0; i < NumElts; ++i) {
6671 SDValue V = Op.getOperand(i);
6672 if (V.isUndef())
6673 continue;
6674 if (i > 0)
6675 isOnlyLowElement = false;
6676 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6677 isConstant = false;
6679 ValueCounts.insert(std::make_pair(V, 0));
6680 unsigned &Count = ValueCounts[V];
6682 // Is this value dominant? (takes up more than half of the lanes)
6683 if (++Count > (NumElts / 2)) {
6684 hasDominantValue = true;
6685 Value = V;
6688 if (ValueCounts.size() != 1)
6689 usesOnlyOneValue = false;
6690 if (!Value.getNode() && !ValueCounts.empty())
6691 Value = ValueCounts.begin()->first;
6693 if (ValueCounts.empty())
6694 return DAG.getUNDEF(VT);
6696 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6697 // Keep going if we are hitting this case.
6698 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6699 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6701 unsigned EltSize = VT.getScalarSizeInBits();
6703 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
6704 // i32 and try again.
6705 if (hasDominantValue && EltSize <= 32) {
6706 if (!isConstant) {
6707 SDValue N;
6709 // If we are VDUPing a value that comes directly from a vector, that will
6710 // cause an unnecessary move to and from a GPR, where instead we could
6711 // just use VDUPLANE. We can only do this if the lane being extracted
6712 // is at a constant index, as the VDUP from lane instructions only have
6713 // constant-index forms.
6714 ConstantSDNode *constIndex;
6715 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6716 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6717 // We need to create a new undef vector to use for the VDUPLANE if the
6718 // size of the vector from which we get the value is different than the
6719 // size of the vector that we need to create. We will insert the element
6720 // such that the register coalescer will remove unnecessary copies.
6721 if (VT != Value->getOperand(0).getValueType()) {
6722 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6723 VT.getVectorNumElements();
6724 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6725 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6726 Value, DAG.getConstant(index, dl, MVT::i32)),
6727 DAG.getConstant(index, dl, MVT::i32));
6728 } else
6729 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6730 Value->getOperand(0), Value->getOperand(1));
6731 } else
6732 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6734 if (!usesOnlyOneValue) {
6735 // The dominant value was splatted as 'N', but we now have to insert
6736 // all differing elements.
6737 for (unsigned I = 0; I < NumElts; ++I) {
6738 if (Op.getOperand(I) == Value)
6739 continue;
6740 SmallVector<SDValue, 3> Ops;
6741 Ops.push_back(N);
6742 Ops.push_back(Op.getOperand(I));
6743 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6744 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6747 return N;
6749 if (VT.getVectorElementType().isFloatingPoint()) {
6750 SmallVector<SDValue, 8> Ops;
6751 MVT FVT = VT.getVectorElementType().getSimpleVT();
6752 assert(FVT == MVT::f32 || FVT == MVT::f16);
6753 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
6754 for (unsigned i = 0; i < NumElts; ++i)
6755 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
6756 Op.getOperand(i)));
6757 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
6758 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6759 Val = LowerBUILD_VECTOR(Val, DAG, ST);
6760 if (Val.getNode())
6761 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6763 if (usesOnlyOneValue) {
6764 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6765 if (isConstant && Val.getNode())
6766 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6770 // If all elements are constants and the case above didn't get hit, fall back
6771 // to the default expansion, which will generate a load from the constant
6772 // pool.
6773 if (isConstant)
6774 return SDValue();
6776 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6777 if (NumElts >= 4) {
6778 SDValue shuffle = ReconstructShuffle(Op, DAG);
6779 if (shuffle != SDValue())
6780 return shuffle;
6783 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6784 // If we haven't found an efficient lowering, try splitting a 128-bit vector
6785 // into two 64-bit vectors; we might discover a better way to lower it.
6786 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6787 EVT ExtVT = VT.getVectorElementType();
6788 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6789 SDValue Lower =
6790 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6791 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6792 Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6793 SDValue Upper = DAG.getBuildVector(
6794 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6795 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6796 Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6797 if (Lower && Upper)
6798 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6801 // Vectors with 32- or 64-bit elements can be built by directly assigning
6802 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
6803 // will be legalized.
6804 if (EltSize >= 32) {
6805 // Do the expansion with floating-point types, since that is what the VFP
6806 // registers are defined to use, and since i64 is not legal.
6807 EVT EltVT = EVT::getFloatingPointVT(EltSize);
6808 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6809 SmallVector<SDValue, 8> Ops;
6810 for (unsigned i = 0; i < NumElts; ++i)
6811 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6812 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6813 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6816 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6817 // know the default expansion would otherwise fall back on something even
6818 // worse. For a vector with one or two non-undef values, that's
6819 // scalar_to_vector for the elements followed by a shuffle (provided the
6820 // shuffle is valid for the target) and materialization element by element
6821 // on the stack followed by a load for everything else.
6822 if (!isConstant && !usesOnlyOneValue) {
6823 SDValue Vec = DAG.getUNDEF(VT);
6824 for (unsigned i = 0 ; i < NumElts; ++i) {
6825 SDValue V = Op.getOperand(i);
6826 if (V.isUndef())
6827 continue;
6828 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6829 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6831 return Vec;
6834 return SDValue();
6837 // Gather data to see if the operation can be modelled as a
6838 // shuffle in combination with VEXTs.
6839 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6840 SelectionDAG &DAG) const {
6841 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6842 SDLoc dl(Op);
6843 EVT VT = Op.getValueType();
6844 unsigned NumElts = VT.getVectorNumElements();
6846 struct ShuffleSourceInfo {
6847 SDValue Vec;
6848 unsigned MinElt = std::numeric_limits<unsigned>::max();
6849 unsigned MaxElt = 0;
6851 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6852 // be compatible with the shuffle we intend to construct. As a result
6853 // ShuffleVec will be some sliding window into the original Vec.
6854 SDValue ShuffleVec;
6856 // Code should guarantee that element i in Vec starts at element "WindowBase
6857 // + i * WindowScale in ShuffleVec".
6858 int WindowBase = 0;
6859 int WindowScale = 1;
6861 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
6863 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6866 // First gather all vectors used as an immediate source for this BUILD_VECTOR
6867 // node.
6868 SmallVector<ShuffleSourceInfo, 2> Sources;
6869 for (unsigned i = 0; i < NumElts; ++i) {
6870 SDValue V = Op.getOperand(i);
6871 if (V.isUndef())
6872 continue;
6873 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6874 // A shuffle can only come from building a vector from various
6875 // elements of other vectors.
6876 return SDValue();
6877 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6878 // Furthermore, shuffles require a constant mask, whereas extractelts
6879 // accept variable indices.
6880 return SDValue();
6883 // Add this element source to the list if it's not already there.
6884 SDValue SourceVec = V.getOperand(0);
6885 auto Source = llvm::find(Sources, SourceVec);
6886 if (Source == Sources.end())
6887 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6889 // Update the minimum and maximum lane number seen.
6890 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6891 Source->MinElt = std::min(Source->MinElt, EltNo);
6892 Source->MaxElt = std::max(Source->MaxElt, EltNo);
6895 // Currently only do something sane when at most two source vectors
6896 // are involved.
6897 if (Sources.size() > 2)
6898 return SDValue();
6900 // Find out the smallest element size among result and two sources, and use
6901 // it as element size to build the shuffle_vector.
6902 EVT SmallestEltTy = VT.getVectorElementType();
6903 for (auto &Source : Sources) {
6904 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6905 if (SrcEltTy.bitsLT(SmallestEltTy))
6906 SmallestEltTy = SrcEltTy;
6908 unsigned ResMultiplier =
6909 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6910 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6911 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6913 // If the source vector is too wide or too narrow, we may nevertheless be able
6914 // to construct a compatible shuffle either by concatenating it with UNDEF or
6915 // extracting a suitable range of elements.
6916 for (auto &Src : Sources) {
6917 EVT SrcVT = Src.ShuffleVec.getValueType();
6919 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6920 continue;
6922 // This stage of the search produces a source with the same element type as
6923 // the original, but with a total width matching the BUILD_VECTOR output.
6924 EVT EltVT = SrcVT.getVectorElementType();
6925 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6926 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6928 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6929 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6930 return SDValue();
6931 // We can pad out the smaller vector for free, so if it's part of a
6932 // shuffle...
6933 Src.ShuffleVec =
6934 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6935 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6936 continue;
6939 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6940 return SDValue();
6942 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6943 // Span too large for a VEXT to cope
6944 return SDValue();
6947 if (Src.MinElt >= NumSrcElts) {
6948 // The extraction can just take the second half
6949 Src.ShuffleVec =
6950 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6951 DAG.getConstant(NumSrcElts, dl, MVT::i32));
6952 Src.WindowBase = -NumSrcElts;
6953 } else if (Src.MaxElt < NumSrcElts) {
6954 // The extraction can just take the first half
6955 Src.ShuffleVec =
6956 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6957 DAG.getConstant(0, dl, MVT::i32));
6958 } else {
6959 // An actual VEXT is needed
6960 SDValue VEXTSrc1 =
6961 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6962 DAG.getConstant(0, dl, MVT::i32));
6963 SDValue VEXTSrc2 =
6964 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6965 DAG.getConstant(NumSrcElts, dl, MVT::i32));
6967 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6968 VEXTSrc2,
6969 DAG.getConstant(Src.MinElt, dl, MVT::i32));
6970 Src.WindowBase = -Src.MinElt;
6974 // Another possible incompatibility occurs from the vector element types. We
6975 // can fix this by bitcasting the source vectors to the same type we intend
6976 // for the shuffle.
6977 for (auto &Src : Sources) {
6978 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6979 if (SrcEltTy == SmallestEltTy)
6980 continue;
6981 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6982 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6983 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6984 Src.WindowBase *= Src.WindowScale;
6987 // Final sanity check before we try to actually produce a shuffle.
6988 LLVM_DEBUG(for (auto Src
6989 : Sources)
6990 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
6992 // The stars all align, our next step is to produce the mask for the shuffle.
6993 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6994 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6995 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6996 SDValue Entry = Op.getOperand(i);
6997 if (Entry.isUndef())
6998 continue;
7000 auto Src = llvm::find(Sources, Entry.getOperand(0));
7001 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7003 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7004 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7005 // segment.
7006 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7007 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
7008 VT.getScalarSizeInBits());
7009 int LanesDefined = BitsDefined / BitsPerShuffleLane;
7011 // This source is expected to fill ResMultiplier lanes of the final shuffle,
7012 // starting at the appropriate offset.
7013 int *LaneMask = &Mask[i * ResMultiplier];
7015 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7016 ExtractBase += NumElts * (Src - Sources.begin());
7017 for (int j = 0; j < LanesDefined; ++j)
7018 LaneMask[j] = ExtractBase + j;
7021 // Final check before we try to produce nonsense...
7022 if (!isShuffleMaskLegal(Mask, ShuffleVT))
7023 return SDValue();
7025 // We can't handle more than two sources. This should have already
7026 // been checked before this point.
7027 assert(Sources.size() <= 2 && "Too many sources!");
7029 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7030 for (unsigned i = 0; i < Sources.size(); ++i)
7031 ShuffleOps[i] = Sources[i].ShuffleVec;
7033 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7034 ShuffleOps[1], Mask);
7035 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
7038 enum ShuffleOpCodes {
7039 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7040 OP_VREV,
7041 OP_VDUP0,
7042 OP_VDUP1,
7043 OP_VDUP2,
7044 OP_VDUP3,
7045 OP_VEXT1,
7046 OP_VEXT2,
7047 OP_VEXT3,
7048 OP_VUZPL, // VUZP, left result
7049 OP_VUZPR, // VUZP, right result
7050 OP_VZIPL, // VZIP, left result
7051 OP_VZIPR, // VZIP, right result
7052 OP_VTRNL, // VTRN, left result
7053 OP_VTRNR // VTRN, right result
7056 static bool isLegalMVEShuffleOp(unsigned PFEntry) {
7057 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7058 switch (OpNum) {
7059 case OP_COPY:
7060 case OP_VREV:
7061 case OP_VDUP0:
7062 case OP_VDUP1:
7063 case OP_VDUP2:
7064 case OP_VDUP3:
7065 return true;
7067 return false;
7070 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7071 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7072 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7073 /// are assumed to be legal.
7074 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7075 if (VT.getVectorNumElements() == 4 &&
7076 (VT.is128BitVector() || VT.is64BitVector())) {
7077 unsigned PFIndexes[4];
7078 for (unsigned i = 0; i != 4; ++i) {
7079 if (M[i] < 0)
7080 PFIndexes[i] = 8;
7081 else
7082 PFIndexes[i] = M[i];
7085 // Compute the index in the perfect shuffle table.
7086 unsigned PFTableIndex =
7087 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7088 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7089 unsigned Cost = (PFEntry >> 30);
7091 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
7092 return true;
7095 bool ReverseVEXT, isV_UNDEF;
7096 unsigned Imm, WhichResult;
7098 unsigned EltSize = VT.getScalarSizeInBits();
7099 if (EltSize >= 32 ||
7100 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7101 isVREVMask(M, VT, 64) ||
7102 isVREVMask(M, VT, 32) ||
7103 isVREVMask(M, VT, 16))
7104 return true;
7105 else if (Subtarget->hasNEON() &&
7106 (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
7107 isVTBLMask(M, VT) ||
7108 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
7109 return true;
7110 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) &&
7111 isReverseMask(M, VT))
7112 return true;
7113 else
7114 return false;
7117 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7118 /// the specified operations to build the shuffle.
7119 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7120 SDValue RHS, SelectionDAG &DAG,
7121 const SDLoc &dl) {
7122 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7123 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7124 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7126 if (OpNum == OP_COPY) {
7127 if (LHSID == (1*9+2)*9+3) return LHS;
7128 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7129 return RHS;
7132 SDValue OpLHS, OpRHS;
7133 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7134 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7135 EVT VT = OpLHS.getValueType();
7137 switch (OpNum) {
7138 default: llvm_unreachable("Unknown shuffle opcode!");
7139 case OP_VREV:
7140 // VREV divides the vector in half and swaps within the half.
7141 if (VT.getVectorElementType() == MVT::i32 ||
7142 VT.getVectorElementType() == MVT::f32)
7143 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
7144 // vrev <4 x i16> -> VREV32
7145 if (VT.getVectorElementType() == MVT::i16)
7146 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
7147 // vrev <4 x i8> -> VREV16
7148 assert(VT.getVectorElementType() == MVT::i8);
7149 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
7150 case OP_VDUP0:
7151 case OP_VDUP1:
7152 case OP_VDUP2:
7153 case OP_VDUP3:
7154 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7155 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
7156 case OP_VEXT1:
7157 case OP_VEXT2:
7158 case OP_VEXT3:
7159 return DAG.getNode(ARMISD::VEXT, dl, VT,
7160 OpLHS, OpRHS,
7161 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
7162 case OP_VUZPL:
7163 case OP_VUZPR:
7164 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
7165 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
7166 case OP_VZIPL:
7167 case OP_VZIPR:
7168 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
7169 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
7170 case OP_VTRNL:
7171 case OP_VTRNR:
7172 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
7173 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
7177 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
7178 ArrayRef<int> ShuffleMask,
7179 SelectionDAG &DAG) {
7180 // Check to see if we can use the VTBL instruction.
7181 SDValue V1 = Op.getOperand(0);
7182 SDValue V2 = Op.getOperand(1);
7183 SDLoc DL(Op);
7185 SmallVector<SDValue, 8> VTBLMask;
7186 for (ArrayRef<int>::iterator
7187 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
7188 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
7190 if (V2.getNode()->isUndef())
7191 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
7192 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7194 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
7195 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7198 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
7199 SelectionDAG &DAG) {
7200 SDLoc DL(Op);
7201 SDValue OpLHS = Op.getOperand(0);
7202 EVT VT = OpLHS.getValueType();
7204 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
7205 "Expect an v8i16/v16i8 type");
7206 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
7207 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
7208 // extract the first 8 bytes into the top double word and the last 8 bytes
7209 // into the bottom double word. The v8i16 case is similar.
7210 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
7211 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
7212 DAG.getConstant(ExtractNum, DL, MVT::i32));
7215 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
7216 const ARMSubtarget *ST) {
7217 SDValue V1 = Op.getOperand(0);
7218 SDValue V2 = Op.getOperand(1);
7219 SDLoc dl(Op);
7220 EVT VT = Op.getValueType();
7221 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7223 // Convert shuffles that are directly supported on NEON to target-specific
7224 // DAG nodes, instead of keeping them as shuffles and matching them again
7225 // during code selection. This is more efficient and avoids the possibility
7226 // of inconsistencies between legalization and selection.
7227 // FIXME: floating-point vectors should be canonicalized to integer vectors
7228 // of the same time so that they get CSEd properly.
7229 ArrayRef<int> ShuffleMask = SVN->getMask();
7231 unsigned EltSize = VT.getScalarSizeInBits();
7232 if (EltSize <= 32) {
7233 if (SVN->isSplat()) {
7234 int Lane = SVN->getSplatIndex();
7235 // If this is undef splat, generate it via "just" vdup, if possible.
7236 if (Lane == -1) Lane = 0;
7238 // Test if V1 is a SCALAR_TO_VECTOR.
7239 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
7240 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7242 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
7243 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
7244 // reaches it).
7245 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
7246 !isa<ConstantSDNode>(V1.getOperand(0))) {
7247 bool IsScalarToVector = true;
7248 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
7249 if (!V1.getOperand(i).isUndef()) {
7250 IsScalarToVector = false;
7251 break;
7253 if (IsScalarToVector)
7254 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7256 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
7257 DAG.getConstant(Lane, dl, MVT::i32));
7260 bool ReverseVEXT = false;
7261 unsigned Imm = 0;
7262 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
7263 if (ReverseVEXT)
7264 std::swap(V1, V2);
7265 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
7266 DAG.getConstant(Imm, dl, MVT::i32));
7269 if (isVREVMask(ShuffleMask, VT, 64))
7270 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
7271 if (isVREVMask(ShuffleMask, VT, 32))
7272 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
7273 if (isVREVMask(ShuffleMask, VT, 16))
7274 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
7276 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
7277 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
7278 DAG.getConstant(Imm, dl, MVT::i32));
7281 // Check for Neon shuffles that modify both input vectors in place.
7282 // If both results are used, i.e., if there are two shuffles with the same
7283 // source operands and with masks corresponding to both results of one of
7284 // these operations, DAG memoization will ensure that a single node is
7285 // used for both shuffles.
7286 unsigned WhichResult = 0;
7287 bool isV_UNDEF = false;
7288 if (ST->hasNEON()) {
7289 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7290 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
7291 if (isV_UNDEF)
7292 V2 = V1;
7293 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
7294 .getValue(WhichResult);
7298 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
7299 // shuffles that produce a result larger than their operands with:
7300 // shuffle(concat(v1, undef), concat(v2, undef))
7301 // ->
7302 // shuffle(concat(v1, v2), undef)
7303 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
7305 // This is useful in the general case, but there are special cases where
7306 // native shuffles produce larger results: the two-result ops.
7308 // Look through the concat when lowering them:
7309 // shuffle(concat(v1, v2), undef)
7310 // ->
7311 // concat(VZIP(v1, v2):0, :1)
7313 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
7314 SDValue SubV1 = V1->getOperand(0);
7315 SDValue SubV2 = V1->getOperand(1);
7316 EVT SubVT = SubV1.getValueType();
7318 // We expect these to have been canonicalized to -1.
7319 assert(llvm::all_of(ShuffleMask, [&](int i) {
7320 return i < (int)VT.getVectorNumElements();
7321 }) && "Unexpected shuffle index into UNDEF operand!");
7323 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7324 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
7325 if (isV_UNDEF)
7326 SubV2 = SubV1;
7327 assert((WhichResult == 0) &&
7328 "In-place shuffle of concat can only have one result!");
7329 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
7330 SubV1, SubV2);
7331 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
7332 Res.getValue(1));
7337 // If the shuffle is not directly supported and it has 4 elements, use
7338 // the PerfectShuffle-generated table to synthesize it from other shuffles.
7339 unsigned NumElts = VT.getVectorNumElements();
7340 if (NumElts == 4) {
7341 unsigned PFIndexes[4];
7342 for (unsigned i = 0; i != 4; ++i) {
7343 if (ShuffleMask[i] < 0)
7344 PFIndexes[i] = 8;
7345 else
7346 PFIndexes[i] = ShuffleMask[i];
7349 // Compute the index in the perfect shuffle table.
7350 unsigned PFTableIndex =
7351 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7352 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7353 unsigned Cost = (PFEntry >> 30);
7355 if (Cost <= 4) {
7356 if (ST->hasNEON())
7357 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7358 else if (isLegalMVEShuffleOp(PFEntry)) {
7359 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7360 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7361 unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
7362 unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
7363 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
7364 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7369 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
7370 if (EltSize >= 32) {
7371 // Do the expansion with floating-point types, since that is what the VFP
7372 // registers are defined to use, and since i64 is not legal.
7373 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7374 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7375 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
7376 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
7377 SmallVector<SDValue, 8> Ops;
7378 for (unsigned i = 0; i < NumElts; ++i) {
7379 if (ShuffleMask[i] < 0)
7380 Ops.push_back(DAG.getUNDEF(EltVT));
7381 else
7382 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7383 ShuffleMask[i] < (int)NumElts ? V1 : V2,
7384 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
7385 dl, MVT::i32)));
7387 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7388 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7391 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
7392 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
7394 if (ST->hasNEON() && VT == MVT::v8i8)
7395 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
7396 return NewOp;
7398 return SDValue();
7401 SDValue ARMTargetLowering::
7402 LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7403 // INSERT_VECTOR_ELT is legal only for immediate indexes.
7404 SDValue Lane = Op.getOperand(2);
7405 if (!isa<ConstantSDNode>(Lane))
7406 return SDValue();
7408 SDValue Elt = Op.getOperand(1);
7409 EVT EltVT = Elt.getValueType();
7410 if (getTypeAction(*DAG.getContext(), EltVT) ==
7411 TargetLowering::TypePromoteFloat) {
7412 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
7413 // but the type system will try to do that if we don't intervene.
7414 // Reinterpret any such vector-element insertion as one with the
7415 // corresponding integer types.
7417 SDLoc dl(Op);
7419 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
7420 assert(getTypeAction(*DAG.getContext(), IEltVT) !=
7421 TargetLowering::TypePromoteFloat);
7423 SDValue VecIn = Op.getOperand(0);
7424 EVT VecVT = VecIn.getValueType();
7425 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
7426 VecVT.getVectorNumElements());
7428 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
7429 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
7430 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
7431 IVecIn, IElt, Lane);
7432 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
7435 return Op;
7438 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
7439 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
7440 SDValue Lane = Op.getOperand(1);
7441 if (!isa<ConstantSDNode>(Lane))
7442 return SDValue();
7444 SDValue Vec = Op.getOperand(0);
7445 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
7446 SDLoc dl(Op);
7447 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
7450 return Op;
7453 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7454 // The only time a CONCAT_VECTORS operation can have legal types is when
7455 // two 64-bit vectors are concatenated to a 128-bit vector.
7456 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
7457 "unexpected CONCAT_VECTORS");
7458 SDLoc dl(Op);
7459 SDValue Val = DAG.getUNDEF(MVT::v2f64);
7460 SDValue Op0 = Op.getOperand(0);
7461 SDValue Op1 = Op.getOperand(1);
7462 if (!Op0.isUndef())
7463 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7464 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
7465 DAG.getIntPtrConstant(0, dl));
7466 if (!Op1.isUndef())
7467 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7468 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
7469 DAG.getIntPtrConstant(1, dl));
7470 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
7473 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
7474 /// element has been zero/sign-extended, depending on the isSigned parameter,
7475 /// from an integer type half its size.
7476 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
7477 bool isSigned) {
7478 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
7479 EVT VT = N->getValueType(0);
7480 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
7481 SDNode *BVN = N->getOperand(0).getNode();
7482 if (BVN->getValueType(0) != MVT::v4i32 ||
7483 BVN->getOpcode() != ISD::BUILD_VECTOR)
7484 return false;
7485 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7486 unsigned HiElt = 1 - LoElt;
7487 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
7488 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
7489 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
7490 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
7491 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
7492 return false;
7493 if (isSigned) {
7494 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
7495 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
7496 return true;
7497 } else {
7498 if (Hi0->isNullValue() && Hi1->isNullValue())
7499 return true;
7501 return false;
7504 if (N->getOpcode() != ISD::BUILD_VECTOR)
7505 return false;
7507 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
7508 SDNode *Elt = N->getOperand(i).getNode();
7509 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
7510 unsigned EltSize = VT.getScalarSizeInBits();
7511 unsigned HalfSize = EltSize / 2;
7512 if (isSigned) {
7513 if (!isIntN(HalfSize, C->getSExtValue()))
7514 return false;
7515 } else {
7516 if (!isUIntN(HalfSize, C->getZExtValue()))
7517 return false;
7519 continue;
7521 return false;
7524 return true;
7527 /// isSignExtended - Check if a node is a vector value that is sign-extended
7528 /// or a constant BUILD_VECTOR with sign-extended elements.
7529 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
7530 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
7531 return true;
7532 if (isExtendedBUILD_VECTOR(N, DAG, true))
7533 return true;
7534 return false;
7537 /// isZeroExtended - Check if a node is a vector value that is zero-extended
7538 /// or a constant BUILD_VECTOR with zero-extended elements.
7539 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
7540 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
7541 return true;
7542 if (isExtendedBUILD_VECTOR(N, DAG, false))
7543 return true;
7544 return false;
7547 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
7548 if (OrigVT.getSizeInBits() >= 64)
7549 return OrigVT;
7551 assert(OrigVT.isSimple() && "Expecting a simple value type");
7553 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
7554 switch (OrigSimpleTy) {
7555 default: llvm_unreachable("Unexpected Vector Type");
7556 case MVT::v2i8:
7557 case MVT::v2i16:
7558 return MVT::v2i32;
7559 case MVT::v4i8:
7560 return MVT::v4i16;
7564 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
7565 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
7566 /// We insert the required extension here to get the vector to fill a D register.
7567 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
7568 const EVT &OrigTy,
7569 const EVT &ExtTy,
7570 unsigned ExtOpcode) {
7571 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
7572 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
7573 // 64-bits we need to insert a new extension so that it will be 64-bits.
7574 assert(ExtTy.is128BitVector() && "Unexpected extension size");
7575 if (OrigTy.getSizeInBits() >= 64)
7576 return N;
7578 // Must extend size to at least 64 bits to be used as an operand for VMULL.
7579 EVT NewVT = getExtensionTo64Bits(OrigTy);
7581 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
7584 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
7585 /// does not do any sign/zero extension. If the original vector is less
7586 /// than 64 bits, an appropriate extension will be added after the load to
7587 /// reach a total size of 64 bits. We have to add the extension separately
7588 /// because ARM does not have a sign/zero extending load for vectors.
7589 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
7590 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
7592 // The load already has the right type.
7593 if (ExtendedTy == LD->getMemoryVT())
7594 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
7595 LD->getBasePtr(), LD->getPointerInfo(),
7596 LD->getAlignment(), LD->getMemOperand()->getFlags());
7598 // We need to create a zextload/sextload. We cannot just create a load
7599 // followed by a zext/zext node because LowerMUL is also run during normal
7600 // operation legalization where we can't create illegal types.
7601 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
7602 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
7603 LD->getMemoryVT(), LD->getAlignment(),
7604 LD->getMemOperand()->getFlags());
7607 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
7608 /// extending load, or BUILD_VECTOR with extended elements, return the
7609 /// unextended value. The unextended vector should be 64 bits so that it can
7610 /// be used as an operand to a VMULL instruction. If the original vector size
7611 /// before extension is less than 64 bits we add a an extension to resize
7612 /// the vector to 64 bits.
7613 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
7614 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
7615 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
7616 N->getOperand(0)->getValueType(0),
7617 N->getValueType(0),
7618 N->getOpcode());
7620 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7621 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
7622 "Expected extending load");
7624 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
7625 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
7626 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
7627 SDValue extLoad =
7628 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
7629 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
7631 return newLoad;
7634 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
7635 // have been legalized as a BITCAST from v4i32.
7636 if (N->getOpcode() == ISD::BITCAST) {
7637 SDNode *BVN = N->getOperand(0).getNode();
7638 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
7639 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
7640 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7641 return DAG.getBuildVector(
7642 MVT::v2i32, SDLoc(N),
7643 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
7645 // Construct a new BUILD_VECTOR with elements truncated to half the size.
7646 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
7647 EVT VT = N->getValueType(0);
7648 unsigned EltSize = VT.getScalarSizeInBits() / 2;
7649 unsigned NumElts = VT.getVectorNumElements();
7650 MVT TruncVT = MVT::getIntegerVT(EltSize);
7651 SmallVector<SDValue, 8> Ops;
7652 SDLoc dl(N);
7653 for (unsigned i = 0; i != NumElts; ++i) {
7654 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
7655 const APInt &CInt = C->getAPIntValue();
7656 // Element types smaller than 32 bits are not legal, so use i32 elements.
7657 // The values are implicitly truncated so sext vs. zext doesn't matter.
7658 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
7660 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
7663 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
7664 unsigned Opcode = N->getOpcode();
7665 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7666 SDNode *N0 = N->getOperand(0).getNode();
7667 SDNode *N1 = N->getOperand(1).getNode();
7668 return N0->hasOneUse() && N1->hasOneUse() &&
7669 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
7671 return false;
7674 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
7675 unsigned Opcode = N->getOpcode();
7676 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7677 SDNode *N0 = N->getOperand(0).getNode();
7678 SDNode *N1 = N->getOperand(1).getNode();
7679 return N0->hasOneUse() && N1->hasOneUse() &&
7680 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
7682 return false;
7685 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
7686 // Multiplications are only custom-lowered for 128-bit vectors so that
7687 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
7688 EVT VT = Op.getValueType();
7689 assert(VT.is128BitVector() && VT.isInteger() &&
7690 "unexpected type for custom-lowering ISD::MUL");
7691 SDNode *N0 = Op.getOperand(0).getNode();
7692 SDNode *N1 = Op.getOperand(1).getNode();
7693 unsigned NewOpc = 0;
7694 bool isMLA = false;
7695 bool isN0SExt = isSignExtended(N0, DAG);
7696 bool isN1SExt = isSignExtended(N1, DAG);
7697 if (isN0SExt && isN1SExt)
7698 NewOpc = ARMISD::VMULLs;
7699 else {
7700 bool isN0ZExt = isZeroExtended(N0, DAG);
7701 bool isN1ZExt = isZeroExtended(N1, DAG);
7702 if (isN0ZExt && isN1ZExt)
7703 NewOpc = ARMISD::VMULLu;
7704 else if (isN1SExt || isN1ZExt) {
7705 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7706 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7707 if (isN1SExt && isAddSubSExt(N0, DAG)) {
7708 NewOpc = ARMISD::VMULLs;
7709 isMLA = true;
7710 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7711 NewOpc = ARMISD::VMULLu;
7712 isMLA = true;
7713 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7714 std::swap(N0, N1);
7715 NewOpc = ARMISD::VMULLu;
7716 isMLA = true;
7720 if (!NewOpc) {
7721 if (VT == MVT::v2i64)
7722 // Fall through to expand this. It is not legal.
7723 return SDValue();
7724 else
7725 // Other vector multiplications are legal.
7726 return Op;
7730 // Legalize to a VMULL instruction.
7731 SDLoc DL(Op);
7732 SDValue Op0;
7733 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7734 if (!isMLA) {
7735 Op0 = SkipExtensionForVMULL(N0, DAG);
7736 assert(Op0.getValueType().is64BitVector() &&
7737 Op1.getValueType().is64BitVector() &&
7738 "unexpected types for extended operands to VMULL");
7739 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7742 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7743 // isel lowering to take advantage of no-stall back to back vmul + vmla.
7744 // vmull q0, d4, d6
7745 // vmlal q0, d5, d6
7746 // is faster than
7747 // vaddl q0, d4, d5
7748 // vmovl q1, d6
7749 // vmul q0, q0, q1
7750 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7751 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7752 EVT Op1VT = Op1.getValueType();
7753 return DAG.getNode(N0->getOpcode(), DL, VT,
7754 DAG.getNode(NewOpc, DL, VT,
7755 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7756 DAG.getNode(NewOpc, DL, VT,
7757 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7760 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7761 SelectionDAG &DAG) {
7762 // TODO: Should this propagate fast-math-flags?
7764 // Convert to float
7765 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7766 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7767 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7768 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7769 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7770 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7771 // Get reciprocal estimate.
7772 // float4 recip = vrecpeq_f32(yf);
7773 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7774 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7776 // Because char has a smaller range than uchar, we can actually get away
7777 // without any newton steps. This requires that we use a weird bias
7778 // of 0xb000, however (again, this has been exhaustively tested).
7779 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7780 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7781 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7782 Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7783 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7784 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7785 // Convert back to short.
7786 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7787 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7788 return X;
7791 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7792 SelectionDAG &DAG) {
7793 // TODO: Should this propagate fast-math-flags?
7795 SDValue N2;
7796 // Convert to float.
7797 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7798 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7799 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7800 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7801 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7802 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7804 // Use reciprocal estimate and one refinement step.
7805 // float4 recip = vrecpeq_f32(yf);
7806 // recip *= vrecpsq_f32(yf, recip);
7807 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7808 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7809 N1);
7810 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7811 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7812 N1, N2);
7813 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7814 // Because short has a smaller range than ushort, we can actually get away
7815 // with only a single newton step. This requires that we use a weird bias
7816 // of 89, however (again, this has been exhaustively tested).
7817 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7818 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7819 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7820 N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7821 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7822 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7823 // Convert back to integer and return.
7824 // return vmovn_s32(vcvt_s32_f32(result));
7825 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7826 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7827 return N0;
7830 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7831 EVT VT = Op.getValueType();
7832 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7833 "unexpected type for custom-lowering ISD::SDIV");
7835 SDLoc dl(Op);
7836 SDValue N0 = Op.getOperand(0);
7837 SDValue N1 = Op.getOperand(1);
7838 SDValue N2, N3;
7840 if (VT == MVT::v8i8) {
7841 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7842 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7844 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7845 DAG.getIntPtrConstant(4, dl));
7846 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7847 DAG.getIntPtrConstant(4, dl));
7848 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7849 DAG.getIntPtrConstant(0, dl));
7850 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7851 DAG.getIntPtrConstant(0, dl));
7853 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7854 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7856 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7857 N0 = LowerCONCAT_VECTORS(N0, DAG);
7859 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7860 return N0;
7862 return LowerSDIV_v4i16(N0, N1, dl, DAG);
7865 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7866 // TODO: Should this propagate fast-math-flags?
7867 EVT VT = Op.getValueType();
7868 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7869 "unexpected type for custom-lowering ISD::UDIV");
7871 SDLoc dl(Op);
7872 SDValue N0 = Op.getOperand(0);
7873 SDValue N1 = Op.getOperand(1);
7874 SDValue N2, N3;
7876 if (VT == MVT::v8i8) {
7877 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
7878 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
7880 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7881 DAG.getIntPtrConstant(4, dl));
7882 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7883 DAG.getIntPtrConstant(4, dl));
7884 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7885 DAG.getIntPtrConstant(0, dl));
7886 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7887 DAG.getIntPtrConstant(0, dl));
7889 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
7890 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
7892 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7893 N0 = LowerCONCAT_VECTORS(N0, DAG);
7895 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7896 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7897 MVT::i32),
7898 N0);
7899 return N0;
7902 // v4i16 sdiv ... Convert to float.
7903 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7904 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7905 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7906 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7907 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7908 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7910 // Use reciprocal estimate and two refinement steps.
7911 // float4 recip = vrecpeq_f32(yf);
7912 // recip *= vrecpsq_f32(yf, recip);
7913 // recip *= vrecpsq_f32(yf, recip);
7914 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7915 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7916 BN1);
7917 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7918 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7919 BN1, N2);
7920 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7921 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7922 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7923 BN1, N2);
7924 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7925 // Simply multiplying by the reciprocal estimate can leave us a few ulps
7926 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7927 // and that it will never cause us to return an answer too large).
7928 // float4 result = as_float4(as_int4(xf*recip) + 2);
7929 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7930 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7931 N1 = DAG.getConstant(2, dl, MVT::v4i32);
7932 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7933 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7934 // Convert back to integer and return.
7935 // return vmovn_u32(vcvt_s32_f32(result));
7936 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7937 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7938 return N0;
7941 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
7942 SDNode *N = Op.getNode();
7943 EVT VT = N->getValueType(0);
7944 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7946 SDValue Carry = Op.getOperand(2);
7948 SDLoc DL(Op);
7950 SDValue Result;
7951 if (Op.getOpcode() == ISD::ADDCARRY) {
7952 // This converts the boolean value carry into the carry flag.
7953 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7955 // Do the addition proper using the carry flag we wanted.
7956 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
7957 Op.getOperand(1), Carry);
7959 // Now convert the carry flag into a boolean value.
7960 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7961 } else {
7962 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
7963 // have to invert the carry first.
7964 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7965 DAG.getConstant(1, DL, MVT::i32), Carry);
7966 // This converts the boolean value carry into the carry flag.
7967 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7969 // Do the subtraction proper using the carry flag we wanted.
7970 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
7971 Op.getOperand(1), Carry);
7973 // Now convert the carry flag into a boolean value.
7974 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7975 // But the carry returned by ARMISD::SUBE is not a borrow as expected
7976 // by ISD::SUBCARRY, so compute 1 - C.
7977 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7978 DAG.getConstant(1, DL, MVT::i32), Carry);
7981 // Return both values.
7982 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
7985 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7986 assert(Subtarget->isTargetDarwin());
7988 // For iOS, we want to call an alternative entry point: __sincos_stret,
7989 // return values are passed via sret.
7990 SDLoc dl(Op);
7991 SDValue Arg = Op.getOperand(0);
7992 EVT ArgVT = Arg.getValueType();
7993 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7994 auto PtrVT = getPointerTy(DAG.getDataLayout());
7996 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7997 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7999 // Pair of floats / doubles used to pass the result.
8000 Type *RetTy = StructType::get(ArgTy, ArgTy);
8001 auto &DL = DAG.getDataLayout();
8003 ArgListTy Args;
8004 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
8005 SDValue SRet;
8006 if (ShouldUseSRet) {
8007 // Create stack object for sret.
8008 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
8009 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
8010 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
8011 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
8013 ArgListEntry Entry;
8014 Entry.Node = SRet;
8015 Entry.Ty = RetTy->getPointerTo();
8016 Entry.IsSExt = false;
8017 Entry.IsZExt = false;
8018 Entry.IsSRet = true;
8019 Args.push_back(Entry);
8020 RetTy = Type::getVoidTy(*DAG.getContext());
8023 ArgListEntry Entry;
8024 Entry.Node = Arg;
8025 Entry.Ty = ArgTy;
8026 Entry.IsSExt = false;
8027 Entry.IsZExt = false;
8028 Args.push_back(Entry);
8030 RTLIB::Libcall LC =
8031 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
8032 const char *LibcallName = getLibcallName(LC);
8033 CallingConv::ID CC = getLibcallCallingConv(LC);
8034 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
8036 TargetLowering::CallLoweringInfo CLI(DAG);
8037 CLI.setDebugLoc(dl)
8038 .setChain(DAG.getEntryNode())
8039 .setCallee(CC, RetTy, Callee, std::move(Args))
8040 .setDiscardResult(ShouldUseSRet);
8041 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
8043 if (!ShouldUseSRet)
8044 return CallResult.first;
8046 SDValue LoadSin =
8047 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
8049 // Address of cos field.
8050 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
8051 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
8052 SDValue LoadCos =
8053 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
8055 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
8056 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
8057 LoadSin.getValue(0), LoadCos.getValue(0));
8060 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
8061 bool Signed,
8062 SDValue &Chain) const {
8063 EVT VT = Op.getValueType();
8064 assert((VT == MVT::i32 || VT == MVT::i64) &&
8065 "unexpected type for custom lowering DIV");
8066 SDLoc dl(Op);
8068 const auto &DL = DAG.getDataLayout();
8069 const auto &TLI = DAG.getTargetLoweringInfo();
8071 const char *Name = nullptr;
8072 if (Signed)
8073 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
8074 else
8075 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
8077 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
8079 ARMTargetLowering::ArgListTy Args;
8081 for (auto AI : {1, 0}) {
8082 ArgListEntry Arg;
8083 Arg.Node = Op.getOperand(AI);
8084 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
8085 Args.push_back(Arg);
8088 CallLoweringInfo CLI(DAG);
8089 CLI.setDebugLoc(dl)
8090 .setChain(Chain)
8091 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
8092 ES, std::move(Args));
8094 return LowerCallTo(CLI).first;
8097 // This is a code size optimisation: return the original SDIV node to
8098 // DAGCombiner when we don't want to expand SDIV into a sequence of
8099 // instructions, and an empty node otherwise which will cause the
8100 // SDIV to be expanded in DAGCombine.
8101 SDValue
8102 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8103 SelectionDAG &DAG,
8104 SmallVectorImpl<SDNode *> &Created) const {
8105 // TODO: Support SREM
8106 if (N->getOpcode() != ISD::SDIV)
8107 return SDValue();
8109 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
8110 const bool MinSize = ST.hasMinSize();
8111 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
8112 : ST.hasDivideInARMMode();
8114 // Don't touch vector types; rewriting this may lead to scalarizing
8115 // the int divs.
8116 if (N->getOperand(0).getValueType().isVector())
8117 return SDValue();
8119 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
8120 // hwdiv support for this to be really profitable.
8121 if (!(MinSize && HasDivide))
8122 return SDValue();
8124 // ARM mode is a bit simpler than Thumb: we can handle large power
8125 // of 2 immediates with 1 mov instruction; no further checks required,
8126 // just return the sdiv node.
8127 if (!ST.isThumb())
8128 return SDValue(N, 0);
8130 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
8131 // and thus lose the code size benefits of a MOVS that requires only 2.
8132 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
8133 // but as it's doing exactly this, it's not worth the trouble to get TTI.
8134 if (Divisor.sgt(128))
8135 return SDValue();
8137 return SDValue(N, 0);
8140 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
8141 bool Signed) const {
8142 assert(Op.getValueType() == MVT::i32 &&
8143 "unexpected type for custom lowering DIV");
8144 SDLoc dl(Op);
8146 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
8147 DAG.getEntryNode(), Op.getOperand(1));
8149 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8152 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
8153 SDLoc DL(N);
8154 SDValue Op = N->getOperand(1);
8155 if (N->getValueType(0) == MVT::i32)
8156 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
8157 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8158 DAG.getConstant(0, DL, MVT::i32));
8159 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8160 DAG.getConstant(1, DL, MVT::i32));
8161 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
8162 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
8165 void ARMTargetLowering::ExpandDIV_Windows(
8166 SDValue Op, SelectionDAG &DAG, bool Signed,
8167 SmallVectorImpl<SDValue> &Results) const {
8168 const auto &DL = DAG.getDataLayout();
8169 const auto &TLI = DAG.getTargetLoweringInfo();
8171 assert(Op.getValueType() == MVT::i64 &&
8172 "unexpected type for custom lowering DIV");
8173 SDLoc dl(Op);
8175 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
8177 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8179 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
8180 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
8181 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
8182 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
8184 Results.push_back(Lower);
8185 Results.push_back(Upper);
8188 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
8189 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
8190 // Acquire/Release load/store is not legal for targets without a dmb or
8191 // equivalent available.
8192 return SDValue();
8194 // Monotonic load/store is legal for all targets.
8195 return Op;
8198 static void ReplaceREADCYCLECOUNTER(SDNode *N,
8199 SmallVectorImpl<SDValue> &Results,
8200 SelectionDAG &DAG,
8201 const ARMSubtarget *Subtarget) {
8202 SDLoc DL(N);
8203 // Under Power Management extensions, the cycle-count is:
8204 // mrc p15, #0, <Rt>, c9, c13, #0
8205 SDValue Ops[] = { N->getOperand(0), // Chain
8206 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
8207 DAG.getConstant(15, DL, MVT::i32),
8208 DAG.getConstant(0, DL, MVT::i32),
8209 DAG.getConstant(9, DL, MVT::i32),
8210 DAG.getConstant(13, DL, MVT::i32),
8211 DAG.getConstant(0, DL, MVT::i32)
8214 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
8215 DAG.getVTList(MVT::i32, MVT::Other), Ops);
8216 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
8217 DAG.getConstant(0, DL, MVT::i32)));
8218 Results.push_back(Cycles32.getValue(1));
8221 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
8222 SDLoc dl(V.getNode());
8223 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
8224 SDValue VHi = DAG.getAnyExtOrTrunc(
8225 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
8226 dl, MVT::i32);
8227 bool isBigEndian = DAG.getDataLayout().isBigEndian();
8228 if (isBigEndian)
8229 std::swap (VLo, VHi);
8230 SDValue RegClass =
8231 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
8232 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
8233 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
8234 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
8235 return SDValue(
8236 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
8239 static void ReplaceCMP_SWAP_64Results(SDNode *N,
8240 SmallVectorImpl<SDValue> & Results,
8241 SelectionDAG &DAG) {
8242 assert(N->getValueType(0) == MVT::i64 &&
8243 "AtomicCmpSwap on types less than 64 should be legal");
8244 SDValue Ops[] = {N->getOperand(1),
8245 createGPRPairNode(DAG, N->getOperand(2)),
8246 createGPRPairNode(DAG, N->getOperand(3)),
8247 N->getOperand(0)};
8248 SDNode *CmpSwap = DAG.getMachineNode(
8249 ARM::CMP_SWAP_64, SDLoc(N),
8250 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
8252 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
8253 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
8255 bool isBigEndian = DAG.getDataLayout().isBigEndian();
8257 Results.push_back(
8258 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
8259 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8260 Results.push_back(
8261 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
8262 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8263 Results.push_back(SDValue(CmpSwap, 2));
8266 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
8267 SelectionDAG &DAG) {
8268 const auto &TLI = DAG.getTargetLoweringInfo();
8270 assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
8271 "Custom lowering is MSVCRT specific!");
8273 SDLoc dl(Op);
8274 SDValue Val = Op.getOperand(0);
8275 MVT Ty = Val->getSimpleValueType(0);
8276 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
8277 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
8278 TLI.getPointerTy(DAG.getDataLayout()));
8280 TargetLowering::ArgListTy Args;
8281 TargetLowering::ArgListEntry Entry;
8283 Entry.Node = Val;
8284 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
8285 Entry.IsZExt = true;
8286 Args.push_back(Entry);
8288 Entry.Node = Exponent;
8289 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
8290 Entry.IsZExt = true;
8291 Args.push_back(Entry);
8293 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
8295 // In the in-chain to the call is the entry node If we are emitting a
8296 // tailcall, the chain will be mutated if the node has a non-entry input
8297 // chain.
8298 SDValue InChain = DAG.getEntryNode();
8299 SDValue TCChain = InChain;
8301 const Function &F = DAG.getMachineFunction().getFunction();
8302 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
8303 F.getReturnType() == LCRTy;
8304 if (IsTC)
8305 InChain = TCChain;
8307 TargetLowering::CallLoweringInfo CLI(DAG);
8308 CLI.setDebugLoc(dl)
8309 .setChain(InChain)
8310 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
8311 .setTailCall(IsTC);
8312 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
8314 // Return the chain (the DAG root) if it is a tail call
8315 return !CI.second.getNode() ? DAG.getRoot() : CI.first;
8318 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8319 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
8320 switch (Op.getOpcode()) {
8321 default: llvm_unreachable("Don't know how to custom lower this!");
8322 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
8323 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8324 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8325 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8326 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8327 case ISD::SELECT: return LowerSELECT(Op, DAG);
8328 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
8329 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
8330 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
8331 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
8332 case ISD::VASTART: return LowerVASTART(Op, DAG);
8333 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
8334 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
8335 case ISD::SINT_TO_FP:
8336 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
8337 case ISD::FP_TO_SINT:
8338 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
8339 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
8340 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8341 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8342 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
8343 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
8344 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
8345 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
8346 Subtarget);
8347 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
8348 case ISD::SHL:
8349 case ISD::SRL:
8350 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
8351 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
8352 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
8353 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
8354 case ISD::SRL_PARTS:
8355 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
8356 case ISD::CTTZ:
8357 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
8358 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
8359 case ISD::SETCC: return LowerVSETCC(Op, DAG);
8360 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
8361 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
8362 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
8363 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
8364 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8365 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8366 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
8367 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8368 case ISD::MUL: return LowerMUL(Op, DAG);
8369 case ISD::SDIV:
8370 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8371 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
8372 return LowerSDIV(Op, DAG);
8373 case ISD::UDIV:
8374 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8375 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
8376 return LowerUDIV(Op, DAG);
8377 case ISD::ADDCARRY:
8378 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG);
8379 case ISD::SADDO:
8380 case ISD::SSUBO:
8381 return LowerSignedALUO(Op, DAG);
8382 case ISD::UADDO:
8383 case ISD::USUBO:
8384 return LowerUnsignedALUO(Op, DAG);
8385 case ISD::ATOMIC_LOAD:
8386 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
8387 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
8388 case ISD::SDIVREM:
8389 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
8390 case ISD::DYNAMIC_STACKALLOC:
8391 if (Subtarget->isTargetWindows())
8392 return LowerDYNAMIC_STACKALLOC(Op, DAG);
8393 llvm_unreachable("Don't know how to custom lower this!");
8394 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
8395 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
8396 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
8397 case ARMISD::WIN__DBZCHK: return SDValue();
8401 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
8402 SelectionDAG &DAG) {
8403 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8404 unsigned Opc = 0;
8405 if (IntNo == Intrinsic::arm_smlald)
8406 Opc = ARMISD::SMLALD;
8407 else if (IntNo == Intrinsic::arm_smlaldx)
8408 Opc = ARMISD::SMLALDX;
8409 else if (IntNo == Intrinsic::arm_smlsld)
8410 Opc = ARMISD::SMLSLD;
8411 else if (IntNo == Intrinsic::arm_smlsldx)
8412 Opc = ARMISD::SMLSLDX;
8413 else
8414 return;
8416 SDLoc dl(N);
8417 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8418 N->getOperand(3),
8419 DAG.getConstant(0, dl, MVT::i32));
8420 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8421 N->getOperand(3),
8422 DAG.getConstant(1, dl, MVT::i32));
8424 SDValue LongMul = DAG.getNode(Opc, dl,
8425 DAG.getVTList(MVT::i32, MVT::i32),
8426 N->getOperand(1), N->getOperand(2),
8427 Lo, Hi);
8428 Results.push_back(LongMul.getValue(0));
8429 Results.push_back(LongMul.getValue(1));
8432 /// ReplaceNodeResults - Replace the results of node with an illegal result
8433 /// type with new values built out of custom code.
8434 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
8435 SmallVectorImpl<SDValue> &Results,
8436 SelectionDAG &DAG) const {
8437 SDValue Res;
8438 switch (N->getOpcode()) {
8439 default:
8440 llvm_unreachable("Don't know how to custom expand this!");
8441 case ISD::READ_REGISTER:
8442 ExpandREAD_REGISTER(N, Results, DAG);
8443 break;
8444 case ISD::BITCAST:
8445 Res = ExpandBITCAST(N, DAG, Subtarget);
8446 break;
8447 case ISD::SRL:
8448 case ISD::SRA:
8449 case ISD::SHL:
8450 Res = Expand64BitShift(N, DAG, Subtarget);
8451 break;
8452 case ISD::SREM:
8453 case ISD::UREM:
8454 Res = LowerREM(N, DAG);
8455 break;
8456 case ISD::SDIVREM:
8457 case ISD::UDIVREM:
8458 Res = LowerDivRem(SDValue(N, 0), DAG);
8459 assert(Res.getNumOperands() == 2 && "DivRem needs two values");
8460 Results.push_back(Res.getValue(0));
8461 Results.push_back(Res.getValue(1));
8462 return;
8463 case ISD::READCYCLECOUNTER:
8464 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
8465 return;
8466 case ISD::UDIV:
8467 case ISD::SDIV:
8468 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
8469 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
8470 Results);
8471 case ISD::ATOMIC_CMP_SWAP:
8472 ReplaceCMP_SWAP_64Results(N, Results, DAG);
8473 return;
8474 case ISD::INTRINSIC_WO_CHAIN:
8475 return ReplaceLongIntrinsic(N, Results, DAG);
8476 case ISD::ABS:
8477 lowerABS(N, Results, DAG);
8478 return ;
8481 if (Res.getNode())
8482 Results.push_back(Res);
8485 //===----------------------------------------------------------------------===//
8486 // ARM Scheduler Hooks
8487 //===----------------------------------------------------------------------===//
8489 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
8490 /// registers the function context.
8491 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
8492 MachineBasicBlock *MBB,
8493 MachineBasicBlock *DispatchBB,
8494 int FI) const {
8495 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
8496 "ROPI/RWPI not currently supported with SjLj");
8497 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8498 DebugLoc dl = MI.getDebugLoc();
8499 MachineFunction *MF = MBB->getParent();
8500 MachineRegisterInfo *MRI = &MF->getRegInfo();
8501 MachineConstantPool *MCP = MF->getConstantPool();
8502 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
8503 const Function &F = MF->getFunction();
8505 bool isThumb = Subtarget->isThumb();
8506 bool isThumb2 = Subtarget->isThumb2();
8508 unsigned PCLabelId = AFI->createPICLabelUId();
8509 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
8510 ARMConstantPoolValue *CPV =
8511 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
8512 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
8514 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
8515 : &ARM::GPRRegClass;
8517 // Grab constant pool and fixed stack memory operands.
8518 MachineMemOperand *CPMMO =
8519 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
8520 MachineMemOperand::MOLoad, 4, 4);
8522 MachineMemOperand *FIMMOSt =
8523 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
8524 MachineMemOperand::MOStore, 4, 4);
8526 // Load the address of the dispatch MBB into the jump buffer.
8527 if (isThumb2) {
8528 // Incoming value: jbuf
8529 // ldr.n r5, LCPI1_1
8530 // orr r5, r5, #1
8531 // add r5, pc
8532 // str r5, [$jbuf, #+4] ; &jbuf[1]
8533 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8534 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
8535 .addConstantPoolIndex(CPI)
8536 .addMemOperand(CPMMO)
8537 .add(predOps(ARMCC::AL));
8538 // Set the low bit because of thumb mode.
8539 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8540 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
8541 .addReg(NewVReg1, RegState::Kill)
8542 .addImm(0x01)
8543 .add(predOps(ARMCC::AL))
8544 .add(condCodeOp());
8545 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8546 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
8547 .addReg(NewVReg2, RegState::Kill)
8548 .addImm(PCLabelId);
8549 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
8550 .addReg(NewVReg3, RegState::Kill)
8551 .addFrameIndex(FI)
8552 .addImm(36) // &jbuf[1] :: pc
8553 .addMemOperand(FIMMOSt)
8554 .add(predOps(ARMCC::AL));
8555 } else if (isThumb) {
8556 // Incoming value: jbuf
8557 // ldr.n r1, LCPI1_4
8558 // add r1, pc
8559 // mov r2, #1
8560 // orrs r1, r2
8561 // add r2, $jbuf, #+4 ; &jbuf[1]
8562 // str r1, [r2]
8563 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8564 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
8565 .addConstantPoolIndex(CPI)
8566 .addMemOperand(CPMMO)
8567 .add(predOps(ARMCC::AL));
8568 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8569 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
8570 .addReg(NewVReg1, RegState::Kill)
8571 .addImm(PCLabelId);
8572 // Set the low bit because of thumb mode.
8573 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8574 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
8575 .addReg(ARM::CPSR, RegState::Define)
8576 .addImm(1)
8577 .add(predOps(ARMCC::AL));
8578 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8579 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
8580 .addReg(ARM::CPSR, RegState::Define)
8581 .addReg(NewVReg2, RegState::Kill)
8582 .addReg(NewVReg3, RegState::Kill)
8583 .add(predOps(ARMCC::AL));
8584 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8585 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
8586 .addFrameIndex(FI)
8587 .addImm(36); // &jbuf[1] :: pc
8588 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
8589 .addReg(NewVReg4, RegState::Kill)
8590 .addReg(NewVReg5, RegState::Kill)
8591 .addImm(0)
8592 .addMemOperand(FIMMOSt)
8593 .add(predOps(ARMCC::AL));
8594 } else {
8595 // Incoming value: jbuf
8596 // ldr r1, LCPI1_1
8597 // add r1, pc, r1
8598 // str r1, [$jbuf, #+4] ; &jbuf[1]
8599 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8600 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
8601 .addConstantPoolIndex(CPI)
8602 .addImm(0)
8603 .addMemOperand(CPMMO)
8604 .add(predOps(ARMCC::AL));
8605 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8606 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
8607 .addReg(NewVReg1, RegState::Kill)
8608 .addImm(PCLabelId)
8609 .add(predOps(ARMCC::AL));
8610 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
8611 .addReg(NewVReg2, RegState::Kill)
8612 .addFrameIndex(FI)
8613 .addImm(36) // &jbuf[1] :: pc
8614 .addMemOperand(FIMMOSt)
8615 .add(predOps(ARMCC::AL));
8619 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
8620 MachineBasicBlock *MBB) const {
8621 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8622 DebugLoc dl = MI.getDebugLoc();
8623 MachineFunction *MF = MBB->getParent();
8624 MachineRegisterInfo *MRI = &MF->getRegInfo();
8625 MachineFrameInfo &MFI = MF->getFrameInfo();
8626 int FI = MFI.getFunctionContextIndex();
8628 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
8629 : &ARM::GPRnopcRegClass;
8631 // Get a mapping of the call site numbers to all of the landing pads they're
8632 // associated with.
8633 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
8634 unsigned MaxCSNum = 0;
8635 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
8636 ++BB) {
8637 if (!BB->isEHPad()) continue;
8639 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
8640 // pad.
8641 for (MachineBasicBlock::iterator
8642 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
8643 if (!II->isEHLabel()) continue;
8645 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
8646 if (!MF->hasCallSiteLandingPad(Sym)) continue;
8648 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
8649 for (SmallVectorImpl<unsigned>::iterator
8650 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
8651 CSI != CSE; ++CSI) {
8652 CallSiteNumToLPad[*CSI].push_back(&*BB);
8653 MaxCSNum = std::max(MaxCSNum, *CSI);
8655 break;
8659 // Get an ordered list of the machine basic blocks for the jump table.
8660 std::vector<MachineBasicBlock*> LPadList;
8661 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
8662 LPadList.reserve(CallSiteNumToLPad.size());
8663 for (unsigned I = 1; I <= MaxCSNum; ++I) {
8664 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
8665 for (SmallVectorImpl<MachineBasicBlock*>::iterator
8666 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
8667 LPadList.push_back(*II);
8668 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
8672 assert(!LPadList.empty() &&
8673 "No landing pad destinations for the dispatch jump table!");
8675 // Create the jump table and associated information.
8676 MachineJumpTableInfo *JTI =
8677 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
8678 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
8680 // Create the MBBs for the dispatch code.
8682 // Shove the dispatch's address into the return slot in the function context.
8683 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
8684 DispatchBB->setIsEHPad();
8686 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8687 unsigned trap_opcode;
8688 if (Subtarget->isThumb())
8689 trap_opcode = ARM::tTRAP;
8690 else
8691 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
8693 BuildMI(TrapBB, dl, TII->get(trap_opcode));
8694 DispatchBB->addSuccessor(TrapBB);
8696 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
8697 DispatchBB->addSuccessor(DispContBB);
8699 // Insert and MBBs.
8700 MF->insert(MF->end(), DispatchBB);
8701 MF->insert(MF->end(), DispContBB);
8702 MF->insert(MF->end(), TrapBB);
8704 // Insert code into the entry block that creates and registers the function
8705 // context.
8706 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
8708 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
8709 MachinePointerInfo::getFixedStack(*MF, FI),
8710 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
8712 MachineInstrBuilder MIB;
8713 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
8715 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
8716 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
8718 // Add a register mask with no preserved registers. This results in all
8719 // registers being marked as clobbered. This can't work if the dispatch block
8720 // is in a Thumb1 function and is linked with ARM code which uses the FP
8721 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
8722 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
8724 bool IsPositionIndependent = isPositionIndependent();
8725 unsigned NumLPads = LPadList.size();
8726 if (Subtarget->isThumb2()) {
8727 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8728 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
8729 .addFrameIndex(FI)
8730 .addImm(4)
8731 .addMemOperand(FIMMOLd)
8732 .add(predOps(ARMCC::AL));
8734 if (NumLPads < 256) {
8735 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
8736 .addReg(NewVReg1)
8737 .addImm(LPadList.size())
8738 .add(predOps(ARMCC::AL));
8739 } else {
8740 unsigned VReg1 = MRI->createVirtualRegister(TRC);
8741 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
8742 .addImm(NumLPads & 0xFFFF)
8743 .add(predOps(ARMCC::AL));
8745 unsigned VReg2 = VReg1;
8746 if ((NumLPads & 0xFFFF0000) != 0) {
8747 VReg2 = MRI->createVirtualRegister(TRC);
8748 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
8749 .addReg(VReg1)
8750 .addImm(NumLPads >> 16)
8751 .add(predOps(ARMCC::AL));
8754 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
8755 .addReg(NewVReg1)
8756 .addReg(VReg2)
8757 .add(predOps(ARMCC::AL));
8760 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
8761 .addMBB(TrapBB)
8762 .addImm(ARMCC::HI)
8763 .addReg(ARM::CPSR);
8765 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8766 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
8767 .addJumpTableIndex(MJTI)
8768 .add(predOps(ARMCC::AL));
8770 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8771 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
8772 .addReg(NewVReg3, RegState::Kill)
8773 .addReg(NewVReg1)
8774 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8775 .add(predOps(ARMCC::AL))
8776 .add(condCodeOp());
8778 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
8779 .addReg(NewVReg4, RegState::Kill)
8780 .addReg(NewVReg1)
8781 .addJumpTableIndex(MJTI);
8782 } else if (Subtarget->isThumb()) {
8783 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8784 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
8785 .addFrameIndex(FI)
8786 .addImm(1)
8787 .addMemOperand(FIMMOLd)
8788 .add(predOps(ARMCC::AL));
8790 if (NumLPads < 256) {
8791 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
8792 .addReg(NewVReg1)
8793 .addImm(NumLPads)
8794 .add(predOps(ARMCC::AL));
8795 } else {
8796 MachineConstantPool *ConstantPool = MF->getConstantPool();
8797 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8798 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8800 // MachineConstantPool wants an explicit alignment.
8801 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8802 if (Align == 0)
8803 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8804 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8806 unsigned VReg1 = MRI->createVirtualRegister(TRC);
8807 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
8808 .addReg(VReg1, RegState::Define)
8809 .addConstantPoolIndex(Idx)
8810 .add(predOps(ARMCC::AL));
8811 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
8812 .addReg(NewVReg1)
8813 .addReg(VReg1)
8814 .add(predOps(ARMCC::AL));
8817 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
8818 .addMBB(TrapBB)
8819 .addImm(ARMCC::HI)
8820 .addReg(ARM::CPSR);
8822 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8823 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
8824 .addReg(ARM::CPSR, RegState::Define)
8825 .addReg(NewVReg1)
8826 .addImm(2)
8827 .add(predOps(ARMCC::AL));
8829 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8830 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
8831 .addJumpTableIndex(MJTI)
8832 .add(predOps(ARMCC::AL));
8834 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8835 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
8836 .addReg(ARM::CPSR, RegState::Define)
8837 .addReg(NewVReg2, RegState::Kill)
8838 .addReg(NewVReg3)
8839 .add(predOps(ARMCC::AL));
8841 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8842 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8844 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8845 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
8846 .addReg(NewVReg4, RegState::Kill)
8847 .addImm(0)
8848 .addMemOperand(JTMMOLd)
8849 .add(predOps(ARMCC::AL));
8851 unsigned NewVReg6 = NewVReg5;
8852 if (IsPositionIndependent) {
8853 NewVReg6 = MRI->createVirtualRegister(TRC);
8854 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8855 .addReg(ARM::CPSR, RegState::Define)
8856 .addReg(NewVReg5, RegState::Kill)
8857 .addReg(NewVReg3)
8858 .add(predOps(ARMCC::AL));
8861 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8862 .addReg(NewVReg6, RegState::Kill)
8863 .addJumpTableIndex(MJTI);
8864 } else {
8865 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8866 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8867 .addFrameIndex(FI)
8868 .addImm(4)
8869 .addMemOperand(FIMMOLd)
8870 .add(predOps(ARMCC::AL));
8872 if (NumLPads < 256) {
8873 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8874 .addReg(NewVReg1)
8875 .addImm(NumLPads)
8876 .add(predOps(ARMCC::AL));
8877 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8878 unsigned VReg1 = MRI->createVirtualRegister(TRC);
8879 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8880 .addImm(NumLPads & 0xFFFF)
8881 .add(predOps(ARMCC::AL));
8883 unsigned VReg2 = VReg1;
8884 if ((NumLPads & 0xFFFF0000) != 0) {
8885 VReg2 = MRI->createVirtualRegister(TRC);
8886 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8887 .addReg(VReg1)
8888 .addImm(NumLPads >> 16)
8889 .add(predOps(ARMCC::AL));
8892 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8893 .addReg(NewVReg1)
8894 .addReg(VReg2)
8895 .add(predOps(ARMCC::AL));
8896 } else {
8897 MachineConstantPool *ConstantPool = MF->getConstantPool();
8898 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8899 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8901 // MachineConstantPool wants an explicit alignment.
8902 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8903 if (Align == 0)
8904 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8905 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8907 unsigned VReg1 = MRI->createVirtualRegister(TRC);
8908 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8909 .addReg(VReg1, RegState::Define)
8910 .addConstantPoolIndex(Idx)
8911 .addImm(0)
8912 .add(predOps(ARMCC::AL));
8913 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8914 .addReg(NewVReg1)
8915 .addReg(VReg1, RegState::Kill)
8916 .add(predOps(ARMCC::AL));
8919 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8920 .addMBB(TrapBB)
8921 .addImm(ARMCC::HI)
8922 .addReg(ARM::CPSR);
8924 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8925 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8926 .addReg(NewVReg1)
8927 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8928 .add(predOps(ARMCC::AL))
8929 .add(condCodeOp());
8930 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8931 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8932 .addJumpTableIndex(MJTI)
8933 .add(predOps(ARMCC::AL));
8935 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8936 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8937 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8938 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8939 .addReg(NewVReg3, RegState::Kill)
8940 .addReg(NewVReg4)
8941 .addImm(0)
8942 .addMemOperand(JTMMOLd)
8943 .add(predOps(ARMCC::AL));
8945 if (IsPositionIndependent) {
8946 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8947 .addReg(NewVReg5, RegState::Kill)
8948 .addReg(NewVReg4)
8949 .addJumpTableIndex(MJTI);
8950 } else {
8951 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8952 .addReg(NewVReg5, RegState::Kill)
8953 .addJumpTableIndex(MJTI);
8957 // Add the jump table entries as successors to the MBB.
8958 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8959 for (std::vector<MachineBasicBlock*>::iterator
8960 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8961 MachineBasicBlock *CurMBB = *I;
8962 if (SeenMBBs.insert(CurMBB).second)
8963 DispContBB->addSuccessor(CurMBB);
8966 // N.B. the order the invoke BBs are processed in doesn't matter here.
8967 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8968 SmallVector<MachineBasicBlock*, 64> MBBLPads;
8969 for (MachineBasicBlock *BB : InvokeBBs) {
8971 // Remove the landing pad successor from the invoke block and replace it
8972 // with the new dispatch block.
8973 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8974 BB->succ_end());
8975 while (!Successors.empty()) {
8976 MachineBasicBlock *SMBB = Successors.pop_back_val();
8977 if (SMBB->isEHPad()) {
8978 BB->removeSuccessor(SMBB);
8979 MBBLPads.push_back(SMBB);
8983 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8984 BB->normalizeSuccProbs();
8986 // Find the invoke call and mark all of the callee-saved registers as
8987 // 'implicit defined' so that they're spilled. This prevents code from
8988 // moving instructions to before the EH block, where they will never be
8989 // executed.
8990 for (MachineBasicBlock::reverse_iterator
8991 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8992 if (!II->isCall()) continue;
8994 DenseMap<unsigned, bool> DefRegs;
8995 for (MachineInstr::mop_iterator
8996 OI = II->operands_begin(), OE = II->operands_end();
8997 OI != OE; ++OI) {
8998 if (!OI->isReg()) continue;
8999 DefRegs[OI->getReg()] = true;
9002 MachineInstrBuilder MIB(*MF, &*II);
9004 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
9005 unsigned Reg = SavedRegs[i];
9006 if (Subtarget->isThumb2() &&
9007 !ARM::tGPRRegClass.contains(Reg) &&
9008 !ARM::hGPRRegClass.contains(Reg))
9009 continue;
9010 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
9011 continue;
9012 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
9013 continue;
9014 if (!DefRegs[Reg])
9015 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
9018 break;
9022 // Mark all former landing pads as non-landing pads. The dispatch is the only
9023 // landing pad now.
9024 for (SmallVectorImpl<MachineBasicBlock*>::iterator
9025 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
9026 (*I)->setIsEHPad(false);
9028 // The instruction is gone now.
9029 MI.eraseFromParent();
9032 static
9033 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
9034 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
9035 E = MBB->succ_end(); I != E; ++I)
9036 if (*I != Succ)
9037 return *I;
9038 llvm_unreachable("Expecting a BB with two successors!");
9041 /// Return the load opcode for a given load size. If load size >= 8,
9042 /// neon opcode will be returned.
9043 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
9044 if (LdSize >= 8)
9045 return LdSize == 16 ? ARM::VLD1q32wb_fixed
9046 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
9047 if (IsThumb1)
9048 return LdSize == 4 ? ARM::tLDRi
9049 : LdSize == 2 ? ARM::tLDRHi
9050 : LdSize == 1 ? ARM::tLDRBi : 0;
9051 if (IsThumb2)
9052 return LdSize == 4 ? ARM::t2LDR_POST
9053 : LdSize == 2 ? ARM::t2LDRH_POST
9054 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
9055 return LdSize == 4 ? ARM::LDR_POST_IMM
9056 : LdSize == 2 ? ARM::LDRH_POST
9057 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
9060 /// Return the store opcode for a given store size. If store size >= 8,
9061 /// neon opcode will be returned.
9062 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
9063 if (StSize >= 8)
9064 return StSize == 16 ? ARM::VST1q32wb_fixed
9065 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
9066 if (IsThumb1)
9067 return StSize == 4 ? ARM::tSTRi
9068 : StSize == 2 ? ARM::tSTRHi
9069 : StSize == 1 ? ARM::tSTRBi : 0;
9070 if (IsThumb2)
9071 return StSize == 4 ? ARM::t2STR_POST
9072 : StSize == 2 ? ARM::t2STRH_POST
9073 : StSize == 1 ? ARM::t2STRB_POST : 0;
9074 return StSize == 4 ? ARM::STR_POST_IMM
9075 : StSize == 2 ? ARM::STRH_POST
9076 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
9079 /// Emit a post-increment load operation with given size. The instructions
9080 /// will be added to BB at Pos.
9081 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9082 const TargetInstrInfo *TII, const DebugLoc &dl,
9083 unsigned LdSize, unsigned Data, unsigned AddrIn,
9084 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9085 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
9086 assert(LdOpc != 0 && "Should have a load opcode");
9087 if (LdSize >= 8) {
9088 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9089 .addReg(AddrOut, RegState::Define)
9090 .addReg(AddrIn)
9091 .addImm(0)
9092 .add(predOps(ARMCC::AL));
9093 } else if (IsThumb1) {
9094 // load + update AddrIn
9095 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9096 .addReg(AddrIn)
9097 .addImm(0)
9098 .add(predOps(ARMCC::AL));
9099 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9100 .add(t1CondCodeOp())
9101 .addReg(AddrIn)
9102 .addImm(LdSize)
9103 .add(predOps(ARMCC::AL));
9104 } else if (IsThumb2) {
9105 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9106 .addReg(AddrOut, RegState::Define)
9107 .addReg(AddrIn)
9108 .addImm(LdSize)
9109 .add(predOps(ARMCC::AL));
9110 } else { // arm
9111 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9112 .addReg(AddrOut, RegState::Define)
9113 .addReg(AddrIn)
9114 .addReg(0)
9115 .addImm(LdSize)
9116 .add(predOps(ARMCC::AL));
9120 /// Emit a post-increment store operation with given size. The instructions
9121 /// will be added to BB at Pos.
9122 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9123 const TargetInstrInfo *TII, const DebugLoc &dl,
9124 unsigned StSize, unsigned Data, unsigned AddrIn,
9125 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9126 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
9127 assert(StOpc != 0 && "Should have a store opcode");
9128 if (StSize >= 8) {
9129 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9130 .addReg(AddrIn)
9131 .addImm(0)
9132 .addReg(Data)
9133 .add(predOps(ARMCC::AL));
9134 } else if (IsThumb1) {
9135 // store + update AddrIn
9136 BuildMI(*BB, Pos, dl, TII->get(StOpc))
9137 .addReg(Data)
9138 .addReg(AddrIn)
9139 .addImm(0)
9140 .add(predOps(ARMCC::AL));
9141 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9142 .add(t1CondCodeOp())
9143 .addReg(AddrIn)
9144 .addImm(StSize)
9145 .add(predOps(ARMCC::AL));
9146 } else if (IsThumb2) {
9147 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9148 .addReg(Data)
9149 .addReg(AddrIn)
9150 .addImm(StSize)
9151 .add(predOps(ARMCC::AL));
9152 } else { // arm
9153 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9154 .addReg(Data)
9155 .addReg(AddrIn)
9156 .addReg(0)
9157 .addImm(StSize)
9158 .add(predOps(ARMCC::AL));
9162 MachineBasicBlock *
9163 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
9164 MachineBasicBlock *BB) const {
9165 // This pseudo instruction has 3 operands: dst, src, size
9166 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
9167 // Otherwise, we will generate unrolled scalar copies.
9168 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9169 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9170 MachineFunction::iterator It = ++BB->getIterator();
9172 unsigned dest = MI.getOperand(0).getReg();
9173 unsigned src = MI.getOperand(1).getReg();
9174 unsigned SizeVal = MI.getOperand(2).getImm();
9175 unsigned Align = MI.getOperand(3).getImm();
9176 DebugLoc dl = MI.getDebugLoc();
9178 MachineFunction *MF = BB->getParent();
9179 MachineRegisterInfo &MRI = MF->getRegInfo();
9180 unsigned UnitSize = 0;
9181 const TargetRegisterClass *TRC = nullptr;
9182 const TargetRegisterClass *VecTRC = nullptr;
9184 bool IsThumb1 = Subtarget->isThumb1Only();
9185 bool IsThumb2 = Subtarget->isThumb2();
9186 bool IsThumb = Subtarget->isThumb();
9188 if (Align & 1) {
9189 UnitSize = 1;
9190 } else if (Align & 2) {
9191 UnitSize = 2;
9192 } else {
9193 // Check whether we can use NEON instructions.
9194 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
9195 Subtarget->hasNEON()) {
9196 if ((Align % 16 == 0) && SizeVal >= 16)
9197 UnitSize = 16;
9198 else if ((Align % 8 == 0) && SizeVal >= 8)
9199 UnitSize = 8;
9201 // Can't use NEON instructions.
9202 if (UnitSize == 0)
9203 UnitSize = 4;
9206 // Select the correct opcode and register class for unit size load/store
9207 bool IsNeon = UnitSize >= 8;
9208 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
9209 if (IsNeon)
9210 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
9211 : UnitSize == 8 ? &ARM::DPRRegClass
9212 : nullptr;
9214 unsigned BytesLeft = SizeVal % UnitSize;
9215 unsigned LoopSize = SizeVal - BytesLeft;
9217 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
9218 // Use LDR and STR to copy.
9219 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
9220 // [destOut] = STR_POST(scratch, destIn, UnitSize)
9221 unsigned srcIn = src;
9222 unsigned destIn = dest;
9223 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
9224 unsigned srcOut = MRI.createVirtualRegister(TRC);
9225 unsigned destOut = MRI.createVirtualRegister(TRC);
9226 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9227 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
9228 IsThumb1, IsThumb2);
9229 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
9230 IsThumb1, IsThumb2);
9231 srcIn = srcOut;
9232 destIn = destOut;
9235 // Handle the leftover bytes with LDRB and STRB.
9236 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
9237 // [destOut] = STRB_POST(scratch, destIn, 1)
9238 for (unsigned i = 0; i < BytesLeft; i++) {
9239 unsigned srcOut = MRI.createVirtualRegister(TRC);
9240 unsigned destOut = MRI.createVirtualRegister(TRC);
9241 unsigned scratch = MRI.createVirtualRegister(TRC);
9242 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
9243 IsThumb1, IsThumb2);
9244 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
9245 IsThumb1, IsThumb2);
9246 srcIn = srcOut;
9247 destIn = destOut;
9249 MI.eraseFromParent(); // The instruction is gone now.
9250 return BB;
9253 // Expand the pseudo op to a loop.
9254 // thisMBB:
9255 // ...
9256 // movw varEnd, # --> with thumb2
9257 // movt varEnd, #
9258 // ldrcp varEnd, idx --> without thumb2
9259 // fallthrough --> loopMBB
9260 // loopMBB:
9261 // PHI varPhi, varEnd, varLoop
9262 // PHI srcPhi, src, srcLoop
9263 // PHI destPhi, dst, destLoop
9264 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9265 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
9266 // subs varLoop, varPhi, #UnitSize
9267 // bne loopMBB
9268 // fallthrough --> exitMBB
9269 // exitMBB:
9270 // epilogue to handle left-over bytes
9271 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9272 // [destOut] = STRB_POST(scratch, destLoop, 1)
9273 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9274 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9275 MF->insert(It, loopMBB);
9276 MF->insert(It, exitMBB);
9278 // Transfer the remainder of BB and its successor edges to exitMBB.
9279 exitMBB->splice(exitMBB->begin(), BB,
9280 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9281 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9283 // Load an immediate to varEnd.
9284 unsigned varEnd = MRI.createVirtualRegister(TRC);
9285 if (Subtarget->useMovt()) {
9286 unsigned Vtmp = varEnd;
9287 if ((LoopSize & 0xFFFF0000) != 0)
9288 Vtmp = MRI.createVirtualRegister(TRC);
9289 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
9290 .addImm(LoopSize & 0xFFFF)
9291 .add(predOps(ARMCC::AL));
9293 if ((LoopSize & 0xFFFF0000) != 0)
9294 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
9295 .addReg(Vtmp)
9296 .addImm(LoopSize >> 16)
9297 .add(predOps(ARMCC::AL));
9298 } else {
9299 MachineConstantPool *ConstantPool = MF->getConstantPool();
9300 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9301 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
9303 // MachineConstantPool wants an explicit alignment.
9304 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9305 if (Align == 0)
9306 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9307 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9308 MachineMemOperand *CPMMO =
9309 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9310 MachineMemOperand::MOLoad, 4, 4);
9312 if (IsThumb)
9313 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
9314 .addReg(varEnd, RegState::Define)
9315 .addConstantPoolIndex(Idx)
9316 .add(predOps(ARMCC::AL))
9317 .addMemOperand(CPMMO);
9318 else
9319 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
9320 .addReg(varEnd, RegState::Define)
9321 .addConstantPoolIndex(Idx)
9322 .addImm(0)
9323 .add(predOps(ARMCC::AL))
9324 .addMemOperand(CPMMO);
9326 BB->addSuccessor(loopMBB);
9328 // Generate the loop body:
9329 // varPhi = PHI(varLoop, varEnd)
9330 // srcPhi = PHI(srcLoop, src)
9331 // destPhi = PHI(destLoop, dst)
9332 MachineBasicBlock *entryBB = BB;
9333 BB = loopMBB;
9334 unsigned varLoop = MRI.createVirtualRegister(TRC);
9335 unsigned varPhi = MRI.createVirtualRegister(TRC);
9336 unsigned srcLoop = MRI.createVirtualRegister(TRC);
9337 unsigned srcPhi = MRI.createVirtualRegister(TRC);
9338 unsigned destLoop = MRI.createVirtualRegister(TRC);
9339 unsigned destPhi = MRI.createVirtualRegister(TRC);
9341 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
9342 .addReg(varLoop).addMBB(loopMBB)
9343 .addReg(varEnd).addMBB(entryBB);
9344 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
9345 .addReg(srcLoop).addMBB(loopMBB)
9346 .addReg(src).addMBB(entryBB);
9347 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
9348 .addReg(destLoop).addMBB(loopMBB)
9349 .addReg(dest).addMBB(entryBB);
9351 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9352 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
9353 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9354 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
9355 IsThumb1, IsThumb2);
9356 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
9357 IsThumb1, IsThumb2);
9359 // Decrement loop variable by UnitSize.
9360 if (IsThumb1) {
9361 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
9362 .add(t1CondCodeOp())
9363 .addReg(varPhi)
9364 .addImm(UnitSize)
9365 .add(predOps(ARMCC::AL));
9366 } else {
9367 MachineInstrBuilder MIB =
9368 BuildMI(*BB, BB->end(), dl,
9369 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
9370 MIB.addReg(varPhi)
9371 .addImm(UnitSize)
9372 .add(predOps(ARMCC::AL))
9373 .add(condCodeOp());
9374 MIB->getOperand(5).setReg(ARM::CPSR);
9375 MIB->getOperand(5).setIsDef(true);
9377 BuildMI(*BB, BB->end(), dl,
9378 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
9379 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
9381 // loopMBB can loop back to loopMBB or fall through to exitMBB.
9382 BB->addSuccessor(loopMBB);
9383 BB->addSuccessor(exitMBB);
9385 // Add epilogue to handle BytesLeft.
9386 BB = exitMBB;
9387 auto StartOfExit = exitMBB->begin();
9389 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9390 // [destOut] = STRB_POST(scratch, destLoop, 1)
9391 unsigned srcIn = srcLoop;
9392 unsigned destIn = destLoop;
9393 for (unsigned i = 0; i < BytesLeft; i++) {
9394 unsigned srcOut = MRI.createVirtualRegister(TRC);
9395 unsigned destOut = MRI.createVirtualRegister(TRC);
9396 unsigned scratch = MRI.createVirtualRegister(TRC);
9397 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
9398 IsThumb1, IsThumb2);
9399 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
9400 IsThumb1, IsThumb2);
9401 srcIn = srcOut;
9402 destIn = destOut;
9405 MI.eraseFromParent(); // The instruction is gone now.
9406 return BB;
9409 MachineBasicBlock *
9410 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
9411 MachineBasicBlock *MBB) const {
9412 const TargetMachine &TM = getTargetMachine();
9413 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
9414 DebugLoc DL = MI.getDebugLoc();
9416 assert(Subtarget->isTargetWindows() &&
9417 "__chkstk is only supported on Windows");
9418 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
9420 // __chkstk takes the number of words to allocate on the stack in R4, and
9421 // returns the stack adjustment in number of bytes in R4. This will not
9422 // clober any other registers (other than the obvious lr).
9424 // Although, technically, IP should be considered a register which may be
9425 // clobbered, the call itself will not touch it. Windows on ARM is a pure
9426 // thumb-2 environment, so there is no interworking required. As a result, we
9427 // do not expect a veneer to be emitted by the linker, clobbering IP.
9429 // Each module receives its own copy of __chkstk, so no import thunk is
9430 // required, again, ensuring that IP is not clobbered.
9432 // Finally, although some linkers may theoretically provide a trampoline for
9433 // out of range calls (which is quite common due to a 32M range limitation of
9434 // branches for Thumb), we can generate the long-call version via
9435 // -mcmodel=large, alleviating the need for the trampoline which may clobber
9436 // IP.
9438 switch (TM.getCodeModel()) {
9439 case CodeModel::Tiny:
9440 llvm_unreachable("Tiny code model not available on ARM.");
9441 case CodeModel::Small:
9442 case CodeModel::Medium:
9443 case CodeModel::Kernel:
9444 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
9445 .add(predOps(ARMCC::AL))
9446 .addExternalSymbol("__chkstk")
9447 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9448 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9449 .addReg(ARM::R12,
9450 RegState::Implicit | RegState::Define | RegState::Dead)
9451 .addReg(ARM::CPSR,
9452 RegState::Implicit | RegState::Define | RegState::Dead);
9453 break;
9454 case CodeModel::Large: {
9455 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9456 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
9458 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
9459 .addExternalSymbol("__chkstk");
9460 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
9461 .add(predOps(ARMCC::AL))
9462 .addReg(Reg, RegState::Kill)
9463 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9464 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9465 .addReg(ARM::R12,
9466 RegState::Implicit | RegState::Define | RegState::Dead)
9467 .addReg(ARM::CPSR,
9468 RegState::Implicit | RegState::Define | RegState::Dead);
9469 break;
9473 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
9474 .addReg(ARM::SP, RegState::Kill)
9475 .addReg(ARM::R4, RegState::Kill)
9476 .setMIFlags(MachineInstr::FrameSetup)
9477 .add(predOps(ARMCC::AL))
9478 .add(condCodeOp());
9480 MI.eraseFromParent();
9481 return MBB;
9484 MachineBasicBlock *
9485 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
9486 MachineBasicBlock *MBB) const {
9487 DebugLoc DL = MI.getDebugLoc();
9488 MachineFunction *MF = MBB->getParent();
9489 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9491 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
9492 MF->insert(++MBB->getIterator(), ContBB);
9493 ContBB->splice(ContBB->begin(), MBB,
9494 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9495 ContBB->transferSuccessorsAndUpdatePHIs(MBB);
9496 MBB->addSuccessor(ContBB);
9498 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9499 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
9500 MF->push_back(TrapBB);
9501 MBB->addSuccessor(TrapBB);
9503 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
9504 .addReg(MI.getOperand(0).getReg())
9505 .addImm(0)
9506 .add(predOps(ARMCC::AL));
9507 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
9508 .addMBB(TrapBB)
9509 .addImm(ARMCC::EQ)
9510 .addReg(ARM::CPSR);
9512 MI.eraseFromParent();
9513 return ContBB;
9516 // The CPSR operand of SelectItr might be missing a kill marker
9517 // because there were multiple uses of CPSR, and ISel didn't know
9518 // which to mark. Figure out whether SelectItr should have had a
9519 // kill marker, and set it if it should. Returns the correct kill
9520 // marker value.
9521 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
9522 MachineBasicBlock* BB,
9523 const TargetRegisterInfo* TRI) {
9524 // Scan forward through BB for a use/def of CPSR.
9525 MachineBasicBlock::iterator miI(std::next(SelectItr));
9526 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
9527 const MachineInstr& mi = *miI;
9528 if (mi.readsRegister(ARM::CPSR))
9529 return false;
9530 if (mi.definesRegister(ARM::CPSR))
9531 break; // Should have kill-flag - update below.
9534 // If we hit the end of the block, check whether CPSR is live into a
9535 // successor.
9536 if (miI == BB->end()) {
9537 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
9538 sEnd = BB->succ_end();
9539 sItr != sEnd; ++sItr) {
9540 MachineBasicBlock* succ = *sItr;
9541 if (succ->isLiveIn(ARM::CPSR))
9542 return false;
9546 // We found a def, or hit the end of the basic block and CPSR wasn't live
9547 // out. SelectMI should have a kill flag on CPSR.
9548 SelectItr->addRegisterKilled(ARM::CPSR, TRI);
9549 return true;
9552 MachineBasicBlock *
9553 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9554 MachineBasicBlock *BB) const {
9555 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9556 DebugLoc dl = MI.getDebugLoc();
9557 bool isThumb2 = Subtarget->isThumb2();
9558 switch (MI.getOpcode()) {
9559 default: {
9560 MI.print(errs());
9561 llvm_unreachable("Unexpected instr type to insert");
9564 // Thumb1 post-indexed loads are really just single-register LDMs.
9565 case ARM::tLDR_postidx: {
9566 MachineOperand Def(MI.getOperand(1));
9567 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
9568 .add(Def) // Rn_wb
9569 .add(MI.getOperand(2)) // Rn
9570 .add(MI.getOperand(3)) // PredImm
9571 .add(MI.getOperand(4)) // PredReg
9572 .add(MI.getOperand(0)) // Rt
9573 .cloneMemRefs(MI);
9574 MI.eraseFromParent();
9575 return BB;
9578 // The Thumb2 pre-indexed stores have the same MI operands, they just
9579 // define them differently in the .td files from the isel patterns, so
9580 // they need pseudos.
9581 case ARM::t2STR_preidx:
9582 MI.setDesc(TII->get(ARM::t2STR_PRE));
9583 return BB;
9584 case ARM::t2STRB_preidx:
9585 MI.setDesc(TII->get(ARM::t2STRB_PRE));
9586 return BB;
9587 case ARM::t2STRH_preidx:
9588 MI.setDesc(TII->get(ARM::t2STRH_PRE));
9589 return BB;
9591 case ARM::STRi_preidx:
9592 case ARM::STRBi_preidx: {
9593 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
9594 : ARM::STRB_PRE_IMM;
9595 // Decode the offset.
9596 unsigned Offset = MI.getOperand(4).getImm();
9597 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
9598 Offset = ARM_AM::getAM2Offset(Offset);
9599 if (isSub)
9600 Offset = -Offset;
9602 MachineMemOperand *MMO = *MI.memoperands_begin();
9603 BuildMI(*BB, MI, dl, TII->get(NewOpc))
9604 .add(MI.getOperand(0)) // Rn_wb
9605 .add(MI.getOperand(1)) // Rt
9606 .add(MI.getOperand(2)) // Rn
9607 .addImm(Offset) // offset (skip GPR==zero_reg)
9608 .add(MI.getOperand(5)) // pred
9609 .add(MI.getOperand(6))
9610 .addMemOperand(MMO);
9611 MI.eraseFromParent();
9612 return BB;
9614 case ARM::STRr_preidx:
9615 case ARM::STRBr_preidx:
9616 case ARM::STRH_preidx: {
9617 unsigned NewOpc;
9618 switch (MI.getOpcode()) {
9619 default: llvm_unreachable("unexpected opcode!");
9620 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
9621 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
9622 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
9624 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
9625 for (unsigned i = 0; i < MI.getNumOperands(); ++i)
9626 MIB.add(MI.getOperand(i));
9627 MI.eraseFromParent();
9628 return BB;
9631 case ARM::tMOVCCr_pseudo: {
9632 // To "insert" a SELECT_CC instruction, we actually have to insert the
9633 // diamond control-flow pattern. The incoming instruction knows the
9634 // destination vreg to set, the condition code register to branch on, the
9635 // true/false values to select between, and a branch opcode to use.
9636 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9637 MachineFunction::iterator It = ++BB->getIterator();
9639 // thisMBB:
9640 // ...
9641 // TrueVal = ...
9642 // cmpTY ccX, r1, r2
9643 // bCC copy1MBB
9644 // fallthrough --> copy0MBB
9645 MachineBasicBlock *thisMBB = BB;
9646 MachineFunction *F = BB->getParent();
9647 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9648 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9649 F->insert(It, copy0MBB);
9650 F->insert(It, sinkMBB);
9652 // Check whether CPSR is live past the tMOVCCr_pseudo.
9653 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
9654 if (!MI.killsRegister(ARM::CPSR) &&
9655 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
9656 copy0MBB->addLiveIn(ARM::CPSR);
9657 sinkMBB->addLiveIn(ARM::CPSR);
9660 // Transfer the remainder of BB and its successor edges to sinkMBB.
9661 sinkMBB->splice(sinkMBB->begin(), BB,
9662 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9663 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9665 BB->addSuccessor(copy0MBB);
9666 BB->addSuccessor(sinkMBB);
9668 BuildMI(BB, dl, TII->get(ARM::tBcc))
9669 .addMBB(sinkMBB)
9670 .addImm(MI.getOperand(3).getImm())
9671 .addReg(MI.getOperand(4).getReg());
9673 // copy0MBB:
9674 // %FalseValue = ...
9675 // # fallthrough to sinkMBB
9676 BB = copy0MBB;
9678 // Update machine-CFG edges
9679 BB->addSuccessor(sinkMBB);
9681 // sinkMBB:
9682 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9683 // ...
9684 BB = sinkMBB;
9685 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
9686 .addReg(MI.getOperand(1).getReg())
9687 .addMBB(copy0MBB)
9688 .addReg(MI.getOperand(2).getReg())
9689 .addMBB(thisMBB);
9691 MI.eraseFromParent(); // The pseudo instruction is gone now.
9692 return BB;
9695 case ARM::BCCi64:
9696 case ARM::BCCZi64: {
9697 // If there is an unconditional branch to the other successor, remove it.
9698 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
9700 // Compare both parts that make up the double comparison separately for
9701 // equality.
9702 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
9704 unsigned LHS1 = MI.getOperand(1).getReg();
9705 unsigned LHS2 = MI.getOperand(2).getReg();
9706 if (RHSisZero) {
9707 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9708 .addReg(LHS1)
9709 .addImm(0)
9710 .add(predOps(ARMCC::AL));
9711 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9712 .addReg(LHS2).addImm(0)
9713 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9714 } else {
9715 unsigned RHS1 = MI.getOperand(3).getReg();
9716 unsigned RHS2 = MI.getOperand(4).getReg();
9717 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9718 .addReg(LHS1)
9719 .addReg(RHS1)
9720 .add(predOps(ARMCC::AL));
9721 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9722 .addReg(LHS2).addReg(RHS2)
9723 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9726 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
9727 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
9728 if (MI.getOperand(0).getImm() == ARMCC::NE)
9729 std::swap(destMBB, exitMBB);
9731 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
9732 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
9733 if (isThumb2)
9734 BuildMI(BB, dl, TII->get(ARM::t2B))
9735 .addMBB(exitMBB)
9736 .add(predOps(ARMCC::AL));
9737 else
9738 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
9740 MI.eraseFromParent(); // The pseudo instruction is gone now.
9741 return BB;
9744 case ARM::Int_eh_sjlj_setjmp:
9745 case ARM::Int_eh_sjlj_setjmp_nofp:
9746 case ARM::tInt_eh_sjlj_setjmp:
9747 case ARM::t2Int_eh_sjlj_setjmp:
9748 case ARM::t2Int_eh_sjlj_setjmp_nofp:
9749 return BB;
9751 case ARM::Int_eh_sjlj_setup_dispatch:
9752 EmitSjLjDispatchBlock(MI, BB);
9753 return BB;
9755 case ARM::ABS:
9756 case ARM::t2ABS: {
9757 // To insert an ABS instruction, we have to insert the
9758 // diamond control-flow pattern. The incoming instruction knows the
9759 // source vreg to test against 0, the destination vreg to set,
9760 // the condition code register to branch on, the
9761 // true/false values to select between, and a branch opcode to use.
9762 // It transforms
9763 // V1 = ABS V0
9764 // into
9765 // V2 = MOVS V0
9766 // BCC (branch to SinkBB if V0 >= 0)
9767 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
9768 // SinkBB: V1 = PHI(V2, V3)
9769 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9770 MachineFunction::iterator BBI = ++BB->getIterator();
9771 MachineFunction *Fn = BB->getParent();
9772 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
9773 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
9774 Fn->insert(BBI, RSBBB);
9775 Fn->insert(BBI, SinkBB);
9777 unsigned int ABSSrcReg = MI.getOperand(1).getReg();
9778 unsigned int ABSDstReg = MI.getOperand(0).getReg();
9779 bool ABSSrcKIll = MI.getOperand(1).isKill();
9780 bool isThumb2 = Subtarget->isThumb2();
9781 MachineRegisterInfo &MRI = Fn->getRegInfo();
9782 // In Thumb mode S must not be specified if source register is the SP or
9783 // PC and if destination register is the SP, so restrict register class
9784 unsigned NewRsbDstReg =
9785 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
9787 // Transfer the remainder of BB and its successor edges to sinkMBB.
9788 SinkBB->splice(SinkBB->begin(), BB,
9789 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9790 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
9792 BB->addSuccessor(RSBBB);
9793 BB->addSuccessor(SinkBB);
9795 // fall through to SinkMBB
9796 RSBBB->addSuccessor(SinkBB);
9798 // insert a cmp at the end of BB
9799 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9800 .addReg(ABSSrcReg)
9801 .addImm(0)
9802 .add(predOps(ARMCC::AL));
9804 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
9805 BuildMI(BB, dl,
9806 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
9807 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
9809 // insert rsbri in RSBBB
9810 // Note: BCC and rsbri will be converted into predicated rsbmi
9811 // by if-conversion pass
9812 BuildMI(*RSBBB, RSBBB->begin(), dl,
9813 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
9814 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
9815 .addImm(0)
9816 .add(predOps(ARMCC::AL))
9817 .add(condCodeOp());
9819 // insert PHI in SinkBB,
9820 // reuse ABSDstReg to not change uses of ABS instruction
9821 BuildMI(*SinkBB, SinkBB->begin(), dl,
9822 TII->get(ARM::PHI), ABSDstReg)
9823 .addReg(NewRsbDstReg).addMBB(RSBBB)
9824 .addReg(ABSSrcReg).addMBB(BB);
9826 // remove ABS instruction
9827 MI.eraseFromParent();
9829 // return last added BB
9830 return SinkBB;
9832 case ARM::COPY_STRUCT_BYVAL_I32:
9833 ++NumLoopByVals;
9834 return EmitStructByval(MI, BB);
9835 case ARM::WIN__CHKSTK:
9836 return EmitLowered__chkstk(MI, BB);
9837 case ARM::WIN__DBZCHK:
9838 return EmitLowered__dbzchk(MI, BB);
9842 /// Attaches vregs to MEMCPY that it will use as scratch registers
9843 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
9844 /// instead of as a custom inserter because we need the use list from the SDNode.
9845 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
9846 MachineInstr &MI, const SDNode *Node) {
9847 bool isThumb1 = Subtarget->isThumb1Only();
9849 DebugLoc DL = MI.getDebugLoc();
9850 MachineFunction *MF = MI.getParent()->getParent();
9851 MachineRegisterInfo &MRI = MF->getRegInfo();
9852 MachineInstrBuilder MIB(*MF, MI);
9854 // If the new dst/src is unused mark it as dead.
9855 if (!Node->hasAnyUseOfValue(0)) {
9856 MI.getOperand(0).setIsDead(true);
9858 if (!Node->hasAnyUseOfValue(1)) {
9859 MI.getOperand(1).setIsDead(true);
9862 // The MEMCPY both defines and kills the scratch registers.
9863 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
9864 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
9865 : &ARM::GPRRegClass);
9866 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
9870 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9871 SDNode *Node) const {
9872 if (MI.getOpcode() == ARM::MEMCPY) {
9873 attachMEMCPYScratchRegs(Subtarget, MI, Node);
9874 return;
9877 const MCInstrDesc *MCID = &MI.getDesc();
9878 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
9879 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
9880 // operand is still set to noreg. If needed, set the optional operand's
9881 // register to CPSR, and remove the redundant implicit def.
9883 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
9885 // Rename pseudo opcodes.
9886 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
9887 unsigned ccOutIdx;
9888 if (NewOpc) {
9889 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
9890 MCID = &TII->get(NewOpc);
9892 assert(MCID->getNumOperands() ==
9893 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
9894 && "converted opcode should be the same except for cc_out"
9895 " (and, on Thumb1, pred)");
9897 MI.setDesc(*MCID);
9899 // Add the optional cc_out operand
9900 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
9902 // On Thumb1, move all input operands to the end, then add the predicate
9903 if (Subtarget->isThumb1Only()) {
9904 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
9905 MI.addOperand(MI.getOperand(1));
9906 MI.RemoveOperand(1);
9909 // Restore the ties
9910 for (unsigned i = MI.getNumOperands(); i--;) {
9911 const MachineOperand& op = MI.getOperand(i);
9912 if (op.isReg() && op.isUse()) {
9913 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
9914 if (DefIdx != -1)
9915 MI.tieOperands(DefIdx, i);
9919 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
9920 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
9921 ccOutIdx = 1;
9922 } else
9923 ccOutIdx = MCID->getNumOperands() - 1;
9924 } else
9925 ccOutIdx = MCID->getNumOperands() - 1;
9927 // Any ARM instruction that sets the 's' bit should specify an optional
9928 // "cc_out" operand in the last operand position.
9929 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
9930 assert(!NewOpc && "Optional cc_out operand required");
9931 return;
9933 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
9934 // since we already have an optional CPSR def.
9935 bool definesCPSR = false;
9936 bool deadCPSR = false;
9937 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
9938 ++i) {
9939 const MachineOperand &MO = MI.getOperand(i);
9940 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
9941 definesCPSR = true;
9942 if (MO.isDead())
9943 deadCPSR = true;
9944 MI.RemoveOperand(i);
9945 break;
9948 if (!definesCPSR) {
9949 assert(!NewOpc && "Optional cc_out operand required");
9950 return;
9952 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
9953 if (deadCPSR) {
9954 assert(!MI.getOperand(ccOutIdx).getReg() &&
9955 "expect uninitialized optional cc_out operand");
9956 // Thumb1 instructions must have the S bit even if the CPSR is dead.
9957 if (!Subtarget->isThumb1Only())
9958 return;
9961 // If this instruction was defined with an optional CPSR def and its dag node
9962 // had a live implicit CPSR def, then activate the optional CPSR def.
9963 MachineOperand &MO = MI.getOperand(ccOutIdx);
9964 MO.setReg(ARM::CPSR);
9965 MO.setIsDef(true);
9968 //===----------------------------------------------------------------------===//
9969 // ARM Optimization Hooks
9970 //===----------------------------------------------------------------------===//
9972 // Helper function that checks if N is a null or all ones constant.
9973 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
9974 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
9977 // Return true if N is conditionally 0 or all ones.
9978 // Detects these expressions where cc is an i1 value:
9980 // (select cc 0, y) [AllOnes=0]
9981 // (select cc y, 0) [AllOnes=0]
9982 // (zext cc) [AllOnes=0]
9983 // (sext cc) [AllOnes=0/1]
9984 // (select cc -1, y) [AllOnes=1]
9985 // (select cc y, -1) [AllOnes=1]
9987 // Invert is set when N is the null/all ones constant when CC is false.
9988 // OtherOp is set to the alternative value of N.
9989 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9990 SDValue &CC, bool &Invert,
9991 SDValue &OtherOp,
9992 SelectionDAG &DAG) {
9993 switch (N->getOpcode()) {
9994 default: return false;
9995 case ISD::SELECT: {
9996 CC = N->getOperand(0);
9997 SDValue N1 = N->getOperand(1);
9998 SDValue N2 = N->getOperand(2);
9999 if (isZeroOrAllOnes(N1, AllOnes)) {
10000 Invert = false;
10001 OtherOp = N2;
10002 return true;
10004 if (isZeroOrAllOnes(N2, AllOnes)) {
10005 Invert = true;
10006 OtherOp = N1;
10007 return true;
10009 return false;
10011 case ISD::ZERO_EXTEND:
10012 // (zext cc) can never be the all ones value.
10013 if (AllOnes)
10014 return false;
10015 LLVM_FALLTHROUGH;
10016 case ISD::SIGN_EXTEND: {
10017 SDLoc dl(N);
10018 EVT VT = N->getValueType(0);
10019 CC = N->getOperand(0);
10020 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
10021 return false;
10022 Invert = !AllOnes;
10023 if (AllOnes)
10024 // When looking for an AllOnes constant, N is an sext, and the 'other'
10025 // value is 0.
10026 OtherOp = DAG.getConstant(0, dl, VT);
10027 else if (N->getOpcode() == ISD::ZERO_EXTEND)
10028 // When looking for a 0 constant, N can be zext or sext.
10029 OtherOp = DAG.getConstant(1, dl, VT);
10030 else
10031 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
10032 VT);
10033 return true;
10038 // Combine a constant select operand into its use:
10040 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10041 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10042 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
10043 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10044 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10046 // The transform is rejected if the select doesn't have a constant operand that
10047 // is null, or all ones when AllOnes is set.
10049 // Also recognize sext/zext from i1:
10051 // (add (zext cc), x) -> (select cc (add x, 1), x)
10052 // (add (sext cc), x) -> (select cc (add x, -1), x)
10054 // These transformations eventually create predicated instructions.
10056 // @param N The node to transform.
10057 // @param Slct The N operand that is a select.
10058 // @param OtherOp The other N operand (x above).
10059 // @param DCI Context.
10060 // @param AllOnes Require the select constant to be all ones instead of null.
10061 // @returns The new node, or SDValue() on failure.
10062 static
10063 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
10064 TargetLowering::DAGCombinerInfo &DCI,
10065 bool AllOnes = false) {
10066 SelectionDAG &DAG = DCI.DAG;
10067 EVT VT = N->getValueType(0);
10068 SDValue NonConstantVal;
10069 SDValue CCOp;
10070 bool SwapSelectOps;
10071 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
10072 NonConstantVal, DAG))
10073 return SDValue();
10075 // Slct is now know to be the desired identity constant when CC is true.
10076 SDValue TrueVal = OtherOp;
10077 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10078 OtherOp, NonConstantVal);
10079 // Unless SwapSelectOps says CC should be false.
10080 if (SwapSelectOps)
10081 std::swap(TrueVal, FalseVal);
10083 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
10084 CCOp, TrueVal, FalseVal);
10087 // Attempt combineSelectAndUse on each operand of a commutative operator N.
10088 static
10089 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
10090 TargetLowering::DAGCombinerInfo &DCI) {
10091 SDValue N0 = N->getOperand(0);
10092 SDValue N1 = N->getOperand(1);
10093 if (N0.getNode()->hasOneUse())
10094 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
10095 return Result;
10096 if (N1.getNode()->hasOneUse())
10097 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
10098 return Result;
10099 return SDValue();
10102 static bool IsVUZPShuffleNode(SDNode *N) {
10103 // VUZP shuffle node.
10104 if (N->getOpcode() == ARMISD::VUZP)
10105 return true;
10107 // "VUZP" on i32 is an alias for VTRN.
10108 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
10109 return true;
10111 return false;
10114 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
10115 TargetLowering::DAGCombinerInfo &DCI,
10116 const ARMSubtarget *Subtarget) {
10117 // Look for ADD(VUZP.0, VUZP.1).
10118 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
10119 N0 == N1)
10120 return SDValue();
10122 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
10123 if (!N->getValueType(0).is64BitVector())
10124 return SDValue();
10126 // Generate vpadd.
10127 SelectionDAG &DAG = DCI.DAG;
10128 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10129 SDLoc dl(N);
10130 SDNode *Unzip = N0.getNode();
10131 EVT VT = N->getValueType(0);
10133 SmallVector<SDValue, 8> Ops;
10134 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
10135 TLI.getPointerTy(DAG.getDataLayout())));
10136 Ops.push_back(Unzip->getOperand(0));
10137 Ops.push_back(Unzip->getOperand(1));
10139 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10142 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10143 TargetLowering::DAGCombinerInfo &DCI,
10144 const ARMSubtarget *Subtarget) {
10145 // Check for two extended operands.
10146 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
10147 N1.getOpcode() == ISD::SIGN_EXTEND) &&
10148 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
10149 N1.getOpcode() == ISD::ZERO_EXTEND))
10150 return SDValue();
10152 SDValue N00 = N0.getOperand(0);
10153 SDValue N10 = N1.getOperand(0);
10155 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
10156 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
10157 N00 == N10)
10158 return SDValue();
10160 // We only recognize Q register paddl here; this can't be reached until
10161 // after type legalization.
10162 if (!N00.getValueType().is64BitVector() ||
10163 !N0.getValueType().is128BitVector())
10164 return SDValue();
10166 // Generate vpaddl.
10167 SelectionDAG &DAG = DCI.DAG;
10168 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10169 SDLoc dl(N);
10170 EVT VT = N->getValueType(0);
10172 SmallVector<SDValue, 8> Ops;
10173 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
10174 unsigned Opcode;
10175 if (N0.getOpcode() == ISD::SIGN_EXTEND)
10176 Opcode = Intrinsic::arm_neon_vpaddls;
10177 else
10178 Opcode = Intrinsic::arm_neon_vpaddlu;
10179 Ops.push_back(DAG.getConstant(Opcode, dl,
10180 TLI.getPointerTy(DAG.getDataLayout())));
10181 EVT ElemTy = N00.getValueType().getVectorElementType();
10182 unsigned NumElts = VT.getVectorNumElements();
10183 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
10184 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
10185 N00.getOperand(0), N00.getOperand(1));
10186 Ops.push_back(Concat);
10188 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10191 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
10192 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
10193 // much easier to match.
10194 static SDValue
10195 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10196 TargetLowering::DAGCombinerInfo &DCI,
10197 const ARMSubtarget *Subtarget) {
10198 // Only perform optimization if after legalize, and if NEON is available. We
10199 // also expected both operands to be BUILD_VECTORs.
10200 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
10201 || N0.getOpcode() != ISD::BUILD_VECTOR
10202 || N1.getOpcode() != ISD::BUILD_VECTOR)
10203 return SDValue();
10205 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
10206 EVT VT = N->getValueType(0);
10207 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
10208 return SDValue();
10210 // Check that the vector operands are of the right form.
10211 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
10212 // operands, where N is the size of the formed vector.
10213 // Each EXTRACT_VECTOR should have the same input vector and odd or even
10214 // index such that we have a pair wise add pattern.
10216 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
10217 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10218 return SDValue();
10219 SDValue Vec = N0->getOperand(0)->getOperand(0);
10220 SDNode *V = Vec.getNode();
10221 unsigned nextIndex = 0;
10223 // For each operands to the ADD which are BUILD_VECTORs,
10224 // check to see if each of their operands are an EXTRACT_VECTOR with
10225 // the same vector and appropriate index.
10226 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
10227 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
10228 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10230 SDValue ExtVec0 = N0->getOperand(i);
10231 SDValue ExtVec1 = N1->getOperand(i);
10233 // First operand is the vector, verify its the same.
10234 if (V != ExtVec0->getOperand(0).getNode() ||
10235 V != ExtVec1->getOperand(0).getNode())
10236 return SDValue();
10238 // Second is the constant, verify its correct.
10239 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
10240 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
10242 // For the constant, we want to see all the even or all the odd.
10243 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
10244 || C1->getZExtValue() != nextIndex+1)
10245 return SDValue();
10247 // Increment index.
10248 nextIndex+=2;
10249 } else
10250 return SDValue();
10253 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
10254 // we're using the entire input vector, otherwise there's a size/legality
10255 // mismatch somewhere.
10256 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
10257 Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
10258 return SDValue();
10260 // Create VPADDL node.
10261 SelectionDAG &DAG = DCI.DAG;
10262 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10264 SDLoc dl(N);
10266 // Build operand list.
10267 SmallVector<SDValue, 8> Ops;
10268 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
10269 TLI.getPointerTy(DAG.getDataLayout())));
10271 // Input is the vector.
10272 Ops.push_back(Vec);
10274 // Get widened type and narrowed type.
10275 MVT widenType;
10276 unsigned numElem = VT.getVectorNumElements();
10278 EVT inputLaneType = Vec.getValueType().getVectorElementType();
10279 switch (inputLaneType.getSimpleVT().SimpleTy) {
10280 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
10281 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
10282 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
10283 default:
10284 llvm_unreachable("Invalid vector element type for padd optimization.");
10287 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
10288 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
10289 return DAG.getNode(ExtOp, dl, VT, tmp);
10292 static SDValue findMUL_LOHI(SDValue V) {
10293 if (V->getOpcode() == ISD::UMUL_LOHI ||
10294 V->getOpcode() == ISD::SMUL_LOHI)
10295 return V;
10296 return SDValue();
10299 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
10300 TargetLowering::DAGCombinerInfo &DCI,
10301 const ARMSubtarget *Subtarget) {
10302 if (Subtarget->isThumb()) {
10303 if (!Subtarget->hasDSP())
10304 return SDValue();
10305 } else if (!Subtarget->hasV5TEOps())
10306 return SDValue();
10308 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
10309 // accumulates the product into a 64-bit value. The 16-bit values will
10310 // be sign extended somehow or SRA'd into 32-bit values
10311 // (addc (adde (mul 16bit, 16bit), lo), hi)
10312 SDValue Mul = AddcNode->getOperand(0);
10313 SDValue Lo = AddcNode->getOperand(1);
10314 if (Mul.getOpcode() != ISD::MUL) {
10315 Lo = AddcNode->getOperand(0);
10316 Mul = AddcNode->getOperand(1);
10317 if (Mul.getOpcode() != ISD::MUL)
10318 return SDValue();
10321 SDValue SRA = AddeNode->getOperand(0);
10322 SDValue Hi = AddeNode->getOperand(1);
10323 if (SRA.getOpcode() != ISD::SRA) {
10324 SRA = AddeNode->getOperand(1);
10325 Hi = AddeNode->getOperand(0);
10326 if (SRA.getOpcode() != ISD::SRA)
10327 return SDValue();
10329 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
10330 if (Const->getZExtValue() != 31)
10331 return SDValue();
10332 } else
10333 return SDValue();
10335 if (SRA.getOperand(0) != Mul)
10336 return SDValue();
10338 SelectionDAG &DAG = DCI.DAG;
10339 SDLoc dl(AddcNode);
10340 unsigned Opcode = 0;
10341 SDValue Op0;
10342 SDValue Op1;
10344 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
10345 Opcode = ARMISD::SMLALBB;
10346 Op0 = Mul.getOperand(0);
10347 Op1 = Mul.getOperand(1);
10348 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
10349 Opcode = ARMISD::SMLALBT;
10350 Op0 = Mul.getOperand(0);
10351 Op1 = Mul.getOperand(1).getOperand(0);
10352 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
10353 Opcode = ARMISD::SMLALTB;
10354 Op0 = Mul.getOperand(0).getOperand(0);
10355 Op1 = Mul.getOperand(1);
10356 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
10357 Opcode = ARMISD::SMLALTT;
10358 Op0 = Mul->getOperand(0).getOperand(0);
10359 Op1 = Mul->getOperand(1).getOperand(0);
10362 if (!Op0 || !Op1)
10363 return SDValue();
10365 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
10366 Op0, Op1, Lo, Hi);
10367 // Replace the ADDs' nodes uses by the MLA node's values.
10368 SDValue HiMLALResult(SMLAL.getNode(), 1);
10369 SDValue LoMLALResult(SMLAL.getNode(), 0);
10371 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
10372 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
10374 // Return original node to notify the driver to stop replacing.
10375 SDValue resNode(AddcNode, 0);
10376 return resNode;
10379 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
10380 TargetLowering::DAGCombinerInfo &DCI,
10381 const ARMSubtarget *Subtarget) {
10382 // Look for multiply add opportunities.
10383 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
10384 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
10385 // a glue link from the first add to the second add.
10386 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
10387 // a S/UMLAL instruction.
10388 // UMUL_LOHI
10389 // / :lo \ :hi
10390 // V \ [no multiline comment]
10391 // loAdd -> ADDC |
10392 // \ :carry /
10393 // V V
10394 // ADDE <- hiAdd
10396 // In the special case where only the higher part of a signed result is used
10397 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
10398 // a constant with the exact value of 0x80000000, we recognize we are dealing
10399 // with a "rounded multiply and add" (or subtract) and transform it into
10400 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
10402 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
10403 AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
10404 "Expect an ADDE or SUBE");
10406 assert(AddeSubeNode->getNumOperands() == 3 &&
10407 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
10408 "ADDE node has the wrong inputs");
10410 // Check that we are chained to the right ADDC or SUBC node.
10411 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
10412 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10413 AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
10414 (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
10415 AddcSubcNode->getOpcode() != ARMISD::SUBC))
10416 return SDValue();
10418 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
10419 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
10421 // Check if the two operands are from the same mul_lohi node.
10422 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
10423 return SDValue();
10425 assert(AddcSubcNode->getNumValues() == 2 &&
10426 AddcSubcNode->getValueType(0) == MVT::i32 &&
10427 "Expect ADDC with two result values. First: i32");
10429 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
10430 // maybe a SMLAL which multiplies two 16-bit values.
10431 if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10432 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
10433 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
10434 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
10435 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
10436 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
10438 // Check for the triangle shape.
10439 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
10440 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
10442 // Make sure that the ADDE/SUBE operands are not coming from the same node.
10443 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
10444 return SDValue();
10446 // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
10447 bool IsLeftOperandMUL = false;
10448 SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
10449 if (MULOp == SDValue())
10450 MULOp = findMUL_LOHI(AddeSubeOp1);
10451 else
10452 IsLeftOperandMUL = true;
10453 if (MULOp == SDValue())
10454 return SDValue();
10456 // Figure out the right opcode.
10457 unsigned Opc = MULOp->getOpcode();
10458 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
10460 // Figure out the high and low input values to the MLAL node.
10461 SDValue *HiAddSub = nullptr;
10462 SDValue *LoMul = nullptr;
10463 SDValue *LowAddSub = nullptr;
10465 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
10466 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
10467 return SDValue();
10469 if (IsLeftOperandMUL)
10470 HiAddSub = &AddeSubeOp1;
10471 else
10472 HiAddSub = &AddeSubeOp0;
10474 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
10475 // whose low result is fed to the ADDC/SUBC we are checking.
10477 if (AddcSubcOp0 == MULOp.getValue(0)) {
10478 LoMul = &AddcSubcOp0;
10479 LowAddSub = &AddcSubcOp1;
10481 if (AddcSubcOp1 == MULOp.getValue(0)) {
10482 LoMul = &AddcSubcOp1;
10483 LowAddSub = &AddcSubcOp0;
10486 if (!LoMul)
10487 return SDValue();
10489 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
10490 // the replacement below will create a cycle.
10491 if (AddcSubcNode == HiAddSub->getNode() ||
10492 AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
10493 return SDValue();
10495 // Create the merged node.
10496 SelectionDAG &DAG = DCI.DAG;
10498 // Start building operand list.
10499 SmallVector<SDValue, 8> Ops;
10500 Ops.push_back(LoMul->getOperand(0));
10501 Ops.push_back(LoMul->getOperand(1));
10503 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be
10504 // the case, we must be doing signed multiplication and only use the higher
10505 // part of the result of the MLAL, furthermore the LowAddSub must be a constant
10506 // addition or subtraction with the value of 0x800000.
10507 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
10508 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
10509 LowAddSub->getNode()->getOpcode() == ISD::Constant &&
10510 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
10511 0x80000000) {
10512 Ops.push_back(*HiAddSub);
10513 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
10514 FinalOpc = ARMISD::SMMLSR;
10515 } else {
10516 FinalOpc = ARMISD::SMMLAR;
10518 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
10519 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
10521 return SDValue(AddeSubeNode, 0);
10522 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
10523 // SMMLS is generated during instruction selection and the rest of this
10524 // function can not handle the case where AddcSubcNode is a SUBC.
10525 return SDValue();
10527 // Finish building the operand list for {U/S}MLAL
10528 Ops.push_back(*LowAddSub);
10529 Ops.push_back(*HiAddSub);
10531 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
10532 DAG.getVTList(MVT::i32, MVT::i32), Ops);
10534 // Replace the ADDs' nodes uses by the MLA node's values.
10535 SDValue HiMLALResult(MLALNode.getNode(), 1);
10536 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
10538 SDValue LoMLALResult(MLALNode.getNode(), 0);
10539 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
10541 // Return original node to notify the driver to stop replacing.
10542 return SDValue(AddeSubeNode, 0);
10545 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
10546 TargetLowering::DAGCombinerInfo &DCI,
10547 const ARMSubtarget *Subtarget) {
10548 // UMAAL is similar to UMLAL except that it adds two unsigned values.
10549 // While trying to combine for the other MLAL nodes, first search for the
10550 // chance to use UMAAL. Check if Addc uses a node which has already
10551 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
10552 // as the addend, and it's handled in PerformUMLALCombine.
10554 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10555 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10557 // Check that we have a glued ADDC node.
10558 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
10559 if (AddcNode->getOpcode() != ARMISD::ADDC)
10560 return SDValue();
10562 // Find the converted UMAAL or quit if it doesn't exist.
10563 SDNode *UmlalNode = nullptr;
10564 SDValue AddHi;
10565 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
10566 UmlalNode = AddcNode->getOperand(0).getNode();
10567 AddHi = AddcNode->getOperand(1);
10568 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
10569 UmlalNode = AddcNode->getOperand(1).getNode();
10570 AddHi = AddcNode->getOperand(0);
10571 } else {
10572 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10575 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
10576 // the ADDC as well as Zero.
10577 if (!isNullConstant(UmlalNode->getOperand(3)))
10578 return SDValue();
10580 if ((isNullConstant(AddeNode->getOperand(0)) &&
10581 AddeNode->getOperand(1).getNode() == UmlalNode) ||
10582 (AddeNode->getOperand(0).getNode() == UmlalNode &&
10583 isNullConstant(AddeNode->getOperand(1)))) {
10584 SelectionDAG &DAG = DCI.DAG;
10585 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
10586 UmlalNode->getOperand(2), AddHi };
10587 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
10588 DAG.getVTList(MVT::i32, MVT::i32), Ops);
10590 // Replace the ADDs' nodes uses by the UMAAL node's values.
10591 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
10592 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
10594 // Return original node to notify the driver to stop replacing.
10595 return SDValue(AddeNode, 0);
10597 return SDValue();
10600 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
10601 const ARMSubtarget *Subtarget) {
10602 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10603 return SDValue();
10605 // Check that we have a pair of ADDC and ADDE as operands.
10606 // Both addends of the ADDE must be zero.
10607 SDNode* AddcNode = N->getOperand(2).getNode();
10608 SDNode* AddeNode = N->getOperand(3).getNode();
10609 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
10610 (AddeNode->getOpcode() == ARMISD::ADDE) &&
10611 isNullConstant(AddeNode->getOperand(0)) &&
10612 isNullConstant(AddeNode->getOperand(1)) &&
10613 (AddeNode->getOperand(2).getNode() == AddcNode))
10614 return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
10615 DAG.getVTList(MVT::i32, MVT::i32),
10616 {N->getOperand(0), N->getOperand(1),
10617 AddcNode->getOperand(0), AddcNode->getOperand(1)});
10618 else
10619 return SDValue();
10622 static SDValue PerformAddcSubcCombine(SDNode *N,
10623 TargetLowering::DAGCombinerInfo &DCI,
10624 const ARMSubtarget *Subtarget) {
10625 SelectionDAG &DAG(DCI.DAG);
10627 if (N->getOpcode() == ARMISD::SUBC) {
10628 // (SUBC (ADDE 0, 0, C), 1) -> C
10629 SDValue LHS = N->getOperand(0);
10630 SDValue RHS = N->getOperand(1);
10631 if (LHS->getOpcode() == ARMISD::ADDE &&
10632 isNullConstant(LHS->getOperand(0)) &&
10633 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
10634 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
10638 if (Subtarget->isThumb1Only()) {
10639 SDValue RHS = N->getOperand(1);
10640 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10641 int32_t imm = C->getSExtValue();
10642 if (imm < 0 && imm > std::numeric_limits<int>::min()) {
10643 SDLoc DL(N);
10644 RHS = DAG.getConstant(-imm, DL, MVT::i32);
10645 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
10646 : ARMISD::ADDC;
10647 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
10652 return SDValue();
10655 static SDValue PerformAddeSubeCombine(SDNode *N,
10656 TargetLowering::DAGCombinerInfo &DCI,
10657 const ARMSubtarget *Subtarget) {
10658 if (Subtarget->isThumb1Only()) {
10659 SelectionDAG &DAG = DCI.DAG;
10660 SDValue RHS = N->getOperand(1);
10661 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10662 int64_t imm = C->getSExtValue();
10663 if (imm < 0) {
10664 SDLoc DL(N);
10666 // The with-carry-in form matches bitwise not instead of the negation.
10667 // Effectively, the inverse interpretation of the carry flag already
10668 // accounts for part of the negation.
10669 RHS = DAG.getConstant(~imm, DL, MVT::i32);
10671 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
10672 : ARMISD::ADDE;
10673 return DAG.getNode(Opcode, DL, N->getVTList(),
10674 N->getOperand(0), RHS, N->getOperand(2));
10677 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
10678 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
10680 return SDValue();
10683 static SDValue PerformABSCombine(SDNode *N,
10684 TargetLowering::DAGCombinerInfo &DCI,
10685 const ARMSubtarget *Subtarget) {
10686 SDValue res;
10687 SelectionDAG &DAG = DCI.DAG;
10688 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10690 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
10691 return SDValue();
10693 if (!TLI.expandABS(N, res, DAG))
10694 return SDValue();
10696 return res;
10699 /// PerformADDECombine - Target-specific dag combine transform from
10700 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
10701 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
10702 static SDValue PerformADDECombine(SDNode *N,
10703 TargetLowering::DAGCombinerInfo &DCI,
10704 const ARMSubtarget *Subtarget) {
10705 // Only ARM and Thumb2 support UMLAL/SMLAL.
10706 if (Subtarget->isThumb1Only())
10707 return PerformAddeSubeCombine(N, DCI, Subtarget);
10709 // Only perform the checks after legalize when the pattern is available.
10710 if (DCI.isBeforeLegalize()) return SDValue();
10712 return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
10715 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
10716 /// operands N0 and N1. This is a helper for PerformADDCombine that is
10717 /// called with the default operands, and if that fails, with commuted
10718 /// operands.
10719 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
10720 TargetLowering::DAGCombinerInfo &DCI,
10721 const ARMSubtarget *Subtarget){
10722 // Attempt to create vpadd for this add.
10723 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
10724 return Result;
10726 // Attempt to create vpaddl for this add.
10727 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
10728 return Result;
10729 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
10730 Subtarget))
10731 return Result;
10733 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10734 if (N0.getNode()->hasOneUse())
10735 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
10736 return Result;
10737 return SDValue();
10740 bool
10741 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
10742 CombineLevel Level) const {
10743 if (Level == BeforeLegalizeTypes)
10744 return true;
10746 if (N->getOpcode() != ISD::SHL)
10747 return true;
10749 if (Subtarget->isThumb1Only()) {
10750 // Avoid making expensive immediates by commuting shifts. (This logic
10751 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
10752 // for free.)
10753 if (N->getOpcode() != ISD::SHL)
10754 return true;
10755 SDValue N1 = N->getOperand(0);
10756 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
10757 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
10758 return true;
10759 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
10760 if (Const->getAPIntValue().ult(256))
10761 return false;
10762 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
10763 Const->getAPIntValue().sgt(-256))
10764 return false;
10766 return true;
10769 // Turn off commute-with-shift transform after legalization, so it doesn't
10770 // conflict with PerformSHLSimplify. (We could try to detect when
10771 // PerformSHLSimplify would trigger more precisely, but it isn't
10772 // really necessary.)
10773 return false;
10776 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
10777 const SDNode *N, CombineLevel Level) const {
10778 if (!Subtarget->isThumb1Only())
10779 return true;
10781 if (Level == BeforeLegalizeTypes)
10782 return true;
10784 return false;
10787 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
10788 if (!Subtarget->hasNEON()) {
10789 if (Subtarget->isThumb1Only())
10790 return VT.getScalarSizeInBits() <= 32;
10791 return true;
10793 return VT.isScalarInteger();
10796 static SDValue PerformSHLSimplify(SDNode *N,
10797 TargetLowering::DAGCombinerInfo &DCI,
10798 const ARMSubtarget *ST) {
10799 // Allow the generic combiner to identify potential bswaps.
10800 if (DCI.isBeforeLegalize())
10801 return SDValue();
10803 // DAG combiner will fold:
10804 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
10805 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
10806 // Other code patterns that can be also be modified have the following form:
10807 // b + ((a << 1) | 510)
10808 // b + ((a << 1) & 510)
10809 // b + ((a << 1) ^ 510)
10810 // b + ((a << 1) + 510)
10812 // Many instructions can perform the shift for free, but it requires both
10813 // the operands to be registers. If c1 << c2 is too large, a mov immediate
10814 // instruction will needed. So, unfold back to the original pattern if:
10815 // - if c1 and c2 are small enough that they don't require mov imms.
10816 // - the user(s) of the node can perform an shl
10818 // No shifted operands for 16-bit instructions.
10819 if (ST->isThumb() && ST->isThumb1Only())
10820 return SDValue();
10822 // Check that all the users could perform the shl themselves.
10823 for (auto U : N->uses()) {
10824 switch(U->getOpcode()) {
10825 default:
10826 return SDValue();
10827 case ISD::SUB:
10828 case ISD::ADD:
10829 case ISD::AND:
10830 case ISD::OR:
10831 case ISD::XOR:
10832 case ISD::SETCC:
10833 case ARMISD::CMP:
10834 // Check that the user isn't already using a constant because there
10835 // aren't any instructions that support an immediate operand and a
10836 // shifted operand.
10837 if (isa<ConstantSDNode>(U->getOperand(0)) ||
10838 isa<ConstantSDNode>(U->getOperand(1)))
10839 return SDValue();
10841 // Check that it's not already using a shift.
10842 if (U->getOperand(0).getOpcode() == ISD::SHL ||
10843 U->getOperand(1).getOpcode() == ISD::SHL)
10844 return SDValue();
10845 break;
10849 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
10850 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
10851 return SDValue();
10853 if (N->getOperand(0).getOpcode() != ISD::SHL)
10854 return SDValue();
10856 SDValue SHL = N->getOperand(0);
10858 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
10859 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
10860 if (!C1ShlC2 || !C2)
10861 return SDValue();
10863 APInt C2Int = C2->getAPIntValue();
10864 APInt C1Int = C1ShlC2->getAPIntValue();
10866 // Check that performing a lshr will not lose any information.
10867 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
10868 C2Int.getBitWidth() - C2->getZExtValue());
10869 if ((C1Int & Mask) != C1Int)
10870 return SDValue();
10872 // Shift the first constant.
10873 C1Int.lshrInPlace(C2Int);
10875 // The immediates are encoded as an 8-bit value that can be rotated.
10876 auto LargeImm = [](const APInt &Imm) {
10877 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
10878 return Imm.getBitWidth() - Zeros > 8;
10881 if (LargeImm(C1Int) || LargeImm(C2Int))
10882 return SDValue();
10884 SelectionDAG &DAG = DCI.DAG;
10885 SDLoc dl(N);
10886 SDValue X = SHL.getOperand(0);
10887 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
10888 DAG.getConstant(C1Int, dl, MVT::i32));
10889 // Shift left to compensate for the lshr of C1Int.
10890 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
10892 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
10893 SHL.dump(); N->dump());
10894 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
10895 return Res;
10899 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
10901 static SDValue PerformADDCombine(SDNode *N,
10902 TargetLowering::DAGCombinerInfo &DCI,
10903 const ARMSubtarget *Subtarget) {
10904 SDValue N0 = N->getOperand(0);
10905 SDValue N1 = N->getOperand(1);
10907 // Only works one way, because it needs an immediate operand.
10908 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10909 return Result;
10911 // First try with the default operand order.
10912 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
10913 return Result;
10915 // If that didn't work, try again with the operands commuted.
10916 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
10919 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
10921 static SDValue PerformSUBCombine(SDNode *N,
10922 TargetLowering::DAGCombinerInfo &DCI) {
10923 SDValue N0 = N->getOperand(0);
10924 SDValue N1 = N->getOperand(1);
10926 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10927 if (N1.getNode()->hasOneUse())
10928 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
10929 return Result;
10931 return SDValue();
10934 /// PerformVMULCombine
10935 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
10936 /// special multiplier accumulator forwarding.
10937 /// vmul d3, d0, d2
10938 /// vmla d3, d1, d2
10939 /// is faster than
10940 /// vadd d3, d0, d1
10941 /// vmul d3, d3, d2
10942 // However, for (A + B) * (A + B),
10943 // vadd d2, d0, d1
10944 // vmul d3, d0, d2
10945 // vmla d3, d1, d2
10946 // is slower than
10947 // vadd d2, d0, d1
10948 // vmul d3, d2, d2
10949 static SDValue PerformVMULCombine(SDNode *N,
10950 TargetLowering::DAGCombinerInfo &DCI,
10951 const ARMSubtarget *Subtarget) {
10952 if (!Subtarget->hasVMLxForwarding())
10953 return SDValue();
10955 SelectionDAG &DAG = DCI.DAG;
10956 SDValue N0 = N->getOperand(0);
10957 SDValue N1 = N->getOperand(1);
10958 unsigned Opcode = N0.getOpcode();
10959 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10960 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
10961 Opcode = N1.getOpcode();
10962 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10963 Opcode != ISD::FADD && Opcode != ISD::FSUB)
10964 return SDValue();
10965 std::swap(N0, N1);
10968 if (N0 == N1)
10969 return SDValue();
10971 EVT VT = N->getValueType(0);
10972 SDLoc DL(N);
10973 SDValue N00 = N0->getOperand(0);
10974 SDValue N01 = N0->getOperand(1);
10975 return DAG.getNode(Opcode, DL, VT,
10976 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
10977 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
10980 static SDValue PerformMULCombine(SDNode *N,
10981 TargetLowering::DAGCombinerInfo &DCI,
10982 const ARMSubtarget *Subtarget) {
10983 SelectionDAG &DAG = DCI.DAG;
10985 if (Subtarget->isThumb1Only())
10986 return SDValue();
10988 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10989 return SDValue();
10991 EVT VT = N->getValueType(0);
10992 if (VT.is64BitVector() || VT.is128BitVector())
10993 return PerformVMULCombine(N, DCI, Subtarget);
10994 if (VT != MVT::i32)
10995 return SDValue();
10997 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10998 if (!C)
10999 return SDValue();
11001 int64_t MulAmt = C->getSExtValue();
11002 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
11004 ShiftAmt = ShiftAmt & (32 - 1);
11005 SDValue V = N->getOperand(0);
11006 SDLoc DL(N);
11008 SDValue Res;
11009 MulAmt >>= ShiftAmt;
11011 if (MulAmt >= 0) {
11012 if (isPowerOf2_32(MulAmt - 1)) {
11013 // (mul x, 2^N + 1) => (add (shl x, N), x)
11014 Res = DAG.getNode(ISD::ADD, DL, VT,
11016 DAG.getNode(ISD::SHL, DL, VT,
11018 DAG.getConstant(Log2_32(MulAmt - 1), DL,
11019 MVT::i32)));
11020 } else if (isPowerOf2_32(MulAmt + 1)) {
11021 // (mul x, 2^N - 1) => (sub (shl x, N), x)
11022 Res = DAG.getNode(ISD::SUB, DL, VT,
11023 DAG.getNode(ISD::SHL, DL, VT,
11025 DAG.getConstant(Log2_32(MulAmt + 1), DL,
11026 MVT::i32)),
11028 } else
11029 return SDValue();
11030 } else {
11031 uint64_t MulAmtAbs = -MulAmt;
11032 if (isPowerOf2_32(MulAmtAbs + 1)) {
11033 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
11034 Res = DAG.getNode(ISD::SUB, DL, VT,
11036 DAG.getNode(ISD::SHL, DL, VT,
11038 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
11039 MVT::i32)));
11040 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
11041 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
11042 Res = DAG.getNode(ISD::ADD, DL, VT,
11044 DAG.getNode(ISD::SHL, DL, VT,
11046 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
11047 MVT::i32)));
11048 Res = DAG.getNode(ISD::SUB, DL, VT,
11049 DAG.getConstant(0, DL, MVT::i32), Res);
11050 } else
11051 return SDValue();
11054 if (ShiftAmt != 0)
11055 Res = DAG.getNode(ISD::SHL, DL, VT,
11056 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
11058 // Do not add new nodes to DAG combiner worklist.
11059 DCI.CombineTo(N, Res, false);
11060 return SDValue();
11063 static SDValue CombineANDShift(SDNode *N,
11064 TargetLowering::DAGCombinerInfo &DCI,
11065 const ARMSubtarget *Subtarget) {
11066 // Allow DAGCombine to pattern-match before we touch the canonical form.
11067 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11068 return SDValue();
11070 if (N->getValueType(0) != MVT::i32)
11071 return SDValue();
11073 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11074 if (!N1C)
11075 return SDValue();
11077 uint32_t C1 = (uint32_t)N1C->getZExtValue();
11078 // Don't transform uxtb/uxth.
11079 if (C1 == 255 || C1 == 65535)
11080 return SDValue();
11082 SDNode *N0 = N->getOperand(0).getNode();
11083 if (!N0->hasOneUse())
11084 return SDValue();
11086 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
11087 return SDValue();
11089 bool LeftShift = N0->getOpcode() == ISD::SHL;
11091 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11092 if (!N01C)
11093 return SDValue();
11095 uint32_t C2 = (uint32_t)N01C->getZExtValue();
11096 if (!C2 || C2 >= 32)
11097 return SDValue();
11099 // Clear irrelevant bits in the mask.
11100 if (LeftShift)
11101 C1 &= (-1U << C2);
11102 else
11103 C1 &= (-1U >> C2);
11105 SelectionDAG &DAG = DCI.DAG;
11106 SDLoc DL(N);
11108 // We have a pattern of the form "(and (shl x, c2) c1)" or
11109 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
11110 // transform to a pair of shifts, to save materializing c1.
11112 // First pattern: right shift, then mask off leading bits.
11113 // FIXME: Use demanded bits?
11114 if (!LeftShift && isMask_32(C1)) {
11115 uint32_t C3 = countLeadingZeros(C1);
11116 if (C2 < C3) {
11117 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11118 DAG.getConstant(C3 - C2, DL, MVT::i32));
11119 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11120 DAG.getConstant(C3, DL, MVT::i32));
11124 // First pattern, reversed: left shift, then mask off trailing bits.
11125 if (LeftShift && isMask_32(~C1)) {
11126 uint32_t C3 = countTrailingZeros(C1);
11127 if (C2 < C3) {
11128 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11129 DAG.getConstant(C3 - C2, DL, MVT::i32));
11130 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11131 DAG.getConstant(C3, DL, MVT::i32));
11135 // Second pattern: left shift, then mask off leading bits.
11136 // FIXME: Use demanded bits?
11137 if (LeftShift && isShiftedMask_32(C1)) {
11138 uint32_t Trailing = countTrailingZeros(C1);
11139 uint32_t C3 = countLeadingZeros(C1);
11140 if (Trailing == C2 && C2 + C3 < 32) {
11141 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11142 DAG.getConstant(C2 + C3, DL, MVT::i32));
11143 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11144 DAG.getConstant(C3, DL, MVT::i32));
11148 // Second pattern, reversed: right shift, then mask off trailing bits.
11149 // FIXME: Handle other patterns of known/demanded bits.
11150 if (!LeftShift && isShiftedMask_32(C1)) {
11151 uint32_t Leading = countLeadingZeros(C1);
11152 uint32_t C3 = countTrailingZeros(C1);
11153 if (Leading == C2 && C2 + C3 < 32) {
11154 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11155 DAG.getConstant(C2 + C3, DL, MVT::i32));
11156 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11157 DAG.getConstant(C3, DL, MVT::i32));
11161 // FIXME: Transform "(and (shl x, c2) c1)" ->
11162 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
11163 // c1.
11164 return SDValue();
11167 static SDValue PerformANDCombine(SDNode *N,
11168 TargetLowering::DAGCombinerInfo &DCI,
11169 const ARMSubtarget *Subtarget) {
11170 // Attempt to use immediate-form VBIC
11171 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
11172 SDLoc dl(N);
11173 EVT VT = N->getValueType(0);
11174 SelectionDAG &DAG = DCI.DAG;
11176 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11177 return SDValue();
11179 APInt SplatBits, SplatUndef;
11180 unsigned SplatBitSize;
11181 bool HasAnyUndefs;
11182 if (BVN &&
11183 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
11184 if (SplatBitSize <= 64) {
11185 EVT VbicVT;
11186 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
11187 SplatUndef.getZExtValue(), SplatBitSize,
11188 DAG, dl, VbicVT, VT.is128BitVector(),
11189 OtherModImm);
11190 if (Val.getNode()) {
11191 SDValue Input =
11192 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
11193 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
11194 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
11199 if (!Subtarget->isThumb1Only()) {
11200 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
11201 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
11202 return Result;
11204 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11205 return Result;
11208 if (Subtarget->isThumb1Only())
11209 if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
11210 return Result;
11212 return SDValue();
11215 // Try combining OR nodes to SMULWB, SMULWT.
11216 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
11217 TargetLowering::DAGCombinerInfo &DCI,
11218 const ARMSubtarget *Subtarget) {
11219 if (!Subtarget->hasV6Ops() ||
11220 (Subtarget->isThumb() &&
11221 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
11222 return SDValue();
11224 SDValue SRL = OR->getOperand(0);
11225 SDValue SHL = OR->getOperand(1);
11227 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
11228 SRL = OR->getOperand(1);
11229 SHL = OR->getOperand(0);
11231 if (!isSRL16(SRL) || !isSHL16(SHL))
11232 return SDValue();
11234 // The first operands to the shifts need to be the two results from the
11235 // same smul_lohi node.
11236 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
11237 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
11238 return SDValue();
11240 SDNode *SMULLOHI = SRL.getOperand(0).getNode();
11241 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
11242 SHL.getOperand(0) != SDValue(SMULLOHI, 1))
11243 return SDValue();
11245 // Now we have:
11246 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
11247 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
11248 // For SMUWB the 16-bit value will signed extended somehow.
11249 // For SMULWT only the SRA is required.
11250 // Check both sides of SMUL_LOHI
11251 SDValue OpS16 = SMULLOHI->getOperand(0);
11252 SDValue OpS32 = SMULLOHI->getOperand(1);
11254 SelectionDAG &DAG = DCI.DAG;
11255 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
11256 OpS16 = OpS32;
11257 OpS32 = SMULLOHI->getOperand(0);
11260 SDLoc dl(OR);
11261 unsigned Opcode = 0;
11262 if (isS16(OpS16, DAG))
11263 Opcode = ARMISD::SMULWB;
11264 else if (isSRA16(OpS16)) {
11265 Opcode = ARMISD::SMULWT;
11266 OpS16 = OpS16->getOperand(0);
11268 else
11269 return SDValue();
11271 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
11272 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
11273 return SDValue(OR, 0);
11276 static SDValue PerformORCombineToBFI(SDNode *N,
11277 TargetLowering::DAGCombinerInfo &DCI,
11278 const ARMSubtarget *Subtarget) {
11279 // BFI is only available on V6T2+
11280 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
11281 return SDValue();
11283 EVT VT = N->getValueType(0);
11284 SDValue N0 = N->getOperand(0);
11285 SDValue N1 = N->getOperand(1);
11286 SelectionDAG &DAG = DCI.DAG;
11287 SDLoc DL(N);
11288 // 1) or (and A, mask), val => ARMbfi A, val, mask
11289 // iff (val & mask) == val
11291 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
11292 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
11293 // && mask == ~mask2
11294 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
11295 // && ~mask == mask2
11296 // (i.e., copy a bitfield value into another bitfield of the same width)
11298 if (VT != MVT::i32)
11299 return SDValue();
11301 SDValue N00 = N0.getOperand(0);
11303 // The value and the mask need to be constants so we can verify this is
11304 // actually a bitfield set. If the mask is 0xffff, we can do better
11305 // via a movt instruction, so don't use BFI in that case.
11306 SDValue MaskOp = N0.getOperand(1);
11307 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
11308 if (!MaskC)
11309 return SDValue();
11310 unsigned Mask = MaskC->getZExtValue();
11311 if (Mask == 0xffff)
11312 return SDValue();
11313 SDValue Res;
11314 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
11315 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11316 if (N1C) {
11317 unsigned Val = N1C->getZExtValue();
11318 if ((Val & ~Mask) != Val)
11319 return SDValue();
11321 if (ARM::isBitFieldInvertedMask(Mask)) {
11322 Val >>= countTrailingZeros(~Mask);
11324 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
11325 DAG.getConstant(Val, DL, MVT::i32),
11326 DAG.getConstant(Mask, DL, MVT::i32));
11328 DCI.CombineTo(N, Res, false);
11329 // Return value from the original node to inform the combiner than N is
11330 // now dead.
11331 return SDValue(N, 0);
11333 } else if (N1.getOpcode() == ISD::AND) {
11334 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
11335 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
11336 if (!N11C)
11337 return SDValue();
11338 unsigned Mask2 = N11C->getZExtValue();
11340 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
11341 // as is to match.
11342 if (ARM::isBitFieldInvertedMask(Mask) &&
11343 (Mask == ~Mask2)) {
11344 // The pack halfword instruction works better for masks that fit it,
11345 // so use that when it's available.
11346 if (Subtarget->hasDSP() &&
11347 (Mask == 0xffff || Mask == 0xffff0000))
11348 return SDValue();
11349 // 2a
11350 unsigned amt = countTrailingZeros(Mask2);
11351 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
11352 DAG.getConstant(amt, DL, MVT::i32));
11353 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
11354 DAG.getConstant(Mask, DL, MVT::i32));
11355 DCI.CombineTo(N, Res, false);
11356 // Return value from the original node to inform the combiner than N is
11357 // now dead.
11358 return SDValue(N, 0);
11359 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
11360 (~Mask == Mask2)) {
11361 // The pack halfword instruction works better for masks that fit it,
11362 // so use that when it's available.
11363 if (Subtarget->hasDSP() &&
11364 (Mask2 == 0xffff || Mask2 == 0xffff0000))
11365 return SDValue();
11366 // 2b
11367 unsigned lsb = countTrailingZeros(Mask);
11368 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
11369 DAG.getConstant(lsb, DL, MVT::i32));
11370 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
11371 DAG.getConstant(Mask2, DL, MVT::i32));
11372 DCI.CombineTo(N, Res, false);
11373 // Return value from the original node to inform the combiner than N is
11374 // now dead.
11375 return SDValue(N, 0);
11379 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
11380 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
11381 ARM::isBitFieldInvertedMask(~Mask)) {
11382 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
11383 // where lsb(mask) == #shamt and masked bits of B are known zero.
11384 SDValue ShAmt = N00.getOperand(1);
11385 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
11386 unsigned LSB = countTrailingZeros(Mask);
11387 if (ShAmtC != LSB)
11388 return SDValue();
11390 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
11391 DAG.getConstant(~Mask, DL, MVT::i32));
11393 DCI.CombineTo(N, Res, false);
11394 // Return value from the original node to inform the combiner than N is
11395 // now dead.
11396 return SDValue(N, 0);
11399 return SDValue();
11402 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
11403 static SDValue PerformORCombine(SDNode *N,
11404 TargetLowering::DAGCombinerInfo &DCI,
11405 const ARMSubtarget *Subtarget) {
11406 // Attempt to use immediate-form VORR
11407 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
11408 SDLoc dl(N);
11409 EVT VT = N->getValueType(0);
11410 SelectionDAG &DAG = DCI.DAG;
11412 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11413 return SDValue();
11415 APInt SplatBits, SplatUndef;
11416 unsigned SplatBitSize;
11417 bool HasAnyUndefs;
11418 if (BVN && Subtarget->hasNEON() &&
11419 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
11420 if (SplatBitSize <= 64) {
11421 EVT VorrVT;
11422 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
11423 SplatUndef.getZExtValue(), SplatBitSize,
11424 DAG, dl, VorrVT, VT.is128BitVector(),
11425 OtherModImm);
11426 if (Val.getNode()) {
11427 SDValue Input =
11428 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
11429 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
11430 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
11435 if (!Subtarget->isThumb1Only()) {
11436 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
11437 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
11438 return Result;
11439 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
11440 return Result;
11443 SDValue N0 = N->getOperand(0);
11444 SDValue N1 = N->getOperand(1);
11446 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
11447 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
11448 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11450 // The code below optimizes (or (and X, Y), Z).
11451 // The AND operand needs to have a single user to make these optimizations
11452 // profitable.
11453 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
11454 return SDValue();
11456 APInt SplatUndef;
11457 unsigned SplatBitSize;
11458 bool HasAnyUndefs;
11460 APInt SplatBits0, SplatBits1;
11461 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
11462 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
11463 // Ensure that the second operand of both ands are constants
11464 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
11465 HasAnyUndefs) && !HasAnyUndefs) {
11466 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
11467 HasAnyUndefs) && !HasAnyUndefs) {
11468 // Ensure that the bit width of the constants are the same and that
11469 // the splat arguments are logical inverses as per the pattern we
11470 // are trying to simplify.
11471 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
11472 SplatBits0 == ~SplatBits1) {
11473 // Canonicalize the vector type to make instruction selection
11474 // simpler.
11475 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
11476 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
11477 N0->getOperand(1),
11478 N0->getOperand(0),
11479 N1->getOperand(0));
11480 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11486 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
11487 // reasonable.
11488 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
11489 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
11490 return Res;
11493 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11494 return Result;
11496 return SDValue();
11499 static SDValue PerformXORCombine(SDNode *N,
11500 TargetLowering::DAGCombinerInfo &DCI,
11501 const ARMSubtarget *Subtarget) {
11502 EVT VT = N->getValueType(0);
11503 SelectionDAG &DAG = DCI.DAG;
11505 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11506 return SDValue();
11508 if (!Subtarget->isThumb1Only()) {
11509 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
11510 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
11511 return Result;
11513 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11514 return Result;
11517 return SDValue();
11520 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
11521 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
11522 // their position in "to" (Rd).
11523 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
11524 assert(N->getOpcode() == ARMISD::BFI);
11526 SDValue From = N->getOperand(1);
11527 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
11528 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
11530 // If the Base came from a SHR #C, we can deduce that it is really testing bit
11531 // #C in the base of the SHR.
11532 if (From->getOpcode() == ISD::SRL &&
11533 isa<ConstantSDNode>(From->getOperand(1))) {
11534 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
11535 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
11536 FromMask <<= Shift.getLimitedValue(31);
11537 From = From->getOperand(0);
11540 return From;
11543 // If A and B contain one contiguous set of bits, does A | B == A . B?
11545 // Neither A nor B must be zero.
11546 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
11547 unsigned LastActiveBitInA = A.countTrailingZeros();
11548 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
11549 return LastActiveBitInA - 1 == FirstActiveBitInB;
11552 static SDValue FindBFIToCombineWith(SDNode *N) {
11553 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
11554 // if one exists.
11555 APInt ToMask, FromMask;
11556 SDValue From = ParseBFI(N, ToMask, FromMask);
11557 SDValue To = N->getOperand(0);
11559 // Now check for a compatible BFI to merge with. We can pass through BFIs that
11560 // aren't compatible, but not if they set the same bit in their destination as
11561 // we do (or that of any BFI we're going to combine with).
11562 SDValue V = To;
11563 APInt CombinedToMask = ToMask;
11564 while (V.getOpcode() == ARMISD::BFI) {
11565 APInt NewToMask, NewFromMask;
11566 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
11567 if (NewFrom != From) {
11568 // This BFI has a different base. Keep going.
11569 CombinedToMask |= NewToMask;
11570 V = V.getOperand(0);
11571 continue;
11574 // Do the written bits conflict with any we've seen so far?
11575 if ((NewToMask & CombinedToMask).getBoolValue())
11576 // Conflicting bits - bail out because going further is unsafe.
11577 return SDValue();
11579 // Are the new bits contiguous when combined with the old bits?
11580 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
11581 BitsProperlyConcatenate(FromMask, NewFromMask))
11582 return V;
11583 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
11584 BitsProperlyConcatenate(NewFromMask, FromMask))
11585 return V;
11587 // We've seen a write to some bits, so track it.
11588 CombinedToMask |= NewToMask;
11589 // Keep going...
11590 V = V.getOperand(0);
11593 return SDValue();
11596 static SDValue PerformBFICombine(SDNode *N,
11597 TargetLowering::DAGCombinerInfo &DCI) {
11598 SDValue N1 = N->getOperand(1);
11599 if (N1.getOpcode() == ISD::AND) {
11600 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
11601 // the bits being cleared by the AND are not demanded by the BFI.
11602 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
11603 if (!N11C)
11604 return SDValue();
11605 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11606 unsigned LSB = countTrailingZeros(~InvMask);
11607 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
11608 assert(Width <
11609 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
11610 "undefined behavior");
11611 unsigned Mask = (1u << Width) - 1;
11612 unsigned Mask2 = N11C->getZExtValue();
11613 if ((Mask & (~Mask2)) == 0)
11614 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
11615 N->getOperand(0), N1.getOperand(0),
11616 N->getOperand(2));
11617 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
11618 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
11619 // Keep track of any consecutive bits set that all come from the same base
11620 // value. We can combine these together into a single BFI.
11621 SDValue CombineBFI = FindBFIToCombineWith(N);
11622 if (CombineBFI == SDValue())
11623 return SDValue();
11625 // We've found a BFI.
11626 APInt ToMask1, FromMask1;
11627 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
11629 APInt ToMask2, FromMask2;
11630 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
11631 assert(From1 == From2);
11632 (void)From2;
11634 // First, unlink CombineBFI.
11635 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
11636 // Then create a new BFI, combining the two together.
11637 APInt NewFromMask = FromMask1 | FromMask2;
11638 APInt NewToMask = ToMask1 | ToMask2;
11640 EVT VT = N->getValueType(0);
11641 SDLoc dl(N);
11643 if (NewFromMask[0] == 0)
11644 From1 = DCI.DAG.getNode(
11645 ISD::SRL, dl, VT, From1,
11646 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
11647 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
11648 DCI.DAG.getConstant(~NewToMask, dl, VT));
11650 return SDValue();
11653 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
11654 /// ARMISD::VMOVRRD.
11655 static SDValue PerformVMOVRRDCombine(SDNode *N,
11656 TargetLowering::DAGCombinerInfo &DCI,
11657 const ARMSubtarget *Subtarget) {
11658 // vmovrrd(vmovdrr x, y) -> x,y
11659 SDValue InDouble = N->getOperand(0);
11660 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
11661 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
11663 // vmovrrd(load f64) -> (load i32), (load i32)
11664 SDNode *InNode = InDouble.getNode();
11665 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
11666 InNode->getValueType(0) == MVT::f64 &&
11667 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
11668 !cast<LoadSDNode>(InNode)->isVolatile()) {
11669 // TODO: Should this be done for non-FrameIndex operands?
11670 LoadSDNode *LD = cast<LoadSDNode>(InNode);
11672 SelectionDAG &DAG = DCI.DAG;
11673 SDLoc DL(LD);
11674 SDValue BasePtr = LD->getBasePtr();
11675 SDValue NewLD1 =
11676 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
11677 LD->getAlignment(), LD->getMemOperand()->getFlags());
11679 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11680 DAG.getConstant(4, DL, MVT::i32));
11681 SDValue NewLD2 = DAG.getLoad(
11682 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
11683 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
11685 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
11686 if (DCI.DAG.getDataLayout().isBigEndian())
11687 std::swap (NewLD1, NewLD2);
11688 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
11689 return Result;
11692 return SDValue();
11695 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
11696 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
11697 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
11698 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
11699 SDValue Op0 = N->getOperand(0);
11700 SDValue Op1 = N->getOperand(1);
11701 if (Op0.getOpcode() == ISD::BITCAST)
11702 Op0 = Op0.getOperand(0);
11703 if (Op1.getOpcode() == ISD::BITCAST)
11704 Op1 = Op1.getOperand(0);
11705 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
11706 Op0.getNode() == Op1.getNode() &&
11707 Op0.getResNo() == 0 && Op1.getResNo() == 1)
11708 return DAG.getNode(ISD::BITCAST, SDLoc(N),
11709 N->getValueType(0), Op0.getOperand(0));
11710 return SDValue();
11713 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
11714 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
11715 /// i64 vector to have f64 elements, since the value can then be loaded
11716 /// directly into a VFP register.
11717 static bool hasNormalLoadOperand(SDNode *N) {
11718 unsigned NumElts = N->getValueType(0).getVectorNumElements();
11719 for (unsigned i = 0; i < NumElts; ++i) {
11720 SDNode *Elt = N->getOperand(i).getNode();
11721 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
11722 return true;
11724 return false;
11727 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
11728 /// ISD::BUILD_VECTOR.
11729 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
11730 TargetLowering::DAGCombinerInfo &DCI,
11731 const ARMSubtarget *Subtarget) {
11732 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
11733 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
11734 // into a pair of GPRs, which is fine when the value is used as a scalar,
11735 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
11736 SelectionDAG &DAG = DCI.DAG;
11737 if (N->getNumOperands() == 2)
11738 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
11739 return RV;
11741 // Load i64 elements as f64 values so that type legalization does not split
11742 // them up into i32 values.
11743 EVT VT = N->getValueType(0);
11744 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
11745 return SDValue();
11746 SDLoc dl(N);
11747 SmallVector<SDValue, 8> Ops;
11748 unsigned NumElts = VT.getVectorNumElements();
11749 for (unsigned i = 0; i < NumElts; ++i) {
11750 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
11751 Ops.push_back(V);
11752 // Make the DAGCombiner fold the bitcast.
11753 DCI.AddToWorklist(V.getNode());
11755 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
11756 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
11757 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11760 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
11761 static SDValue
11762 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11763 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
11764 // At that time, we may have inserted bitcasts from integer to float.
11765 // If these bitcasts have survived DAGCombine, change the lowering of this
11766 // BUILD_VECTOR in something more vector friendly, i.e., that does not
11767 // force to use floating point types.
11769 // Make sure we can change the type of the vector.
11770 // This is possible iff:
11771 // 1. The vector is only used in a bitcast to a integer type. I.e.,
11772 // 1.1. Vector is used only once.
11773 // 1.2. Use is a bit convert to an integer type.
11774 // 2. The size of its operands are 32-bits (64-bits are not legal).
11775 EVT VT = N->getValueType(0);
11776 EVT EltVT = VT.getVectorElementType();
11778 // Check 1.1. and 2.
11779 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
11780 return SDValue();
11782 // By construction, the input type must be float.
11783 assert(EltVT == MVT::f32 && "Unexpected type!");
11785 // Check 1.2.
11786 SDNode *Use = *N->use_begin();
11787 if (Use->getOpcode() != ISD::BITCAST ||
11788 Use->getValueType(0).isFloatingPoint())
11789 return SDValue();
11791 // Check profitability.
11792 // Model is, if more than half of the relevant operands are bitcast from
11793 // i32, turn the build_vector into a sequence of insert_vector_elt.
11794 // Relevant operands are everything that is not statically
11795 // (i.e., at compile time) bitcasted.
11796 unsigned NumOfBitCastedElts = 0;
11797 unsigned NumElts = VT.getVectorNumElements();
11798 unsigned NumOfRelevantElts = NumElts;
11799 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
11800 SDValue Elt = N->getOperand(Idx);
11801 if (Elt->getOpcode() == ISD::BITCAST) {
11802 // Assume only bit cast to i32 will go away.
11803 if (Elt->getOperand(0).getValueType() == MVT::i32)
11804 ++NumOfBitCastedElts;
11805 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
11806 // Constants are statically casted, thus do not count them as
11807 // relevant operands.
11808 --NumOfRelevantElts;
11811 // Check if more than half of the elements require a non-free bitcast.
11812 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
11813 return SDValue();
11815 SelectionDAG &DAG = DCI.DAG;
11816 // Create the new vector type.
11817 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
11818 // Check if the type is legal.
11819 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11820 if (!TLI.isTypeLegal(VecVT))
11821 return SDValue();
11823 // Combine:
11824 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
11825 // => BITCAST INSERT_VECTOR_ELT
11826 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
11827 // (BITCAST EN), N.
11828 SDValue Vec = DAG.getUNDEF(VecVT);
11829 SDLoc dl(N);
11830 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
11831 SDValue V = N->getOperand(Idx);
11832 if (V.isUndef())
11833 continue;
11834 if (V.getOpcode() == ISD::BITCAST &&
11835 V->getOperand(0).getValueType() == MVT::i32)
11836 // Fold obvious case.
11837 V = V.getOperand(0);
11838 else {
11839 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
11840 // Make the DAGCombiner fold the bitcasts.
11841 DCI.AddToWorklist(V.getNode());
11843 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
11844 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
11846 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
11847 // Make the DAGCombiner fold the bitcasts.
11848 DCI.AddToWorklist(Vec.getNode());
11849 return Vec;
11852 /// PerformInsertEltCombine - Target-specific dag combine xforms for
11853 /// ISD::INSERT_VECTOR_ELT.
11854 static SDValue PerformInsertEltCombine(SDNode *N,
11855 TargetLowering::DAGCombinerInfo &DCI) {
11856 // Bitcast an i64 load inserted into a vector to f64.
11857 // Otherwise, the i64 value will be legalized to a pair of i32 values.
11858 EVT VT = N->getValueType(0);
11859 SDNode *Elt = N->getOperand(1).getNode();
11860 if (VT.getVectorElementType() != MVT::i64 ||
11861 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
11862 return SDValue();
11864 SelectionDAG &DAG = DCI.DAG;
11865 SDLoc dl(N);
11866 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11867 VT.getVectorNumElements());
11868 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
11869 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
11870 // Make the DAGCombiner fold the bitcasts.
11871 DCI.AddToWorklist(Vec.getNode());
11872 DCI.AddToWorklist(V.getNode());
11873 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
11874 Vec, V, N->getOperand(2));
11875 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
11878 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
11879 /// ISD::VECTOR_SHUFFLE.
11880 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
11881 // The LLVM shufflevector instruction does not require the shuffle mask
11882 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
11883 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
11884 // operands do not match the mask length, they are extended by concatenating
11885 // them with undef vectors. That is probably the right thing for other
11886 // targets, but for NEON it is better to concatenate two double-register
11887 // size vector operands into a single quad-register size vector. Do that
11888 // transformation here:
11889 // shuffle(concat(v1, undef), concat(v2, undef)) ->
11890 // shuffle(concat(v1, v2), undef)
11891 SDValue Op0 = N->getOperand(0);
11892 SDValue Op1 = N->getOperand(1);
11893 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
11894 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
11895 Op0.getNumOperands() != 2 ||
11896 Op1.getNumOperands() != 2)
11897 return SDValue();
11898 SDValue Concat0Op1 = Op0.getOperand(1);
11899 SDValue Concat1Op1 = Op1.getOperand(1);
11900 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
11901 return SDValue();
11902 // Skip the transformation if any of the types are illegal.
11903 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11904 EVT VT = N->getValueType(0);
11905 if (!TLI.isTypeLegal(VT) ||
11906 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
11907 !TLI.isTypeLegal(Concat1Op1.getValueType()))
11908 return SDValue();
11910 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11911 Op0.getOperand(0), Op1.getOperand(0));
11912 // Translate the shuffle mask.
11913 SmallVector<int, 16> NewMask;
11914 unsigned NumElts = VT.getVectorNumElements();
11915 unsigned HalfElts = NumElts/2;
11916 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11917 for (unsigned n = 0; n < NumElts; ++n) {
11918 int MaskElt = SVN->getMaskElt(n);
11919 int NewElt = -1;
11920 if (MaskElt < (int)HalfElts)
11921 NewElt = MaskElt;
11922 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
11923 NewElt = HalfElts + MaskElt - NumElts;
11924 NewMask.push_back(NewElt);
11926 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
11927 DAG.getUNDEF(VT), NewMask);
11930 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
11931 /// NEON load/store intrinsics, and generic vector load/stores, to merge
11932 /// base address updates.
11933 /// For generic load/stores, the memory type is assumed to be a vector.
11934 /// The caller is assumed to have checked legality.
11935 static SDValue CombineBaseUpdate(SDNode *N,
11936 TargetLowering::DAGCombinerInfo &DCI) {
11937 SelectionDAG &DAG = DCI.DAG;
11938 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
11939 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
11940 const bool isStore = N->getOpcode() == ISD::STORE;
11941 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
11942 SDValue Addr = N->getOperand(AddrOpIdx);
11943 MemSDNode *MemN = cast<MemSDNode>(N);
11944 SDLoc dl(N);
11946 // Search for a use of the address operand that is an increment.
11947 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
11948 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
11949 SDNode *User = *UI;
11950 if (User->getOpcode() != ISD::ADD ||
11951 UI.getUse().getResNo() != Addr.getResNo())
11952 continue;
11954 // Check that the add is independent of the load/store. Otherwise, folding
11955 // it would create a cycle. We can avoid searching through Addr as it's a
11956 // predecessor to both.
11957 SmallPtrSet<const SDNode *, 32> Visited;
11958 SmallVector<const SDNode *, 16> Worklist;
11959 Visited.insert(Addr.getNode());
11960 Worklist.push_back(N);
11961 Worklist.push_back(User);
11962 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
11963 SDNode::hasPredecessorHelper(User, Visited, Worklist))
11964 continue;
11966 // Find the new opcode for the updating load/store.
11967 bool isLoadOp = true;
11968 bool isLaneOp = false;
11969 unsigned NewOpc = 0;
11970 unsigned NumVecs = 0;
11971 if (isIntrinsic) {
11972 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11973 switch (IntNo) {
11974 default: llvm_unreachable("unexpected intrinsic for Neon base update");
11975 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
11976 NumVecs = 1; break;
11977 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
11978 NumVecs = 2; break;
11979 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
11980 NumVecs = 3; break;
11981 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
11982 NumVecs = 4; break;
11983 case Intrinsic::arm_neon_vld2dup:
11984 case Intrinsic::arm_neon_vld3dup:
11985 case Intrinsic::arm_neon_vld4dup:
11986 // TODO: Support updating VLDxDUP nodes. For now, we just skip
11987 // combining base updates for such intrinsics.
11988 continue;
11989 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
11990 NumVecs = 2; isLaneOp = true; break;
11991 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
11992 NumVecs = 3; isLaneOp = true; break;
11993 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
11994 NumVecs = 4; isLaneOp = true; break;
11995 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
11996 NumVecs = 1; isLoadOp = false; break;
11997 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
11998 NumVecs = 2; isLoadOp = false; break;
11999 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
12000 NumVecs = 3; isLoadOp = false; break;
12001 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
12002 NumVecs = 4; isLoadOp = false; break;
12003 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
12004 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
12005 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
12006 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
12007 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
12008 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
12010 } else {
12011 isLaneOp = true;
12012 switch (N->getOpcode()) {
12013 default: llvm_unreachable("unexpected opcode for Neon base update");
12014 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
12015 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
12016 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
12017 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
12018 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
12019 NumVecs = 1; isLaneOp = false; break;
12020 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
12021 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
12025 // Find the size of memory referenced by the load/store.
12026 EVT VecTy;
12027 if (isLoadOp) {
12028 VecTy = N->getValueType(0);
12029 } else if (isIntrinsic) {
12030 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
12031 } else {
12032 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
12033 VecTy = N->getOperand(1).getValueType();
12036 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
12037 if (isLaneOp)
12038 NumBytes /= VecTy.getVectorNumElements();
12040 // If the increment is a constant, it must match the memory ref size.
12041 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
12042 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
12043 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
12044 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
12045 // separate instructions that make it harder to use a non-constant update.
12046 continue;
12049 // OK, we found an ADD we can fold into the base update.
12050 // Now, create a _UPD node, taking care of not breaking alignment.
12052 EVT AlignedVecTy = VecTy;
12053 unsigned Alignment = MemN->getAlignment();
12055 // If this is a less-than-standard-aligned load/store, change the type to
12056 // match the standard alignment.
12057 // The alignment is overlooked when selecting _UPD variants; and it's
12058 // easier to introduce bitcasts here than fix that.
12059 // There are 3 ways to get to this base-update combine:
12060 // - intrinsics: they are assumed to be properly aligned (to the standard
12061 // alignment of the memory type), so we don't need to do anything.
12062 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
12063 // intrinsics, so, likewise, there's nothing to do.
12064 // - generic load/store instructions: the alignment is specified as an
12065 // explicit operand, rather than implicitly as the standard alignment
12066 // of the memory type (like the intrisics). We need to change the
12067 // memory type to match the explicit alignment. That way, we don't
12068 // generate non-standard-aligned ARMISD::VLDx nodes.
12069 if (isa<LSBaseSDNode>(N)) {
12070 if (Alignment == 0)
12071 Alignment = 1;
12072 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
12073 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
12074 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
12075 assert(!isLaneOp && "Unexpected generic load/store lane.");
12076 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
12077 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
12079 // Don't set an explicit alignment on regular load/stores that we want
12080 // to transform to VLD/VST 1_UPD nodes.
12081 // This matches the behavior of regular load/stores, which only get an
12082 // explicit alignment if the MMO alignment is larger than the standard
12083 // alignment of the memory type.
12084 // Intrinsics, however, always get an explicit alignment, set to the
12085 // alignment of the MMO.
12086 Alignment = 1;
12089 // Create the new updating load/store node.
12090 // First, create an SDVTList for the new updating node's results.
12091 EVT Tys[6];
12092 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
12093 unsigned n;
12094 for (n = 0; n < NumResultVecs; ++n)
12095 Tys[n] = AlignedVecTy;
12096 Tys[n++] = MVT::i32;
12097 Tys[n] = MVT::Other;
12098 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
12100 // Then, gather the new node's operands.
12101 SmallVector<SDValue, 8> Ops;
12102 Ops.push_back(N->getOperand(0)); // incoming chain
12103 Ops.push_back(N->getOperand(AddrOpIdx));
12104 Ops.push_back(Inc);
12106 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
12107 // Try to match the intrinsic's signature
12108 Ops.push_back(StN->getValue());
12109 } else {
12110 // Loads (and of course intrinsics) match the intrinsics' signature,
12111 // so just add all but the alignment operand.
12112 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
12113 Ops.push_back(N->getOperand(i));
12116 // For all node types, the alignment operand is always the last one.
12117 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
12119 // If this is a non-standard-aligned STORE, the penultimate operand is the
12120 // stored value. Bitcast it to the aligned type.
12121 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
12122 SDValue &StVal = Ops[Ops.size()-2];
12123 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
12126 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
12127 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
12128 MemN->getMemOperand());
12130 // Update the uses.
12131 SmallVector<SDValue, 5> NewResults;
12132 for (unsigned i = 0; i < NumResultVecs; ++i)
12133 NewResults.push_back(SDValue(UpdN.getNode(), i));
12135 // If this is an non-standard-aligned LOAD, the first result is the loaded
12136 // value. Bitcast it to the expected result type.
12137 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
12138 SDValue &LdVal = NewResults[0];
12139 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
12142 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
12143 DCI.CombineTo(N, NewResults);
12144 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
12146 break;
12148 return SDValue();
12151 static SDValue PerformVLDCombine(SDNode *N,
12152 TargetLowering::DAGCombinerInfo &DCI) {
12153 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12154 return SDValue();
12156 return CombineBaseUpdate(N, DCI);
12159 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
12160 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
12161 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
12162 /// return true.
12163 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12164 SelectionDAG &DAG = DCI.DAG;
12165 EVT VT = N->getValueType(0);
12166 // vldN-dup instructions only support 64-bit vectors for N > 1.
12167 if (!VT.is64BitVector())
12168 return false;
12170 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
12171 SDNode *VLD = N->getOperand(0).getNode();
12172 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
12173 return false;
12174 unsigned NumVecs = 0;
12175 unsigned NewOpc = 0;
12176 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
12177 if (IntNo == Intrinsic::arm_neon_vld2lane) {
12178 NumVecs = 2;
12179 NewOpc = ARMISD::VLD2DUP;
12180 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
12181 NumVecs = 3;
12182 NewOpc = ARMISD::VLD3DUP;
12183 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
12184 NumVecs = 4;
12185 NewOpc = ARMISD::VLD4DUP;
12186 } else {
12187 return false;
12190 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
12191 // numbers match the load.
12192 unsigned VLDLaneNo =
12193 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
12194 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
12195 UI != UE; ++UI) {
12196 // Ignore uses of the chain result.
12197 if (UI.getUse().getResNo() == NumVecs)
12198 continue;
12199 SDNode *User = *UI;
12200 if (User->getOpcode() != ARMISD::VDUPLANE ||
12201 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
12202 return false;
12205 // Create the vldN-dup node.
12206 EVT Tys[5];
12207 unsigned n;
12208 for (n = 0; n < NumVecs; ++n)
12209 Tys[n] = VT;
12210 Tys[n] = MVT::Other;
12211 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
12212 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
12213 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
12214 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
12215 Ops, VLDMemInt->getMemoryVT(),
12216 VLDMemInt->getMemOperand());
12218 // Update the uses.
12219 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
12220 UI != UE; ++UI) {
12221 unsigned ResNo = UI.getUse().getResNo();
12222 // Ignore uses of the chain result.
12223 if (ResNo == NumVecs)
12224 continue;
12225 SDNode *User = *UI;
12226 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
12229 // Now the vldN-lane intrinsic is dead except for its chain result.
12230 // Update uses of the chain.
12231 std::vector<SDValue> VLDDupResults;
12232 for (unsigned n = 0; n < NumVecs; ++n)
12233 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
12234 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
12235 DCI.CombineTo(VLD, VLDDupResults);
12237 return true;
12240 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
12241 /// ARMISD::VDUPLANE.
12242 static SDValue PerformVDUPLANECombine(SDNode *N,
12243 TargetLowering::DAGCombinerInfo &DCI) {
12244 SDValue Op = N->getOperand(0);
12246 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
12247 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
12248 if (CombineVLDDUP(N, DCI))
12249 return SDValue(N, 0);
12251 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
12252 // redundant. Ignore bit_converts for now; element sizes are checked below.
12253 while (Op.getOpcode() == ISD::BITCAST)
12254 Op = Op.getOperand(0);
12255 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
12256 return SDValue();
12258 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
12259 unsigned EltSize = Op.getScalarValueSizeInBits();
12260 // The canonical VMOV for a zero vector uses a 32-bit element size.
12261 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12262 unsigned EltBits;
12263 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
12264 EltSize = 8;
12265 EVT VT = N->getValueType(0);
12266 if (EltSize > VT.getScalarSizeInBits())
12267 return SDValue();
12269 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
12272 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
12273 static SDValue PerformVDUPCombine(SDNode *N,
12274 TargetLowering::DAGCombinerInfo &DCI,
12275 const ARMSubtarget *Subtarget) {
12276 SelectionDAG &DAG = DCI.DAG;
12277 SDValue Op = N->getOperand(0);
12279 if (!Subtarget->hasNEON())
12280 return SDValue();
12282 // Match VDUP(LOAD) -> VLD1DUP.
12283 // We match this pattern here rather than waiting for isel because the
12284 // transform is only legal for unindexed loads.
12285 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
12286 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
12287 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
12288 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
12289 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
12290 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
12291 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
12292 Ops, LD->getMemoryVT(),
12293 LD->getMemOperand());
12294 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
12295 return VLDDup;
12298 return SDValue();
12301 static SDValue PerformLOADCombine(SDNode *N,
12302 TargetLowering::DAGCombinerInfo &DCI) {
12303 EVT VT = N->getValueType(0);
12305 // If this is a legal vector load, try to combine it into a VLD1_UPD.
12306 if (ISD::isNormalLoad(N) && VT.isVector() &&
12307 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
12308 return CombineBaseUpdate(N, DCI);
12310 return SDValue();
12313 /// PerformSTORECombine - Target-specific dag combine xforms for
12314 /// ISD::STORE.
12315 static SDValue PerformSTORECombine(SDNode *N,
12316 TargetLowering::DAGCombinerInfo &DCI) {
12317 StoreSDNode *St = cast<StoreSDNode>(N);
12318 if (St->isVolatile())
12319 return SDValue();
12321 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
12322 // pack all of the elements in one place. Next, store to memory in fewer
12323 // chunks.
12324 SDValue StVal = St->getValue();
12325 EVT VT = StVal.getValueType();
12326 if (St->isTruncatingStore() && VT.isVector()) {
12327 SelectionDAG &DAG = DCI.DAG;
12328 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12329 EVT StVT = St->getMemoryVT();
12330 unsigned NumElems = VT.getVectorNumElements();
12331 assert(StVT != VT && "Cannot truncate to the same type");
12332 unsigned FromEltSz = VT.getScalarSizeInBits();
12333 unsigned ToEltSz = StVT.getScalarSizeInBits();
12335 // From, To sizes and ElemCount must be pow of two
12336 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
12338 // We are going to use the original vector elt for storing.
12339 // Accumulated smaller vector elements must be a multiple of the store size.
12340 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
12342 unsigned SizeRatio = FromEltSz / ToEltSz;
12343 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
12345 // Create a type on which we perform the shuffle.
12346 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
12347 NumElems*SizeRatio);
12348 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
12350 SDLoc DL(St);
12351 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
12352 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
12353 for (unsigned i = 0; i < NumElems; ++i)
12354 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
12355 ? (i + 1) * SizeRatio - 1
12356 : i * SizeRatio;
12358 // Can't shuffle using an illegal type.
12359 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
12361 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
12362 DAG.getUNDEF(WideVec.getValueType()),
12363 ShuffleVec);
12364 // At this point all of the data is stored at the bottom of the
12365 // register. We now need to save it to mem.
12367 // Find the largest store unit
12368 MVT StoreType = MVT::i8;
12369 for (MVT Tp : MVT::integer_valuetypes()) {
12370 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
12371 StoreType = Tp;
12373 // Didn't find a legal store type.
12374 if (!TLI.isTypeLegal(StoreType))
12375 return SDValue();
12377 // Bitcast the original vector into a vector of store-size units
12378 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
12379 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
12380 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
12381 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
12382 SmallVector<SDValue, 8> Chains;
12383 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
12384 TLI.getPointerTy(DAG.getDataLayout()));
12385 SDValue BasePtr = St->getBasePtr();
12387 // Perform one or more big stores into memory.
12388 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
12389 for (unsigned I = 0; I < E; I++) {
12390 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
12391 StoreType, ShuffWide,
12392 DAG.getIntPtrConstant(I, DL));
12393 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
12394 St->getPointerInfo(), St->getAlignment(),
12395 St->getMemOperand()->getFlags());
12396 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
12397 Increment);
12398 Chains.push_back(Ch);
12400 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
12403 if (!ISD::isNormalStore(St))
12404 return SDValue();
12406 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
12407 // ARM stores of arguments in the same cache line.
12408 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
12409 StVal.getNode()->hasOneUse()) {
12410 SelectionDAG &DAG = DCI.DAG;
12411 bool isBigEndian = DAG.getDataLayout().isBigEndian();
12412 SDLoc DL(St);
12413 SDValue BasePtr = St->getBasePtr();
12414 SDValue NewST1 = DAG.getStore(
12415 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
12416 BasePtr, St->getPointerInfo(), St->getAlignment(),
12417 St->getMemOperand()->getFlags());
12419 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
12420 DAG.getConstant(4, DL, MVT::i32));
12421 return DAG.getStore(NewST1.getValue(0), DL,
12422 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
12423 OffsetPtr, St->getPointerInfo(),
12424 std::min(4U, St->getAlignment() / 2),
12425 St->getMemOperand()->getFlags());
12428 if (StVal.getValueType() == MVT::i64 &&
12429 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12431 // Bitcast an i64 store extracted from a vector to f64.
12432 // Otherwise, the i64 value will be legalized to a pair of i32 values.
12433 SelectionDAG &DAG = DCI.DAG;
12434 SDLoc dl(StVal);
12435 SDValue IntVec = StVal.getOperand(0);
12436 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
12437 IntVec.getValueType().getVectorNumElements());
12438 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
12439 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12440 Vec, StVal.getOperand(1));
12441 dl = SDLoc(N);
12442 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
12443 // Make the DAGCombiner fold the bitcasts.
12444 DCI.AddToWorklist(Vec.getNode());
12445 DCI.AddToWorklist(ExtElt.getNode());
12446 DCI.AddToWorklist(V.getNode());
12447 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
12448 St->getPointerInfo(), St->getAlignment(),
12449 St->getMemOperand()->getFlags(), St->getAAInfo());
12452 // If this is a legal vector store, try to combine it into a VST1_UPD.
12453 if (ISD::isNormalStore(N) && VT.isVector() &&
12454 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
12455 return CombineBaseUpdate(N, DCI);
12457 return SDValue();
12460 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
12461 /// can replace combinations of VMUL and VCVT (floating-point to integer)
12462 /// when the VMUL has a constant operand that is a power of 2.
12464 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
12465 /// vmul.f32 d16, d17, d16
12466 /// vcvt.s32.f32 d16, d16
12467 /// becomes:
12468 /// vcvt.s32.f32 d16, d16, #3
12469 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
12470 const ARMSubtarget *Subtarget) {
12471 if (!Subtarget->hasNEON())
12472 return SDValue();
12474 SDValue Op = N->getOperand(0);
12475 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
12476 Op.getOpcode() != ISD::FMUL)
12477 return SDValue();
12479 SDValue ConstVec = Op->getOperand(1);
12480 if (!isa<BuildVectorSDNode>(ConstVec))
12481 return SDValue();
12483 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
12484 uint32_t FloatBits = FloatTy.getSizeInBits();
12485 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
12486 uint32_t IntBits = IntTy.getSizeInBits();
12487 unsigned NumLanes = Op.getValueType().getVectorNumElements();
12488 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
12489 // These instructions only exist converting from f32 to i32. We can handle
12490 // smaller integers by generating an extra truncate, but larger ones would
12491 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
12492 // these intructions only support v2i32/v4i32 types.
12493 return SDValue();
12496 BitVector UndefElements;
12497 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
12498 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
12499 if (C == -1 || C == 0 || C > 32)
12500 return SDValue();
12502 SDLoc dl(N);
12503 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
12504 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
12505 Intrinsic::arm_neon_vcvtfp2fxu;
12506 SDValue FixConv = DAG.getNode(
12507 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
12508 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
12509 DAG.getConstant(C, dl, MVT::i32));
12511 if (IntBits < FloatBits)
12512 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
12514 return FixConv;
12517 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
12518 /// can replace combinations of VCVT (integer to floating-point) and VDIV
12519 /// when the VDIV has a constant operand that is a power of 2.
12521 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
12522 /// vcvt.f32.s32 d16, d16
12523 /// vdiv.f32 d16, d17, d16
12524 /// becomes:
12525 /// vcvt.f32.s32 d16, d16, #3
12526 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
12527 const ARMSubtarget *Subtarget) {
12528 if (!Subtarget->hasNEON())
12529 return SDValue();
12531 SDValue Op = N->getOperand(0);
12532 unsigned OpOpcode = Op.getNode()->getOpcode();
12533 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
12534 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
12535 return SDValue();
12537 SDValue ConstVec = N->getOperand(1);
12538 if (!isa<BuildVectorSDNode>(ConstVec))
12539 return SDValue();
12541 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
12542 uint32_t FloatBits = FloatTy.getSizeInBits();
12543 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
12544 uint32_t IntBits = IntTy.getSizeInBits();
12545 unsigned NumLanes = Op.getValueType().getVectorNumElements();
12546 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
12547 // These instructions only exist converting from i32 to f32. We can handle
12548 // smaller integers by generating an extra extend, but larger ones would
12549 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
12550 // these intructions only support v2i32/v4i32 types.
12551 return SDValue();
12554 BitVector UndefElements;
12555 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
12556 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
12557 if (C == -1 || C == 0 || C > 32)
12558 return SDValue();
12560 SDLoc dl(N);
12561 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
12562 SDValue ConvInput = Op.getOperand(0);
12563 if (IntBits < FloatBits)
12564 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
12565 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
12566 ConvInput);
12568 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
12569 Intrinsic::arm_neon_vcvtfxu2fp;
12570 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
12571 Op.getValueType(),
12572 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
12573 ConvInput, DAG.getConstant(C, dl, MVT::i32));
12576 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
12577 /// operand of a vector shift operation, where all the elements of the
12578 /// build_vector must have the same constant integer value.
12579 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
12580 // Ignore bit_converts.
12581 while (Op.getOpcode() == ISD::BITCAST)
12582 Op = Op.getOperand(0);
12583 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
12584 APInt SplatBits, SplatUndef;
12585 unsigned SplatBitSize;
12586 bool HasAnyUndefs;
12587 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
12588 HasAnyUndefs, ElementBits) ||
12589 SplatBitSize > ElementBits)
12590 return false;
12591 Cnt = SplatBits.getSExtValue();
12592 return true;
12595 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
12596 /// operand of a vector shift left operation. That value must be in the range:
12597 /// 0 <= Value < ElementBits for a left shift; or
12598 /// 0 <= Value <= ElementBits for a long left shift.
12599 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
12600 assert(VT.isVector() && "vector shift count is not a vector type");
12601 int64_t ElementBits = VT.getScalarSizeInBits();
12602 if (! getVShiftImm(Op, ElementBits, Cnt))
12603 return false;
12604 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
12607 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
12608 /// operand of a vector shift right operation. For a shift opcode, the value
12609 /// is positive, but for an intrinsic the value count must be negative. The
12610 /// absolute value must be in the range:
12611 /// 1 <= |Value| <= ElementBits for a right shift; or
12612 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
12613 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
12614 int64_t &Cnt) {
12615 assert(VT.isVector() && "vector shift count is not a vector type");
12616 int64_t ElementBits = VT.getScalarSizeInBits();
12617 if (! getVShiftImm(Op, ElementBits, Cnt))
12618 return false;
12619 if (!isIntrinsic)
12620 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
12621 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
12622 Cnt = -Cnt;
12623 return true;
12625 return false;
12628 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
12629 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
12630 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
12631 switch (IntNo) {
12632 default:
12633 // Don't do anything for most intrinsics.
12634 break;
12636 // Vector shifts: check for immediate versions and lower them.
12637 // Note: This is done during DAG combining instead of DAG legalizing because
12638 // the build_vectors for 64-bit vector element shift counts are generally
12639 // not legal, and it is hard to see their values after they get legalized to
12640 // loads from a constant pool.
12641 case Intrinsic::arm_neon_vshifts:
12642 case Intrinsic::arm_neon_vshiftu:
12643 case Intrinsic::arm_neon_vrshifts:
12644 case Intrinsic::arm_neon_vrshiftu:
12645 case Intrinsic::arm_neon_vrshiftn:
12646 case Intrinsic::arm_neon_vqshifts:
12647 case Intrinsic::arm_neon_vqshiftu:
12648 case Intrinsic::arm_neon_vqshiftsu:
12649 case Intrinsic::arm_neon_vqshiftns:
12650 case Intrinsic::arm_neon_vqshiftnu:
12651 case Intrinsic::arm_neon_vqshiftnsu:
12652 case Intrinsic::arm_neon_vqrshiftns:
12653 case Intrinsic::arm_neon_vqrshiftnu:
12654 case Intrinsic::arm_neon_vqrshiftnsu: {
12655 EVT VT = N->getOperand(1).getValueType();
12656 int64_t Cnt;
12657 unsigned VShiftOpc = 0;
12659 switch (IntNo) {
12660 case Intrinsic::arm_neon_vshifts:
12661 case Intrinsic::arm_neon_vshiftu:
12662 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
12663 VShiftOpc = ARMISD::VSHL;
12664 break;
12666 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
12667 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
12668 ARMISD::VSHRs : ARMISD::VSHRu);
12669 break;
12671 return SDValue();
12673 case Intrinsic::arm_neon_vrshifts:
12674 case Intrinsic::arm_neon_vrshiftu:
12675 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
12676 break;
12677 return SDValue();
12679 case Intrinsic::arm_neon_vqshifts:
12680 case Intrinsic::arm_neon_vqshiftu:
12681 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
12682 break;
12683 return SDValue();
12685 case Intrinsic::arm_neon_vqshiftsu:
12686 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
12687 break;
12688 llvm_unreachable("invalid shift count for vqshlu intrinsic");
12690 case Intrinsic::arm_neon_vrshiftn:
12691 case Intrinsic::arm_neon_vqshiftns:
12692 case Intrinsic::arm_neon_vqshiftnu:
12693 case Intrinsic::arm_neon_vqshiftnsu:
12694 case Intrinsic::arm_neon_vqrshiftns:
12695 case Intrinsic::arm_neon_vqrshiftnu:
12696 case Intrinsic::arm_neon_vqrshiftnsu:
12697 // Narrowing shifts require an immediate right shift.
12698 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
12699 break;
12700 llvm_unreachable("invalid shift count for narrowing vector shift "
12701 "intrinsic");
12703 default:
12704 llvm_unreachable("unhandled vector shift");
12707 switch (IntNo) {
12708 case Intrinsic::arm_neon_vshifts:
12709 case Intrinsic::arm_neon_vshiftu:
12710 // Opcode already set above.
12711 break;
12712 case Intrinsic::arm_neon_vrshifts:
12713 VShiftOpc = ARMISD::VRSHRs; break;
12714 case Intrinsic::arm_neon_vrshiftu:
12715 VShiftOpc = ARMISD::VRSHRu; break;
12716 case Intrinsic::arm_neon_vrshiftn:
12717 VShiftOpc = ARMISD::VRSHRN; break;
12718 case Intrinsic::arm_neon_vqshifts:
12719 VShiftOpc = ARMISD::VQSHLs; break;
12720 case Intrinsic::arm_neon_vqshiftu:
12721 VShiftOpc = ARMISD::VQSHLu; break;
12722 case Intrinsic::arm_neon_vqshiftsu:
12723 VShiftOpc = ARMISD::VQSHLsu; break;
12724 case Intrinsic::arm_neon_vqshiftns:
12725 VShiftOpc = ARMISD::VQSHRNs; break;
12726 case Intrinsic::arm_neon_vqshiftnu:
12727 VShiftOpc = ARMISD::VQSHRNu; break;
12728 case Intrinsic::arm_neon_vqshiftnsu:
12729 VShiftOpc = ARMISD::VQSHRNsu; break;
12730 case Intrinsic::arm_neon_vqrshiftns:
12731 VShiftOpc = ARMISD::VQRSHRNs; break;
12732 case Intrinsic::arm_neon_vqrshiftnu:
12733 VShiftOpc = ARMISD::VQRSHRNu; break;
12734 case Intrinsic::arm_neon_vqrshiftnsu:
12735 VShiftOpc = ARMISD::VQRSHRNsu; break;
12738 SDLoc dl(N);
12739 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
12740 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
12743 case Intrinsic::arm_neon_vshiftins: {
12744 EVT VT = N->getOperand(1).getValueType();
12745 int64_t Cnt;
12746 unsigned VShiftOpc = 0;
12748 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
12749 VShiftOpc = ARMISD::VSLI;
12750 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
12751 VShiftOpc = ARMISD::VSRI;
12752 else {
12753 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
12756 SDLoc dl(N);
12757 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
12758 N->getOperand(1), N->getOperand(2),
12759 DAG.getConstant(Cnt, dl, MVT::i32));
12762 case Intrinsic::arm_neon_vqrshifts:
12763 case Intrinsic::arm_neon_vqrshiftu:
12764 // No immediate versions of these to check for.
12765 break;
12768 return SDValue();
12771 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
12772 /// lowers them. As with the vector shift intrinsics, this is done during DAG
12773 /// combining instead of DAG legalizing because the build_vectors for 64-bit
12774 /// vector element shift counts are generally not legal, and it is hard to see
12775 /// their values after they get legalized to loads from a constant pool.
12776 static SDValue PerformShiftCombine(SDNode *N,
12777 TargetLowering::DAGCombinerInfo &DCI,
12778 const ARMSubtarget *ST) {
12779 SelectionDAG &DAG = DCI.DAG;
12780 EVT VT = N->getValueType(0);
12781 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
12782 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
12783 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
12784 SDValue N1 = N->getOperand(1);
12785 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
12786 SDValue N0 = N->getOperand(0);
12787 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
12788 DAG.MaskedValueIsZero(N0.getOperand(0),
12789 APInt::getHighBitsSet(32, 16)))
12790 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
12794 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
12795 N->getOperand(0)->getOpcode() == ISD::AND &&
12796 N->getOperand(0)->hasOneUse()) {
12797 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12798 return SDValue();
12799 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
12800 // usually show up because instcombine prefers to canonicalize it to
12801 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
12802 // out of GEP lowering in some cases.
12803 SDValue N0 = N->getOperand(0);
12804 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
12805 if (!ShiftAmtNode)
12806 return SDValue();
12807 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
12808 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12809 if (!AndMaskNode)
12810 return SDValue();
12811 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
12812 // Don't transform uxtb/uxth.
12813 if (AndMask == 255 || AndMask == 65535)
12814 return SDValue();
12815 if (isMask_32(AndMask)) {
12816 uint32_t MaskedBits = countLeadingZeros(AndMask);
12817 if (MaskedBits > ShiftAmt) {
12818 SDLoc DL(N);
12819 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
12820 DAG.getConstant(MaskedBits, DL, MVT::i32));
12821 return DAG.getNode(
12822 ISD::SRL, DL, MVT::i32, SHL,
12823 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
12828 // Nothing to be done for scalar shifts.
12829 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12830 if (!VT.isVector() || !TLI.isTypeLegal(VT))
12831 return SDValue();
12833 assert(ST->hasNEON() && "unexpected vector shift");
12834 int64_t Cnt;
12836 switch (N->getOpcode()) {
12837 default: llvm_unreachable("unexpected shift opcode");
12839 case ISD::SHL:
12840 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
12841 SDLoc dl(N);
12842 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
12843 DAG.getConstant(Cnt, dl, MVT::i32));
12845 break;
12847 case ISD::SRA:
12848 case ISD::SRL:
12849 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
12850 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
12851 ARMISD::VSHRs : ARMISD::VSHRu);
12852 SDLoc dl(N);
12853 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
12854 DAG.getConstant(Cnt, dl, MVT::i32));
12857 return SDValue();
12860 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
12861 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
12862 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
12863 const ARMSubtarget *ST) {
12864 SDValue N0 = N->getOperand(0);
12866 // Check for sign- and zero-extensions of vector extract operations of 8-
12867 // and 16-bit vector elements. NEON supports these directly. They are
12868 // handled during DAG combining because type legalization will promote them
12869 // to 32-bit types and it is messy to recognize the operations after that.
12870 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12871 SDValue Vec = N0.getOperand(0);
12872 SDValue Lane = N0.getOperand(1);
12873 EVT VT = N->getValueType(0);
12874 EVT EltVT = N0.getValueType();
12875 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12877 if (VT == MVT::i32 &&
12878 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
12879 TLI.isTypeLegal(Vec.getValueType()) &&
12880 isa<ConstantSDNode>(Lane)) {
12882 unsigned Opc = 0;
12883 switch (N->getOpcode()) {
12884 default: llvm_unreachable("unexpected opcode");
12885 case ISD::SIGN_EXTEND:
12886 Opc = ARMISD::VGETLANEs;
12887 break;
12888 case ISD::ZERO_EXTEND:
12889 case ISD::ANY_EXTEND:
12890 Opc = ARMISD::VGETLANEu;
12891 break;
12893 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
12897 return SDValue();
12900 static const APInt *isPowerOf2Constant(SDValue V) {
12901 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12902 if (!C)
12903 return nullptr;
12904 const APInt *CV = &C->getAPIntValue();
12905 return CV->isPowerOf2() ? CV : nullptr;
12908 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
12909 // If we have a CMOV, OR and AND combination such as:
12910 // if (x & CN)
12911 // y |= CM;
12913 // And:
12914 // * CN is a single bit;
12915 // * All bits covered by CM are known zero in y
12917 // Then we can convert this into a sequence of BFI instructions. This will
12918 // always be a win if CM is a single bit, will always be no worse than the
12919 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
12920 // three bits (due to the extra IT instruction).
12922 SDValue Op0 = CMOV->getOperand(0);
12923 SDValue Op1 = CMOV->getOperand(1);
12924 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
12925 auto CC = CCNode->getAPIntValue().getLimitedValue();
12926 SDValue CmpZ = CMOV->getOperand(4);
12928 // The compare must be against zero.
12929 if (!isNullConstant(CmpZ->getOperand(1)))
12930 return SDValue();
12932 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
12933 SDValue And = CmpZ->getOperand(0);
12934 if (And->getOpcode() != ISD::AND)
12935 return SDValue();
12936 const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
12937 if (!AndC)
12938 return SDValue();
12939 SDValue X = And->getOperand(0);
12941 if (CC == ARMCC::EQ) {
12942 // We're performing an "equal to zero" compare. Swap the operands so we
12943 // canonicalize on a "not equal to zero" compare.
12944 std::swap(Op0, Op1);
12945 } else {
12946 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
12949 if (Op1->getOpcode() != ISD::OR)
12950 return SDValue();
12952 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
12953 if (!OrC)
12954 return SDValue();
12955 SDValue Y = Op1->getOperand(0);
12957 if (Op0 != Y)
12958 return SDValue();
12960 // Now, is it profitable to continue?
12961 APInt OrCI = OrC->getAPIntValue();
12962 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
12963 if (OrCI.countPopulation() > Heuristic)
12964 return SDValue();
12966 // Lastly, can we determine that the bits defined by OrCI
12967 // are zero in Y?
12968 KnownBits Known = DAG.computeKnownBits(Y);
12969 if ((OrCI & Known.Zero) != OrCI)
12970 return SDValue();
12972 // OK, we can do the combine.
12973 SDValue V = Y;
12974 SDLoc dl(X);
12975 EVT VT = X.getValueType();
12976 unsigned BitInX = AndC->logBase2();
12978 if (BitInX != 0) {
12979 // We must shift X first.
12980 X = DAG.getNode(ISD::SRL, dl, VT, X,
12981 DAG.getConstant(BitInX, dl, VT));
12984 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
12985 BitInY < NumActiveBits; ++BitInY) {
12986 if (OrCI[BitInY] == 0)
12987 continue;
12988 APInt Mask(VT.getSizeInBits(), 0);
12989 Mask.setBit(BitInY);
12990 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
12991 // Confusingly, the operand is an *inverted* mask.
12992 DAG.getConstant(~Mask, dl, VT));
12995 return V;
12998 static SDValue PerformHWLoopCombine(SDNode *N,
12999 TargetLowering::DAGCombinerInfo &DCI,
13000 const ARMSubtarget *ST) {
13001 // Look for (brcond (xor test.set.loop.iterations, -1)
13002 SDValue CC = N->getOperand(1);
13003 unsigned Opc = CC->getOpcode();
13004 SDValue Int;
13006 if ((Opc == ISD::XOR || Opc == ISD::SETCC) &&
13007 (CC->getOperand(0)->getOpcode() == ISD::INTRINSIC_W_CHAIN)) {
13009 assert((isa<ConstantSDNode>(CC->getOperand(1)) &&
13010 cast<ConstantSDNode>(CC->getOperand(1))->isOne()) &&
13011 "Expected to compare against 1");
13013 Int = CC->getOperand(0);
13014 } else if (CC->getOpcode() == ISD::INTRINSIC_W_CHAIN)
13015 Int = CC;
13016 else
13017 return SDValue();
13019 unsigned IntOp = cast<ConstantSDNode>(Int.getOperand(1))->getZExtValue();
13020 if (IntOp != Intrinsic::test_set_loop_iterations)
13021 return SDValue();
13023 SDLoc dl(Int);
13024 SDValue Chain = N->getOperand(0);
13025 SDValue Elements = Int.getOperand(2);
13026 SDValue ExitBlock = N->getOperand(2);
13028 // TODO: Once we start supporting tail predication, we can add another
13029 // operand to WLS for the number of elements processed in a vector loop.
13031 SDValue Ops[] = { Chain, Elements, ExitBlock };
13032 SDValue Res = DCI.DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
13033 DCI.DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0));
13034 return Res;
13037 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
13038 SDValue
13039 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
13040 SDValue Cmp = N->getOperand(4);
13041 if (Cmp.getOpcode() != ARMISD::CMPZ)
13042 // Only looking at NE cases.
13043 return SDValue();
13045 EVT VT = N->getValueType(0);
13046 SDLoc dl(N);
13047 SDValue LHS = Cmp.getOperand(0);
13048 SDValue RHS = Cmp.getOperand(1);
13049 SDValue Chain = N->getOperand(0);
13050 SDValue BB = N->getOperand(1);
13051 SDValue ARMcc = N->getOperand(2);
13052 ARMCC::CondCodes CC =
13053 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
13055 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
13056 // -> (brcond Chain BB CC CPSR Cmp)
13057 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
13058 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
13059 LHS->getOperand(0)->hasOneUse()) {
13060 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
13061 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
13062 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
13063 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
13064 if ((LHS00C && LHS00C->getZExtValue() == 0) &&
13065 (LHS01C && LHS01C->getZExtValue() == 1) &&
13066 (LHS1C && LHS1C->getZExtValue() == 1) &&
13067 (RHSC && RHSC->getZExtValue() == 0)) {
13068 return DAG.getNode(
13069 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
13070 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
13074 return SDValue();
13077 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
13078 SDValue
13079 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
13080 SDValue Cmp = N->getOperand(4);
13081 if (Cmp.getOpcode() != ARMISD::CMPZ)
13082 // Only looking at EQ and NE cases.
13083 return SDValue();
13085 EVT VT = N->getValueType(0);
13086 SDLoc dl(N);
13087 SDValue LHS = Cmp.getOperand(0);
13088 SDValue RHS = Cmp.getOperand(1);
13089 SDValue FalseVal = N->getOperand(0);
13090 SDValue TrueVal = N->getOperand(1);
13091 SDValue ARMcc = N->getOperand(2);
13092 ARMCC::CondCodes CC =
13093 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
13095 // BFI is only available on V6T2+.
13096 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
13097 SDValue R = PerformCMOVToBFICombine(N, DAG);
13098 if (R)
13099 return R;
13102 // Simplify
13103 // mov r1, r0
13104 // cmp r1, x
13105 // mov r0, y
13106 // moveq r0, x
13107 // to
13108 // cmp r0, x
13109 // movne r0, y
13111 // mov r1, r0
13112 // cmp r1, x
13113 // mov r0, x
13114 // movne r0, y
13115 // to
13116 // cmp r0, x
13117 // movne r0, y
13118 /// FIXME: Turn this into a target neutral optimization?
13119 SDValue Res;
13120 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
13121 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
13122 N->getOperand(3), Cmp);
13123 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
13124 SDValue ARMcc;
13125 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
13126 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
13127 N->getOperand(3), NewCmp);
13130 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
13131 // -> (cmov F T CC CPSR Cmp)
13132 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
13133 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
13134 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
13135 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
13136 if ((LHS0C && LHS0C->getZExtValue() == 0) &&
13137 (LHS1C && LHS1C->getZExtValue() == 1) &&
13138 (RHSC && RHSC->getZExtValue() == 0)) {
13139 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
13140 LHS->getOperand(2), LHS->getOperand(3),
13141 LHS->getOperand(4));
13145 if (!VT.isInteger())
13146 return SDValue();
13148 // Materialize a boolean comparison for integers so we can avoid branching.
13149 if (isNullConstant(FalseVal)) {
13150 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
13151 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
13152 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
13153 // right 5 bits will make that 32 be 1, otherwise it will be 0.
13154 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
13155 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
13156 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
13157 DAG.getConstant(5, dl, MVT::i32));
13158 } else {
13159 // CMOV 0, 1, ==, (CMPZ x, y) ->
13160 // (ADDCARRY (SUB x, y), t:0, t:1)
13161 // where t = (SUBCARRY 0, (SUB x, y), 0)
13163 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
13164 // x != y. In other words, a carry C == 1 when x == y, C == 0
13165 // otherwise.
13166 // The final ADDCARRY computes
13167 // x - y + (0 - (x - y)) + C == C
13168 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
13169 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13170 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
13171 // ISD::SUBCARRY returns a borrow but we want the carry here
13172 // actually.
13173 SDValue Carry =
13174 DAG.getNode(ISD::SUB, dl, MVT::i32,
13175 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
13176 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
13178 } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
13179 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
13180 // This seems pointless but will allow us to combine it further below.
13181 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
13182 SDValue Sub =
13183 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
13184 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
13185 Sub.getValue(1), SDValue());
13186 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
13187 N->getOperand(3), CPSRGlue.getValue(1));
13188 FalseVal = Sub;
13190 } else if (isNullConstant(TrueVal)) {
13191 if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
13192 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
13193 // This seems pointless but will allow us to combine it further below
13194 // Note that we change == for != as this is the dual for the case above.
13195 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
13196 SDValue Sub =
13197 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
13198 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
13199 Sub.getValue(1), SDValue());
13200 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
13201 DAG.getConstant(ARMCC::NE, dl, MVT::i32),
13202 N->getOperand(3), CPSRGlue.getValue(1));
13203 FalseVal = Sub;
13207 // On Thumb1, the DAG above may be further combined if z is a power of 2
13208 // (z == 2 ^ K).
13209 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
13210 // t1 = (USUBO (SUB x, y), 1)
13211 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
13212 // Result = if K != 0 then (SHL t2:0, K) else t2:0
13214 // This also handles the special case of comparing against zero; it's
13215 // essentially, the same pattern, except there's no SUBS:
13216 // CMOV x, z, !=, (CMPZ x, 0) ->
13217 // t1 = (USUBO x, 1)
13218 // t2 = (SUBCARRY x, t1:0, t1:1)
13219 // Result = if K != 0 then (SHL t2:0, K) else t2:0
13220 const APInt *TrueConst;
13221 if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
13222 ((FalseVal.getOpcode() == ARMISD::SUBS &&
13223 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
13224 (FalseVal == LHS && isNullConstant(RHS))) &&
13225 (TrueConst = isPowerOf2Constant(TrueVal))) {
13226 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13227 unsigned ShiftAmount = TrueConst->logBase2();
13228 if (ShiftAmount)
13229 TrueVal = DAG.getConstant(1, dl, VT);
13230 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
13231 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
13233 if (ShiftAmount)
13234 Res = DAG.getNode(ISD::SHL, dl, VT, Res,
13235 DAG.getConstant(ShiftAmount, dl, MVT::i32));
13238 if (Res.getNode()) {
13239 KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
13240 // Capture demanded bits information that would be otherwise lost.
13241 if (Known.Zero == 0xfffffffe)
13242 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
13243 DAG.getValueType(MVT::i1));
13244 else if (Known.Zero == 0xffffff00)
13245 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
13246 DAG.getValueType(MVT::i8));
13247 else if (Known.Zero == 0xffff0000)
13248 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
13249 DAG.getValueType(MVT::i16));
13252 return Res;
13255 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
13256 DAGCombinerInfo &DCI) const {
13257 switch (N->getOpcode()) {
13258 default: break;
13259 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget);
13260 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
13261 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget);
13262 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
13263 case ISD::SUB: return PerformSUBCombine(N, DCI);
13264 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
13265 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
13266 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
13267 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
13268 case ISD::BRCOND: return PerformHWLoopCombine(N, DCI, Subtarget);
13269 case ARMISD::ADDC:
13270 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget);
13271 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget);
13272 case ARMISD::BFI: return PerformBFICombine(N, DCI);
13273 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
13274 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
13275 case ISD::STORE: return PerformSTORECombine(N, DCI);
13276 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
13277 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
13278 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
13279 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
13280 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget);
13281 case ISD::FP_TO_SINT:
13282 case ISD::FP_TO_UINT:
13283 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
13284 case ISD::FDIV:
13285 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
13286 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
13287 case ISD::SHL:
13288 case ISD::SRA:
13289 case ISD::SRL:
13290 return PerformShiftCombine(N, DCI, Subtarget);
13291 case ISD::SIGN_EXTEND:
13292 case ISD::ZERO_EXTEND:
13293 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
13294 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
13295 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
13296 case ISD::LOAD: return PerformLOADCombine(N, DCI);
13297 case ARMISD::VLD1DUP:
13298 case ARMISD::VLD2DUP:
13299 case ARMISD::VLD3DUP:
13300 case ARMISD::VLD4DUP:
13301 return PerformVLDCombine(N, DCI);
13302 case ARMISD::BUILD_VECTOR:
13303 return PerformARMBUILD_VECTORCombine(N, DCI);
13304 case ARMISD::SMULWB: {
13305 unsigned BitWidth = N->getValueType(0).getSizeInBits();
13306 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
13307 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
13308 return SDValue();
13309 break;
13311 case ARMISD::SMULWT: {
13312 unsigned BitWidth = N->getValueType(0).getSizeInBits();
13313 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
13314 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
13315 return SDValue();
13316 break;
13318 case ARMISD::SMLALBB: {
13319 unsigned BitWidth = N->getValueType(0).getSizeInBits();
13320 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
13321 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
13322 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
13323 return SDValue();
13324 break;
13326 case ARMISD::SMLALBT: {
13327 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
13328 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
13329 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
13330 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
13331 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
13332 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
13333 return SDValue();
13334 break;
13336 case ARMISD::SMLALTB: {
13337 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
13338 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
13339 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
13340 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
13341 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
13342 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
13343 return SDValue();
13344 break;
13346 case ARMISD::SMLALTT: {
13347 unsigned BitWidth = N->getValueType(0).getSizeInBits();
13348 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
13349 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
13350 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
13351 return SDValue();
13352 break;
13354 case ISD::INTRINSIC_VOID:
13355 case ISD::INTRINSIC_W_CHAIN:
13356 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13357 case Intrinsic::arm_neon_vld1:
13358 case Intrinsic::arm_neon_vld1x2:
13359 case Intrinsic::arm_neon_vld1x3:
13360 case Intrinsic::arm_neon_vld1x4:
13361 case Intrinsic::arm_neon_vld2:
13362 case Intrinsic::arm_neon_vld3:
13363 case Intrinsic::arm_neon_vld4:
13364 case Intrinsic::arm_neon_vld2lane:
13365 case Intrinsic::arm_neon_vld3lane:
13366 case Intrinsic::arm_neon_vld4lane:
13367 case Intrinsic::arm_neon_vld2dup:
13368 case Intrinsic::arm_neon_vld3dup:
13369 case Intrinsic::arm_neon_vld4dup:
13370 case Intrinsic::arm_neon_vst1:
13371 case Intrinsic::arm_neon_vst1x2:
13372 case Intrinsic::arm_neon_vst1x3:
13373 case Intrinsic::arm_neon_vst1x4:
13374 case Intrinsic::arm_neon_vst2:
13375 case Intrinsic::arm_neon_vst3:
13376 case Intrinsic::arm_neon_vst4:
13377 case Intrinsic::arm_neon_vst2lane:
13378 case Intrinsic::arm_neon_vst3lane:
13379 case Intrinsic::arm_neon_vst4lane:
13380 return PerformVLDCombine(N, DCI);
13381 default: break;
13383 break;
13385 return SDValue();
13388 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
13389 EVT VT) const {
13390 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
13393 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
13394 unsigned Alignment,
13395 MachineMemOperand::Flags,
13396 bool *Fast) const {
13397 // Depends what it gets converted into if the type is weird.
13398 if (!VT.isSimple())
13399 return false;
13401 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
13402 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
13403 auto Ty = VT.getSimpleVT().SimpleTy;
13405 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
13406 // Unaligned access can use (for example) LRDB, LRDH, LDR
13407 if (AllowsUnaligned) {
13408 if (Fast)
13409 *Fast = Subtarget->hasV7Ops();
13410 return true;
13414 if (Ty == MVT::f64 || Ty == MVT::v2f64) {
13415 // For any little-endian targets with neon, we can support unaligned ld/st
13416 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
13417 // A big-endian target may also explicitly support unaligned accesses
13418 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
13419 if (Fast)
13420 *Fast = true;
13421 return true;
13425 if (!Subtarget->hasMVEIntegerOps())
13426 return false;
13427 if (Ty != MVT::v16i8 && Ty != MVT::v8i16 && Ty != MVT::v8f16 &&
13428 Ty != MVT::v4i32 && Ty != MVT::v4f32 && Ty != MVT::v2i64 &&
13429 Ty != MVT::v2f64 &&
13430 // These are for truncated stores
13431 Ty != MVT::v4i8 && Ty != MVT::v8i8 && Ty != MVT::v4i16)
13432 return false;
13434 if (Subtarget->isLittle()) {
13435 // In little-endian MVE, the store instructions VSTRB.U8,
13436 // VSTRH.U16 and VSTRW.U32 all store the vector register in
13437 // exactly the same format, and differ only in the range of
13438 // their immediate offset field and the required alignment.
13440 // In particular, VSTRB.U8 can store a vector at byte alignment.
13441 // So at this stage we can simply say that loads/stores of all
13442 // 128-bit wide vector types are permitted at any alignment,
13443 // because we know at least _one_ instruction can manage that.
13445 // Later on we might find that some of those loads are better
13446 // generated as VLDRW.U32 if alignment permits, to take
13447 // advantage of the larger immediate range. But for the moment,
13448 // all that matters is that if we don't lower the load then
13449 // _some_ instruction can handle it.
13450 if (Fast)
13451 *Fast = true;
13452 return true;
13453 } else {
13454 // In big-endian MVE, those instructions aren't so similar
13455 // after all, because they reorder the bytes of the vector
13456 // differently. So this time we can only store a particular
13457 // kind of vector if its alignment is at least the element
13458 // type. And we can't store vectors of i64 or f64 at all
13459 // without having to do some postprocessing, because there's
13460 // no VSTRD.U64.
13461 if (Ty == MVT::v16i8 ||
13462 ((Ty == MVT::v8i16 || Ty == MVT::v8f16) && Alignment >= 2) ||
13463 ((Ty == MVT::v4i32 || Ty == MVT::v4f32) && Alignment >= 4)) {
13464 if (Fast)
13465 *Fast = true;
13466 return true;
13470 return false;
13473 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
13474 unsigned AlignCheck) {
13475 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
13476 (DstAlign == 0 || DstAlign % AlignCheck == 0));
13479 EVT ARMTargetLowering::getOptimalMemOpType(
13480 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
13481 bool ZeroMemset, bool MemcpyStrSrc,
13482 const AttributeList &FuncAttributes) const {
13483 // See if we can use NEON instructions for this...
13484 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
13485 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
13486 bool Fast;
13487 if (Size >= 16 &&
13488 (memOpAlign(SrcAlign, DstAlign, 16) ||
13489 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1,
13490 MachineMemOperand::MONone, &Fast) &&
13491 Fast))) {
13492 return MVT::v2f64;
13493 } else if (Size >= 8 &&
13494 (memOpAlign(SrcAlign, DstAlign, 8) ||
13495 (allowsMisalignedMemoryAccesses(
13496 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) &&
13497 Fast))) {
13498 return MVT::f64;
13502 // Let the target-independent logic figure it out.
13503 return MVT::Other;
13506 // 64-bit integers are split into their high and low parts and held in two
13507 // different registers, so the trunc is free since the low register can just
13508 // be used.
13509 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
13510 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
13511 return false;
13512 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
13513 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
13514 return (SrcBits == 64 && DestBits == 32);
13517 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
13518 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
13519 !DstVT.isInteger())
13520 return false;
13521 unsigned SrcBits = SrcVT.getSizeInBits();
13522 unsigned DestBits = DstVT.getSizeInBits();
13523 return (SrcBits == 64 && DestBits == 32);
13526 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13527 if (Val.getOpcode() != ISD::LOAD)
13528 return false;
13530 EVT VT1 = Val.getValueType();
13531 if (!VT1.isSimple() || !VT1.isInteger() ||
13532 !VT2.isSimple() || !VT2.isInteger())
13533 return false;
13535 switch (VT1.getSimpleVT().SimpleTy) {
13536 default: break;
13537 case MVT::i1:
13538 case MVT::i8:
13539 case MVT::i16:
13540 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
13541 return true;
13544 return false;
13547 bool ARMTargetLowering::isFNegFree(EVT VT) const {
13548 if (!VT.isSimple())
13549 return false;
13551 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
13552 // negate values directly (fneg is free). So, we don't want to let the DAG
13553 // combiner rewrite fneg into xors and some other instructions. For f16 and
13554 // FullFP16 argument passing, some bitcast nodes may be introduced,
13555 // triggering this DAG combine rewrite, so we are avoiding that with this.
13556 switch (VT.getSimpleVT().SimpleTy) {
13557 default: break;
13558 case MVT::f16:
13559 return Subtarget->hasFullFP16();
13562 return false;
13565 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
13566 /// of the vector elements.
13567 static bool areExtractExts(Value *Ext1, Value *Ext2) {
13568 auto areExtDoubled = [](Instruction *Ext) {
13569 return Ext->getType()->getScalarSizeInBits() ==
13570 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
13573 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
13574 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
13575 !areExtDoubled(cast<Instruction>(Ext1)) ||
13576 !areExtDoubled(cast<Instruction>(Ext2)))
13577 return false;
13579 return true;
13582 /// Check if sinking \p I's operands to I's basic block is profitable, because
13583 /// the operands can be folded into a target instruction, e.g.
13584 /// sext/zext can be folded into vsubl.
13585 bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
13586 SmallVectorImpl<Use *> &Ops) const {
13587 if (!Subtarget->hasNEON() || !I->getType()->isVectorTy())
13588 return false;
13590 switch (I->getOpcode()) {
13591 case Instruction::Sub:
13592 case Instruction::Add: {
13593 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
13594 return false;
13595 Ops.push_back(&I->getOperandUse(0));
13596 Ops.push_back(&I->getOperandUse(1));
13597 return true;
13599 default:
13600 return false;
13602 return false;
13605 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
13606 EVT VT = ExtVal.getValueType();
13608 if (!isTypeLegal(VT))
13609 return false;
13611 // Don't create a loadext if we can fold the extension into a wide/long
13612 // instruction.
13613 // If there's more than one user instruction, the loadext is desirable no
13614 // matter what. There can be two uses by the same instruction.
13615 if (ExtVal->use_empty() ||
13616 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
13617 return true;
13619 SDNode *U = *ExtVal->use_begin();
13620 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
13621 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
13622 return false;
13624 return true;
13627 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
13628 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13629 return false;
13631 if (!isTypeLegal(EVT::getEVT(Ty1)))
13632 return false;
13634 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
13636 // Assuming the caller doesn't have a zeroext or signext return parameter,
13637 // truncation all the way down to i1 is valid.
13638 return true;
13641 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
13642 const AddrMode &AM, Type *Ty,
13643 unsigned AS) const {
13644 if (isLegalAddressingMode(DL, AM, Ty, AS)) {
13645 if (Subtarget->hasFPAO())
13646 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
13647 return 0;
13649 return -1;
13652 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
13653 if (V < 0)
13654 return false;
13656 unsigned Scale = 1;
13657 switch (VT.getSimpleVT().SimpleTy) {
13658 case MVT::i1:
13659 case MVT::i8:
13660 // Scale == 1;
13661 break;
13662 case MVT::i16:
13663 // Scale == 2;
13664 Scale = 2;
13665 break;
13666 default:
13667 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
13668 // Scale == 4;
13669 Scale = 4;
13670 break;
13673 if ((V & (Scale - 1)) != 0)
13674 return false;
13675 return isUInt<5>(V / Scale);
13678 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
13679 const ARMSubtarget *Subtarget) {
13680 if (!VT.isInteger() && !VT.isFloatingPoint())
13681 return false;
13682 if (VT.isVector() && Subtarget->hasNEON())
13683 return false;
13684 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
13685 !Subtarget->hasMVEFloatOps())
13686 return false;
13688 bool IsNeg = false;
13689 if (V < 0) {
13690 IsNeg = true;
13691 V = -V;
13694 unsigned NumBytes = std::max(VT.getSizeInBits() / 8, 1U);
13696 // MVE: size * imm7
13697 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
13698 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
13699 case MVT::i32:
13700 case MVT::f32:
13701 return isShiftedUInt<7,2>(V);
13702 case MVT::i16:
13703 case MVT::f16:
13704 return isShiftedUInt<7,1>(V);
13705 case MVT::i8:
13706 return isUInt<7>(V);
13707 default:
13708 return false;
13712 // half VLDR: 2 * imm8
13713 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
13714 return isShiftedUInt<8, 1>(V);
13715 // VLDR and LDRD: 4 * imm8
13716 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
13717 return isShiftedUInt<8, 2>(V);
13719 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
13720 // + imm12 or - imm8
13721 if (IsNeg)
13722 return isUInt<8>(V);
13723 return isUInt<12>(V);
13726 return false;
13729 /// isLegalAddressImmediate - Return true if the integer value can be used
13730 /// as the offset of the target addressing mode for load / store of the
13731 /// given type.
13732 static bool isLegalAddressImmediate(int64_t V, EVT VT,
13733 const ARMSubtarget *Subtarget) {
13734 if (V == 0)
13735 return true;
13737 if (!VT.isSimple())
13738 return false;
13740 if (Subtarget->isThumb1Only())
13741 return isLegalT1AddressImmediate(V, VT);
13742 else if (Subtarget->isThumb2())
13743 return isLegalT2AddressImmediate(V, VT, Subtarget);
13745 // ARM mode.
13746 if (V < 0)
13747 V = - V;
13748 switch (VT.getSimpleVT().SimpleTy) {
13749 default: return false;
13750 case MVT::i1:
13751 case MVT::i8:
13752 case MVT::i32:
13753 // +- imm12
13754 return isUInt<12>(V);
13755 case MVT::i16:
13756 // +- imm8
13757 return isUInt<8>(V);
13758 case MVT::f32:
13759 case MVT::f64:
13760 if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
13761 return false;
13762 return isShiftedUInt<8, 2>(V);
13766 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
13767 EVT VT) const {
13768 int Scale = AM.Scale;
13769 if (Scale < 0)
13770 return false;
13772 switch (VT.getSimpleVT().SimpleTy) {
13773 default: return false;
13774 case MVT::i1:
13775 case MVT::i8:
13776 case MVT::i16:
13777 case MVT::i32:
13778 if (Scale == 1)
13779 return true;
13780 // r + r << imm
13781 Scale = Scale & ~1;
13782 return Scale == 2 || Scale == 4 || Scale == 8;
13783 case MVT::i64:
13784 // FIXME: What are we trying to model here? ldrd doesn't have an r + r
13785 // version in Thumb mode.
13786 // r + r
13787 if (Scale == 1)
13788 return true;
13789 // r * 2 (this can be lowered to r + r).
13790 if (!AM.HasBaseReg && Scale == 2)
13791 return true;
13792 return false;
13793 case MVT::isVoid:
13794 // Note, we allow "void" uses (basically, uses that aren't loads or
13795 // stores), because arm allows folding a scale into many arithmetic
13796 // operations. This should be made more precise and revisited later.
13798 // Allow r << imm, but the imm has to be a multiple of two.
13799 if (Scale & 1) return false;
13800 return isPowerOf2_32(Scale);
13804 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
13805 EVT VT) const {
13806 const int Scale = AM.Scale;
13808 // Negative scales are not supported in Thumb1.
13809 if (Scale < 0)
13810 return false;
13812 // Thumb1 addressing modes do not support register scaling excepting the
13813 // following cases:
13814 // 1. Scale == 1 means no scaling.
13815 // 2. Scale == 2 this can be lowered to r + r if there is no base register.
13816 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
13819 /// isLegalAddressingMode - Return true if the addressing mode represented
13820 /// by AM is legal for this target, for a load/store of the specified type.
13821 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
13822 const AddrMode &AM, Type *Ty,
13823 unsigned AS, Instruction *I) const {
13824 EVT VT = getValueType(DL, Ty, true);
13825 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
13826 return false;
13828 // Can never fold addr of global into load/store.
13829 if (AM.BaseGV)
13830 return false;
13832 switch (AM.Scale) {
13833 case 0: // no scale reg, must be "r+i" or "r", or "i".
13834 break;
13835 default:
13836 // ARM doesn't support any R+R*scale+imm addr modes.
13837 if (AM.BaseOffs)
13838 return false;
13840 if (!VT.isSimple())
13841 return false;
13843 if (Subtarget->isThumb1Only())
13844 return isLegalT1ScaledAddressingMode(AM, VT);
13846 if (Subtarget->isThumb2())
13847 return isLegalT2ScaledAddressingMode(AM, VT);
13849 int Scale = AM.Scale;
13850 switch (VT.getSimpleVT().SimpleTy) {
13851 default: return false;
13852 case MVT::i1:
13853 case MVT::i8:
13854 case MVT::i32:
13855 if (Scale < 0) Scale = -Scale;
13856 if (Scale == 1)
13857 return true;
13858 // r + r << imm
13859 return isPowerOf2_32(Scale & ~1);
13860 case MVT::i16:
13861 case MVT::i64:
13862 // r +/- r
13863 if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
13864 return true;
13865 // r * 2 (this can be lowered to r + r).
13866 if (!AM.HasBaseReg && Scale == 2)
13867 return true;
13868 return false;
13870 case MVT::isVoid:
13871 // Note, we allow "void" uses (basically, uses that aren't loads or
13872 // stores), because arm allows folding a scale into many arithmetic
13873 // operations. This should be made more precise and revisited later.
13875 // Allow r << imm, but the imm has to be a multiple of two.
13876 if (Scale & 1) return false;
13877 return isPowerOf2_32(Scale);
13880 return true;
13883 /// isLegalICmpImmediate - Return true if the specified immediate is legal
13884 /// icmp immediate, that is the target has icmp instructions which can compare
13885 /// a register against the immediate without having to materialize the
13886 /// immediate into a register.
13887 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13888 // Thumb2 and ARM modes can use cmn for negative immediates.
13889 if (!Subtarget->isThumb())
13890 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
13891 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
13892 if (Subtarget->isThumb2())
13893 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
13894 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
13895 // Thumb1 doesn't have cmn, and only 8-bit immediates.
13896 return Imm >= 0 && Imm <= 255;
13899 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
13900 /// *or sub* immediate, that is the target has add or sub instructions which can
13901 /// add a register with the immediate without having to materialize the
13902 /// immediate into a register.
13903 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
13904 // Same encoding for add/sub, just flip the sign.
13905 int64_t AbsImm = std::abs(Imm);
13906 if (!Subtarget->isThumb())
13907 return ARM_AM::getSOImmVal(AbsImm) != -1;
13908 if (Subtarget->isThumb2())
13909 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
13910 // Thumb1 only has 8-bit unsigned immediate.
13911 return AbsImm >= 0 && AbsImm <= 255;
13914 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
13915 bool isSEXTLoad, SDValue &Base,
13916 SDValue &Offset, bool &isInc,
13917 SelectionDAG &DAG) {
13918 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
13919 return false;
13921 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
13922 // AddressingMode 3
13923 Base = Ptr->getOperand(0);
13924 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13925 int RHSC = (int)RHS->getZExtValue();
13926 if (RHSC < 0 && RHSC > -256) {
13927 assert(Ptr->getOpcode() == ISD::ADD);
13928 isInc = false;
13929 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13930 return true;
13933 isInc = (Ptr->getOpcode() == ISD::ADD);
13934 Offset = Ptr->getOperand(1);
13935 return true;
13936 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
13937 // AddressingMode 2
13938 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13939 int RHSC = (int)RHS->getZExtValue();
13940 if (RHSC < 0 && RHSC > -0x1000) {
13941 assert(Ptr->getOpcode() == ISD::ADD);
13942 isInc = false;
13943 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13944 Base = Ptr->getOperand(0);
13945 return true;
13949 if (Ptr->getOpcode() == ISD::ADD) {
13950 isInc = true;
13951 ARM_AM::ShiftOpc ShOpcVal=
13952 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
13953 if (ShOpcVal != ARM_AM::no_shift) {
13954 Base = Ptr->getOperand(1);
13955 Offset = Ptr->getOperand(0);
13956 } else {
13957 Base = Ptr->getOperand(0);
13958 Offset = Ptr->getOperand(1);
13960 return true;
13963 isInc = (Ptr->getOpcode() == ISD::ADD);
13964 Base = Ptr->getOperand(0);
13965 Offset = Ptr->getOperand(1);
13966 return true;
13969 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
13970 return false;
13973 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
13974 bool isSEXTLoad, SDValue &Base,
13975 SDValue &Offset, bool &isInc,
13976 SelectionDAG &DAG) {
13977 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
13978 return false;
13980 Base = Ptr->getOperand(0);
13981 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13982 int RHSC = (int)RHS->getZExtValue();
13983 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
13984 assert(Ptr->getOpcode() == ISD::ADD);
13985 isInc = false;
13986 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13987 return true;
13988 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
13989 isInc = Ptr->getOpcode() == ISD::ADD;
13990 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
13991 return true;
13995 return false;
13998 /// getPreIndexedAddressParts - returns true by value, base pointer and
13999 /// offset pointer and addressing mode by reference if the node's address
14000 /// can be legally represented as pre-indexed load / store address.
14001 bool
14002 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
14003 SDValue &Offset,
14004 ISD::MemIndexedMode &AM,
14005 SelectionDAG &DAG) const {
14006 if (Subtarget->isThumb1Only())
14007 return false;
14009 EVT VT;
14010 SDValue Ptr;
14011 bool isSEXTLoad = false;
14012 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14013 Ptr = LD->getBasePtr();
14014 VT = LD->getMemoryVT();
14015 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
14016 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14017 Ptr = ST->getBasePtr();
14018 VT = ST->getMemoryVT();
14019 } else
14020 return false;
14022 bool isInc;
14023 bool isLegal = false;
14024 if (Subtarget->isThumb2())
14025 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
14026 Offset, isInc, DAG);
14027 else
14028 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
14029 Offset, isInc, DAG);
14030 if (!isLegal)
14031 return false;
14033 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
14034 return true;
14037 /// getPostIndexedAddressParts - returns true by value, base pointer and
14038 /// offset pointer and addressing mode by reference if this node can be
14039 /// combined with a load / store to form a post-indexed load / store.
14040 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
14041 SDValue &Base,
14042 SDValue &Offset,
14043 ISD::MemIndexedMode &AM,
14044 SelectionDAG &DAG) const {
14045 EVT VT;
14046 SDValue Ptr;
14047 bool isSEXTLoad = false, isNonExt;
14048 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14049 VT = LD->getMemoryVT();
14050 Ptr = LD->getBasePtr();
14051 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
14052 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
14053 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14054 VT = ST->getMemoryVT();
14055 Ptr = ST->getBasePtr();
14056 isNonExt = !ST->isTruncatingStore();
14057 } else
14058 return false;
14060 if (Subtarget->isThumb1Only()) {
14061 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
14062 // must be non-extending/truncating, i32, with an offset of 4.
14063 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
14064 if (Op->getOpcode() != ISD::ADD || !isNonExt)
14065 return false;
14066 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
14067 if (!RHS || RHS->getZExtValue() != 4)
14068 return false;
14070 Offset = Op->getOperand(1);
14071 Base = Op->getOperand(0);
14072 AM = ISD::POST_INC;
14073 return true;
14076 bool isInc;
14077 bool isLegal = false;
14078 if (Subtarget->isThumb2())
14079 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
14080 isInc, DAG);
14081 else
14082 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
14083 isInc, DAG);
14084 if (!isLegal)
14085 return false;
14087 if (Ptr != Base) {
14088 // Swap base ptr and offset to catch more post-index load / store when
14089 // it's legal. In Thumb2 mode, offset must be an immediate.
14090 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
14091 !Subtarget->isThumb2())
14092 std::swap(Base, Offset);
14094 // Post-indexed load / store update the base pointer.
14095 if (Ptr != Base)
14096 return false;
14099 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
14100 return true;
14103 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14104 KnownBits &Known,
14105 const APInt &DemandedElts,
14106 const SelectionDAG &DAG,
14107 unsigned Depth) const {
14108 unsigned BitWidth = Known.getBitWidth();
14109 Known.resetAll();
14110 switch (Op.getOpcode()) {
14111 default: break;
14112 case ARMISD::ADDC:
14113 case ARMISD::ADDE:
14114 case ARMISD::SUBC:
14115 case ARMISD::SUBE:
14116 // Special cases when we convert a carry to a boolean.
14117 if (Op.getResNo() == 0) {
14118 SDValue LHS = Op.getOperand(0);
14119 SDValue RHS = Op.getOperand(1);
14120 // (ADDE 0, 0, C) will give us a single bit.
14121 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
14122 isNullConstant(RHS)) {
14123 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14124 return;
14127 break;
14128 case ARMISD::CMOV: {
14129 // Bits are known zero/one if known on the LHS and RHS.
14130 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
14131 if (Known.isUnknown())
14132 return;
14134 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
14135 Known.Zero &= KnownRHS.Zero;
14136 Known.One &= KnownRHS.One;
14137 return;
14139 case ISD::INTRINSIC_W_CHAIN: {
14140 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
14141 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
14142 switch (IntID) {
14143 default: return;
14144 case Intrinsic::arm_ldaex:
14145 case Intrinsic::arm_ldrex: {
14146 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
14147 unsigned MemBits = VT.getScalarSizeInBits();
14148 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
14149 return;
14153 case ARMISD::BFI: {
14154 // Conservatively, we can recurse down the first operand
14155 // and just mask out all affected bits.
14156 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
14158 // The operand to BFI is already a mask suitable for removing the bits it
14159 // sets.
14160 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
14161 const APInt &Mask = CI->getAPIntValue();
14162 Known.Zero &= Mask;
14163 Known.One &= Mask;
14164 return;
14166 case ARMISD::VGETLANEs:
14167 case ARMISD::VGETLANEu: {
14168 const SDValue &SrcSV = Op.getOperand(0);
14169 EVT VecVT = SrcSV.getValueType();
14170 assert(VecVT.isVector() && "VGETLANE expected a vector type");
14171 const unsigned NumSrcElts = VecVT.getVectorNumElements();
14172 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
14173 assert(Pos->getAPIntValue().ult(NumSrcElts) &&
14174 "VGETLANE index out of bounds");
14175 unsigned Idx = Pos->getZExtValue();
14176 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
14177 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
14179 EVT VT = Op.getValueType();
14180 const unsigned DstSz = VT.getScalarSizeInBits();
14181 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
14182 (void)SrcSz;
14183 assert(SrcSz == Known.getBitWidth());
14184 assert(DstSz > SrcSz);
14185 if (Op.getOpcode() == ARMISD::VGETLANEs)
14186 Known = Known.sext(DstSz);
14187 else {
14188 Known = Known.zext(DstSz, true /* extended bits are known zero */);
14190 assert(DstSz == Known.getBitWidth());
14191 break;
14196 bool
14197 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op,
14198 const APInt &DemandedAPInt,
14199 TargetLoweringOpt &TLO) const {
14200 // Delay optimization, so we don't have to deal with illegal types, or block
14201 // optimizations.
14202 if (!TLO.LegalOps)
14203 return false;
14205 // Only optimize AND for now.
14206 if (Op.getOpcode() != ISD::AND)
14207 return false;
14209 EVT VT = Op.getValueType();
14211 // Ignore vectors.
14212 if (VT.isVector())
14213 return false;
14215 assert(VT == MVT::i32 && "Unexpected integer type");
14217 // Make sure the RHS really is a constant.
14218 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14219 if (!C)
14220 return false;
14222 unsigned Mask = C->getZExtValue();
14224 unsigned Demanded = DemandedAPInt.getZExtValue();
14225 unsigned ShrunkMask = Mask & Demanded;
14226 unsigned ExpandedMask = Mask | ~Demanded;
14228 // If the mask is all zeros, let the target-independent code replace the
14229 // result with zero.
14230 if (ShrunkMask == 0)
14231 return false;
14233 // If the mask is all ones, erase the AND. (Currently, the target-independent
14234 // code won't do this, so we have to do it explicitly to avoid an infinite
14235 // loop in obscure cases.)
14236 if (ExpandedMask == ~0U)
14237 return TLO.CombineTo(Op, Op.getOperand(0));
14239 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
14240 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
14242 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
14243 if (NewMask == Mask)
14244 return true;
14245 SDLoc DL(Op);
14246 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
14247 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
14248 return TLO.CombineTo(Op, NewOp);
14251 // Prefer uxtb mask.
14252 if (IsLegalMask(0xFF))
14253 return UseMask(0xFF);
14255 // Prefer uxth mask.
14256 if (IsLegalMask(0xFFFF))
14257 return UseMask(0xFFFF);
14259 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
14260 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
14261 if (ShrunkMask < 256)
14262 return UseMask(ShrunkMask);
14264 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
14265 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
14266 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
14267 return UseMask(ExpandedMask);
14269 // Potential improvements:
14271 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
14272 // We could try to prefer Thumb1 immediates which can be lowered to a
14273 // two-instruction sequence.
14274 // We could try to recognize more legal ARM/Thumb2 immediates here.
14276 return false;
14280 //===----------------------------------------------------------------------===//
14281 // ARM Inline Assembly Support
14282 //===----------------------------------------------------------------------===//
14284 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
14285 // Looking for "rev" which is V6+.
14286 if (!Subtarget->hasV6Ops())
14287 return false;
14289 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14290 std::string AsmStr = IA->getAsmString();
14291 SmallVector<StringRef, 4> AsmPieces;
14292 SplitString(AsmStr, AsmPieces, ";\n");
14294 switch (AsmPieces.size()) {
14295 default: return false;
14296 case 1:
14297 AsmStr = AsmPieces[0];
14298 AsmPieces.clear();
14299 SplitString(AsmStr, AsmPieces, " \t,");
14301 // rev $0, $1
14302 if (AsmPieces.size() == 3 &&
14303 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
14304 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
14305 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14306 if (Ty && Ty->getBitWidth() == 32)
14307 return IntrinsicLowering::LowerToByteSwap(CI);
14309 break;
14312 return false;
14315 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
14316 // At this point, we have to lower this constraint to something else, so we
14317 // lower it to an "r" or "w". However, by doing this we will force the result
14318 // to be in register, while the X constraint is much more permissive.
14320 // Although we are correct (we are free to emit anything, without
14321 // constraints), we might break use cases that would expect us to be more
14322 // efficient and emit something else.
14323 if (!Subtarget->hasVFP2Base())
14324 return "r";
14325 if (ConstraintVT.isFloatingPoint())
14326 return "w";
14327 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
14328 (ConstraintVT.getSizeInBits() == 64 ||
14329 ConstraintVT.getSizeInBits() == 128))
14330 return "w";
14332 return "r";
14335 /// getConstraintType - Given a constraint letter, return the type of
14336 /// constraint it is for this target.
14337 ARMTargetLowering::ConstraintType
14338 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
14339 if (Constraint.size() == 1) {
14340 switch (Constraint[0]) {
14341 default: break;
14342 case 'l': return C_RegisterClass;
14343 case 'w': return C_RegisterClass;
14344 case 'h': return C_RegisterClass;
14345 case 'x': return C_RegisterClass;
14346 case 't': return C_RegisterClass;
14347 case 'j': return C_Other; // Constant for movw.
14348 // An address with a single base register. Due to the way we
14349 // currently handle addresses it is the same as an 'r' memory constraint.
14350 case 'Q': return C_Memory;
14352 } else if (Constraint.size() == 2) {
14353 switch (Constraint[0]) {
14354 default: break;
14355 case 'T': return C_RegisterClass;
14356 // All 'U+' constraints are addresses.
14357 case 'U': return C_Memory;
14360 return TargetLowering::getConstraintType(Constraint);
14363 /// Examine constraint type and operand type and determine a weight value.
14364 /// This object must already have been set up with the operand type
14365 /// and the current alternative constraint selected.
14366 TargetLowering::ConstraintWeight
14367 ARMTargetLowering::getSingleConstraintMatchWeight(
14368 AsmOperandInfo &info, const char *constraint) const {
14369 ConstraintWeight weight = CW_Invalid;
14370 Value *CallOperandVal = info.CallOperandVal;
14371 // If we don't have a value, we can't do a match,
14372 // but allow it at the lowest weight.
14373 if (!CallOperandVal)
14374 return CW_Default;
14375 Type *type = CallOperandVal->getType();
14376 // Look at the constraint type.
14377 switch (*constraint) {
14378 default:
14379 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14380 break;
14381 case 'l':
14382 if (type->isIntegerTy()) {
14383 if (Subtarget->isThumb())
14384 weight = CW_SpecificReg;
14385 else
14386 weight = CW_Register;
14388 break;
14389 case 'w':
14390 if (type->isFloatingPointTy())
14391 weight = CW_Register;
14392 break;
14394 return weight;
14397 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
14399 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
14400 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
14401 switch (Constraint.size()) {
14402 case 1:
14403 // GCC ARM Constraint Letters
14404 switch (Constraint[0]) {
14405 case 'l': // Low regs or general regs.
14406 if (Subtarget->isThumb())
14407 return RCPair(0U, &ARM::tGPRRegClass);
14408 return RCPair(0U, &ARM::GPRRegClass);
14409 case 'h': // High regs or no regs.
14410 if (Subtarget->isThumb())
14411 return RCPair(0U, &ARM::hGPRRegClass);
14412 break;
14413 case 'r':
14414 if (Subtarget->isThumb1Only())
14415 return RCPair(0U, &ARM::tGPRRegClass);
14416 return RCPair(0U, &ARM::GPRRegClass);
14417 case 'w':
14418 if (VT == MVT::Other)
14419 break;
14420 if (VT == MVT::f32)
14421 return RCPair(0U, &ARM::SPRRegClass);
14422 if (VT.getSizeInBits() == 64)
14423 return RCPair(0U, &ARM::DPRRegClass);
14424 if (VT.getSizeInBits() == 128)
14425 return RCPair(0U, &ARM::QPRRegClass);
14426 break;
14427 case 'x':
14428 if (VT == MVT::Other)
14429 break;
14430 if (VT == MVT::f32)
14431 return RCPair(0U, &ARM::SPR_8RegClass);
14432 if (VT.getSizeInBits() == 64)
14433 return RCPair(0U, &ARM::DPR_8RegClass);
14434 if (VT.getSizeInBits() == 128)
14435 return RCPair(0U, &ARM::QPR_8RegClass);
14436 break;
14437 case 't':
14438 if (VT == MVT::Other)
14439 break;
14440 if (VT == MVT::f32 || VT == MVT::i32)
14441 return RCPair(0U, &ARM::SPRRegClass);
14442 if (VT.getSizeInBits() == 64)
14443 return RCPair(0U, &ARM::DPR_VFP2RegClass);
14444 if (VT.getSizeInBits() == 128)
14445 return RCPair(0U, &ARM::QPR_VFP2RegClass);
14446 break;
14448 break;
14450 case 2:
14451 if (Constraint[0] == 'T') {
14452 switch (Constraint[1]) {
14453 default:
14454 break;
14455 case 'e':
14456 return RCPair(0U, &ARM::tGPREvenRegClass);
14457 case 'o':
14458 return RCPair(0U, &ARM::tGPROddRegClass);
14461 break;
14463 default:
14464 break;
14467 if (StringRef("{cc}").equals_lower(Constraint))
14468 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
14470 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
14473 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14474 /// vector. If it is invalid, don't add anything to Ops.
14475 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14476 std::string &Constraint,
14477 std::vector<SDValue>&Ops,
14478 SelectionDAG &DAG) const {
14479 SDValue Result;
14481 // Currently only support length 1 constraints.
14482 if (Constraint.length() != 1) return;
14484 char ConstraintLetter = Constraint[0];
14485 switch (ConstraintLetter) {
14486 default: break;
14487 case 'j':
14488 case 'I': case 'J': case 'K': case 'L':
14489 case 'M': case 'N': case 'O':
14490 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
14491 if (!C)
14492 return;
14494 int64_t CVal64 = C->getSExtValue();
14495 int CVal = (int) CVal64;
14496 // None of these constraints allow values larger than 32 bits. Check
14497 // that the value fits in an int.
14498 if (CVal != CVal64)
14499 return;
14501 switch (ConstraintLetter) {
14502 case 'j':
14503 // Constant suitable for movw, must be between 0 and
14504 // 65535.
14505 if (Subtarget->hasV6T2Ops())
14506 if (CVal >= 0 && CVal <= 65535)
14507 break;
14508 return;
14509 case 'I':
14510 if (Subtarget->isThumb1Only()) {
14511 // This must be a constant between 0 and 255, for ADD
14512 // immediates.
14513 if (CVal >= 0 && CVal <= 255)
14514 break;
14515 } else if (Subtarget->isThumb2()) {
14516 // A constant that can be used as an immediate value in a
14517 // data-processing instruction.
14518 if (ARM_AM::getT2SOImmVal(CVal) != -1)
14519 break;
14520 } else {
14521 // A constant that can be used as an immediate value in a
14522 // data-processing instruction.
14523 if (ARM_AM::getSOImmVal(CVal) != -1)
14524 break;
14526 return;
14528 case 'J':
14529 if (Subtarget->isThumb1Only()) {
14530 // This must be a constant between -255 and -1, for negated ADD
14531 // immediates. This can be used in GCC with an "n" modifier that
14532 // prints the negated value, for use with SUB instructions. It is
14533 // not useful otherwise but is implemented for compatibility.
14534 if (CVal >= -255 && CVal <= -1)
14535 break;
14536 } else {
14537 // This must be a constant between -4095 and 4095. It is not clear
14538 // what this constraint is intended for. Implemented for
14539 // compatibility with GCC.
14540 if (CVal >= -4095 && CVal <= 4095)
14541 break;
14543 return;
14545 case 'K':
14546 if (Subtarget->isThumb1Only()) {
14547 // A 32-bit value where only one byte has a nonzero value. Exclude
14548 // zero to match GCC. This constraint is used by GCC internally for
14549 // constants that can be loaded with a move/shift combination.
14550 // It is not useful otherwise but is implemented for compatibility.
14551 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
14552 break;
14553 } else if (Subtarget->isThumb2()) {
14554 // A constant whose bitwise inverse can be used as an immediate
14555 // value in a data-processing instruction. This can be used in GCC
14556 // with a "B" modifier that prints the inverted value, for use with
14557 // BIC and MVN instructions. It is not useful otherwise but is
14558 // implemented for compatibility.
14559 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
14560 break;
14561 } else {
14562 // A constant whose bitwise inverse can be used as an immediate
14563 // value in a data-processing instruction. This can be used in GCC
14564 // with a "B" modifier that prints the inverted value, for use with
14565 // BIC and MVN instructions. It is not useful otherwise but is
14566 // implemented for compatibility.
14567 if (ARM_AM::getSOImmVal(~CVal) != -1)
14568 break;
14570 return;
14572 case 'L':
14573 if (Subtarget->isThumb1Only()) {
14574 // This must be a constant between -7 and 7,
14575 // for 3-operand ADD/SUB immediate instructions.
14576 if (CVal >= -7 && CVal < 7)
14577 break;
14578 } else if (Subtarget->isThumb2()) {
14579 // A constant whose negation can be used as an immediate value in a
14580 // data-processing instruction. This can be used in GCC with an "n"
14581 // modifier that prints the negated value, for use with SUB
14582 // instructions. It is not useful otherwise but is implemented for
14583 // compatibility.
14584 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
14585 break;
14586 } else {
14587 // A constant whose negation can be used as an immediate value in a
14588 // data-processing instruction. This can be used in GCC with an "n"
14589 // modifier that prints the negated value, for use with SUB
14590 // instructions. It is not useful otherwise but is implemented for
14591 // compatibility.
14592 if (ARM_AM::getSOImmVal(-CVal) != -1)
14593 break;
14595 return;
14597 case 'M':
14598 if (Subtarget->isThumb1Only()) {
14599 // This must be a multiple of 4 between 0 and 1020, for
14600 // ADD sp + immediate.
14601 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
14602 break;
14603 } else {
14604 // A power of two or a constant between 0 and 32. This is used in
14605 // GCC for the shift amount on shifted register operands, but it is
14606 // useful in general for any shift amounts.
14607 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
14608 break;
14610 return;
14612 case 'N':
14613 if (Subtarget->isThumb()) { // FIXME thumb2
14614 // This must be a constant between 0 and 31, for shift amounts.
14615 if (CVal >= 0 && CVal <= 31)
14616 break;
14618 return;
14620 case 'O':
14621 if (Subtarget->isThumb()) { // FIXME thumb2
14622 // This must be a multiple of 4 between -508 and 508, for
14623 // ADD/SUB sp = sp + immediate.
14624 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
14625 break;
14627 return;
14629 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
14630 break;
14633 if (Result.getNode()) {
14634 Ops.push_back(Result);
14635 return;
14637 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14640 static RTLIB::Libcall getDivRemLibcall(
14641 const SDNode *N, MVT::SimpleValueType SVT) {
14642 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
14643 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
14644 "Unhandled Opcode in getDivRemLibcall");
14645 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
14646 N->getOpcode() == ISD::SREM;
14647 RTLIB::Libcall LC;
14648 switch (SVT) {
14649 default: llvm_unreachable("Unexpected request for libcall!");
14650 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
14651 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
14652 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
14653 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
14655 return LC;
14658 static TargetLowering::ArgListTy getDivRemArgList(
14659 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
14660 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
14661 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
14662 "Unhandled Opcode in getDivRemArgList");
14663 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
14664 N->getOpcode() == ISD::SREM;
14665 TargetLowering::ArgListTy Args;
14666 TargetLowering::ArgListEntry Entry;
14667 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14668 EVT ArgVT = N->getOperand(i).getValueType();
14669 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
14670 Entry.Node = N->getOperand(i);
14671 Entry.Ty = ArgTy;
14672 Entry.IsSExt = isSigned;
14673 Entry.IsZExt = !isSigned;
14674 Args.push_back(Entry);
14676 if (Subtarget->isTargetWindows() && Args.size() >= 2)
14677 std::swap(Args[0], Args[1]);
14678 return Args;
14681 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
14682 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
14683 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
14684 Subtarget->isTargetWindows()) &&
14685 "Register-based DivRem lowering only");
14686 unsigned Opcode = Op->getOpcode();
14687 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
14688 "Invalid opcode for Div/Rem lowering");
14689 bool isSigned = (Opcode == ISD::SDIVREM);
14690 EVT VT = Op->getValueType(0);
14691 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
14692 SDLoc dl(Op);
14694 // If the target has hardware divide, use divide + multiply + subtract:
14695 // div = a / b
14696 // rem = a - b * div
14697 // return {div, rem}
14698 // This should be lowered into UDIV/SDIV + MLS later on.
14699 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
14700 : Subtarget->hasDivideInARMMode();
14701 if (hasDivide && Op->getValueType(0).isSimple() &&
14702 Op->getSimpleValueType(0) == MVT::i32) {
14703 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
14704 const SDValue Dividend = Op->getOperand(0);
14705 const SDValue Divisor = Op->getOperand(1);
14706 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
14707 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
14708 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
14710 SDValue Values[2] = {Div, Rem};
14711 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
14714 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
14715 VT.getSimpleVT().SimpleTy);
14716 SDValue InChain = DAG.getEntryNode();
14718 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
14719 DAG.getContext(),
14720 Subtarget);
14722 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
14723 getPointerTy(DAG.getDataLayout()));
14725 Type *RetTy = StructType::get(Ty, Ty);
14727 if (Subtarget->isTargetWindows())
14728 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
14730 TargetLowering::CallLoweringInfo CLI(DAG);
14731 CLI.setDebugLoc(dl).setChain(InChain)
14732 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
14733 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
14735 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
14736 return CallInfo.first;
14739 // Lowers REM using divmod helpers
14740 // see RTABI section 4.2/4.3
14741 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
14742 // Build return types (div and rem)
14743 std::vector<Type*> RetTyParams;
14744 Type *RetTyElement;
14746 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
14747 default: llvm_unreachable("Unexpected request for libcall!");
14748 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
14749 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
14750 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
14751 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
14754 RetTyParams.push_back(RetTyElement);
14755 RetTyParams.push_back(RetTyElement);
14756 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
14757 Type *RetTy = StructType::get(*DAG.getContext(), ret);
14759 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
14760 SimpleTy);
14761 SDValue InChain = DAG.getEntryNode();
14762 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
14763 Subtarget);
14764 bool isSigned = N->getOpcode() == ISD::SREM;
14765 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
14766 getPointerTy(DAG.getDataLayout()));
14768 if (Subtarget->isTargetWindows())
14769 InChain = WinDBZCheckDenominator(DAG, N, InChain);
14771 // Lower call
14772 CallLoweringInfo CLI(DAG);
14773 CLI.setChain(InChain)
14774 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
14775 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
14776 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
14778 // Return second (rem) result operand (first contains div)
14779 SDNode *ResNode = CallResult.first.getNode();
14780 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
14781 return ResNode->getOperand(1);
14784 SDValue
14785 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
14786 assert(Subtarget->isTargetWindows() && "unsupported target platform");
14787 SDLoc DL(Op);
14789 // Get the inputs.
14790 SDValue Chain = Op.getOperand(0);
14791 SDValue Size = Op.getOperand(1);
14793 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
14794 "no-stack-arg-probe")) {
14795 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14796 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
14797 Chain = SP.getValue(1);
14798 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
14799 if (Align)
14800 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
14801 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32));
14802 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
14803 SDValue Ops[2] = { SP, Chain };
14804 return DAG.getMergeValues(Ops, DL);
14807 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
14808 DAG.getConstant(2, DL, MVT::i32));
14810 SDValue Flag;
14811 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
14812 Flag = Chain.getValue(1);
14814 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14815 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
14817 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
14818 Chain = NewSP.getValue(1);
14820 SDValue Ops[2] = { NewSP, Chain };
14821 return DAG.getMergeValues(Ops, DL);
14824 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
14825 SDValue SrcVal = Op.getOperand(0);
14826 const unsigned DstSz = Op.getValueType().getSizeInBits();
14827 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
14828 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
14829 "Unexpected type for custom-lowering FP_EXTEND");
14831 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
14832 "With both FP DP and 16, any FP conversion is legal!");
14834 assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
14835 "With FP16, 16 to 32 conversion is legal!");
14837 // Either we are converting from 16 -> 64, without FP16 and/or
14838 // FP.double-precision or without Armv8-fp. So we must do it in two
14839 // steps.
14840 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
14841 // without FP16. So we must do a function call.
14842 SDLoc Loc(Op);
14843 RTLIB::Libcall LC;
14844 if (SrcSz == 16) {
14845 // Instruction from 16 -> 32
14846 if (Subtarget->hasFP16())
14847 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f32, SrcVal);
14848 // Lib call from 16 -> 32
14849 else {
14850 LC = RTLIB::getFPEXT(MVT::f16, MVT::f32);
14851 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
14852 "Unexpected type for custom-lowering FP_EXTEND");
14853 SrcVal =
14854 makeLibCall(DAG, LC, MVT::f32, SrcVal, /*isSigned*/ false, Loc).first;
14858 if (DstSz != 64)
14859 return SrcVal;
14860 // For sure now SrcVal is 32 bits
14861 if (Subtarget->hasFP64()) // Instruction from 32 -> 64
14862 return DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f64, SrcVal);
14864 LC = RTLIB::getFPEXT(MVT::f32, MVT::f64);
14865 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
14866 "Unexpected type for custom-lowering FP_EXTEND");
14867 return makeLibCall(DAG, LC, MVT::f64, SrcVal, /*isSigned*/ false, Loc).first;
14870 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
14871 SDValue SrcVal = Op.getOperand(0);
14872 EVT SrcVT = SrcVal.getValueType();
14873 EVT DstVT = Op.getValueType();
14874 const unsigned DstSz = Op.getValueType().getSizeInBits();
14875 const unsigned SrcSz = SrcVT.getSizeInBits();
14876 (void)DstSz;
14877 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
14878 "Unexpected type for custom-lowering FP_ROUND");
14880 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
14881 "With both FP DP and 16, any FP conversion is legal!");
14883 SDLoc Loc(Op);
14885 // Instruction from 32 -> 16 if hasFP16 is valid
14886 if (SrcSz == 32 && Subtarget->hasFP16())
14887 return Op;
14889 // Lib call from 32 -> 16 / 64 -> [32, 16]
14890 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
14891 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
14892 "Unexpected type for custom-lowering FP_ROUND");
14893 return makeLibCall(DAG, LC, DstVT, SrcVal, /*isSigned*/ false, Loc).first;
14896 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
14897 SelectionDAG &DAG) const {
14898 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.");
14899 MVT HalfT = MVT::i32;
14900 SDLoc dl(N);
14901 SDValue Hi, Lo, Tmp;
14903 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
14904 !isOperationLegalOrCustom(ISD::UADDO, HalfT))
14905 return ;
14907 unsigned OpTypeBits = HalfT.getScalarSizeInBits();
14908 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
14910 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
14911 DAG.getConstant(0, dl, HalfT));
14912 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
14913 DAG.getConstant(1, dl, HalfT));
14915 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
14916 DAG.getConstant(OpTypeBits - 1, dl,
14917 getShiftAmountTy(HalfT, DAG.getDataLayout())));
14918 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
14919 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
14920 SDValue(Lo.getNode(), 1));
14921 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
14922 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
14924 Results.push_back(Lo);
14925 Results.push_back(Hi);
14928 bool
14929 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
14930 // The ARM target isn't yet aware of offsets.
14931 return false;
14934 bool ARM::isBitFieldInvertedMask(unsigned v) {
14935 if (v == 0xffffffff)
14936 return false;
14938 // there can be 1's on either or both "outsides", all the "inside"
14939 // bits must be 0's
14940 return isShiftedMask_32(~v);
14943 /// isFPImmLegal - Returns true if the target can instruction select the
14944 /// specified FP immediate natively. If false, the legalizer will
14945 /// materialize the FP immediate as a load from a constant pool.
14946 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
14947 bool ForCodeSize) const {
14948 if (!Subtarget->hasVFP3Base())
14949 return false;
14950 if (VT == MVT::f16 && Subtarget->hasFullFP16())
14951 return ARM_AM::getFP16Imm(Imm) != -1;
14952 if (VT == MVT::f32)
14953 return ARM_AM::getFP32Imm(Imm) != -1;
14954 if (VT == MVT::f64 && Subtarget->hasFP64())
14955 return ARM_AM::getFP64Imm(Imm) != -1;
14956 return false;
14959 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
14960 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
14961 /// specified in the intrinsic calls.
14962 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
14963 const CallInst &I,
14964 MachineFunction &MF,
14965 unsigned Intrinsic) const {
14966 switch (Intrinsic) {
14967 case Intrinsic::arm_neon_vld1:
14968 case Intrinsic::arm_neon_vld2:
14969 case Intrinsic::arm_neon_vld3:
14970 case Intrinsic::arm_neon_vld4:
14971 case Intrinsic::arm_neon_vld2lane:
14972 case Intrinsic::arm_neon_vld3lane:
14973 case Intrinsic::arm_neon_vld4lane:
14974 case Intrinsic::arm_neon_vld2dup:
14975 case Intrinsic::arm_neon_vld3dup:
14976 case Intrinsic::arm_neon_vld4dup: {
14977 Info.opc = ISD::INTRINSIC_W_CHAIN;
14978 // Conservatively set memVT to the entire set of vectors loaded.
14979 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14980 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
14981 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14982 Info.ptrVal = I.getArgOperand(0);
14983 Info.offset = 0;
14984 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
14985 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
14986 // volatile loads with NEON intrinsics not supported
14987 Info.flags = MachineMemOperand::MOLoad;
14988 return true;
14990 case Intrinsic::arm_neon_vld1x2:
14991 case Intrinsic::arm_neon_vld1x3:
14992 case Intrinsic::arm_neon_vld1x4: {
14993 Info.opc = ISD::INTRINSIC_W_CHAIN;
14994 // Conservatively set memVT to the entire set of vectors loaded.
14995 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14996 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
14997 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14998 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
14999 Info.offset = 0;
15000 Info.align = 0;
15001 // volatile loads with NEON intrinsics not supported
15002 Info.flags = MachineMemOperand::MOLoad;
15003 return true;
15005 case Intrinsic::arm_neon_vst1:
15006 case Intrinsic::arm_neon_vst2:
15007 case Intrinsic::arm_neon_vst3:
15008 case Intrinsic::arm_neon_vst4:
15009 case Intrinsic::arm_neon_vst2lane:
15010 case Intrinsic::arm_neon_vst3lane:
15011 case Intrinsic::arm_neon_vst4lane: {
15012 Info.opc = ISD::INTRINSIC_VOID;
15013 // Conservatively set memVT to the entire set of vectors stored.
15014 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15015 unsigned NumElts = 0;
15016 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
15017 Type *ArgTy = I.getArgOperand(ArgI)->getType();
15018 if (!ArgTy->isVectorTy())
15019 break;
15020 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
15022 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15023 Info.ptrVal = I.getArgOperand(0);
15024 Info.offset = 0;
15025 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
15026 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
15027 // volatile stores with NEON intrinsics not supported
15028 Info.flags = MachineMemOperand::MOStore;
15029 return true;
15031 case Intrinsic::arm_neon_vst1x2:
15032 case Intrinsic::arm_neon_vst1x3:
15033 case Intrinsic::arm_neon_vst1x4: {
15034 Info.opc = ISD::INTRINSIC_VOID;
15035 // Conservatively set memVT to the entire set of vectors stored.
15036 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15037 unsigned NumElts = 0;
15038 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
15039 Type *ArgTy = I.getArgOperand(ArgI)->getType();
15040 if (!ArgTy->isVectorTy())
15041 break;
15042 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
15044 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15045 Info.ptrVal = I.getArgOperand(0);
15046 Info.offset = 0;
15047 Info.align = 0;
15048 // volatile stores with NEON intrinsics not supported
15049 Info.flags = MachineMemOperand::MOStore;
15050 return true;
15052 case Intrinsic::arm_ldaex:
15053 case Intrinsic::arm_ldrex: {
15054 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15055 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
15056 Info.opc = ISD::INTRINSIC_W_CHAIN;
15057 Info.memVT = MVT::getVT(PtrTy->getElementType());
15058 Info.ptrVal = I.getArgOperand(0);
15059 Info.offset = 0;
15060 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
15061 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
15062 return true;
15064 case Intrinsic::arm_stlex:
15065 case Intrinsic::arm_strex: {
15066 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15067 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
15068 Info.opc = ISD::INTRINSIC_W_CHAIN;
15069 Info.memVT = MVT::getVT(PtrTy->getElementType());
15070 Info.ptrVal = I.getArgOperand(1);
15071 Info.offset = 0;
15072 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
15073 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
15074 return true;
15076 case Intrinsic::arm_stlexd:
15077 case Intrinsic::arm_strexd:
15078 Info.opc = ISD::INTRINSIC_W_CHAIN;
15079 Info.memVT = MVT::i64;
15080 Info.ptrVal = I.getArgOperand(2);
15081 Info.offset = 0;
15082 Info.align = 8;
15083 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
15084 return true;
15086 case Intrinsic::arm_ldaexd:
15087 case Intrinsic::arm_ldrexd:
15088 Info.opc = ISD::INTRINSIC_W_CHAIN;
15089 Info.memVT = MVT::i64;
15090 Info.ptrVal = I.getArgOperand(0);
15091 Info.offset = 0;
15092 Info.align = 8;
15093 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
15094 return true;
15096 default:
15097 break;
15100 return false;
15103 /// Returns true if it is beneficial to convert a load of a constant
15104 /// to just the constant itself.
15105 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15106 Type *Ty) const {
15107 assert(Ty->isIntegerTy());
15109 unsigned Bits = Ty->getPrimitiveSizeInBits();
15110 if (Bits == 0 || Bits > 32)
15111 return false;
15112 return true;
15115 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
15116 unsigned Index) const {
15117 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
15118 return false;
15120 return (Index == 0 || Index == ResVT.getVectorNumElements());
15123 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
15124 ARM_MB::MemBOpt Domain) const {
15125 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15127 // First, if the target has no DMB, see what fallback we can use.
15128 if (!Subtarget->hasDataBarrier()) {
15129 // Some ARMv6 cpus can support data barriers with an mcr instruction.
15130 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
15131 // here.
15132 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
15133 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
15134 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
15135 Builder.getInt32(0), Builder.getInt32(7),
15136 Builder.getInt32(10), Builder.getInt32(5)};
15137 return Builder.CreateCall(MCR, args);
15138 } else {
15139 // Instead of using barriers, atomic accesses on these subtargets use
15140 // libcalls.
15141 llvm_unreachable("makeDMB on a target so old that it has no barriers");
15143 } else {
15144 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
15145 // Only a full system barrier exists in the M-class architectures.
15146 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
15147 Constant *CDomain = Builder.getInt32(Domain);
15148 return Builder.CreateCall(DMB, CDomain);
15152 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
15153 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
15154 Instruction *Inst,
15155 AtomicOrdering Ord) const {
15156 switch (Ord) {
15157 case AtomicOrdering::NotAtomic:
15158 case AtomicOrdering::Unordered:
15159 llvm_unreachable("Invalid fence: unordered/non-atomic");
15160 case AtomicOrdering::Monotonic:
15161 case AtomicOrdering::Acquire:
15162 return nullptr; // Nothing to do
15163 case AtomicOrdering::SequentiallyConsistent:
15164 if (!Inst->hasAtomicStore())
15165 return nullptr; // Nothing to do
15166 LLVM_FALLTHROUGH;
15167 case AtomicOrdering::Release:
15168 case AtomicOrdering::AcquireRelease:
15169 if (Subtarget->preferISHSTBarriers())
15170 return makeDMB(Builder, ARM_MB::ISHST);
15171 // FIXME: add a comment with a link to documentation justifying this.
15172 else
15173 return makeDMB(Builder, ARM_MB::ISH);
15175 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
15178 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
15179 Instruction *Inst,
15180 AtomicOrdering Ord) const {
15181 switch (Ord) {
15182 case AtomicOrdering::NotAtomic:
15183 case AtomicOrdering::Unordered:
15184 llvm_unreachable("Invalid fence: unordered/not-atomic");
15185 case AtomicOrdering::Monotonic:
15186 case AtomicOrdering::Release:
15187 return nullptr; // Nothing to do
15188 case AtomicOrdering::Acquire:
15189 case AtomicOrdering::AcquireRelease:
15190 case AtomicOrdering::SequentiallyConsistent:
15191 return makeDMB(Builder, ARM_MB::ISH);
15193 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
15196 // Loads and stores less than 64-bits are already atomic; ones above that
15197 // are doomed anyway, so defer to the default libcall and blame the OS when
15198 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
15199 // anything for those.
15200 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
15201 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
15202 return (Size == 64) && !Subtarget->isMClass();
15205 // Loads and stores less than 64-bits are already atomic; ones above that
15206 // are doomed anyway, so defer to the default libcall and blame the OS when
15207 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
15208 // anything for those.
15209 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
15210 // guarantee, see DDI0406C ARM architecture reference manual,
15211 // sections A8.8.72-74 LDRD)
15212 TargetLowering::AtomicExpansionKind
15213 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
15214 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
15215 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
15216 : AtomicExpansionKind::None;
15219 // For the real atomic operations, we have ldrex/strex up to 32 bits,
15220 // and up to 64 bits on the non-M profiles
15221 TargetLowering::AtomicExpansionKind
15222 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
15223 if (AI->isFloatingPointOperation())
15224 return AtomicExpansionKind::CmpXChg;
15226 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
15227 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
15228 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
15229 ? AtomicExpansionKind::LLSC
15230 : AtomicExpansionKind::None;
15233 TargetLowering::AtomicExpansionKind
15234 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
15235 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
15236 // implement cmpxchg without spilling. If the address being exchanged is also
15237 // on the stack and close enough to the spill slot, this can lead to a
15238 // situation where the monitor always gets cleared and the atomic operation
15239 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
15240 bool HasAtomicCmpXchg =
15241 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
15242 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
15243 return AtomicExpansionKind::LLSC;
15244 return AtomicExpansionKind::None;
15247 bool ARMTargetLowering::shouldInsertFencesForAtomic(
15248 const Instruction *I) const {
15249 return InsertFencesForAtomic;
15252 // This has so far only been implemented for MachO.
15253 bool ARMTargetLowering::useLoadStackGuardNode() const {
15254 return Subtarget->isTargetMachO();
15257 void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
15258 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
15259 return TargetLowering::insertSSPDeclarations(M);
15261 // MSVC CRT has a global variable holding security cookie.
15262 M.getOrInsertGlobal("__security_cookie",
15263 Type::getInt8PtrTy(M.getContext()));
15265 // MSVC CRT has a function to validate security cookie.
15266 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
15267 "__security_check_cookie", Type::getVoidTy(M.getContext()),
15268 Type::getInt8PtrTy(M.getContext()));
15269 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
15270 F->addAttribute(1, Attribute::AttrKind::InReg);
15273 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
15274 // MSVC CRT has a global variable holding security cookie.
15275 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
15276 return M.getGlobalVariable("__security_cookie");
15277 return TargetLowering::getSDagStackGuard(M);
15280 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
15281 // MSVC CRT has a function to validate security cookie.
15282 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
15283 return M.getFunction("__security_check_cookie");
15284 return TargetLowering::getSSPStackGuardCheck(M);
15287 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
15288 unsigned &Cost) const {
15289 // If we do not have NEON, vector types are not natively supported.
15290 if (!Subtarget->hasNEON())
15291 return false;
15293 // Floating point values and vector values map to the same register file.
15294 // Therefore, although we could do a store extract of a vector type, this is
15295 // better to leave at float as we have more freedom in the addressing mode for
15296 // those.
15297 if (VectorTy->isFPOrFPVectorTy())
15298 return false;
15300 // If the index is unknown at compile time, this is very expensive to lower
15301 // and it is not possible to combine the store with the extract.
15302 if (!isa<ConstantInt>(Idx))
15303 return false;
15305 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
15306 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
15307 // We can do a store + vector extract on any vector that fits perfectly in a D
15308 // or Q register.
15309 if (BitWidth == 64 || BitWidth == 128) {
15310 Cost = 0;
15311 return true;
15313 return false;
15316 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
15317 return Subtarget->hasV6T2Ops();
15320 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
15321 return Subtarget->hasV6T2Ops();
15324 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
15325 return !Subtarget->hasMinSize();
15328 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
15329 AtomicOrdering Ord) const {
15330 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15331 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
15332 bool IsAcquire = isAcquireOrStronger(Ord);
15334 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
15335 // intrinsic must return {i32, i32} and we have to recombine them into a
15336 // single i64 here.
15337 if (ValTy->getPrimitiveSizeInBits() == 64) {
15338 Intrinsic::ID Int =
15339 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
15340 Function *Ldrex = Intrinsic::getDeclaration(M, Int);
15342 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
15343 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
15345 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
15346 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
15347 if (!Subtarget->isLittle())
15348 std::swap (Lo, Hi);
15349 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
15350 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
15351 return Builder.CreateOr(
15352 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
15355 Type *Tys[] = { Addr->getType() };
15356 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
15357 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
15359 return Builder.CreateTruncOrBitCast(
15360 Builder.CreateCall(Ldrex, Addr),
15361 cast<PointerType>(Addr->getType())->getElementType());
15364 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
15365 IRBuilder<> &Builder) const {
15366 if (!Subtarget->hasV7Ops())
15367 return;
15368 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15369 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
15372 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
15373 Value *Addr,
15374 AtomicOrdering Ord) const {
15375 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15376 bool IsRelease = isReleaseOrStronger(Ord);
15378 // Since the intrinsics must have legal type, the i64 intrinsics take two
15379 // parameters: "i32, i32". We must marshal Val into the appropriate form
15380 // before the call.
15381 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
15382 Intrinsic::ID Int =
15383 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
15384 Function *Strex = Intrinsic::getDeclaration(M, Int);
15385 Type *Int32Ty = Type::getInt32Ty(M->getContext());
15387 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
15388 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
15389 if (!Subtarget->isLittle())
15390 std::swap(Lo, Hi);
15391 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
15392 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
15395 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
15396 Type *Tys[] = { Addr->getType() };
15397 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
15399 return Builder.CreateCall(
15400 Strex, {Builder.CreateZExtOrBitCast(
15401 Val, Strex->getFunctionType()->getParamType(0)),
15402 Addr});
15406 bool ARMTargetLowering::alignLoopsWithOptSize() const {
15407 return Subtarget->isMClass();
15410 /// A helper function for determining the number of interleaved accesses we
15411 /// will generate when lowering accesses of the given type.
15412 unsigned
15413 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
15414 const DataLayout &DL) const {
15415 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
15418 bool ARMTargetLowering::isLegalInterleavedAccessType(
15419 VectorType *VecTy, const DataLayout &DL) const {
15421 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
15422 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
15424 // Ensure the vector doesn't have f16 elements. Even though we could do an
15425 // i16 vldN, we can't hold the f16 vectors and will end up converting via
15426 // f32.
15427 if (VecTy->getElementType()->isHalfTy())
15428 return false;
15430 // Ensure the number of vector elements is greater than 1.
15431 if (VecTy->getNumElements() < 2)
15432 return false;
15434 // Ensure the element type is legal.
15435 if (ElSize != 8 && ElSize != 16 && ElSize != 32)
15436 return false;
15438 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
15439 // 128 will be split into multiple interleaved accesses.
15440 return VecSize == 64 || VecSize % 128 == 0;
15443 /// Lower an interleaved load into a vldN intrinsic.
15445 /// E.g. Lower an interleaved load (Factor = 2):
15446 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
15447 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
15448 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
15450 /// Into:
15451 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
15452 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
15453 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
15454 bool ARMTargetLowering::lowerInterleavedLoad(
15455 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
15456 ArrayRef<unsigned> Indices, unsigned Factor) const {
15457 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
15458 "Invalid interleave factor");
15459 assert(!Shuffles.empty() && "Empty shufflevector input");
15460 assert(Shuffles.size() == Indices.size() &&
15461 "Unmatched number of shufflevectors and indices");
15463 VectorType *VecTy = Shuffles[0]->getType();
15464 Type *EltTy = VecTy->getVectorElementType();
15466 const DataLayout &DL = LI->getModule()->getDataLayout();
15468 // Skip if we do not have NEON and skip illegal vector types. We can
15469 // "legalize" wide vector types into multiple interleaved accesses as long as
15470 // the vector types are divisible by 128.
15471 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
15472 return false;
15474 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
15476 // A pointer vector can not be the return type of the ldN intrinsics. Need to
15477 // load integer vectors first and then convert to pointer vectors.
15478 if (EltTy->isPointerTy())
15479 VecTy =
15480 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
15482 IRBuilder<> Builder(LI);
15484 // The base address of the load.
15485 Value *BaseAddr = LI->getPointerOperand();
15487 if (NumLoads > 1) {
15488 // If we're going to generate more than one load, reset the sub-vector type
15489 // to something legal.
15490 VecTy = VectorType::get(VecTy->getVectorElementType(),
15491 VecTy->getVectorNumElements() / NumLoads);
15493 // We will compute the pointer operand of each load from the original base
15494 // address using GEPs. Cast the base address to a pointer to the scalar
15495 // element type.
15496 BaseAddr = Builder.CreateBitCast(
15497 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
15498 LI->getPointerAddressSpace()));
15501 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
15503 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
15504 Type *Tys[] = {VecTy, Int8Ptr};
15505 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
15506 Intrinsic::arm_neon_vld3,
15507 Intrinsic::arm_neon_vld4};
15508 Function *VldnFunc =
15509 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
15511 // Holds sub-vectors extracted from the load intrinsic return values. The
15512 // sub-vectors are associated with the shufflevector instructions they will
15513 // replace.
15514 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
15516 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
15517 // If we're generating more than one load, compute the base address of
15518 // subsequent loads as an offset from the previous.
15519 if (LoadCount > 0)
15520 BaseAddr =
15521 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
15522 VecTy->getVectorNumElements() * Factor);
15524 SmallVector<Value *, 2> Ops;
15525 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
15526 Ops.push_back(Builder.getInt32(LI->getAlignment()));
15528 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
15530 // Replace uses of each shufflevector with the corresponding vector loaded
15531 // by ldN.
15532 for (unsigned i = 0; i < Shuffles.size(); i++) {
15533 ShuffleVectorInst *SV = Shuffles[i];
15534 unsigned Index = Indices[i];
15536 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
15538 // Convert the integer vector to pointer vector if the element is pointer.
15539 if (EltTy->isPointerTy())
15540 SubVec = Builder.CreateIntToPtr(
15541 SubVec, VectorType::get(SV->getType()->getVectorElementType(),
15542 VecTy->getVectorNumElements()));
15544 SubVecs[SV].push_back(SubVec);
15548 // Replace uses of the shufflevector instructions with the sub-vectors
15549 // returned by the load intrinsic. If a shufflevector instruction is
15550 // associated with more than one sub-vector, those sub-vectors will be
15551 // concatenated into a single wide vector.
15552 for (ShuffleVectorInst *SVI : Shuffles) {
15553 auto &SubVec = SubVecs[SVI];
15554 auto *WideVec =
15555 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
15556 SVI->replaceAllUsesWith(WideVec);
15559 return true;
15562 /// Lower an interleaved store into a vstN intrinsic.
15564 /// E.g. Lower an interleaved store (Factor = 3):
15565 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
15566 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
15567 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
15569 /// Into:
15570 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
15571 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
15572 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
15573 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
15575 /// Note that the new shufflevectors will be removed and we'll only generate one
15576 /// vst3 instruction in CodeGen.
15578 /// Example for a more general valid mask (Factor 3). Lower:
15579 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
15580 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
15581 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
15583 /// Into:
15584 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
15585 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
15586 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
15587 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
15588 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
15589 ShuffleVectorInst *SVI,
15590 unsigned Factor) const {
15591 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
15592 "Invalid interleave factor");
15594 VectorType *VecTy = SVI->getType();
15595 assert(VecTy->getVectorNumElements() % Factor == 0 &&
15596 "Invalid interleaved store");
15598 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
15599 Type *EltTy = VecTy->getVectorElementType();
15600 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
15602 const DataLayout &DL = SI->getModule()->getDataLayout();
15604 // Skip if we do not have NEON and skip illegal vector types. We can
15605 // "legalize" wide vector types into multiple interleaved accesses as long as
15606 // the vector types are divisible by 128.
15607 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
15608 return false;
15610 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
15612 Value *Op0 = SVI->getOperand(0);
15613 Value *Op1 = SVI->getOperand(1);
15614 IRBuilder<> Builder(SI);
15616 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
15617 // vectors to integer vectors.
15618 if (EltTy->isPointerTy()) {
15619 Type *IntTy = DL.getIntPtrType(EltTy);
15621 // Convert to the corresponding integer vector.
15622 Type *IntVecTy =
15623 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
15624 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
15625 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
15627 SubVecTy = VectorType::get(IntTy, LaneLen);
15630 // The base address of the store.
15631 Value *BaseAddr = SI->getPointerOperand();
15633 if (NumStores > 1) {
15634 // If we're going to generate more than one store, reset the lane length
15635 // and sub-vector type to something legal.
15636 LaneLen /= NumStores;
15637 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
15639 // We will compute the pointer operand of each store from the original base
15640 // address using GEPs. Cast the base address to a pointer to the scalar
15641 // element type.
15642 BaseAddr = Builder.CreateBitCast(
15643 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
15644 SI->getPointerAddressSpace()));
15647 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
15649 auto Mask = SVI->getShuffleMask();
15651 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
15652 Type *Tys[] = {Int8Ptr, SubVecTy};
15653 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
15654 Intrinsic::arm_neon_vst3,
15655 Intrinsic::arm_neon_vst4};
15657 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
15658 // If we generating more than one store, we compute the base address of
15659 // subsequent stores as an offset from the previous.
15660 if (StoreCount > 0)
15661 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
15662 BaseAddr, LaneLen * Factor);
15664 SmallVector<Value *, 6> Ops;
15665 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
15667 Function *VstNFunc =
15668 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
15670 // Split the shufflevector operands into sub vectors for the new vstN call.
15671 for (unsigned i = 0; i < Factor; i++) {
15672 unsigned IdxI = StoreCount * LaneLen * Factor + i;
15673 if (Mask[IdxI] >= 0) {
15674 Ops.push_back(Builder.CreateShuffleVector(
15675 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
15676 } else {
15677 unsigned StartMask = 0;
15678 for (unsigned j = 1; j < LaneLen; j++) {
15679 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
15680 if (Mask[IdxJ * Factor + IdxI] >= 0) {
15681 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
15682 break;
15685 // Note: If all elements in a chunk are undefs, StartMask=0!
15686 // Note: Filling undef gaps with random elements is ok, since
15687 // those elements were being written anyway (with undefs).
15688 // In the case of all undefs we're defaulting to using elems from 0
15689 // Note: StartMask cannot be negative, it's checked in
15690 // isReInterleaveMask
15691 Ops.push_back(Builder.CreateShuffleVector(
15692 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
15696 Ops.push_back(Builder.getInt32(SI->getAlignment()));
15697 Builder.CreateCall(VstNFunc, Ops);
15699 return true;
15702 enum HABaseType {
15703 HA_UNKNOWN = 0,
15704 HA_FLOAT,
15705 HA_DOUBLE,
15706 HA_VECT64,
15707 HA_VECT128
15710 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
15711 uint64_t &Members) {
15712 if (auto *ST = dyn_cast<StructType>(Ty)) {
15713 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
15714 uint64_t SubMembers = 0;
15715 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
15716 return false;
15717 Members += SubMembers;
15719 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
15720 uint64_t SubMembers = 0;
15721 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
15722 return false;
15723 Members += SubMembers * AT->getNumElements();
15724 } else if (Ty->isFloatTy()) {
15725 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
15726 return false;
15727 Members = 1;
15728 Base = HA_FLOAT;
15729 } else if (Ty->isDoubleTy()) {
15730 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
15731 return false;
15732 Members = 1;
15733 Base = HA_DOUBLE;
15734 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
15735 Members = 1;
15736 switch (Base) {
15737 case HA_FLOAT:
15738 case HA_DOUBLE:
15739 return false;
15740 case HA_VECT64:
15741 return VT->getBitWidth() == 64;
15742 case HA_VECT128:
15743 return VT->getBitWidth() == 128;
15744 case HA_UNKNOWN:
15745 switch (VT->getBitWidth()) {
15746 case 64:
15747 Base = HA_VECT64;
15748 return true;
15749 case 128:
15750 Base = HA_VECT128;
15751 return true;
15752 default:
15753 return false;
15758 return (Members > 0 && Members <= 4);
15761 /// Return the correct alignment for the current calling convention.
15762 unsigned
15763 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
15764 DataLayout DL) const {
15765 if (!ArgTy->isVectorTy())
15766 return DL.getABITypeAlignment(ArgTy);
15768 // Avoid over-aligning vector parameters. It would require realigning the
15769 // stack and waste space for no real benefit.
15770 return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment());
15773 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
15774 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
15775 /// passing according to AAPCS rules.
15776 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
15777 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
15778 if (getEffectiveCallingConv(CallConv, isVarArg) !=
15779 CallingConv::ARM_AAPCS_VFP)
15780 return false;
15782 HABaseType Base = HA_UNKNOWN;
15783 uint64_t Members = 0;
15784 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
15785 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
15787 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
15788 return IsHA || IsIntArray;
15791 unsigned ARMTargetLowering::getExceptionPointerRegister(
15792 const Constant *PersonalityFn) const {
15793 // Platforms which do not use SjLj EH may return values in these registers
15794 // via the personality function.
15795 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
15798 unsigned ARMTargetLowering::getExceptionSelectorRegister(
15799 const Constant *PersonalityFn) const {
15800 // Platforms which do not use SjLj EH may return values in these registers
15801 // via the personality function.
15802 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
15805 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15806 // Update IsSplitCSR in ARMFunctionInfo.
15807 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
15808 AFI->setIsSplitCSR(true);
15811 void ARMTargetLowering::insertCopiesSplitCSR(
15812 MachineBasicBlock *Entry,
15813 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15814 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
15815 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15816 if (!IStart)
15817 return;
15819 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
15820 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15821 MachineBasicBlock::iterator MBBI = Entry->begin();
15822 for (const MCPhysReg *I = IStart; *I; ++I) {
15823 const TargetRegisterClass *RC = nullptr;
15824 if (ARM::GPRRegClass.contains(*I))
15825 RC = &ARM::GPRRegClass;
15826 else if (ARM::DPRRegClass.contains(*I))
15827 RC = &ARM::DPRRegClass;
15828 else
15829 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15831 unsigned NewVR = MRI->createVirtualRegister(RC);
15832 // Create copy from CSR to a virtual register.
15833 // FIXME: this currently does not emit CFI pseudo-instructions, it works
15834 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15835 // nounwind. If we want to generalize this later, we may need to emit
15836 // CFI pseudo-instructions.
15837 assert(Entry->getParent()->getFunction().hasFnAttribute(
15838 Attribute::NoUnwind) &&
15839 "Function should be nounwind in insertCopiesSplitCSR!");
15840 Entry->addLiveIn(*I);
15841 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15842 .addReg(*I);
15844 // Insert the copy-back instructions right before the terminator.
15845 for (auto *Exit : Exits)
15846 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15847 TII->get(TargetOpcode::COPY), *I)
15848 .addReg(NewVR);
15852 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
15853 MF.getFrameInfo().computeMaxCallFrameSize(MF);
15854 TargetLoweringBase::finalizeLowering(MF);