Bug Summary

File:llvm/lib/Target/ARM/ARMISelLowering.cpp
Warning:line 7136, column 18
Division by zero

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ARMISelLowering.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/lib/Target/ARM -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/lib/Target/ARM -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/lib/Target/ARM -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0=. -ferror-limit 19 -fvisibility hidden -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-08-28-193554-24367-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp

/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp

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.
11//
12//===----------------------------------------------------------------------===//
13
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 "ARMTargetTransformInfo.h"
25#include "MCTargetDesc/ARMAddressingModes.h"
26#include "MCTargetDesc/ARMBaseInfo.h"
27#include "Utils/ARMBaseInfo.h"
28#include "llvm/ADT/APFloat.h"
29#include "llvm/ADT/APInt.h"
30#include "llvm/ADT/ArrayRef.h"
31#include "llvm/ADT/BitVector.h"
32#include "llvm/ADT/DenseMap.h"
33#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/SmallPtrSet.h"
35#include "llvm/ADT/SmallVector.h"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/ADT/StringExtras.h"
38#include "llvm/ADT/StringRef.h"
39#include "llvm/ADT/StringSwitch.h"
40#include "llvm/ADT/Triple.h"
41#include "llvm/ADT/Twine.h"
42#include "llvm/Analysis/VectorUtils.h"
43#include "llvm/CodeGen/CallingConvLower.h"
44#include "llvm/CodeGen/ISDOpcodes.h"
45#include "llvm/CodeGen/IntrinsicLowering.h"
46#include "llvm/CodeGen/MachineBasicBlock.h"
47#include "llvm/CodeGen/MachineConstantPool.h"
48#include "llvm/CodeGen/MachineFrameInfo.h"
49#include "llvm/CodeGen/MachineFunction.h"
50#include "llvm/CodeGen/MachineInstr.h"
51#include "llvm/CodeGen/MachineInstrBuilder.h"
52#include "llvm/CodeGen/MachineJumpTableInfo.h"
53#include "llvm/CodeGen/MachineMemOperand.h"
54#include "llvm/CodeGen/MachineOperand.h"
55#include "llvm/CodeGen/MachineRegisterInfo.h"
56#include "llvm/CodeGen/RuntimeLibcalls.h"
57#include "llvm/CodeGen/SelectionDAG.h"
58#include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
59#include "llvm/CodeGen/SelectionDAGNodes.h"
60#include "llvm/CodeGen/TargetInstrInfo.h"
61#include "llvm/CodeGen/TargetLowering.h"
62#include "llvm/CodeGen/TargetOpcodes.h"
63#include "llvm/CodeGen/TargetRegisterInfo.h"
64#include "llvm/CodeGen/TargetSubtargetInfo.h"
65#include "llvm/CodeGen/ValueTypes.h"
66#include "llvm/IR/Attributes.h"
67#include "llvm/IR/CallingConv.h"
68#include "llvm/IR/Constant.h"
69#include "llvm/IR/Constants.h"
70#include "llvm/IR/DataLayout.h"
71#include "llvm/IR/DebugLoc.h"
72#include "llvm/IR/DerivedTypes.h"
73#include "llvm/IR/Function.h"
74#include "llvm/IR/GlobalAlias.h"
75#include "llvm/IR/GlobalValue.h"
76#include "llvm/IR/GlobalVariable.h"
77#include "llvm/IR/IRBuilder.h"
78#include "llvm/IR/InlineAsm.h"
79#include "llvm/IR/Instruction.h"
80#include "llvm/IR/Instructions.h"
81#include "llvm/IR/IntrinsicInst.h"
82#include "llvm/IR/Intrinsics.h"
83#include "llvm/IR/IntrinsicsARM.h"
84#include "llvm/IR/Module.h"
85#include "llvm/IR/PatternMatch.h"
86#include "llvm/IR/Type.h"
87#include "llvm/IR/User.h"
88#include "llvm/IR/Value.h"
89#include "llvm/MC/MCInstrDesc.h"
90#include "llvm/MC/MCInstrItineraries.h"
91#include "llvm/MC/MCRegisterInfo.h"
92#include "llvm/MC/MCSchedule.h"
93#include "llvm/Support/AtomicOrdering.h"
94#include "llvm/Support/BranchProbability.h"
95#include "llvm/Support/Casting.h"
96#include "llvm/Support/CodeGen.h"
97#include "llvm/Support/CommandLine.h"
98#include "llvm/Support/Compiler.h"
99#include "llvm/Support/Debug.h"
100#include "llvm/Support/ErrorHandling.h"
101#include "llvm/Support/KnownBits.h"
102#include "llvm/Support/MachineValueType.h"
103#include "llvm/Support/MathExtras.h"
104#include "llvm/Support/raw_ostream.h"
105#include "llvm/Target/TargetMachine.h"
106#include "llvm/Target/TargetOptions.h"
107#include <algorithm>
108#include <cassert>
109#include <cstdint>
110#include <cstdlib>
111#include <iterator>
112#include <limits>
113#include <string>
114#include <tuple>
115#include <utility>
116#include <vector>
117
118using namespace llvm;
119using namespace llvm::PatternMatch;
120
121#define DEBUG_TYPE"arm-isel" "arm-isel"
122
123STATISTIC(NumTailCalls, "Number of tail calls")static llvm::Statistic NumTailCalls = {"arm-isel", "NumTailCalls"
, "Number of tail calls"}
;
124STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt")static llvm::Statistic NumMovwMovt = {"arm-isel", "NumMovwMovt"
, "Number of GAs materialized with movw + movt"}
;
125STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments")static llvm::Statistic NumLoopByVals = {"arm-isel", "NumLoopByVals"
, "Number of loops generated for byval arguments"}
;
126STATISTIC(NumConstpoolPromoted,static llvm::Statistic NumConstpoolPromoted = {"arm-isel", "NumConstpoolPromoted"
, "Number of constants with their storage promoted into constant pools"
}
127 "Number of constants with their storage promoted into constant pools")static llvm::Statistic NumConstpoolPromoted = {"arm-isel", "NumConstpoolPromoted"
, "Number of constants with their storage promoted into constant pools"
}
;
128
129static cl::opt<bool>
130ARMInterworking("arm-interworking", cl::Hidden,
131 cl::desc("Enable / disable ARM interworking (for debugging only)"),
132 cl::init(true));
133
134static cl::opt<bool> EnableConstpoolPromotion(
135 "arm-promote-constant", cl::Hidden,
136 cl::desc("Enable / disable promotion of unnamed_addr constants into "
137 "constant pools"),
138 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
139static cl::opt<unsigned> ConstpoolPromotionMaxSize(
140 "arm-promote-constant-max-size", cl::Hidden,
141 cl::desc("Maximum size of constant to promote into a constant pool"),
142 cl::init(64));
143static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
144 "arm-promote-constant-max-total", cl::Hidden,
145 cl::desc("Maximum size of ALL constants to promote into a constant pool"),
146 cl::init(128));
147
148cl::opt<unsigned>
149MVEMaxSupportedInterleaveFactor("mve-max-interleave-factor", cl::Hidden,
150 cl::desc("Maximum interleave factor for MVE VLDn to generate."),
151 cl::init(2));
152
153// The APCS parameter registers.
154static const MCPhysReg GPRArgRegs[] = {
155 ARM::R0, ARM::R1, ARM::R2, ARM::R3
156};
157
158void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT) {
159 if (VT != PromotedLdStVT) {
160 setOperationAction(ISD::LOAD, VT, Promote);
161 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
162
163 setOperationAction(ISD::STORE, VT, Promote);
164 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
165 }
166
167 MVT ElemTy = VT.getVectorElementType();
168 if (ElemTy != MVT::f64)
169 setOperationAction(ISD::SETCC, VT, Custom);
170 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
171 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
172 if (ElemTy == MVT::i32) {
173 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
174 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
175 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
176 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
177 } else {
178 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
179 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
180 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
181 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
182 }
183 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
184 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
185 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
186 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
187 setOperationAction(ISD::SELECT, VT, Expand);
188 setOperationAction(ISD::SELECT_CC, VT, Expand);
189 setOperationAction(ISD::VSELECT, VT, Expand);
190 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
191 if (VT.isInteger()) {
192 setOperationAction(ISD::SHL, VT, Custom);
193 setOperationAction(ISD::SRA, VT, Custom);
194 setOperationAction(ISD::SRL, VT, Custom);
195 }
196
197 // Neon does not support vector divide/remainder operations.
198 setOperationAction(ISD::SDIV, VT, Expand);
199 setOperationAction(ISD::UDIV, VT, Expand);
200 setOperationAction(ISD::FDIV, VT, Expand);
201 setOperationAction(ISD::SREM, VT, Expand);
202 setOperationAction(ISD::UREM, VT, Expand);
203 setOperationAction(ISD::FREM, VT, Expand);
204 setOperationAction(ISD::SDIVREM, VT, Expand);
205 setOperationAction(ISD::UDIVREM, VT, Expand);
206
207 if (!VT.isFloatingPoint() &&
208 VT != MVT::v2i64 && VT != MVT::v1i64)
209 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
210 setOperationAction(Opcode, VT, Legal);
211 if (!VT.isFloatingPoint())
212 for (auto Opcode : {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT})
213 setOperationAction(Opcode, VT, Legal);
214}
215
216void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
217 addRegisterClass(VT, &ARM::DPRRegClass);
218 addTypeForNEON(VT, MVT::f64);
219}
220
221void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
222 addRegisterClass(VT, &ARM::DPairRegClass);
223 addTypeForNEON(VT, MVT::v2f64);
224}
225
226void ARMTargetLowering::setAllExpand(MVT VT) {
227 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
228 setOperationAction(Opc, VT, Expand);
229
230 // We support these really simple operations even on types where all
231 // the actual arithmetic has to be broken down into simpler
232 // operations or turned into library calls.
233 setOperationAction(ISD::BITCAST, VT, Legal);
234 setOperationAction(ISD::LOAD, VT, Legal);
235 setOperationAction(ISD::STORE, VT, Legal);
236 setOperationAction(ISD::UNDEF, VT, Legal);
237}
238
239void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To,
240 LegalizeAction Action) {
241 setLoadExtAction(ISD::EXTLOAD, From, To, Action);
242 setLoadExtAction(ISD::ZEXTLOAD, From, To, Action);
243 setLoadExtAction(ISD::SEXTLOAD, From, To, Action);
244}
245
246void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) {
247 const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 };
248
249 for (auto VT : IntTypes) {
250 addRegisterClass(VT, &ARM::MQPRRegClass);
251 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
252 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
253 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
254 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
255 setOperationAction(ISD::SHL, VT, Custom);
256 setOperationAction(ISD::SRA, VT, Custom);
257 setOperationAction(ISD::SRL, VT, Custom);
258 setOperationAction(ISD::SMIN, VT, Legal);
259 setOperationAction(ISD::SMAX, VT, Legal);
260 setOperationAction(ISD::UMIN, VT, Legal);
261 setOperationAction(ISD::UMAX, VT, Legal);
262 setOperationAction(ISD::ABS, VT, Legal);
263 setOperationAction(ISD::SETCC, VT, Custom);
264 setOperationAction(ISD::MLOAD, VT, Custom);
265 setOperationAction(ISD::MSTORE, VT, Legal);
266 setOperationAction(ISD::CTLZ, VT, Legal);
267 setOperationAction(ISD::CTTZ, VT, Custom);
268 setOperationAction(ISD::BITREVERSE, VT, Legal);
269 setOperationAction(ISD::BSWAP, VT, Legal);
270 setOperationAction(ISD::SADDSAT, VT, Legal);
271 setOperationAction(ISD::UADDSAT, VT, Legal);
272 setOperationAction(ISD::SSUBSAT, VT, Legal);
273 setOperationAction(ISD::USUBSAT, VT, Legal);
274 setOperationAction(ISD::ABDS, VT, Legal);
275 setOperationAction(ISD::ABDU, VT, Legal);
276
277 // No native support for these.
278 setOperationAction(ISD::UDIV, VT, Expand);
279 setOperationAction(ISD::SDIV, VT, Expand);
280 setOperationAction(ISD::UREM, VT, Expand);
281 setOperationAction(ISD::SREM, VT, Expand);
282 setOperationAction(ISD::UDIVREM, VT, Expand);
283 setOperationAction(ISD::SDIVREM, VT, Expand);
284 setOperationAction(ISD::CTPOP, VT, Expand);
285 setOperationAction(ISD::SELECT, VT, Expand);
286 setOperationAction(ISD::SELECT_CC, VT, Expand);
287
288 // Vector reductions
289 setOperationAction(ISD::VECREDUCE_ADD, VT, Legal);
290 setOperationAction(ISD::VECREDUCE_SMAX, VT, Legal);
291 setOperationAction(ISD::VECREDUCE_UMAX, VT, Legal);
292 setOperationAction(ISD::VECREDUCE_SMIN, VT, Legal);
293 setOperationAction(ISD::VECREDUCE_UMIN, VT, Legal);
294 setOperationAction(ISD::VECREDUCE_MUL, VT, Custom);
295 setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
296 setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
297 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
298
299 if (!HasMVEFP) {
300 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
301 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
302 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
303 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
304 }
305
306 // Pre and Post inc are supported on loads and stores
307 for (unsigned im = (unsigned)ISD::PRE_INC;
308 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
309 setIndexedLoadAction(im, VT, Legal);
310 setIndexedStoreAction(im, VT, Legal);
311 setIndexedMaskedLoadAction(im, VT, Legal);
312 setIndexedMaskedStoreAction(im, VT, Legal);
313 }
314 }
315
316 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
317 for (auto VT : FloatTypes) {
318 addRegisterClass(VT, &ARM::MQPRRegClass);
319 if (!HasMVEFP)
320 setAllExpand(VT);
321
322 // These are legal or custom whether we have MVE.fp or not
323 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
324 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
325 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom);
326 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
327 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
328 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom);
329 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal);
330 setOperationAction(ISD::SETCC, VT, Custom);
331 setOperationAction(ISD::MLOAD, VT, Custom);
332 setOperationAction(ISD::MSTORE, VT, Legal);
333 setOperationAction(ISD::SELECT, VT, Expand);
334 setOperationAction(ISD::SELECT_CC, VT, Expand);
335
336 // Pre and Post inc are supported on loads and stores
337 for (unsigned im = (unsigned)ISD::PRE_INC;
338 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
339 setIndexedLoadAction(im, VT, Legal);
340 setIndexedStoreAction(im, VT, Legal);
341 setIndexedMaskedLoadAction(im, VT, Legal);
342 setIndexedMaskedStoreAction(im, VT, Legal);
343 }
344
345 if (HasMVEFP) {
346 setOperationAction(ISD::FMINNUM, VT, Legal);
347 setOperationAction(ISD::FMAXNUM, VT, Legal);
348 setOperationAction(ISD::FROUND, VT, Legal);
349 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
350 setOperationAction(ISD::VECREDUCE_FMUL, VT, Custom);
351 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
352 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
353
354 // No native support for these.
355 setOperationAction(ISD::FDIV, VT, Expand);
356 setOperationAction(ISD::FREM, VT, Expand);
357 setOperationAction(ISD::FSQRT, VT, Expand);
358 setOperationAction(ISD::FSIN, VT, Expand);
359 setOperationAction(ISD::FCOS, VT, Expand);
360 setOperationAction(ISD::FPOW, VT, Expand);
361 setOperationAction(ISD::FLOG, VT, Expand);
362 setOperationAction(ISD::FLOG2, VT, Expand);
363 setOperationAction(ISD::FLOG10, VT, Expand);
364 setOperationAction(ISD::FEXP, VT, Expand);
365 setOperationAction(ISD::FEXP2, VT, Expand);
366 setOperationAction(ISD::FNEARBYINT, VT, Expand);
367 }
368 }
369
370 // Custom Expand smaller than legal vector reductions to prevent false zero
371 // items being added.
372 setOperationAction(ISD::VECREDUCE_FADD, MVT::v4f16, Custom);
373 setOperationAction(ISD::VECREDUCE_FMUL, MVT::v4f16, Custom);
374 setOperationAction(ISD::VECREDUCE_FMIN, MVT::v4f16, Custom);
375 setOperationAction(ISD::VECREDUCE_FMAX, MVT::v4f16, Custom);
376 setOperationAction(ISD::VECREDUCE_FADD, MVT::v2f16, Custom);
377 setOperationAction(ISD::VECREDUCE_FMUL, MVT::v2f16, Custom);
378 setOperationAction(ISD::VECREDUCE_FMIN, MVT::v2f16, Custom);
379 setOperationAction(ISD::VECREDUCE_FMAX, MVT::v2f16, Custom);
380
381 // We 'support' these types up to bitcast/load/store level, regardless of
382 // MVE integer-only / float support. Only doing FP data processing on the FP
383 // vector types is inhibited at integer-only level.
384 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
385 for (auto VT : LongTypes) {
386 addRegisterClass(VT, &ARM::MQPRRegClass);
387 setAllExpand(VT);
388 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
389 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
390 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
391 }
392 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
393
394 // We can do bitwise operations on v2i64 vectors
395 setOperationAction(ISD::AND, MVT::v2i64, Legal);
396 setOperationAction(ISD::OR, MVT::v2i64, Legal);
397 setOperationAction(ISD::XOR, MVT::v2i64, Legal);
398
399 // It is legal to extload from v4i8 to v4i16 or v4i32.
400 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
401 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
402 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
403
404 // It is legal to sign extend from v4i8/v4i16 to v4i32 or v8i8 to v8i16.
405 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal);
406 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
407 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
408 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i8, Legal);
409 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i16, Legal);
410
411 // Some truncating stores are legal too.
412 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
413 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
414 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
415
416 // Pre and Post inc on these are legal, given the correct extends
417 for (unsigned im = (unsigned)ISD::PRE_INC;
418 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
419 for (auto VT : {MVT::v8i8, MVT::v4i8, MVT::v4i16}) {
420 setIndexedLoadAction(im, VT, Legal);
421 setIndexedStoreAction(im, VT, Legal);
422 setIndexedMaskedLoadAction(im, VT, Legal);
423 setIndexedMaskedStoreAction(im, VT, Legal);
424 }
425 }
426
427 // Predicate types
428 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1};
429 for (auto VT : pTypes) {
430 addRegisterClass(VT, &ARM::VCCRRegClass);
431 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
432 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
433 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
434 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
435 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
436 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
437 setOperationAction(ISD::SETCC, VT, Custom);
438 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
439 setOperationAction(ISD::LOAD, VT, Custom);
440 setOperationAction(ISD::STORE, VT, Custom);
441 setOperationAction(ISD::TRUNCATE, VT, Custom);
442 setOperationAction(ISD::VSELECT, VT, Expand);
443 setOperationAction(ISD::SELECT, VT, Expand);
444 }
445 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
446 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
447 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
448 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
449 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
450 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
451 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
452 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
453}
454
455ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
456 const ARMSubtarget &STI)
457 : TargetLowering(TM), Subtarget(&STI) {
458 RegInfo = Subtarget->getRegisterInfo();
459 Itins = Subtarget->getInstrItineraryData();
460
461 setBooleanContents(ZeroOrOneBooleanContent);
462 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
463
464 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
465 !Subtarget->isTargetWatchOS()) {
466 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
467 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
468 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
469 IsHFTarget ? CallingConv::ARM_AAPCS_VFP
470 : CallingConv::ARM_AAPCS);
471 }
472
473 if (Subtarget->isTargetMachO()) {
474 // Uses VFP for Thumb libfuncs if available.
475 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
476 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
477 static const struct {
478 const RTLIB::Libcall Op;
479 const char * const Name;
480 const ISD::CondCode Cond;
481 } LibraryCalls[] = {
482 // Single-precision floating-point arithmetic.
483 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
484 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
485 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
486 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
487
488 // Double-precision floating-point arithmetic.
489 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
490 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
491 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
492 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
493
494 // Single-precision comparisons.
495 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
496 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
497 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
498 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
499 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
500 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
501 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
502
503 // Double-precision comparisons.
504 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
505 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
506 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
507 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
508 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
509 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
510 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
511
512 // Floating-point to integer conversions.
513 // i64 conversions are done via library routines even when generating VFP
514 // instructions, so use the same ones.
515 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
516 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
517 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
518 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
519
520 // Conversions between floating types.
521 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
522 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
523
524 // Integer to floating-point conversions.
525 // i64 conversions are done via library routines even when generating VFP
526 // instructions, so use the same ones.
527 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
528 // e.g., __floatunsidf vs. __floatunssidfvfp.
529 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
530 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
531 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
532 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
533 };
534
535 for (const auto &LC : LibraryCalls) {
536 setLibcallName(LC.Op, LC.Name);
537 if (LC.Cond != ISD::SETCC_INVALID)
538 setCmpLibcallCC(LC.Op, LC.Cond);
539 }
540 }
541 }
542
543 // These libcalls are not available in 32-bit.
544 setLibcallName(RTLIB::SHL_I128, nullptr);
545 setLibcallName(RTLIB::SRL_I128, nullptr);
546 setLibcallName(RTLIB::SRA_I128, nullptr);
547 setLibcallName(RTLIB::MUL_I128, nullptr);
548 setLibcallName(RTLIB::MULO_I64, nullptr);
549 setLibcallName(RTLIB::MULO_I128, nullptr);
550
551 // RTLIB
552 if (Subtarget->isAAPCS_ABI() &&
553 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
554 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
555 static const struct {
556 const RTLIB::Libcall Op;
557 const char * const Name;
558 const CallingConv::ID CC;
559 const ISD::CondCode Cond;
560 } LibraryCalls[] = {
561 // Double-precision floating-point arithmetic helper functions
562 // RTABI chapter 4.1.2, Table 2
563 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
564 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
565 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
566 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
567
568 // Double-precision floating-point comparison helper functions
569 // RTABI chapter 4.1.2, Table 3
570 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
571 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
572 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
573 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
574 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
575 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
576 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
577
578 // Single-precision floating-point arithmetic helper functions
579 // RTABI chapter 4.1.2, Table 4
580 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
581 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
582 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
583 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
584
585 // Single-precision floating-point comparison helper functions
586 // RTABI chapter 4.1.2, Table 5
587 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
588 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
589 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
590 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
591 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
592 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
593 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
594
595 // Floating-point to integer conversions.
596 // RTABI chapter 4.1.2, Table 6
597 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
598 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
599 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
600 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
601 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
602 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
603 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
604 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
605
606 // Conversions between floating types.
607 // RTABI chapter 4.1.2, Table 7
608 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
609 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
610 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
611
612 // Integer to floating-point conversions.
613 // RTABI chapter 4.1.2, Table 8
614 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
615 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
616 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
617 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
618 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
619 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
620 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
621 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
622
623 // Long long helper functions
624 // RTABI chapter 4.2, Table 9
625 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
626 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
627 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
628 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
629
630 // Integer division functions
631 // RTABI chapter 4.3.1
632 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
633 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
634 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
635 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
636 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
637 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
638 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
639 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
640 };
641
642 for (const auto &LC : LibraryCalls) {
643 setLibcallName(LC.Op, LC.Name);
644 setLibcallCallingConv(LC.Op, LC.CC);
645 if (LC.Cond != ISD::SETCC_INVALID)
646 setCmpLibcallCC(LC.Op, LC.Cond);
647 }
648
649 // EABI dependent RTLIB
650 if (TM.Options.EABIVersion == EABI::EABI4 ||
651 TM.Options.EABIVersion == EABI::EABI5) {
652 static const struct {
653 const RTLIB::Libcall Op;
654 const char *const Name;
655 const CallingConv::ID CC;
656 const ISD::CondCode Cond;
657 } MemOpsLibraryCalls[] = {
658 // Memory operations
659 // RTABI chapter 4.3.4
660 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
661 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
662 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
663 };
664
665 for (const auto &LC : MemOpsLibraryCalls) {
666 setLibcallName(LC.Op, LC.Name);
667 setLibcallCallingConv(LC.Op, LC.CC);
668 if (LC.Cond != ISD::SETCC_INVALID)
669 setCmpLibcallCC(LC.Op, LC.Cond);
670 }
671 }
672 }
673
674 if (Subtarget->isTargetWindows()) {
675 static const struct {
676 const RTLIB::Libcall Op;
677 const char * const Name;
678 const CallingConv::ID CC;
679 } LibraryCalls[] = {
680 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
681 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
682 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
683 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
684 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
685 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
686 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
687 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
688 };
689
690 for (const auto &LC : LibraryCalls) {
691 setLibcallName(LC.Op, LC.Name);
692 setLibcallCallingConv(LC.Op, LC.CC);
693 }
694 }
695
696 // Use divmod compiler-rt calls for iOS 5.0 and later.
697 if (Subtarget->isTargetMachO() &&
698 !(Subtarget->isTargetIOS() &&
699 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
700 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
701 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
702 }
703
704 // The half <-> float conversion functions are always soft-float on
705 // non-watchos platforms, but are needed for some targets which use a
706 // hard-float calling convention by default.
707 if (!Subtarget->isTargetWatchABI()) {
708 if (Subtarget->isAAPCS_ABI()) {
709 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
710 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
711 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
712 } else {
713 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
714 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
715 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
716 }
717 }
718
719 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
720 // a __gnu_ prefix (which is the default).
721 if (Subtarget->isTargetAEABI()) {
722 static const struct {
723 const RTLIB::Libcall Op;
724 const char * const Name;
725 const CallingConv::ID CC;
726 } LibraryCalls[] = {
727 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
728 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
729 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
730 };
731
732 for (const auto &LC : LibraryCalls) {
733 setLibcallName(LC.Op, LC.Name);
734 setLibcallCallingConv(LC.Op, LC.CC);
735 }
736 }
737
738 if (Subtarget->isThumb1Only())
739 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
740 else
741 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
742
743 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
744 Subtarget->hasFPRegs()) {
745 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
746 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
747 if (!Subtarget->hasVFP2Base())
748 setAllExpand(MVT::f32);
749 if (!Subtarget->hasFP64())
750 setAllExpand(MVT::f64);
751 }
752
753 if (Subtarget->hasFullFP16()) {
754 addRegisterClass(MVT::f16, &ARM::HPRRegClass);
755 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
756 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
757
758 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
759 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
760 }
761
762 if (Subtarget->hasBF16()) {
763 addRegisterClass(MVT::bf16, &ARM::HPRRegClass);
764 setAllExpand(MVT::bf16);
765 if (!Subtarget->hasFullFP16())
766 setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
767 }
768
769 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
770 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
771 setTruncStoreAction(VT, InnerVT, Expand);
772 addAllExtLoads(VT, InnerVT, Expand);
773 }
774
775 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
776 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
777
778 setOperationAction(ISD::BSWAP, VT, Expand);
779 }
780
781 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
782 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
783
784 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
785 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
786
787 if (Subtarget->hasMVEIntegerOps())
788 addMVEVectorTypes(Subtarget->hasMVEFloatOps());
789
790 // Combine low-overhead loop intrinsics so that we can lower i1 types.
791 if (Subtarget->hasLOB()) {
792 setTargetDAGCombine(ISD::BRCOND);
793 setTargetDAGCombine(ISD::BR_CC);
794 }
795
796 if (Subtarget->hasNEON()) {
797 addDRTypeForNEON(MVT::v2f32);
798 addDRTypeForNEON(MVT::v8i8);
799 addDRTypeForNEON(MVT::v4i16);
800 addDRTypeForNEON(MVT::v2i32);
801 addDRTypeForNEON(MVT::v1i64);
802
803 addQRTypeForNEON(MVT::v4f32);
804 addQRTypeForNEON(MVT::v2f64);
805 addQRTypeForNEON(MVT::v16i8);
806 addQRTypeForNEON(MVT::v8i16);
807 addQRTypeForNEON(MVT::v4i32);
808 addQRTypeForNEON(MVT::v2i64);
809
810 if (Subtarget->hasFullFP16()) {
811 addQRTypeForNEON(MVT::v8f16);
812 addDRTypeForNEON(MVT::v4f16);
813 }
814
815 if (Subtarget->hasBF16()) {
816 addQRTypeForNEON(MVT::v8bf16);
817 addDRTypeForNEON(MVT::v4bf16);
818 }
819 }
820
821 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
822 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
823 // none of Neon, MVE or VFP supports any arithmetic operations on it.
824 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
825 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
826 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
827 // FIXME: Code duplication: FDIV and FREM are expanded always, see
828 // ARMTargetLowering::addTypeForNEON method for details.
829 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
830 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
831 // FIXME: Create unittest.
832 // In another words, find a way when "copysign" appears in DAG with vector
833 // operands.
834 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
835 // FIXME: Code duplication: SETCC has custom operation action, see
836 // ARMTargetLowering::addTypeForNEON method for details.
837 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
838 // FIXME: Create unittest for FNEG and for FABS.
839 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
840 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
841 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
842 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
843 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
844 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
845 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
846 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
847 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
848 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
849 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
850 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
851 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
852 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
853 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
854 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
855 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
856 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
857 }
858
859 if (Subtarget->hasNEON()) {
860 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
861 // supported for v4f32.
862 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
863 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
864 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
865 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
866 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
867 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
868 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
869 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
870 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
871 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
872 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
873 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
874 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
875 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
876
877 // Mark v2f32 intrinsics.
878 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
879 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
880 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
881 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
882 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
883 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
884 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
885 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
886 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
887 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
888 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
889 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
890 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
891 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
892
893 // Neon does not support some operations on v1i64 and v2i64 types.
894 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
895 // Custom handling for some quad-vector types to detect VMULL.
896 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
897 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
898 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
899 // Custom handling for some vector types to avoid expensive expansions
900 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
901 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
902 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
903 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
904 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
905 // a destination type that is wider than the source, and nor does
906 // it have a FP_TO_[SU]INT instruction with a narrower destination than
907 // source.
908 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
909 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
910 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
911 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
912 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
913 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
914 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
915 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
916
917 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
918 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
919
920 // NEON does not have single instruction CTPOP for vectors with element
921 // types wider than 8-bits. However, custom lowering can leverage the
922 // v8i8/v16i8 vcnt instruction.
923 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
924 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
925 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
926 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
927 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom);
928 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
929
930 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
931 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
932
933 // NEON does not have single instruction CTTZ for vectors.
934 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
935 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
936 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
937 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
938
939 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
940 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
941 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
942 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
943
944 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
945 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
946 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
947 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
948
949 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
950 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
951 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
952 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
953
954 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
955 setOperationAction(ISD::MULHS, VT, Expand);
956 setOperationAction(ISD::MULHU, VT, Expand);
957 }
958
959 // NEON only has FMA instructions as of VFP4.
960 if (!Subtarget->hasVFP4Base()) {
961 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
962 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
963 }
964
965 setTargetDAGCombine(ISD::SHL);
966 setTargetDAGCombine(ISD::SRL);
967 setTargetDAGCombine(ISD::SRA);
968 setTargetDAGCombine(ISD::FP_TO_SINT);
969 setTargetDAGCombine(ISD::FP_TO_UINT);
970 setTargetDAGCombine(ISD::FDIV);
971 setTargetDAGCombine(ISD::LOAD);
972
973 // It is legal to extload from v4i8 to v4i16 or v4i32.
974 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
975 MVT::v2i32}) {
976 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
977 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
978 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
979 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
980 }
981 }
982 }
983
984 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
985 setTargetDAGCombine(ISD::BUILD_VECTOR);
986 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
987 setTargetDAGCombine(ISD::INSERT_SUBVECTOR);
988 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
989 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
990 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
991 setTargetDAGCombine(ISD::STORE);
992 setTargetDAGCombine(ISD::SIGN_EXTEND);
993 setTargetDAGCombine(ISD::ZERO_EXTEND);
994 setTargetDAGCombine(ISD::ANY_EXTEND);
995 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
996 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
997 setTargetDAGCombine(ISD::INTRINSIC_VOID);
998 setTargetDAGCombine(ISD::VECREDUCE_ADD);
999 setTargetDAGCombine(ISD::ADD);
1000 setTargetDAGCombine(ISD::BITCAST);
1001 }
1002 if (Subtarget->hasMVEIntegerOps()) {
1003 setTargetDAGCombine(ISD::SMIN);
1004 setTargetDAGCombine(ISD::UMIN);
1005 setTargetDAGCombine(ISD::SMAX);
1006 setTargetDAGCombine(ISD::UMAX);
1007 setTargetDAGCombine(ISD::FP_EXTEND);
1008 setTargetDAGCombine(ISD::SELECT);
1009 setTargetDAGCombine(ISD::SELECT_CC);
1010 }
1011
1012 if (!Subtarget->hasFP64()) {
1013 // When targeting a floating-point unit with only single-precision
1014 // operations, f64 is legal for the few double-precision instructions which
1015 // are present However, no double-precision operations other than moves,
1016 // loads and stores are provided by the hardware.
1017 setOperationAction(ISD::FADD, MVT::f64, Expand);
1018 setOperationAction(ISD::FSUB, MVT::f64, Expand);
1019 setOperationAction(ISD::FMUL, MVT::f64, Expand);
1020 setOperationAction(ISD::FMA, MVT::f64, Expand);
1021 setOperationAction(ISD::FDIV, MVT::f64, Expand);
1022 setOperationAction(ISD::FREM, MVT::f64, Expand);
1023 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
1024 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
1025 setOperationAction(ISD::FNEG, MVT::f64, Expand);
1026 setOperationAction(ISD::FABS, MVT::f64, Expand);
1027 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
1028 setOperationAction(ISD::FSIN, MVT::f64, Expand);
1029 setOperationAction(ISD::FCOS, MVT::f64, Expand);
1030 setOperationAction(ISD::FPOW, MVT::f64, Expand);
1031 setOperationAction(ISD::FLOG, MVT::f64, Expand);
1032 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
1033 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
1034 setOperationAction(ISD::FEXP, MVT::f64, Expand);
1035 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
1036 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
1037 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
1038 setOperationAction(ISD::FRINT, MVT::f64, Expand);
1039 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
1040 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
1041 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
1042 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
1043 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
1044 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
1045 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
1046 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
1047 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
1048 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
1049 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
1050 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::f64, Custom);
1051 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::f64, Custom);
1052 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
1053 }
1054
1055 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
1056 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
1057 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom);
1058 if (Subtarget->hasFullFP16()) {
1059 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
1060 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
1061 }
1062 }
1063
1064 if (!Subtarget->hasFP16()) {
1065 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom);
1066 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom);
1067 }
1068
1069 computeRegisterProperties(Subtarget->getRegisterInfo());
1070
1071 // ARM does not have floating-point extending loads.
1072 for (MVT VT : MVT::fp_valuetypes()) {
1073 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
1074 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
1075 }
1076
1077 // ... or truncating stores
1078 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1079 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
1080 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
1081
1082 // ARM does not have i1 sign extending load.
1083 for (MVT VT : MVT::integer_valuetypes())
1084 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
1085
1086 // ARM supports all 4 flavors of integer indexed load / store.
1087 if (!Subtarget->isThumb1Only()) {
1088 for (unsigned im = (unsigned)ISD::PRE_INC;
1089 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1090 setIndexedLoadAction(im, MVT::i1, Legal);
1091 setIndexedLoadAction(im, MVT::i8, Legal);
1092 setIndexedLoadAction(im, MVT::i16, Legal);
1093 setIndexedLoadAction(im, MVT::i32, Legal);
1094 setIndexedStoreAction(im, MVT::i1, Legal);
1095 setIndexedStoreAction(im, MVT::i8, Legal);
1096 setIndexedStoreAction(im, MVT::i16, Legal);
1097 setIndexedStoreAction(im, MVT::i32, Legal);
1098 }
1099 } else {
1100 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
1101 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal);
1102 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal);
1103 }
1104
1105 setOperationAction(ISD::SADDO, MVT::i32, Custom);
1106 setOperationAction(ISD::UADDO, MVT::i32, Custom);
1107 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1108 setOperationAction(ISD::USUBO, MVT::i32, Custom);
1109
1110 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
1111 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
1112 if (Subtarget->hasDSP()) {
1113 setOperationAction(ISD::SADDSAT, MVT::i8, Custom);
1114 setOperationAction(ISD::SSUBSAT, MVT::i8, Custom);
1115 setOperationAction(ISD::SADDSAT, MVT::i16, Custom);
1116 setOperationAction(ISD::SSUBSAT, MVT::i16, Custom);
1117 setOperationAction(ISD::UADDSAT, MVT::i8, Custom);
1118 setOperationAction(ISD::USUBSAT, MVT::i8, Custom);
1119 setOperationAction(ISD::UADDSAT, MVT::i16, Custom);
1120 setOperationAction(ISD::USUBSAT, MVT::i16, Custom);
1121 }
1122 if (Subtarget->hasBaseDSP()) {
1123 setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
1124 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
1125 }
1126
1127 // i64 operation support.
1128 setOperationAction(ISD::MUL, MVT::i64, Expand);
1129 setOperationAction(ISD::MULHU, MVT::i32, Expand);
1130 if (Subtarget->isThumb1Only()) {
1131 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1132 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1133 }
1134 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
1135 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
1136 setOperationAction(ISD::MULHS, MVT::i32, Expand);
1137
1138 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
1139 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
1140 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
1141 setOperationAction(ISD::SRL, MVT::i64, Custom);
1142 setOperationAction(ISD::SRA, MVT::i64, Custom);
1143 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1144 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1145 setOperationAction(ISD::LOAD, MVT::i64, Custom);
1146 setOperationAction(ISD::STORE, MVT::i64, Custom);
1147
1148 // MVE lowers 64 bit shifts to lsll and lsrl
1149 // assuming that ISD::SRL and SRA of i64 are already marked custom
1150 if (Subtarget->hasMVEIntegerOps())
1151 setOperationAction(ISD::SHL, MVT::i64, Custom);
1152
1153 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1154 if (Subtarget->isThumb1Only()) {
1155 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1156 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1157 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1158 }
1159
1160 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1161 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1162
1163 // ARM does not have ROTL.
1164 setOperationAction(ISD::ROTL, MVT::i32, Expand);
1165 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1166 setOperationAction(ISD::ROTL, VT, Expand);
1167 setOperationAction(ISD::ROTR, VT, Expand);
1168 }
1169 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
1170 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1171 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1172 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1173 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
1174 }
1175
1176 // @llvm.readcyclecounter requires the Performance Monitors extension.
1177 // Default to the 0 expansion on unsupported platforms.
1178 // FIXME: Technically there are older ARM CPUs that have
1179 // implementation-specific ways of obtaining this information.
1180 if (Subtarget->hasPerfMon())
1181 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1182
1183 // Only ARMv6 has BSWAP.
1184 if (!Subtarget->hasV6Ops())
1185 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1186
1187 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1188 : Subtarget->hasDivideInARMMode();
1189 if (!hasDivide) {
1190 // These are expanded into libcalls if the cpu doesn't have HW divider.
1191 setOperationAction(ISD::SDIV, MVT::i32, LibCall);
1192 setOperationAction(ISD::UDIV, MVT::i32, LibCall);
1193 }
1194
1195 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
1196 setOperationAction(ISD::SDIV, MVT::i32, Custom);
1197 setOperationAction(ISD::UDIV, MVT::i32, Custom);
1198
1199 setOperationAction(ISD::SDIV, MVT::i64, Custom);
1200 setOperationAction(ISD::UDIV, MVT::i64, Custom);
1201 }
1202
1203 setOperationAction(ISD::SREM, MVT::i32, Expand);
1204 setOperationAction(ISD::UREM, MVT::i32, Expand);
1205
1206 // Register based DivRem for AEABI (RTABI 4.2)
1207 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
1208 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
1209 Subtarget->isTargetWindows()) {
1210 setOperationAction(ISD::SREM, MVT::i64, Custom);
1211 setOperationAction(ISD::UREM, MVT::i64, Custom);
1212 HasStandaloneRem = false;
1213
1214 if (Subtarget->isTargetWindows()) {
1215 const struct {
1216 const RTLIB::Libcall Op;
1217 const char * const Name;
1218 const CallingConv::ID CC;
1219 } LibraryCalls[] = {
1220 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
1221 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
1222 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
1223 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
1224
1225 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
1226 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
1227 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
1228 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
1229 };
1230
1231 for (const auto &LC : LibraryCalls) {
1232 setLibcallName(LC.Op, LC.Name);
1233 setLibcallCallingConv(LC.Op, LC.CC);
1234 }
1235 } else {
1236 const struct {
1237 const RTLIB::Libcall Op;
1238 const char * const Name;
1239 const CallingConv::ID CC;
1240 } LibraryCalls[] = {
1241 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1242 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1243 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1244 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
1245
1246 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1247 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1248 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1249 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
1250 };
1251
1252 for (const auto &LC : LibraryCalls) {
1253 setLibcallName(LC.Op, LC.Name);
1254 setLibcallCallingConv(LC.Op, LC.CC);
1255 }
1256 }
1257
1258 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1259 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1260 setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1261 setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1262 } else {
1263 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1264 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1265 }
1266
1267 if (Subtarget->getTargetTriple().isOSMSVCRT()) {
1268 // MSVCRT doesn't have powi; fall back to pow
1269 setLibcallName(RTLIB::POWI_F32, nullptr);
1270 setLibcallName(RTLIB::POWI_F64, nullptr);
1271 }
1272
1273 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1274 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
1275 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1276 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1277
1278 setOperationAction(ISD::TRAP, MVT::Other, Legal);
1279 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1280
1281 // Use the default implementation.
1282 setOperationAction(ISD::VASTART, MVT::Other, Custom);
1283 setOperationAction(ISD::VAARG, MVT::Other, Expand);
1284 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
1285 setOperationAction(ISD::VAEND, MVT::Other, Expand);
1286 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
1287 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
1288
1289 if (Subtarget->isTargetWindows())
1290 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1291 else
1292 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1293
1294 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1295 // the default expansion.
1296 InsertFencesForAtomic = false;
1297 if (Subtarget->hasAnyDataBarrier() &&
1298 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1299 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1300 // to ldrex/strex loops already.
1301 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
1302 if (!Subtarget->isThumb() || !Subtarget->isMClass())
1303 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
1304
1305 // On v8, we have particularly efficient implementations of atomic fences
1306 // if they can be combined with nearby atomic loads and stores.
1307 if (!Subtarget->hasAcquireRelease() ||
1308 getTargetMachine().getOptLevel() == 0) {
1309 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1310 InsertFencesForAtomic = true;
1311 }
1312 } else {
1313 // If there's anything we can use as a barrier, go through custom lowering
1314 // for ATOMIC_FENCE.
1315 // If target has DMB in thumb, Fences can be inserted.
1316 if (Subtarget->hasDataBarrier())
1317 InsertFencesForAtomic = true;
1318
1319 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
1320 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1321
1322 // Set them all for expansion, which will force libcalls.
1323 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
1324 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
1325 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
1326 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
1327 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
1328 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
1329 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
1330 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1331 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1332 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1333 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1334 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1335 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1336 // Unordered/Monotonic case.
1337 if (!InsertFencesForAtomic) {
1338 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1339 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1340 }
1341 }
1342
1343 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
1344
1345 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1346 if (!Subtarget->hasV6Ops()) {
1347 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1348 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
1349 }
1350 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1351
1352 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1353 !Subtarget->isThumb1Only()) {
1354 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1355 // iff target supports vfp2.
1356 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1357 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1358 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
1359 }
1360
1361 // We want to custom lower some of our intrinsics.
1362 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1363 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1364 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1365 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1366 if (Subtarget->useSjLjEH())
1367 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1368
1369 setOperationAction(ISD::SETCC, MVT::i32, Expand);
1370 setOperationAction(ISD::SETCC, MVT::f32, Expand);
1371 setOperationAction(ISD::SETCC, MVT::f64, Expand);
1372 setOperationAction(ISD::SELECT, MVT::i32, Custom);
1373 setOperationAction(ISD::SELECT, MVT::f32, Custom);
1374 setOperationAction(ISD::SELECT, MVT::f64, Custom);
1375 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1376 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1377 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1378 if (Subtarget->hasFullFP16()) {
1379 setOperationAction(ISD::SETCC, MVT::f16, Expand);
1380 setOperationAction(ISD::SELECT, MVT::f16, Custom);
1381 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1382 }
1383
1384 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1385
1386 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
1387 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
1388 if (Subtarget->hasFullFP16())
1389 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
1390 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
1391 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
1392 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1393
1394 // We don't support sin/cos/fmod/copysign/pow
1395 setOperationAction(ISD::FSIN, MVT::f64, Expand);
1396 setOperationAction(ISD::FSIN, MVT::f32, Expand);
1397 setOperationAction(ISD::FCOS, MVT::f32, Expand);
1398 setOperationAction(ISD::FCOS, MVT::f64, Expand);
1399 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1400 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1401 setOperationAction(ISD::FREM, MVT::f64, Expand);
1402 setOperationAction(ISD::FREM, MVT::f32, Expand);
1403 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1404 !Subtarget->isThumb1Only()) {
1405 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1406 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1407 }
1408 setOperationAction(ISD::FPOW, MVT::f64, Expand);
1409 setOperationAction(ISD::FPOW, MVT::f32, Expand);
1410
1411 if (!Subtarget->hasVFP4Base()) {
1412 setOperationAction(ISD::FMA, MVT::f64, Expand);
1413 setOperationAction(ISD::FMA, MVT::f32, Expand);
1414 }
1415
1416 // Various VFP goodness
1417 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1418 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1419 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1420 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1421 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1422 }
1423
1424 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1425 if (!Subtarget->hasFP16()) {
1426 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1427 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1428 }
1429
1430 // Strict floating-point comparisons need custom lowering.
1431 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom);
1432 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
1433 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom);
1434 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
1435 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom);
1436 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
1437 }
1438
1439 // Use __sincos_stret if available.
1440 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1441 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1442 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1443 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1444 }
1445
1446 // FP-ARMv8 implements a lot of rounding-like FP operations.
1447 if (Subtarget->hasFPARMv8Base()) {
1448 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1449 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1450 setOperationAction(ISD::FROUND, MVT::f32, Legal);
1451 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1452 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1453 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1454 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1455 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1456 if (Subtarget->hasNEON()) {
1457 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1458 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1459 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1460 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1461 }
1462
1463 if (Subtarget->hasFP64()) {
1464 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1465 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1466 setOperationAction(ISD::FROUND, MVT::f64, Legal);
1467 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1468 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1469 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1470 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1471 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1472 }
1473 }
1474
1475 // FP16 often need to be promoted to call lib functions
1476 if (Subtarget->hasFullFP16()) {
1477 setOperationAction(ISD::FREM, MVT::f16, Promote);
1478 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1479 setOperationAction(ISD::FSIN, MVT::f16, Promote);
1480 setOperationAction(ISD::FCOS, MVT::f16, Promote);
1481 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1482 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1483 setOperationAction(ISD::FPOW, MVT::f16, Promote);
1484 setOperationAction(ISD::FEXP, MVT::f16, Promote);
1485 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1486 setOperationAction(ISD::FLOG, MVT::f16, Promote);
1487 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1488 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1489
1490 setOperationAction(ISD::FROUND, MVT::f16, Legal);
1491 }
1492
1493 if (Subtarget->hasNEON()) {
1494 // vmin and vmax aren't available in a scalar form, so we can use
1495 // a NEON instruction with an undef lane instead. This has a performance
1496 // penalty on some cores, so we don't do this unless we have been
1497 // asked to by the core tuning model.
1498 if (Subtarget->useNEONForSinglePrecisionFP()) {
1499 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1500 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1501 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1502 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1503 }
1504 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1505 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1506 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1507 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1508
1509 if (Subtarget->hasFullFP16()) {
1510 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1511 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1512 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1513 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1514
1515 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1516 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1517 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1518 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1519 }
1520 }
1521
1522 // We have target-specific dag combine patterns for the following nodes:
1523 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1524 setTargetDAGCombine(ISD::ADD);
1525 setTargetDAGCombine(ISD::SUB);
1526 setTargetDAGCombine(ISD::MUL);
1527 setTargetDAGCombine(ISD::AND);
1528 setTargetDAGCombine(ISD::OR);
1529 setTargetDAGCombine(ISD::XOR);
1530
1531 if (Subtarget->hasMVEIntegerOps())
1532 setTargetDAGCombine(ISD::VSELECT);
1533
1534 if (Subtarget->hasV6Ops())
1535 setTargetDAGCombine(ISD::SRL);
1536 if (Subtarget->isThumb1Only())
1537 setTargetDAGCombine(ISD::SHL);
1538
1539 setStackPointerRegisterToSaveRestore(ARM::SP);
1540
1541 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1542 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1543 setSchedulingPreference(Sched::RegPressure);
1544 else
1545 setSchedulingPreference(Sched::Hybrid);
1546
1547 //// temporary - rewrite interface to use type
1548 MaxStoresPerMemset = 8;
1549 MaxStoresPerMemsetOptSize = 4;
1550 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1551 MaxStoresPerMemcpyOptSize = 2;
1552 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1553 MaxStoresPerMemmoveOptSize = 2;
1554
1555 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1556 // are at least 4 bytes aligned.
1557 setMinStackArgumentAlignment(Align(4));
1558
1559 // Prefer likely predicted branches to selects on out-of-order cores.
1560 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1561
1562 setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment()));
1563
1564 setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4));
1565
1566 if (Subtarget->isThumb() || Subtarget->isThumb2())
1567 setTargetDAGCombine(ISD::ABS);
1568}
1569
1570bool ARMTargetLowering::useSoftFloat() const {
1571 return Subtarget->useSoftFloat();
1572}
1573
1574// FIXME: It might make sense to define the representative register class as the
1575// nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1576// a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1577// SPR's representative would be DPR_VFP2. This should work well if register
1578// pressure tracking were modified such that a register use would increment the
1579// pressure of the register class's representative and all of it's super
1580// classes' representatives transitively. We have not implemented this because
1581// of the difficulty prior to coalescing of modeling operand register classes
1582// due to the common occurrence of cross class copies and subregister insertions
1583// and extractions.
1584std::pair<const TargetRegisterClass *, uint8_t>
1585ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1586 MVT VT) const {
1587 const TargetRegisterClass *RRC = nullptr;
1588 uint8_t Cost = 1;
1589 switch (VT.SimpleTy) {
1590 default:
1591 return TargetLowering::findRepresentativeClass(TRI, VT);
1592 // Use DPR as representative register class for all floating point
1593 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1594 // the cost is 1 for both f32 and f64.
1595 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1596 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1597 RRC = &ARM::DPRRegClass;
1598 // When NEON is used for SP, only half of the register file is available
1599 // because operations that define both SP and DP results will be constrained
1600 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1601 // coalescing by double-counting the SP regs. See the FIXME above.
1602 if (Subtarget->useNEONForSinglePrecisionFP())
1603 Cost = 2;
1604 break;
1605 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1606 case MVT::v4f32: case MVT::v2f64:
1607 RRC = &ARM::DPRRegClass;
1608 Cost = 2;
1609 break;
1610 case MVT::v4i64:
1611 RRC = &ARM::DPRRegClass;
1612 Cost = 4;
1613 break;
1614 case MVT::v8i64:
1615 RRC = &ARM::DPRRegClass;
1616 Cost = 8;
1617 break;
1618 }
1619 return std::make_pair(RRC, Cost);
1620}
1621
1622const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1623#define MAKE_CASE(V) \
1624 case V: \
1625 return #V;
1626 switch ((ARMISD::NodeType)Opcode) {
1627 case ARMISD::FIRST_NUMBER:
1628 break;
1629 MAKE_CASE(ARMISD::Wrapper)
1630 MAKE_CASE(ARMISD::WrapperPIC)
1631 MAKE_CASE(ARMISD::WrapperJT)
1632 MAKE_CASE(ARMISD::COPY_STRUCT_BYVAL)
1633 MAKE_CASE(ARMISD::CALL)
1634 MAKE_CASE(ARMISD::CALL_PRED)
1635 MAKE_CASE(ARMISD::CALL_NOLINK)
1636 MAKE_CASE(ARMISD::tSECALL)
1637 MAKE_CASE(ARMISD::BRCOND)
1638 MAKE_CASE(ARMISD::BR_JT)
1639 MAKE_CASE(ARMISD::BR2_JT)
1640 MAKE_CASE(ARMISD::RET_FLAG)
1641 MAKE_CASE(ARMISD::SERET_FLAG)
1642 MAKE_CASE(ARMISD::INTRET_FLAG)
1643 MAKE_CASE(ARMISD::PIC_ADD)
1644 MAKE_CASE(ARMISD::CMP)
1645 MAKE_CASE(ARMISD::CMN)
1646 MAKE_CASE(ARMISD::CMPZ)
1647 MAKE_CASE(ARMISD::CMPFP)
1648 MAKE_CASE(ARMISD::CMPFPE)
1649 MAKE_CASE(ARMISD::CMPFPw0)
1650 MAKE_CASE(ARMISD::CMPFPEw0)
1651 MAKE_CASE(ARMISD::BCC_i64)
1652 MAKE_CASE(ARMISD::FMSTAT)
1653 MAKE_CASE(ARMISD::CMOV)
1654 MAKE_CASE(ARMISD::SUBS)
1655 MAKE_CASE(ARMISD::SSAT)
1656 MAKE_CASE(ARMISD::USAT)
1657 MAKE_CASE(ARMISD::ASRL)
1658 MAKE_CASE(ARMISD::LSRL)
1659 MAKE_CASE(ARMISD::LSLL)
1660 MAKE_CASE(ARMISD::SRL_FLAG)
1661 MAKE_CASE(ARMISD::SRA_FLAG)
1662 MAKE_CASE(ARMISD::RRX)
1663 MAKE_CASE(ARMISD::ADDC)
1664 MAKE_CASE(ARMISD::ADDE)
1665 MAKE_CASE(ARMISD::SUBC)
1666 MAKE_CASE(ARMISD::SUBE)
1667 MAKE_CASE(ARMISD::LSLS)
1668 MAKE_CASE(ARMISD::VMOVRRD)
1669 MAKE_CASE(ARMISD::VMOVDRR)
1670 MAKE_CASE(ARMISD::VMOVhr)
1671 MAKE_CASE(ARMISD::VMOVrh)
1672 MAKE_CASE(ARMISD::VMOVSR)
1673 MAKE_CASE(ARMISD::EH_SJLJ_SETJMP)
1674 MAKE_CASE(ARMISD::EH_SJLJ_LONGJMP)
1675 MAKE_CASE(ARMISD::EH_SJLJ_SETUP_DISPATCH)
1676 MAKE_CASE(ARMISD::TC_RETURN)
1677 MAKE_CASE(ARMISD::THREAD_POINTER)
1678 MAKE_CASE(ARMISD::DYN_ALLOC)
1679 MAKE_CASE(ARMISD::MEMBARRIER_MCR)
1680 MAKE_CASE(ARMISD::PRELOAD)
1681 MAKE_CASE(ARMISD::LDRD)
1682 MAKE_CASE(ARMISD::STRD)
1683 MAKE_CASE(ARMISD::WIN__CHKSTK)
1684 MAKE_CASE(ARMISD::WIN__DBZCHK)
1685 MAKE_CASE(ARMISD::PREDICATE_CAST)
1686 MAKE_CASE(ARMISD::VECTOR_REG_CAST)
1687 MAKE_CASE(ARMISD::MVESEXT)
1688 MAKE_CASE(ARMISD::MVEZEXT)
1689 MAKE_CASE(ARMISD::MVETRUNC)
1690 MAKE_CASE(ARMISD::VCMP)
1691 MAKE_CASE(ARMISD::VCMPZ)
1692 MAKE_CASE(ARMISD::VTST)
1693 MAKE_CASE(ARMISD::VSHLs)
1694 MAKE_CASE(ARMISD::VSHLu)
1695 MAKE_CASE(ARMISD::VSHLIMM)
1696 MAKE_CASE(ARMISD::VSHRsIMM)
1697 MAKE_CASE(ARMISD::VSHRuIMM)
1698 MAKE_CASE(ARMISD::VRSHRsIMM)
1699 MAKE_CASE(ARMISD::VRSHRuIMM)
1700 MAKE_CASE(ARMISD::VRSHRNIMM)
1701 MAKE_CASE(ARMISD::VQSHLsIMM)
1702 MAKE_CASE(ARMISD::VQSHLuIMM)
1703 MAKE_CASE(ARMISD::VQSHLsuIMM)
1704 MAKE_CASE(ARMISD::VQSHRNsIMM)
1705 MAKE_CASE(ARMISD::VQSHRNuIMM)
1706 MAKE_CASE(ARMISD::VQSHRNsuIMM)
1707 MAKE_CASE(ARMISD::VQRSHRNsIMM)
1708 MAKE_CASE(ARMISD::VQRSHRNuIMM)
1709 MAKE_CASE(ARMISD::VQRSHRNsuIMM)
1710 MAKE_CASE(ARMISD::VSLIIMM)
1711 MAKE_CASE(ARMISD::VSRIIMM)
1712 MAKE_CASE(ARMISD::VGETLANEu)
1713 MAKE_CASE(ARMISD::VGETLANEs)
1714 MAKE_CASE(ARMISD::VMOVIMM)
1715 MAKE_CASE(ARMISD::VMVNIMM)
1716 MAKE_CASE(ARMISD::VMOVFPIMM)
1717 MAKE_CASE(ARMISD::VDUP)
1718 MAKE_CASE(ARMISD::VDUPLANE)
1719 MAKE_CASE(ARMISD::VEXT)
1720 MAKE_CASE(ARMISD::VREV64)
1721 MAKE_CASE(ARMISD::VREV32)
1722 MAKE_CASE(ARMISD::VREV16)
1723 MAKE_CASE(ARMISD::VZIP)
1724 MAKE_CASE(ARMISD::VUZP)
1725 MAKE_CASE(ARMISD::VTRN)
1726 MAKE_CASE(ARMISD::VTBL1)
1727 MAKE_CASE(ARMISD::VTBL2)
1728 MAKE_CASE(ARMISD::VMOVN)
1729 MAKE_CASE(ARMISD::VQMOVNs)
1730 MAKE_CASE(ARMISD::VQMOVNu)
1731 MAKE_CASE(ARMISD::VCVTN)
1732 MAKE_CASE(ARMISD::VCVTL)
1733 MAKE_CASE(ARMISD::VIDUP)
1734 MAKE_CASE(ARMISD::VMULLs)
1735 MAKE_CASE(ARMISD::VMULLu)
1736 MAKE_CASE(ARMISD::VQDMULH)
1737 MAKE_CASE(ARMISD::VADDVs)
1738 MAKE_CASE(ARMISD::VADDVu)
1739 MAKE_CASE(ARMISD::VADDVps)
1740 MAKE_CASE(ARMISD::VADDVpu)
1741 MAKE_CASE(ARMISD::VADDLVs)
1742 MAKE_CASE(ARMISD::VADDLVu)
1743 MAKE_CASE(ARMISD::VADDLVAs)
1744 MAKE_CASE(ARMISD::VADDLVAu)
1745 MAKE_CASE(ARMISD::VADDLVps)
1746 MAKE_CASE(ARMISD::VADDLVpu)
1747 MAKE_CASE(ARMISD::VADDLVAps)
1748 MAKE_CASE(ARMISD::VADDLVApu)
1749 MAKE_CASE(ARMISD::VMLAVs)
1750 MAKE_CASE(ARMISD::VMLAVu)
1751 MAKE_CASE(ARMISD::VMLAVps)
1752 MAKE_CASE(ARMISD::VMLAVpu)
1753 MAKE_CASE(ARMISD::VMLALVs)
1754 MAKE_CASE(ARMISD::VMLALVu)
1755 MAKE_CASE(ARMISD::VMLALVps)
1756 MAKE_CASE(ARMISD::VMLALVpu)
1757 MAKE_CASE(ARMISD::VMLALVAs)
1758 MAKE_CASE(ARMISD::VMLALVAu)
1759 MAKE_CASE(ARMISD::VMLALVAps)
1760 MAKE_CASE(ARMISD::VMLALVApu)
1761 MAKE_CASE(ARMISD::VMINVu)
1762 MAKE_CASE(ARMISD::VMINVs)
1763 MAKE_CASE(ARMISD::VMAXVu)
1764 MAKE_CASE(ARMISD::VMAXVs)
1765 MAKE_CASE(ARMISD::UMAAL)
1766 MAKE_CASE(ARMISD::UMLAL)
1767 MAKE_CASE(ARMISD::SMLAL)
1768 MAKE_CASE(ARMISD::SMLALBB)
1769 MAKE_CASE(ARMISD::SMLALBT)
1770 MAKE_CASE(ARMISD::SMLALTB)
1771 MAKE_CASE(ARMISD::SMLALTT)
1772 MAKE_CASE(ARMISD::SMULWB)
1773 MAKE_CASE(ARMISD::SMULWT)
1774 MAKE_CASE(ARMISD::SMLALD)
1775 MAKE_CASE(ARMISD::SMLALDX)
1776 MAKE_CASE(ARMISD::SMLSLD)
1777 MAKE_CASE(ARMISD::SMLSLDX)
1778 MAKE_CASE(ARMISD::SMMLAR)
1779 MAKE_CASE(ARMISD::SMMLSR)
1780 MAKE_CASE(ARMISD::QADD16b)
1781 MAKE_CASE(ARMISD::QSUB16b)
1782 MAKE_CASE(ARMISD::QADD8b)
1783 MAKE_CASE(ARMISD::QSUB8b)
1784 MAKE_CASE(ARMISD::UQADD16b)
1785 MAKE_CASE(ARMISD::UQSUB16b)
1786 MAKE_CASE(ARMISD::UQADD8b)
1787 MAKE_CASE(ARMISD::UQSUB8b)
1788 MAKE_CASE(ARMISD::BUILD_VECTOR)
1789 MAKE_CASE(ARMISD::BFI)
1790 MAKE_CASE(ARMISD::VORRIMM)
1791 MAKE_CASE(ARMISD::VBICIMM)
1792 MAKE_CASE(ARMISD::VBSP)
1793 MAKE_CASE(ARMISD::MEMCPY)
1794 MAKE_CASE(ARMISD::VLD1DUP)
1795 MAKE_CASE(ARMISD::VLD2DUP)
1796 MAKE_CASE(ARMISD::VLD3DUP)
1797 MAKE_CASE(ARMISD::VLD4DUP)
1798 MAKE_CASE(ARMISD::VLD1_UPD)
1799 MAKE_CASE(ARMISD::VLD2_UPD)
1800 MAKE_CASE(ARMISD::VLD3_UPD)
1801 MAKE_CASE(ARMISD::VLD4_UPD)
1802 MAKE_CASE(ARMISD::VLD1x2_UPD)
1803 MAKE_CASE(ARMISD::VLD1x3_UPD)
1804 MAKE_CASE(ARMISD::VLD1x4_UPD)
1805 MAKE_CASE(ARMISD::VLD2LN_UPD)
1806 MAKE_CASE(ARMISD::VLD3LN_UPD)
1807 MAKE_CASE(ARMISD::VLD4LN_UPD)
1808 MAKE_CASE(ARMISD::VLD1DUP_UPD)
1809 MAKE_CASE(ARMISD::VLD2DUP_UPD)
1810 MAKE_CASE(ARMISD::VLD3DUP_UPD)
1811 MAKE_CASE(ARMISD::VLD4DUP_UPD)
1812 MAKE_CASE(ARMISD::VST1_UPD)
1813 MAKE_CASE(ARMISD::VST2_UPD)
1814 MAKE_CASE(ARMISD::VST3_UPD)
1815 MAKE_CASE(ARMISD::VST4_UPD)
1816 MAKE_CASE(ARMISD::VST1x2_UPD)
1817 MAKE_CASE(ARMISD::VST1x3_UPD)
1818 MAKE_CASE(ARMISD::VST1x4_UPD)
1819 MAKE_CASE(ARMISD::VST2LN_UPD)
1820 MAKE_CASE(ARMISD::VST3LN_UPD)
1821 MAKE_CASE(ARMISD::VST4LN_UPD)
1822 MAKE_CASE(ARMISD::WLS)
1823 MAKE_CASE(ARMISD::WLSSETUP)
1824 MAKE_CASE(ARMISD::LE)
1825 MAKE_CASE(ARMISD::LOOP_DEC)
1826 MAKE_CASE(ARMISD::CSINV)
1827 MAKE_CASE(ARMISD::CSNEG)
1828 MAKE_CASE(ARMISD::CSINC)
1829 MAKE_CASE(ARMISD::MEMCPYLOOP)
1830 MAKE_CASE(ARMISD::MEMSETLOOP)
1831#undef MAKE_CASE
1832 }
1833 return nullptr;
1834}
1835
1836EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1837 EVT VT) const {
1838 if (!VT.isVector())
1839 return getPointerTy(DL);
1840
1841 // MVE has a predicate register.
1842 if ((Subtarget->hasMVEIntegerOps() &&
1843 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8)) ||
1844 (Subtarget->hasMVEFloatOps() && (VT == MVT::v4f32 || VT == MVT::v8f16)))
1845 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1846 return VT.changeVectorElementTypeToInteger();
1847}
1848
1849/// getRegClassFor - Return the register class that should be used for the
1850/// specified value type.
1851const TargetRegisterClass *
1852ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1853 (void)isDivergent;
1854 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1855 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1856 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1857 // MVE Q registers.
1858 if (Subtarget->hasNEON()) {
1859 if (VT == MVT::v4i64)
1860 return &ARM::QQPRRegClass;
1861 if (VT == MVT::v8i64)
1862 return &ARM::QQQQPRRegClass;
1863 }
1864 if (Subtarget->hasMVEIntegerOps()) {
1865 if (VT == MVT::v4i64)
1866 return &ARM::MQQPRRegClass;
1867 if (VT == MVT::v8i64)
1868 return &ARM::MQQQQPRRegClass;
1869 }
1870 return TargetLowering::getRegClassFor(VT);
1871}
1872
1873// memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1874// source/dest is aligned and the copy size is large enough. We therefore want
1875// to align such objects passed to memory intrinsics.
1876bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1877 unsigned &PrefAlign) const {
1878 if (!isa<MemIntrinsic>(CI))
1879 return false;
1880 MinSize = 8;
1881 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1882 // cycle faster than 4-byte aligned LDM.
1883 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1884 return true;
1885}
1886
1887// Create a fast isel object.
1888FastISel *
1889ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1890 const TargetLibraryInfo *libInfo) const {
1891 return ARM::createFastISel(funcInfo, libInfo);
1892}
1893
1894Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1895 unsigned NumVals = N->getNumValues();
1896 if (!NumVals)
1897 return Sched::RegPressure;
1898
1899 for (unsigned i = 0; i != NumVals; ++i) {
1900 EVT VT = N->getValueType(i);
1901 if (VT == MVT::Glue || VT == MVT::Other)
1902 continue;
1903 if (VT.isFloatingPoint() || VT.isVector())
1904 return Sched::ILP;
1905 }
1906
1907 if (!N->isMachineOpcode())
1908 return Sched::RegPressure;
1909
1910 // Load are scheduled for latency even if there instruction itinerary
1911 // is not available.
1912 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1913 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1914
1915 if (MCID.getNumDefs() == 0)
1916 return Sched::RegPressure;
1917 if (!Itins->isEmpty() &&
1918 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1919 return Sched::ILP;
1920
1921 return Sched::RegPressure;
1922}
1923
1924//===----------------------------------------------------------------------===//
1925// Lowering Code
1926//===----------------------------------------------------------------------===//
1927
1928static bool isSRL16(const SDValue &Op) {
1929 if (Op.getOpcode() != ISD::SRL)
1930 return false;
1931 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1932 return Const->getZExtValue() == 16;
1933 return false;
1934}
1935
1936static bool isSRA16(const SDValue &Op) {
1937 if (Op.getOpcode() != ISD::SRA)
1938 return false;
1939 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1940 return Const->getZExtValue() == 16;
1941 return false;
1942}
1943
1944static bool isSHL16(const SDValue &Op) {
1945 if (Op.getOpcode() != ISD::SHL)
1946 return false;
1947 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1948 return Const->getZExtValue() == 16;
1949 return false;
1950}
1951
1952// Check for a signed 16-bit value. We special case SRA because it makes it
1953// more simple when also looking for SRAs that aren't sign extending a
1954// smaller value. Without the check, we'd need to take extra care with
1955// checking order for some operations.
1956static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1957 if (isSRA16(Op))
1958 return isSHL16(Op.getOperand(0));
1959 return DAG.ComputeNumSignBits(Op) == 17;
1960}
1961
1962/// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1963static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1964 switch (CC) {
1965 default: llvm_unreachable("Unknown condition code!")::llvm::llvm_unreachable_internal("Unknown condition code!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 1965)
;
1966 case ISD::SETNE: return ARMCC::NE;
1967 case ISD::SETEQ: return ARMCC::EQ;
1968 case ISD::SETGT: return ARMCC::GT;
1969 case ISD::SETGE: return ARMCC::GE;
1970 case ISD::SETLT: return ARMCC::LT;
1971 case ISD::SETLE: return ARMCC::LE;
1972 case ISD::SETUGT: return ARMCC::HI;
1973 case ISD::SETUGE: return ARMCC::HS;
1974 case ISD::SETULT: return ARMCC::LO;
1975 case ISD::SETULE: return ARMCC::LS;
1976 }
1977}
1978
1979/// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1980static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1981 ARMCC::CondCodes &CondCode2) {
1982 CondCode2 = ARMCC::AL;
1983 switch (CC) {
1984 default: llvm_unreachable("Unknown FP condition!")::llvm::llvm_unreachable_internal("Unknown FP condition!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 1984)
;
1985 case ISD::SETEQ:
1986 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1987 case ISD::SETGT:
1988 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1989 case ISD::SETGE:
1990 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1991 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1992 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1993 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1994 case ISD::SETO: CondCode = ARMCC::VC; break;
1995 case ISD::SETUO: CondCode = ARMCC::VS; break;
1996 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1997 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1998 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1999 case ISD::SETLT:
2000 case ISD::SETULT: CondCode = ARMCC::LT; break;
2001 case ISD::SETLE:
2002 case ISD::SETULE: CondCode = ARMCC::LE; break;
2003 case ISD::SETNE:
2004 case ISD::SETUNE: CondCode = ARMCC::NE; break;
2005 }
2006}
2007
2008//===----------------------------------------------------------------------===//
2009// Calling Convention Implementation
2010//===----------------------------------------------------------------------===//
2011
2012/// getEffectiveCallingConv - Get the effective calling convention, taking into
2013/// account presence of floating point hardware and calling convention
2014/// limitations, such as support for variadic functions.
2015CallingConv::ID
2016ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
2017 bool isVarArg) const {
2018 switch (CC) {
2019 default:
2020 report_fatal_error("Unsupported calling convention");
2021 case CallingConv::ARM_AAPCS:
2022 case CallingConv::ARM_APCS:
2023 case CallingConv::GHC:
2024 case CallingConv::CFGuard_Check:
2025 return CC;
2026 case CallingConv::PreserveMost:
2027 return CallingConv::PreserveMost;
2028 case CallingConv::ARM_AAPCS_VFP:
2029 case CallingConv::Swift:
2030 case CallingConv::SwiftTail:
2031 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
2032 case CallingConv::C:
2033 case CallingConv::Tail:
2034 if (!Subtarget->isAAPCS_ABI())
2035 return CallingConv::ARM_APCS;
2036 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
2037 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
2038 !isVarArg)
2039 return CallingConv::ARM_AAPCS_VFP;
2040 else
2041 return CallingConv::ARM_AAPCS;
2042 case CallingConv::Fast:
2043 case CallingConv::CXX_FAST_TLS:
2044 if (!Subtarget->isAAPCS_ABI()) {
2045 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
2046 return CallingConv::Fast;
2047 return CallingConv::ARM_APCS;
2048 } else if (Subtarget->hasVFP2Base() &&
2049 !Subtarget->isThumb1Only() && !isVarArg)
2050 return CallingConv::ARM_AAPCS_VFP;
2051 else
2052 return CallingConv::ARM_AAPCS;
2053 }
2054}
2055
2056CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2057 bool isVarArg) const {
2058 return CCAssignFnForNode(CC, false, isVarArg);
2059}
2060
2061CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
2062 bool isVarArg) const {
2063 return CCAssignFnForNode(CC, true, isVarArg);
2064}
2065
2066/// CCAssignFnForNode - Selects the correct CCAssignFn for the given
2067/// CallingConvention.
2068CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
2069 bool Return,
2070 bool isVarArg) const {
2071 switch (getEffectiveCallingConv(CC, isVarArg)) {
2072 default:
2073 report_fatal_error("Unsupported calling convention");
2074 case CallingConv::ARM_APCS:
2075 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
2076 case CallingConv::ARM_AAPCS:
2077 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
2078 case CallingConv::ARM_AAPCS_VFP:
2079 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
2080 case CallingConv::Fast:
2081 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
2082 case CallingConv::GHC:
2083 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
2084 case CallingConv::PreserveMost:
2085 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
2086 case CallingConv::CFGuard_Check:
2087 return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check);
2088 }
2089}
2090
2091SDValue ARMTargetLowering::MoveToHPR(const SDLoc &dl, SelectionDAG &DAG,
2092 MVT LocVT, MVT ValVT, SDValue Val) const {
2093 Val = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocVT.getSizeInBits()),
2094 Val);
2095 if (Subtarget->hasFullFP16()) {
2096 Val = DAG.getNode(ARMISD::VMOVhr, dl, ValVT, Val);
2097 } else {
2098 Val = DAG.getNode(ISD::TRUNCATE, dl,
2099 MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
2100 Val = DAG.getNode(ISD::BITCAST, dl, ValVT, Val);
2101 }
2102 return Val;
2103}
2104
2105SDValue ARMTargetLowering::MoveFromHPR(const SDLoc &dl, SelectionDAG &DAG,
2106 MVT LocVT, MVT ValVT,
2107 SDValue Val) const {
2108 if (Subtarget->hasFullFP16()) {
2109 Val = DAG.getNode(ARMISD::VMOVrh, dl,
2110 MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
2111 } else {
2112 Val = DAG.getNode(ISD::BITCAST, dl,
2113 MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
2114 Val = DAG.getNode(ISD::ZERO_EXTEND, dl,
2115 MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
2116 }
2117 return DAG.getNode(ISD::BITCAST, dl, LocVT, Val);
2118}
2119
2120/// LowerCallResult - Lower the result values of a call into the
2121/// appropriate copies out of appropriate physical registers.
2122SDValue ARMTargetLowering::LowerCallResult(
2123 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2124 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2125 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2126 SDValue ThisVal) const {
2127 // Assign locations to each value returned by this call.
2128 SmallVector<CCValAssign, 16> RVLocs;
2129 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2130 *DAG.getContext());
2131 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
2132
2133 // Copy all of the result registers out of their specified physreg.
2134 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2135 CCValAssign VA = RVLocs[i];
2136
2137 // Pass 'this' value directly from the argument to return value, to avoid
2138 // reg unit interference
2139 if (i == 0 && isThisReturn) {
2140 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&(static_cast <bool> (!VA.needsCustom() && VA.getLocVT
() == MVT::i32 && "unexpected return calling convention register assignment"
) ? void (0) : __assert_fail ("!VA.needsCustom() && VA.getLocVT() == MVT::i32 && \"unexpected return calling convention register assignment\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2141, __extension__ __PRETTY_FUNCTION__))
2141 "unexpected return calling convention register assignment")(static_cast <bool> (!VA.needsCustom() && VA.getLocVT
() == MVT::i32 && "unexpected return calling convention register assignment"
) ? void (0) : __assert_fail ("!VA.needsCustom() && VA.getLocVT() == MVT::i32 && \"unexpected return calling convention register assignment\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2141, __extension__ __PRETTY_FUNCTION__))
;
2142 InVals.push_back(ThisVal);
2143 continue;
2144 }
2145
2146 SDValue Val;
2147 if (VA.needsCustom() &&
2148 (VA.getLocVT() == MVT::f64 || VA.getLocVT() == MVT::v2f64)) {
2149 // Handle f64 or half of a v2f64.
2150 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2151 InFlag);
2152 Chain = Lo.getValue(1);
2153 InFlag = Lo.getValue(2);
2154 VA = RVLocs[++i]; // skip ahead to next loc
2155 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2156 InFlag);
2157 Chain = Hi.getValue(1);
2158 InFlag = Hi.getValue(2);
2159 if (!Subtarget->isLittle())
2160 std::swap (Lo, Hi);
2161 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2162
2163 if (VA.getLocVT() == MVT::v2f64) {
2164 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2165 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2166 DAG.getConstant(0, dl, MVT::i32));
2167
2168 VA = RVLocs[++i]; // skip ahead to next loc
2169 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
2170 Chain = Lo.getValue(1);
2171 InFlag = Lo.getValue(2);
2172 VA = RVLocs[++i]; // skip ahead to next loc
2173 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
2174 Chain = Hi.getValue(1);
2175 InFlag = Hi.getValue(2);
2176 if (!Subtarget->isLittle())
2177 std::swap (Lo, Hi);
2178 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2179 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2180 DAG.getConstant(1, dl, MVT::i32));
2181 }
2182 } else {
2183 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
2184 InFlag);
2185 Chain = Val.getValue(1);
2186 InFlag = Val.getValue(2);
2187 }
2188
2189 switch (VA.getLocInfo()) {
2190 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2190)
;
2191 case CCValAssign::Full: break;
2192 case CCValAssign::BCvt:
2193 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
2194 break;
2195 }
2196
2197 // f16 arguments have their size extended to 4 bytes and passed as if they
2198 // had been copied to the LSBs of a 32-bit register.
2199 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2200 if (VA.needsCustom() &&
2201 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
2202 Val = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Val);
2203
2204 InVals.push_back(Val);
2205 }
2206
2207 return Chain;
2208}
2209
2210std::pair<SDValue, MachinePointerInfo> ARMTargetLowering::computeAddrForCallArg(
2211 const SDLoc &dl, SelectionDAG &DAG, const CCValAssign &VA, SDValue StackPtr,
2212 bool IsTailCall, int SPDiff) const {
2213 SDValue DstAddr;
2214 MachinePointerInfo DstInfo;
2215 int32_t Offset = VA.getLocMemOffset();
2216 MachineFunction &MF = DAG.getMachineFunction();
2217
2218 if (IsTailCall) {
2219 Offset += SPDiff;
2220 auto PtrVT = getPointerTy(DAG.getDataLayout());
2221 int Size = VA.getLocVT().getFixedSizeInBits() / 8;
2222 int FI = MF.getFrameInfo().CreateFixedObject(Size, Offset, true);
2223 DstAddr = DAG.getFrameIndex(FI, PtrVT);
2224 DstInfo =
2225 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
2226 } else {
2227 SDValue PtrOff = DAG.getIntPtrConstant(Offset, dl);
2228 DstAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2229 StackPtr, PtrOff);
2230 DstInfo =
2231 MachinePointerInfo::getStack(DAG.getMachineFunction(), Offset);
2232 }
2233
2234 return std::make_pair(DstAddr, DstInfo);
2235}
2236
2237void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
2238 SDValue Chain, SDValue &Arg,
2239 RegsToPassVector &RegsToPass,
2240 CCValAssign &VA, CCValAssign &NextVA,
2241 SDValue &StackPtr,
2242 SmallVectorImpl<SDValue> &MemOpChains,
2243 bool IsTailCall,
2244 int SPDiff) const {
2245 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2246 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2247 unsigned id = Subtarget->isLittle() ? 0 : 1;
2248 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2249
2250 if (NextVA.isRegLoc())
2251 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2252 else {
2253 assert(NextVA.isMemLoc())(static_cast <bool> (NextVA.isMemLoc()) ? void (0) : __assert_fail
("NextVA.isMemLoc()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2253, __extension__ __PRETTY_FUNCTION__))
;
2254 if (!StackPtr.getNode())
2255 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2256 getPointerTy(DAG.getDataLayout()));
2257
2258 SDValue DstAddr;
2259 MachinePointerInfo DstInfo;
2260 std::tie(DstAddr, DstInfo) =
2261 computeAddrForCallArg(dl, DAG, NextVA, StackPtr, IsTailCall, SPDiff);
2262 MemOpChains.push_back(
2263 DAG.getStore(Chain, dl, fmrrd.getValue(1 - id), DstAddr, DstInfo));
2264 }
2265}
2266
2267static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls) {
2268 return (CC == CallingConv::Fast && GuaranteeTailCalls) ||
2269 CC == CallingConv::Tail || CC == CallingConv::SwiftTail;
2270}
2271
2272/// LowerCall - Lowering a call into a callseq_start <-
2273/// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2274/// nodes.
2275SDValue
2276ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2277 SmallVectorImpl<SDValue> &InVals) const {
2278 SelectionDAG &DAG = CLI.DAG;
2279 SDLoc &dl = CLI.DL;
2280 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2281 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2282 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2283 SDValue Chain = CLI.Chain;
2284 SDValue Callee = CLI.Callee;
2285 bool &isTailCall = CLI.IsTailCall;
2286 CallingConv::ID CallConv = CLI.CallConv;
2287 bool doesNotRet = CLI.DoesNotReturn;
2288 bool isVarArg = CLI.IsVarArg;
2289
2290 MachineFunction &MF = DAG.getMachineFunction();
2291 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2292 MachineFunction::CallSiteInfo CSInfo;
2293 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2294 bool isThisReturn = false;
2295 bool isCmseNSCall = false;
2296 bool isSibCall = false;
2297 bool PreferIndirect = false;
2298
2299 // Determine whether this is a non-secure function call.
2300 if (CLI.CB && CLI.CB->getAttributes().hasFnAttr("cmse_nonsecure_call"))
2301 isCmseNSCall = true;
2302
2303 // Disable tail calls if they're not supported.
2304 if (!Subtarget->supportsTailCall())
2305 isTailCall = false;
2306
2307 // For both the non-secure calls and the returns from a CMSE entry function,
2308 // the function needs to do some extra work afte r the call, or before the
2309 // return, respectively, thus it cannot end with atail call
2310 if (isCmseNSCall || AFI->isCmseNSEntryFunction())
2311 isTailCall = false;
2312
2313 if (isa<GlobalAddressSDNode>(Callee)) {
2314 // If we're optimizing for minimum size and the function is called three or
2315 // more times in this block, we can improve codesize by calling indirectly
2316 // as BLXr has a 16-bit encoding.
2317 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2318 if (CLI.CB) {
2319 auto *BB = CLI.CB->getParent();
2320 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2321 count_if(GV->users(), [&BB](const User *U) {
2322 return isa<Instruction>(U) &&
2323 cast<Instruction>(U)->getParent() == BB;
2324 }) > 2;
2325 }
2326 }
2327 if (isTailCall) {
2328 // Check if it's really possible to do a tail call.
2329 isTailCall = IsEligibleForTailCallOptimization(
2330 Callee, CallConv, isVarArg, isStructRet,
2331 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2332 PreferIndirect);
2333
2334 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt &&
2335 CallConv != CallingConv::Tail && CallConv != CallingConv::SwiftTail)
2336 isSibCall = true;
2337
2338 // We don't support GuaranteedTailCallOpt for ARM, only automatically
2339 // detected sibcalls.
2340 if (isTailCall)
2341 ++NumTailCalls;
2342 }
2343
2344 if (!isTailCall && CLI.CB && CLI.CB->isMustTailCall())
2345 report_fatal_error("failed to perform tail call elimination on a call "
2346 "site marked musttail");
2347 // Analyze operands of the call, assigning locations to each operand.
2348 SmallVector<CCValAssign, 16> ArgLocs;
2349 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2350 *DAG.getContext());
2351 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2352
2353 // Get a count of how many bytes are to be pushed on the stack.
2354 unsigned NumBytes = CCInfo.getNextStackOffset();
2355
2356 // SPDiff is the byte offset of the call's argument area from the callee's.
2357 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2358 // by this amount for a tail call. In a sibling call it must be 0 because the
2359 // caller will deallocate the entire stack and the callee still expects its
2360 // arguments to begin at SP+0. Completely unused for non-tail calls.
2361 int SPDiff = 0;
2362
2363 if (isTailCall && !isSibCall) {
2364 auto FuncInfo = MF.getInfo<ARMFunctionInfo>();
2365 unsigned NumReusableBytes = FuncInfo->getArgumentStackSize();
2366
2367 // Since callee will pop argument stack as a tail call, we must keep the
2368 // popped size 16-byte aligned.
2369 Align StackAlign = DAG.getDataLayout().getStackAlignment();
2370 NumBytes = alignTo(NumBytes, StackAlign);
2371
2372 // SPDiff will be negative if this tail call requires more space than we
2373 // would automatically have in our incoming argument space. Positive if we
2374 // can actually shrink the stack.
2375 SPDiff = NumReusableBytes - NumBytes;
2376
2377 // If this call requires more stack than we have available from
2378 // LowerFormalArguments, tell FrameLowering to reserve space for it.
2379 if (SPDiff < 0 && AFI->getArgRegsSaveSize() < (unsigned)-SPDiff)
2380 AFI->setArgRegsSaveSize(-SPDiff);
2381 }
2382
2383 if (isSibCall) {
2384 // For sibling tail calls, memory operands are available in our caller's stack.
2385 NumBytes = 0;
2386 } else {
2387 // Adjust the stack pointer for the new arguments...
2388 // These operations are automatically eliminated by the prolog/epilog pass
2389 Chain = DAG.getCALLSEQ_START(Chain, isTailCall ? 0 : NumBytes, 0, dl);
2390 }
2391
2392 SDValue StackPtr =
2393 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2394
2395 RegsToPassVector RegsToPass;
2396 SmallVector<SDValue, 8> MemOpChains;
2397
2398 // During a tail call, stores to the argument area must happen after all of
2399 // the function's incoming arguments have been loaded because they may alias.
2400 // This is done by folding in a TokenFactor from LowerFormalArguments, but
2401 // there's no point in doing so repeatedly so this tracks whether that's
2402 // happened yet.
2403 bool AfterFormalArgLoads = false;
2404
2405 // Walk the register/memloc assignments, inserting copies/loads. In the case
2406 // of tail call optimization, arguments are handled later.
2407 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2408 i != e;
2409 ++i, ++realArgIdx) {
2410 CCValAssign &VA = ArgLocs[i];
2411 SDValue Arg = OutVals[realArgIdx];
2412 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2413 bool isByVal = Flags.isByVal();
2414
2415 // Promote the value if needed.
2416 switch (VA.getLocInfo()) {
2417 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2417)
;
2418 case CCValAssign::Full: break;
2419 case CCValAssign::SExt:
2420 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2421 break;
2422 case CCValAssign::ZExt:
2423 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2424 break;
2425 case CCValAssign::AExt:
2426 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2427 break;
2428 case CCValAssign::BCvt:
2429 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2430 break;
2431 }
2432
2433 if (isTailCall && VA.isMemLoc() && !AfterFormalArgLoads) {
2434 Chain = DAG.getStackArgumentTokenFactor(Chain);
2435 AfterFormalArgLoads = true;
2436 }
2437
2438 // f16 arguments have their size extended to 4 bytes and passed as if they
2439 // had been copied to the LSBs of a 32-bit register.
2440 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2441 if (VA.needsCustom() &&
2442 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) {
2443 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
2444 } else {
2445 // f16 arguments could have been extended prior to argument lowering.
2446 // Mask them arguments if this is a CMSE nonsecure call.
2447 auto ArgVT = Outs[realArgIdx].ArgVT;
2448 if (isCmseNSCall && (ArgVT == MVT::f16)) {
2449 auto LocBits = VA.getLocVT().getSizeInBits();
2450 auto MaskValue = APInt::getLowBitsSet(LocBits, ArgVT.getSizeInBits());
2451 SDValue Mask =
2452 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
2453 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
2454 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
2455 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2456 }
2457 }
2458
2459 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2460 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
2461 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2462 DAG.getConstant(0, dl, MVT::i32));
2463 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2464 DAG.getConstant(1, dl, MVT::i32));
2465
2466 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, VA, ArgLocs[++i],
2467 StackPtr, MemOpChains, isTailCall, SPDiff);
2468
2469 VA = ArgLocs[++i]; // skip ahead to next loc
2470 if (VA.isRegLoc()) {
2471 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, VA, ArgLocs[++i],
2472 StackPtr, MemOpChains, isTailCall, SPDiff);
2473 } else {
2474 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2474, __extension__ __PRETTY_FUNCTION__))
;
2475 SDValue DstAddr;
2476 MachinePointerInfo DstInfo;
2477 std::tie(DstAddr, DstInfo) =
2478 computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2479 MemOpChains.push_back(DAG.getStore(Chain, dl, Op1, DstAddr, DstInfo));
2480 }
2481 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
2482 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2483 StackPtr, MemOpChains, isTailCall, SPDiff);
2484 } else if (VA.isRegLoc()) {
2485 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2486 Outs[0].VT == MVT::i32) {
2487 assert(VA.getLocVT() == MVT::i32 &&(static_cast <bool> (VA.getLocVT() == MVT::i32 &&
"unexpected calling convention register assignment") ? void (
0) : __assert_fail ("VA.getLocVT() == MVT::i32 && \"unexpected calling convention register assignment\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2488, __extension__ __PRETTY_FUNCTION__))
2488 "unexpected calling convention register assignment")(static_cast <bool> (VA.getLocVT() == MVT::i32 &&
"unexpected calling convention register assignment") ? void (
0) : __assert_fail ("VA.getLocVT() == MVT::i32 && \"unexpected calling convention register assignment\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2488, __extension__ __PRETTY_FUNCTION__))
;
2489 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&(static_cast <bool> (!Ins.empty() && Ins[0].VT ==
MVT::i32 && "unexpected use of 'returned'") ? void (
0) : __assert_fail ("!Ins.empty() && Ins[0].VT == MVT::i32 && \"unexpected use of 'returned'\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2490, __extension__ __PRETTY_FUNCTION__))
2490 "unexpected use of 'returned'")(static_cast <bool> (!Ins.empty() && Ins[0].VT ==
MVT::i32 && "unexpected use of 'returned'") ? void (
0) : __assert_fail ("!Ins.empty() && Ins[0].VT == MVT::i32 && \"unexpected use of 'returned'\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2490, __extension__ __PRETTY_FUNCTION__))
;
2491 isThisReturn = true;
2492 }
2493 const TargetOptions &Options = DAG.getTarget().Options;
2494 if (Options.EmitCallSiteInfo)
2495 CSInfo.emplace_back(VA.getLocReg(), i);
2496 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2497 } else if (isByVal) {
2498 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2498, __extension__ __PRETTY_FUNCTION__))
;
2499 unsigned offset = 0;
2500
2501 // True if this byval aggregate will be split between registers
2502 // and memory.
2503 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2504 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2505
2506 if (CurByValIdx < ByValArgsCount) {
2507
2508 unsigned RegBegin, RegEnd;
2509 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2510
2511 EVT PtrVT =
2512 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2513 unsigned int i, j;
2514 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2515 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2516 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2517 SDValue Load =
2518 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(),
2519 DAG.InferPtrAlign(AddArg));
2520 MemOpChains.push_back(Load.getValue(1));
2521 RegsToPass.push_back(std::make_pair(j, Load));
2522 }
2523
2524 // If parameter size outsides register area, "offset" value
2525 // helps us to calculate stack slot for remained part properly.
2526 offset = RegEnd - RegBegin;
2527
2528 CCInfo.nextInRegsParam();
2529 }
2530
2531 if (Flags.getByValSize() > 4*offset) {
2532 auto PtrVT = getPointerTy(DAG.getDataLayout());
2533 SDValue Dst;
2534 MachinePointerInfo DstInfo;
2535 std::tie(Dst, DstInfo) =
2536 computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2537 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2538 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2539 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2540 MVT::i32);
2541 SDValue AlignNode =
2542 DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32);
2543
2544 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2545 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2546 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2547 Ops));
2548 }
2549 } else {
2550 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2550, __extension__ __PRETTY_FUNCTION__))
;
2551 SDValue DstAddr;
2552 MachinePointerInfo DstInfo;
2553 std::tie(DstAddr, DstInfo) =
2554 computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2555
2556 SDValue Store = DAG.getStore(Chain, dl, Arg, DstAddr, DstInfo);
2557 MemOpChains.push_back(Store);
2558 }
2559 }
2560
2561 if (!MemOpChains.empty())
2562 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2563
2564 // Build a sequence of copy-to-reg nodes chained together with token chain
2565 // and flag operands which copy the outgoing args into the appropriate regs.
2566 SDValue InFlag;
2567 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2568 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2569 RegsToPass[i].second, InFlag);
2570 InFlag = Chain.getValue(1);
2571 }
2572
2573 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2574 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2575 // node so that legalize doesn't hack it.
2576 bool isDirect = false;
2577
2578 const TargetMachine &TM = getTargetMachine();
2579 const Module *Mod = MF.getFunction().getParent();
2580 const GlobalValue *GV = nullptr;
2581 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2582 GV = G->getGlobal();
2583 bool isStub =
2584 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2585
2586 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2587 bool isLocalARMFunc = false;
2588 auto PtrVt = getPointerTy(DAG.getDataLayout());
2589
2590 if (Subtarget->genLongCalls()) {
2591 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&(static_cast <bool> ((!isPositionIndependent() || Subtarget
->isTargetWindows()) && "long-calls codegen is not position independent!"
) ? void (0) : __assert_fail ("(!isPositionIndependent() || Subtarget->isTargetWindows()) && \"long-calls codegen is not position independent!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2592, __extension__ __PRETTY_FUNCTION__))
2592 "long-calls codegen is not position independent!")(static_cast <bool> ((!isPositionIndependent() || Subtarget
->isTargetWindows()) && "long-calls codegen is not position independent!"
) ? void (0) : __assert_fail ("(!isPositionIndependent() || Subtarget->isTargetWindows()) && \"long-calls codegen is not position independent!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2592, __extension__ __PRETTY_FUNCTION__))
;
2593 // Handle a global address or an external symbol. If it's not one of
2594 // those, the target's already in a register, so we don't need to do
2595 // anything extra.
2596 if (isa<GlobalAddressSDNode>(Callee)) {
2597 // Create a constant pool entry for the callee address
2598 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2599 ARMConstantPoolValue *CPV =
2600 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2601
2602 // Get the address of the callee into a register
2603 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2604 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2605 Callee = DAG.getLoad(
2606 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2607 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2608 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2609 const char *Sym = S->getSymbol();
2610
2611 // Create a constant pool entry for the callee address
2612 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2613 ARMConstantPoolValue *CPV =
2614 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2615 ARMPCLabelIndex, 0);
2616 // Get the address of the callee into a register
2617 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2618 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2619 Callee = DAG.getLoad(
2620 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2621 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2622 }
2623 } else if (isa<GlobalAddressSDNode>(Callee)) {
2624 if (!PreferIndirect) {
2625 isDirect = true;
2626 bool isDef = GV->isStrongDefinitionForLinker();
2627
2628 // ARM call to a local ARM function is predicable.
2629 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2630 // tBX takes a register source operand.
2631 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2632 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?")(static_cast <bool> (Subtarget->isTargetMachO() &&
"WrapperPIC use on non-MachO?") ? void (0) : __assert_fail (
"Subtarget->isTargetMachO() && \"WrapperPIC use on non-MachO?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2632, __extension__ __PRETTY_FUNCTION__))
;
2633 Callee = DAG.getNode(
2634 ARMISD::WrapperPIC, dl, PtrVt,
2635 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2636 Callee = DAG.getLoad(
2637 PtrVt, dl, DAG.getEntryNode(), Callee,
2638 MachinePointerInfo::getGOT(DAG.getMachineFunction()), MaybeAlign(),
2639 MachineMemOperand::MODereferenceable |
2640 MachineMemOperand::MOInvariant);
2641 } else if (Subtarget->isTargetCOFF()) {
2642 assert(Subtarget->isTargetWindows() &&(static_cast <bool> (Subtarget->isTargetWindows() &&
"Windows is the only supported COFF target") ? void (0) : __assert_fail
("Subtarget->isTargetWindows() && \"Windows is the only supported COFF target\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2643, __extension__ __PRETTY_FUNCTION__))
2643 "Windows is the only supported COFF target")(static_cast <bool> (Subtarget->isTargetWindows() &&
"Windows is the only supported COFF target") ? void (0) : __assert_fail
("Subtarget->isTargetWindows() && \"Windows is the only supported COFF target\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2643, __extension__ __PRETTY_FUNCTION__))
;
2644 unsigned TargetFlags = ARMII::MO_NO_FLAG;
2645 if (GV->hasDLLImportStorageClass())
2646 TargetFlags = ARMII::MO_DLLIMPORT;
2647 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
2648 TargetFlags = ARMII::MO_COFFSTUB;
2649 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0,
2650 TargetFlags);
2651 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
2652 Callee =
2653 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2654 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2655 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2656 } else {
2657 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2658 }
2659 }
2660 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2661 isDirect = true;
2662 // tBX takes a register source operand.
2663 const char *Sym = S->getSymbol();
2664 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2665 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2666 ARMConstantPoolValue *CPV =
2667 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2668 ARMPCLabelIndex, 4);
2669 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2670 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2671 Callee = DAG.getLoad(
2672 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2673 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2674 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2675 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2676 } else {
2677 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2678 }
2679 }
2680
2681 if (isCmseNSCall) {
2682 assert(!isARMFunc && !isDirect &&(static_cast <bool> (!isARMFunc && !isDirect &&
"Cannot handle call to ARM function or direct call") ? void (
0) : __assert_fail ("!isARMFunc && !isDirect && \"Cannot handle call to ARM function or direct call\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2683, __extension__ __PRETTY_FUNCTION__))
2683 "Cannot handle call to ARM function or direct call")(static_cast <bool> (!isARMFunc && !isDirect &&
"Cannot handle call to ARM function or direct call") ? void (
0) : __assert_fail ("!isARMFunc && !isDirect && \"Cannot handle call to ARM function or direct call\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2683, __extension__ __PRETTY_FUNCTION__))
;
2684 if (NumBytes > 0) {
2685 DiagnosticInfoUnsupported Diag(DAG.getMachineFunction().getFunction(),
2686 "call to non-secure function would "
2687 "require passing arguments on stack",
2688 dl.getDebugLoc());
2689 DAG.getContext()->diagnose(Diag);
2690 }
2691 if (isStructRet) {
2692 DiagnosticInfoUnsupported Diag(
2693 DAG.getMachineFunction().getFunction(),
2694 "call to non-secure function would return value through pointer",
2695 dl.getDebugLoc());
2696 DAG.getContext()->diagnose(Diag);
2697 }
2698 }
2699
2700 // FIXME: handle tail calls differently.
2701 unsigned CallOpc;
2702 if (Subtarget->isThumb()) {
2703 if (isCmseNSCall)
2704 CallOpc = ARMISD::tSECALL;
2705 else if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2706 CallOpc = ARMISD::CALL_NOLINK;
2707 else
2708 CallOpc = ARMISD::CALL;
2709 } else {
2710 if (!isDirect && !Subtarget->hasV5TOps())
2711 CallOpc = ARMISD::CALL_NOLINK;
2712 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2713 // Emit regular call when code size is the priority
2714 !Subtarget->hasMinSize())
2715 // "mov lr, pc; b _foo" to avoid confusing the RSP
2716 CallOpc = ARMISD::CALL_NOLINK;
2717 else
2718 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2719 }
2720
2721 // We don't usually want to end the call-sequence here because we would tidy
2722 // the frame up *after* the call, however in the ABI-changing tail-call case
2723 // we've carefully laid out the parameters so that when sp is reset they'll be
2724 // in the correct location.
2725 if (isTailCall && !isSibCall) {
2726 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
2727 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2728 InFlag = Chain.getValue(1);
2729 }
2730
2731 std::vector<SDValue> Ops;
2732 Ops.push_back(Chain);
2733 Ops.push_back(Callee);
2734
2735 if (isTailCall) {
2736 Ops.push_back(DAG.getTargetConstant(SPDiff, dl, MVT::i32));
2737 }
2738
2739 // Add argument registers to the end of the list so that they are known live
2740 // into the call.
2741 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2742 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2743 RegsToPass[i].second.getValueType()));
2744
2745 // Add a register mask operand representing the call-preserved registers.
2746 if (!isTailCall) {
2747 const uint32_t *Mask;
2748 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2749 if (isThisReturn) {
2750 // For 'this' returns, use the R0-preserving mask if applicable
2751 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2752 if (!Mask) {
2753 // Set isThisReturn to false if the calling convention is not one that
2754 // allows 'returned' to be modeled in this way, so LowerCallResult does
2755 // not try to pass 'this' straight through
2756 isThisReturn = false;
2757 Mask = ARI->getCallPreservedMask(MF, CallConv);
2758 }
2759 } else
2760 Mask = ARI->getCallPreservedMask(MF, CallConv);
2761
2762 assert(Mask && "Missing call preserved mask for calling convention")(static_cast <bool> (Mask && "Missing call preserved mask for calling convention"
) ? void (0) : __assert_fail ("Mask && \"Missing call preserved mask for calling convention\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2762, __extension__ __PRETTY_FUNCTION__))
;
2763 Ops.push_back(DAG.getRegisterMask(Mask));
2764 }
2765
2766 if (InFlag.getNode())
2767 Ops.push_back(InFlag);
2768
2769 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2770 if (isTailCall) {
2771 MF.getFrameInfo().setHasTailCall();
2772 SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2773 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
2774 return Ret;
2775 }
2776
2777 // Returns a chain and a flag for retval copy to use.
2778 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2779 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2780 InFlag = Chain.getValue(1);
2781 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
2782
2783 // If we're guaranteeing tail-calls will be honoured, the callee must
2784 // pop its own argument stack on return. But this call is *not* a tail call so
2785 // we need to undo that after it returns to restore the status-quo.
2786 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
2787 uint64_t CalleePopBytes =
2788 canGuaranteeTCO(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : -1ULL;
2789
2790 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2791 DAG.getIntPtrConstant(CalleePopBytes, dl, true),
2792 InFlag, dl);
2793 if (!Ins.empty())
2794 InFlag = Chain.getValue(1);
2795
2796 // Handle result values, copying them out of physregs into vregs that we
2797 // return.
2798 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2799 InVals, isThisReturn,
2800 isThisReturn ? OutVals[0] : SDValue());
2801}
2802
2803/// HandleByVal - Every parameter *after* a byval parameter is passed
2804/// on the stack. Remember the next parameter register to allocate,
2805/// and then confiscate the rest of the parameter registers to insure
2806/// this.
2807void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2808 Align Alignment) const {
2809 // Byval (as with any stack) slots are always at least 4 byte aligned.
2810 Alignment = std::max(Alignment, Align(4));
2811
2812 unsigned Reg = State->AllocateReg(GPRArgRegs);
2813 if (!Reg)
2814 return;
2815
2816 unsigned AlignInRegs = Alignment.value() / 4;
2817 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2818 for (unsigned i = 0; i < Waste; ++i)
2819 Reg = State->AllocateReg(GPRArgRegs);
2820
2821 if (!Reg)
2822 return;
2823
2824 unsigned Excess = 4 * (ARM::R4 - Reg);
2825
2826 // Special case when NSAA != SP and parameter size greater than size of
2827 // all remained GPR regs. In that case we can't split parameter, we must
2828 // send it to stack. We also must set NCRN to R4, so waste all
2829 // remained registers.
2830 const unsigned NSAAOffset = State->getNextStackOffset();
2831 if (NSAAOffset != 0 && Size > Excess) {
2832 while (State->AllocateReg(GPRArgRegs))
2833 ;
2834 return;
2835 }
2836
2837 // First register for byval parameter is the first register that wasn't
2838 // allocated before this method call, so it would be "reg".
2839 // If parameter is small enough to be saved in range [reg, r4), then
2840 // the end (first after last) register would be reg + param-size-in-regs,
2841 // else parameter would be splitted between registers and stack,
2842 // end register would be r4 in this case.
2843 unsigned ByValRegBegin = Reg;
2844 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2845 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2846 // Note, first register is allocated in the beginning of function already,
2847 // allocate remained amount of registers we need.
2848 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2849 State->AllocateReg(GPRArgRegs);
2850 // A byval parameter that is split between registers and memory needs its
2851 // size truncated here.
2852 // In the case where the entire structure fits in registers, we set the
2853 // size in memory to zero.
2854 Size = std::max<int>(Size - Excess, 0);
2855}
2856
2857/// MatchingStackOffset - Return true if the given stack call argument is
2858/// already available in the same position (relatively) of the caller's
2859/// incoming argument stack.
2860static
2861bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2862 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2863 const TargetInstrInfo *TII) {
2864 unsigned Bytes = Arg.getValueSizeInBits() / 8;
2865 int FI = std::numeric_limits<int>::max();
2866 if (Arg.getOpcode() == ISD::CopyFromReg) {
2867 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2868 if (!Register::isVirtualRegister(VR))
2869 return false;
2870 MachineInstr *Def = MRI->getVRegDef(VR);
2871 if (!Def)
2872 return false;
2873 if (!Flags.isByVal()) {
2874 if (!TII->isLoadFromStackSlot(*Def, FI))
2875 return false;
2876 } else {
2877 return false;
2878 }
2879 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2880 if (Flags.isByVal())
2881 // ByVal argument is passed in as a pointer but it's now being
2882 // dereferenced. e.g.
2883 // define @foo(%struct.X* %A) {
2884 // tail call @bar(%struct.X* byval %A)
2885 // }
2886 return false;
2887 SDValue Ptr = Ld->getBasePtr();
2888 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2889 if (!FINode)
2890 return false;
2891 FI = FINode->getIndex();
2892 } else
2893 return false;
2894
2895 assert(FI != std::numeric_limits<int>::max())(static_cast <bool> (FI != std::numeric_limits<int>
::max()) ? void (0) : __assert_fail ("FI != std::numeric_limits<int>::max()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2895, __extension__ __PRETTY_FUNCTION__))
;
2896 if (!MFI.isFixedObjectIndex(FI))
2897 return false;
2898 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2899}
2900
2901/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2902/// for tail call optimization. Targets which want to do tail call
2903/// optimization should implement this function.
2904bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2905 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2906 bool isCalleeStructRet, bool isCallerStructRet,
2907 const SmallVectorImpl<ISD::OutputArg> &Outs,
2908 const SmallVectorImpl<SDValue> &OutVals,
2909 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2910 const bool isIndirect) const {
2911 MachineFunction &MF = DAG.getMachineFunction();
2912 const Function &CallerF = MF.getFunction();
2913 CallingConv::ID CallerCC = CallerF.getCallingConv();
2914
2915 assert(Subtarget->supportsTailCall())(static_cast <bool> (Subtarget->supportsTailCall()) ?
void (0) : __assert_fail ("Subtarget->supportsTailCall()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 2915, __extension__ __PRETTY_FUNCTION__))
;
2916
2917 // Indirect tail calls cannot be optimized for Thumb1 if the args
2918 // to the call take up r0-r3. The reason is that there are no legal registers
2919 // left to hold the pointer to the function to be called.
2920 if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2921 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2922 return false;
2923
2924 // Look for obvious safe cases to perform tail call optimization that do not
2925 // require ABI changes. This is what gcc calls sibcall.
2926
2927 // Exception-handling functions need a special set of instructions to indicate
2928 // a return to the hardware. Tail-calling another function would probably
2929 // break this.
2930 if (CallerF.hasFnAttribute("interrupt"))
2931 return false;
2932
2933 if (canGuaranteeTCO(CalleeCC, getTargetMachine().Options.GuaranteedTailCallOpt))
2934 return CalleeCC == CallerCC;
2935
2936 // Also avoid sibcall optimization if either caller or callee uses struct
2937 // return semantics.
2938 if (isCalleeStructRet || isCallerStructRet)
2939 return false;
2940
2941 // Externally-defined functions with weak linkage should not be
2942 // tail-called on ARM when the OS does not support dynamic
2943 // pre-emption of symbols, as the AAELF spec requires normal calls
2944 // to undefined weak functions to be replaced with a NOP or jump to the
2945 // next instruction. The behaviour of branch instructions in this
2946 // situation (as used for tail calls) is implementation-defined, so we
2947 // cannot rely on the linker replacing the tail call with a return.
2948 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2949 const GlobalValue *GV = G->getGlobal();
2950 const Triple &TT = getTargetMachine().getTargetTriple();
2951 if (GV->hasExternalWeakLinkage() &&
2952 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2953 return false;
2954 }
2955
2956 // Check that the call results are passed in the same way.
2957 LLVMContext &C = *DAG.getContext();
2958 if (!CCState::resultsCompatible(
2959 getEffectiveCallingConv(CalleeCC, isVarArg),
2960 getEffectiveCallingConv(CallerCC, CallerF.isVarArg()), MF, C, Ins,
2961 CCAssignFnForReturn(CalleeCC, isVarArg),
2962 CCAssignFnForReturn(CallerCC, CallerF.isVarArg())))
2963 return false;
2964 // The callee has to preserve all registers the caller needs to preserve.
2965 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2966 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2967 if (CalleeCC != CallerCC) {
2968 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2969 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2970 return false;
2971 }
2972
2973 // If Caller's vararg or byval argument has been split between registers and
2974 // stack, do not perform tail call, since part of the argument is in caller's
2975 // local frame.
2976 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2977 if (AFI_Caller->getArgRegsSaveSize())
2978 return false;
2979
2980 // If the callee takes no arguments then go on to check the results of the
2981 // call.
2982 if (!Outs.empty()) {
2983 // Check if stack adjustment is needed. For now, do not do this if any
2984 // argument is passed on the stack.
2985 SmallVector<CCValAssign, 16> ArgLocs;
2986 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2987 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2988 if (CCInfo.getNextStackOffset()) {
2989 // Check if the arguments are already laid out in the right way as
2990 // the caller's fixed stack objects.
2991 MachineFrameInfo &MFI = MF.getFrameInfo();
2992 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2993 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2994 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2995 i != e;
2996 ++i, ++realArgIdx) {
2997 CCValAssign &VA = ArgLocs[i];
2998 EVT RegVT = VA.getLocVT();
2999 SDValue Arg = OutVals[realArgIdx];
3000 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3001 if (VA.getLocInfo() == CCValAssign::Indirect)
3002 return false;
3003 if (VA.needsCustom() && (RegVT == MVT::f64 || RegVT == MVT::v2f64)) {
3004 // f64 and vector types are split into multiple registers or
3005 // register/stack-slot combinations. The types will not match
3006 // the registers; give up on memory f64 refs until we figure
3007 // out what to do about this.
3008 if (!VA.isRegLoc())
3009 return false;
3010 if (!ArgLocs[++i].isRegLoc())
3011 return false;
3012 if (RegVT == MVT::v2f64) {
3013 if (!ArgLocs[++i].isRegLoc())
3014 return false;
3015 if (!ArgLocs[++i].isRegLoc())
3016 return false;
3017 }
3018 } else if (!VA.isRegLoc()) {
3019 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3020 MFI, MRI, TII))
3021 return false;
3022 }
3023 }
3024 }
3025
3026 const MachineRegisterInfo &MRI = MF.getRegInfo();
3027 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3028 return false;
3029 }
3030
3031 return true;
3032}
3033
3034bool
3035ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3036 MachineFunction &MF, bool isVarArg,
3037 const SmallVectorImpl<ISD::OutputArg> &Outs,
3038 LLVMContext &Context) const {
3039 SmallVector<CCValAssign, 16> RVLocs;
3040 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3041 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
3042}
3043
3044static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
3045 const SDLoc &DL, SelectionDAG &DAG) {
3046 const MachineFunction &MF = DAG.getMachineFunction();
3047 const Function &F = MF.getFunction();
3048
3049 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
3050
3051 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
3052 // version of the "preferred return address". These offsets affect the return
3053 // instruction if this is a return from PL1 without hypervisor extensions.
3054 // IRQ/FIQ: +4 "subs pc, lr, #4"
3055 // SWI: 0 "subs pc, lr, #0"
3056 // ABORT: +4 "subs pc, lr, #4"
3057 // UNDEF: +4/+2 "subs pc, lr, #0"
3058 // UNDEF varies depending on where the exception came from ARM or Thumb
3059 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
3060
3061 int64_t LROffset;
3062 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
3063 IntKind == "ABORT")
3064 LROffset = 4;
3065 else if (IntKind == "SWI" || IntKind == "UNDEF")
3066 LROffset = 0;
3067 else
3068 report_fatal_error("Unsupported interrupt attribute. If present, value "
3069 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
3070
3071 RetOps.insert(RetOps.begin() + 1,
3072 DAG.getConstant(LROffset, DL, MVT::i32, false));
3073
3074 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
3075}
3076
3077SDValue
3078ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3079 bool isVarArg,
3080 const SmallVectorImpl<ISD::OutputArg> &Outs,
3081 const SmallVectorImpl<SDValue> &OutVals,
3082 const SDLoc &dl, SelectionDAG &DAG) const {
3083 // CCValAssign - represent the assignment of the return value to a location.
3084 SmallVector<CCValAssign, 16> RVLocs;
3085
3086 // CCState - Info about the registers and stack slots.
3087 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3088 *DAG.getContext());
3089
3090 // Analyze outgoing return values.
3091 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
3092
3093 SDValue Flag;
3094 SmallVector<SDValue, 4> RetOps;
3095 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
3096 bool isLittleEndian = Subtarget->isLittle();
3097
3098 MachineFunction &MF = DAG.getMachineFunction();
3099 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3100 AFI->setReturnRegsCount(RVLocs.size());
3101
3102 // Report error if cmse entry function returns structure through first ptr arg.
3103 if (AFI->isCmseNSEntryFunction() && MF.getFunction().hasStructRetAttr()) {
3104 // Note: using an empty SDLoc(), as the first line of the function is a
3105 // better place to report than the last line.
3106 DiagnosticInfoUnsupported Diag(
3107 DAG.getMachineFunction().getFunction(),
3108 "secure entry function would return value through pointer",
3109 SDLoc().getDebugLoc());
3110 DAG.getContext()->diagnose(Diag);
3111 }
3112
3113 // Copy the result values into the output registers.
3114 for (unsigned i = 0, realRVLocIdx = 0;
3115 i != RVLocs.size();
3116 ++i, ++realRVLocIdx) {
3117 CCValAssign &VA = RVLocs[i];
3118 assert(VA.isRegLoc() && "Can only return in registers!")(static_cast <bool> (VA.isRegLoc() && "Can only return in registers!"
) ? void (0) : __assert_fail ("VA.isRegLoc() && \"Can only return in registers!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3118, __extension__ __PRETTY_FUNCTION__))
;
3119
3120 SDValue Arg = OutVals[realRVLocIdx];
3121 bool ReturnF16 = false;
3122
3123 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
3124 // Half-precision return values can be returned like this:
3125 //
3126 // t11 f16 = fadd ...
3127 // t12: i16 = bitcast t11
3128 // t13: i32 = zero_extend t12
3129 // t14: f32 = bitcast t13 <~~~~~~~ Arg
3130 //
3131 // to avoid code generation for bitcasts, we simply set Arg to the node
3132 // that produces the f16 value, t11 in this case.
3133 //
3134 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
3135 SDValue ZE = Arg.getOperand(0);
3136 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
3137 SDValue BC = ZE.getOperand(0);
3138 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
3139 Arg = BC.getOperand(0);
3140 ReturnF16 = true;
3141 }
3142 }
3143 }
3144 }
3145
3146 switch (VA.getLocInfo()) {
3147 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3147)
;
3148 case CCValAssign::Full: break;
3149 case CCValAssign::BCvt:
3150 if (!ReturnF16)
3151 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3152 break;
3153 }
3154
3155 // Mask f16 arguments if this is a CMSE nonsecure entry.
3156 auto RetVT = Outs[realRVLocIdx].ArgVT;
3157 if (AFI->isCmseNSEntryFunction() && (RetVT == MVT::f16)) {
3158 if (VA.needsCustom() && VA.getValVT() == MVT::f16) {
3159 Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
3160 } else {
3161 auto LocBits = VA.getLocVT().getSizeInBits();
3162 auto MaskValue = APInt::getLowBitsSet(LocBits, RetVT.getSizeInBits());
3163 SDValue Mask =
3164 DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
3165 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
3166 Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
3167 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3168 }
3169 }
3170
3171 if (VA.needsCustom() &&
3172 (VA.getLocVT() == MVT::v2f64 || VA.getLocVT() == MVT::f64)) {
3173 if (VA.getLocVT() == MVT::v2f64) {
3174 // Extract the first half and return it in two registers.
3175 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3176 DAG.getConstant(0, dl, MVT::i32));
3177 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
3178 DAG.getVTList(MVT::i32, MVT::i32), Half);
3179
3180 Chain =
3181 DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3182 HalfGPRs.getValue(isLittleEndian ? 0 : 1), Flag);
3183 Flag = Chain.getValue(1);
3184 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3185 VA = RVLocs[++i]; // skip ahead to next loc
3186 Chain =
3187 DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3188 HalfGPRs.getValue(isLittleEndian ? 1 : 0), Flag);
3189 Flag = Chain.getValue(1);
3190 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3191 VA = RVLocs[++i]; // skip ahead to next loc
3192
3193 // Extract the 2nd half and fall through to handle it as an f64 value.
3194 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3195 DAG.getConstant(1, dl, MVT::i32));
3196 }
3197 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
3198 // available.
3199 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
3200 DAG.getVTList(MVT::i32, MVT::i32), Arg);
3201 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3202 fmrrd.getValue(isLittleEndian ? 0 : 1), Flag);
3203 Flag = Chain.getValue(1);
3204 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3205 VA = RVLocs[++i]; // skip ahead to next loc
3206 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3207 fmrrd.getValue(isLittleEndian ? 1 : 0), Flag);
3208 } else
3209 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
3210
3211 // Guarantee that all emitted copies are
3212 // stuck together, avoiding something bad.
3213 Flag = Chain.getValue(1);
3214 RetOps.push_back(DAG.getRegister(
3215 VA.getLocReg(), ReturnF16 ? Arg.getValueType() : VA.getLocVT()));
3216 }
3217 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
3218 const MCPhysReg *I =
3219 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3220 if (I) {
3221 for (; *I; ++I) {
3222 if (ARM::GPRRegClass.contains(*I))
3223 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
3224 else if (ARM::DPRRegClass.contains(*I))
3225 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3226 else
3227 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3227)
;
3228 }
3229 }
3230
3231 // Update chain and glue.
3232 RetOps[0] = Chain;
3233 if (Flag.getNode())
3234 RetOps.push_back(Flag);
3235
3236 // CPUs which aren't M-class use a special sequence to return from
3237 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
3238 // though we use "subs pc, lr, #N").
3239 //
3240 // M-class CPUs actually use a normal return sequence with a special
3241 // (hardware-provided) value in LR, so the normal code path works.
3242 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
3243 !Subtarget->isMClass()) {
3244 if (Subtarget->isThumb1Only())
3245 report_fatal_error("interrupt attribute is not supported in Thumb1");
3246 return LowerInterruptReturn(RetOps, dl, DAG);
3247 }
3248
3249 ARMISD::NodeType RetNode = AFI->isCmseNSEntryFunction() ? ARMISD::SERET_FLAG :
3250 ARMISD::RET_FLAG;
3251 return DAG.getNode(RetNode, dl, MVT::Other, RetOps);
3252}
3253
3254bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
3255 if (N->getNumValues() != 1)
3256 return false;
3257 if (!N->hasNUsesOfValue(1, 0))
3258 return false;
3259
3260 SDValue TCChain = Chain;
3261 SDNode *Copy = *N->use_begin();
3262 if (Copy->getOpcode() == ISD::CopyToReg) {
3263 // If the copy has a glue operand, we conservatively assume it isn't safe to
3264 // perform a tail call.
3265 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3266 return false;
3267 TCChain = Copy->getOperand(0);
3268 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
3269 SDNode *VMov = Copy;
3270 // f64 returned in a pair of GPRs.
3271 SmallPtrSet<SDNode*, 2> Copies;
3272 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
3273 UI != UE; ++UI) {
3274 if (UI->getOpcode() != ISD::CopyToReg)
3275 return false;
3276 Copies.insert(*UI);
3277 }
3278 if (Copies.size() > 2)
3279 return false;
3280
3281 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
3282 UI != UE; ++UI) {
3283 SDValue UseChain = UI->getOperand(0);
3284 if (Copies.count(UseChain.getNode()))
3285 // Second CopyToReg
3286 Copy = *UI;
3287 else {
3288 // We are at the top of this chain.
3289 // If the copy has a glue operand, we conservatively assume it
3290 // isn't safe to perform a tail call.
3291 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
3292 return false;
3293 // First CopyToReg
3294 TCChain = UseChain;
3295 }
3296 }
3297 } else if (Copy->getOpcode() == ISD::BITCAST) {
3298 // f32 returned in a single GPR.
3299 if (!Copy->hasOneUse())
3300 return false;
3301 Copy = *Copy->use_begin();
3302 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
3303 return false;
3304 // If the copy has a glue operand, we conservatively assume it isn't safe to
3305 // perform a tail call.
3306 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3307 return false;
3308 TCChain = Copy->getOperand(0);
3309 } else {
3310 return false;
3311 }
3312
3313 bool HasRet = false;
3314 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
3315 UI != UE; ++UI) {
3316 if (UI->getOpcode() != ARMISD::RET_FLAG &&
3317 UI->getOpcode() != ARMISD::INTRET_FLAG)
3318 return false;
3319 HasRet = true;
3320 }
3321
3322 if (!HasRet)
3323 return false;
3324
3325 Chain = TCChain;
3326 return true;
3327}
3328
3329bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3330 if (!Subtarget->supportsTailCall())
3331 return false;
3332
3333 if (!CI->isTailCall())
3334 return false;
3335
3336 return true;
3337}
3338
3339// Trying to write a 64 bit value so need to split into two 32 bit values first,
3340// and pass the lower and high parts through.
3341static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
3342 SDLoc DL(Op);
3343 SDValue WriteValue = Op->getOperand(2);
3344
3345 // This function is only supposed to be called for i64 type argument.
3346 assert(WriteValue.getValueType() == MVT::i64(static_cast <bool> (WriteValue.getValueType() == MVT::
i64 && "LowerWRITE_REGISTER called for non-i64 type argument."
) ? void (0) : __assert_fail ("WriteValue.getValueType() == MVT::i64 && \"LowerWRITE_REGISTER called for non-i64 type argument.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3347, __extension__ __PRETTY_FUNCTION__))
3347 && "LowerWRITE_REGISTER called for non-i64 type argument.")(static_cast <bool> (WriteValue.getValueType() == MVT::
i64 && "LowerWRITE_REGISTER called for non-i64 type argument."
) ? void (0) : __assert_fail ("WriteValue.getValueType() == MVT::i64 && \"LowerWRITE_REGISTER called for non-i64 type argument.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3347, __extension__ __PRETTY_FUNCTION__))
;
3348
3349 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
3350 DAG.getConstant(0, DL, MVT::i32));
3351 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
3352 DAG.getConstant(1, DL, MVT::i32));
3353 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
3354 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
3355}
3356
3357// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3358// their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
3359// one of the above mentioned nodes. It has to be wrapped because otherwise
3360// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3361// be used to form addressing mode. These wrapped nodes will be selected
3362// into MOVi.
3363SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
3364 SelectionDAG &DAG) const {
3365 EVT PtrVT = Op.getValueType();
3366 // FIXME there is no actual debug info here
3367 SDLoc dl(Op);
3368 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3369 SDValue Res;
3370
3371 // When generating execute-only code Constant Pools must be promoted to the
3372 // global data section. It's a bit ugly that we can't share them across basic
3373 // blocks, but this way we guarantee that execute-only behaves correct with
3374 // position-independent addressing modes.
3375 if (Subtarget->genExecuteOnly()) {
3376 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3377 auto T = const_cast<Type*>(CP->getType());
3378 auto C = const_cast<Constant*>(CP->getConstVal());
3379 auto M = const_cast<Module*>(DAG.getMachineFunction().
3380 getFunction().getParent());
3381 auto GV = new GlobalVariable(
3382 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
3383 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
3384 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
3385 Twine(AFI->createPICLabelUId())
3386 );
3387 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
3388 dl, PtrVT);
3389 return LowerGlobalAddress(GA, DAG);
3390 }
3391
3392 if (CP->isMachineConstantPoolEntry())
3393 Res =
3394 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign());
3395 else
3396 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign());
3397 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
3398}
3399
3400unsigned ARMTargetLowering::getJumpTableEncoding() const {
3401 return MachineJumpTableInfo::EK_Inline;
3402}
3403
3404SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3405 SelectionDAG &DAG) const {
3406 MachineFunction &MF = DAG.getMachineFunction();
3407 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3408 unsigned ARMPCLabelIndex = 0;
3409 SDLoc DL(Op);
3410 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3411 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3412 SDValue CPAddr;
3413 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3414 if (!IsPositionIndependent) {
3415 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, Align(4));
3416 } else {
3417 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3418 ARMPCLabelIndex = AFI->createPICLabelUId();
3419 ARMConstantPoolValue *CPV =
3420 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3421 ARMCP::CPBlockAddress, PCAdj);
3422 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3423 }
3424 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3425 SDValue Result = DAG.getLoad(
3426 PtrVT, DL, DAG.getEntryNode(), CPAddr,
3427 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3428 if (!IsPositionIndependent)
3429 return Result;
3430 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3431 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3432}
3433
3434/// Convert a TLS address reference into the correct sequence of loads
3435/// and calls to compute the variable's address for Darwin, and return an
3436/// SDValue containing the final node.
3437
3438/// Darwin only has one TLS scheme which must be capable of dealing with the
3439/// fully general situation, in the worst case. This means:
3440/// + "extern __thread" declaration.
3441/// + Defined in a possibly unknown dynamic library.
3442///
3443/// The general system is that each __thread variable has a [3 x i32] descriptor
3444/// which contains information used by the runtime to calculate the address. The
3445/// only part of this the compiler needs to know about is the first word, which
3446/// contains a function pointer that must be called with the address of the
3447/// entire descriptor in "r0".
3448///
3449/// Since this descriptor may be in a different unit, in general access must
3450/// proceed along the usual ARM rules. A common sequence to produce is:
3451///
3452/// movw rT1, :lower16:_var$non_lazy_ptr
3453/// movt rT1, :upper16:_var$non_lazy_ptr
3454/// ldr r0, [rT1]
3455/// ldr rT2, [r0]
3456/// blx rT2
3457/// [...address now in r0...]
3458SDValue
3459ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3460 SelectionDAG &DAG) const {
3461 assert(Subtarget->isTargetDarwin() &&(static_cast <bool> (Subtarget->isTargetDarwin() &&
"This function expects a Darwin target") ? void (0) : __assert_fail
("Subtarget->isTargetDarwin() && \"This function expects a Darwin target\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3462, __extension__ __PRETTY_FUNCTION__))
3462 "This function expects a Darwin target")(static_cast <bool> (Subtarget->isTargetDarwin() &&
"This function expects a Darwin target") ? void (0) : __assert_fail
("Subtarget->isTargetDarwin() && \"This function expects a Darwin target\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3462, __extension__ __PRETTY_FUNCTION__))
;
3463 SDLoc DL(Op);
3464
3465 // First step is to get the address of the actua global symbol. This is where
3466 // the TLS descriptor lives.
3467 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3468
3469 // The first entry in the descriptor is a function pointer that we must call
3470 // to obtain the address of the variable.
3471 SDValue Chain = DAG.getEntryNode();
3472 SDValue FuncTLVGet = DAG.getLoad(
3473 MVT::i32, DL, Chain, DescAddr,
3474 MachinePointerInfo::getGOT(DAG.getMachineFunction()), Align(4),
3475 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3476 MachineMemOperand::MOInvariant);
3477 Chain = FuncTLVGet.getValue(1);
3478
3479 MachineFunction &F = DAG.getMachineFunction();
3480 MachineFrameInfo &MFI = F.getFrameInfo();
3481 MFI.setAdjustsStack(true);
3482
3483 // TLS calls preserve all registers except those that absolutely must be
3484 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3485 // silly).
3486 auto TRI =
3487 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3488 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3489 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3490
3491 // Finally, we can make the call. This is just a degenerate version of a
3492 // normal AArch64 call node: r0 takes the address of the descriptor, and
3493 // returns the address of the variable in this thread.
3494 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3495 Chain =
3496 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3497 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3498 DAG.getRegisterMask(Mask), Chain.getValue(1));
3499 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3500}
3501
3502SDValue
3503ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3504 SelectionDAG &DAG) const {
3505 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering")(static_cast <bool> (Subtarget->isTargetWindows() &&
"Windows specific TLS lowering") ? void (0) : __assert_fail (
"Subtarget->isTargetWindows() && \"Windows specific TLS lowering\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3505, __extension__ __PRETTY_FUNCTION__))
;
3506
3507 SDValue Chain = DAG.getEntryNode();
3508 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3509 SDLoc DL(Op);
3510
3511 // Load the current TEB (thread environment block)
3512 SDValue Ops[] = {Chain,
3513 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3514 DAG.getTargetConstant(15, DL, MVT::i32),
3515 DAG.getTargetConstant(0, DL, MVT::i32),
3516 DAG.getTargetConstant(13, DL, MVT::i32),
3517 DAG.getTargetConstant(0, DL, MVT::i32),
3518 DAG.getTargetConstant(2, DL, MVT::i32)};
3519 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3520 DAG.getVTList(MVT::i32, MVT::Other), Ops);
3521
3522 SDValue TEB = CurrentTEB.getValue(0);
3523 Chain = CurrentTEB.getValue(1);
3524
3525 // Load the ThreadLocalStoragePointer from the TEB
3526 // A pointer to the TLS array is located at offset 0x2c from the TEB.
3527 SDValue TLSArray =
3528 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3529 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3530
3531 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3532 // offset into the TLSArray.
3533
3534 // Load the TLS index from the C runtime
3535 SDValue TLSIndex =
3536 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3537 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3538 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3539
3540 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3541 DAG.getConstant(2, DL, MVT::i32));
3542 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3543 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3544 MachinePointerInfo());
3545
3546 // Get the offset of the start of the .tls section (section base)
3547 const auto *GA = cast<GlobalAddressSDNode>(Op);
3548 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3549 SDValue Offset = DAG.getLoad(
3550 PtrVT, DL, Chain,
3551 DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3552 DAG.getTargetConstantPool(CPV, PtrVT, Align(4))),
3553 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3554
3555 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3556}
3557
3558// Lower ISD::GlobalTLSAddress using the "general dynamic" model
3559SDValue
3560ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3561 SelectionDAG &DAG) const {
3562 SDLoc dl(GA);
3563 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3564 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3565 MachineFunction &MF = DAG.getMachineFunction();
3566 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3567 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3568 ARMConstantPoolValue *CPV =
3569 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3570 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3571 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3572 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3573 Argument = DAG.getLoad(
3574 PtrVT, dl, DAG.getEntryNode(), Argument,
3575 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3576 SDValue Chain = Argument.getValue(1);
3577
3578 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3579 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3580
3581 // call __tls_get_addr.
3582 ArgListTy Args;
3583 ArgListEntry Entry;
3584 Entry.Node = Argument;
3585 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3586 Args.push_back(Entry);
3587
3588 // FIXME: is there useful debug info available here?
3589 TargetLowering::CallLoweringInfo CLI(DAG);
3590 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3591 CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3592 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3593
3594 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3595 return CallResult.first;
3596}
3597
3598// Lower ISD::GlobalTLSAddress using the "initial exec" or
3599// "local exec" model.
3600SDValue
3601ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3602 SelectionDAG &DAG,
3603 TLSModel::Model model) const {
3604 const GlobalValue *GV = GA->getGlobal();
3605 SDLoc dl(GA);
3606 SDValue Offset;
3607 SDValue Chain = DAG.getEntryNode();
3608 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3609 // Get the Thread Pointer
3610 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3611
3612 if (model == TLSModel::InitialExec) {
3613 MachineFunction &MF = DAG.getMachineFunction();
3614 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3615 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3616 // Initial exec model.
3617 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3618 ARMConstantPoolValue *CPV =
3619 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3620 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3621 true);
3622 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3623 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3624 Offset = DAG.getLoad(
3625 PtrVT, dl, Chain, Offset,
3626 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3627 Chain = Offset.getValue(1);
3628
3629 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3630 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3631
3632 Offset = DAG.getLoad(
3633 PtrVT, dl, Chain, Offset,
3634 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3635 } else {
3636 // local exec model
3637 assert(model == TLSModel::LocalExec)(static_cast <bool> (model == TLSModel::LocalExec) ? void
(0) : __assert_fail ("model == TLSModel::LocalExec", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3637, __extension__ __PRETTY_FUNCTION__))
;
3638 ARMConstantPoolValue *CPV =
3639 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3640 Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3641 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3642 Offset = DAG.getLoad(
3643 PtrVT, dl, Chain, Offset,
3644 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3645 }
3646
3647 // The address of the thread local variable is the add of the thread
3648 // pointer with the offset of the variable.
3649 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3650}
3651
3652SDValue
3653ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3654 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3655 if (DAG.getTarget().useEmulatedTLS())
3656 return LowerToTLSEmulatedModel(GA, DAG);
3657
3658 if (Subtarget->isTargetDarwin())
3659 return LowerGlobalTLSAddressDarwin(Op, DAG);
3660
3661 if (Subtarget->isTargetWindows())
3662 return LowerGlobalTLSAddressWindows(Op, DAG);
3663
3664 // TODO: implement the "local dynamic" model
3665 assert(Subtarget->isTargetELF() && "Only ELF implemented here")(static_cast <bool> (Subtarget->isTargetELF() &&
"Only ELF implemented here") ? void (0) : __assert_fail ("Subtarget->isTargetELF() && \"Only ELF implemented here\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3665, __extension__ __PRETTY_FUNCTION__))
;
3666 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3667
3668 switch (model) {
3669 case TLSModel::GeneralDynamic:
3670 case TLSModel::LocalDynamic:
3671 return LowerToTLSGeneralDynamicModel(GA, DAG);
3672 case TLSModel::InitialExec:
3673 case TLSModel::LocalExec:
3674 return LowerToTLSExecModels(GA, DAG, model);
3675 }
3676 llvm_unreachable("bogus TLS model")::llvm::llvm_unreachable_internal("bogus TLS model", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3676)
;
3677}
3678
3679/// Return true if all users of V are within function F, looking through
3680/// ConstantExprs.
3681static bool allUsersAreInFunction(const Value *V, const Function *F) {
3682 SmallVector<const User*,4> Worklist(V->users());
3683 while (!Worklist.empty()) {
3684 auto *U = Worklist.pop_back_val();
3685 if (isa<ConstantExpr>(U)) {
3686 append_range(Worklist, U->users());
3687 continue;
3688 }
3689
3690 auto *I = dyn_cast<Instruction>(U);
3691 if (!I || I->getParent()->getParent() != F)
3692 return false;
3693 }
3694 return true;
3695}
3696
3697static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3698 const GlobalValue *GV, SelectionDAG &DAG,
3699 EVT PtrVT, const SDLoc &dl) {
3700 // If we're creating a pool entry for a constant global with unnamed address,
3701 // and the global is small enough, we can emit it inline into the constant pool
3702 // to save ourselves an indirection.
3703 //
3704 // This is a win if the constant is only used in one function (so it doesn't
3705 // need to be duplicated) or duplicating the constant wouldn't increase code
3706 // size (implying the constant is no larger than 4 bytes).
3707 const Function &F = DAG.getMachineFunction().getFunction();
3708
3709 // We rely on this decision to inline being idemopotent and unrelated to the
3710 // use-site. We know that if we inline a variable at one use site, we'll
3711 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3712 // doesn't know about this optimization, so bail out if it's enabled else
3713 // we could decide to inline here (and thus never emit the GV) but require
3714 // the GV from fast-isel generated code.
3715 if (!EnableConstpoolPromotion ||
3716 DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3717 return SDValue();
3718
3719 auto *GVar = dyn_cast<GlobalVariable>(GV);
3720 if (!GVar || !GVar->hasInitializer() ||
3721 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3722 !GVar->hasLocalLinkage())
3723 return SDValue();
3724
3725 // If we inline a value that contains relocations, we move the relocations
3726 // from .data to .text. This is not allowed in position-independent code.
3727 auto *Init = GVar->getInitializer();
3728 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3729 Init->needsDynamicRelocation())
3730 return SDValue();
3731
3732 // The constant islands pass can only really deal with alignment requests
3733 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3734 // any type wanting greater alignment requirements than 4 bytes. We also
3735 // can only promote constants that are multiples of 4 bytes in size or
3736 // are paddable to a multiple of 4. Currently we only try and pad constants
3737 // that are strings for simplicity.
3738 auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3739 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3740 Align PrefAlign = DAG.getDataLayout().getPreferredAlign(GVar);
3741 unsigned RequiredPadding = 4 - (Size % 4);
3742 bool PaddingPossible =
3743 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3744 if (!PaddingPossible || PrefAlign > 4 || Size > ConstpoolPromotionMaxSize ||
3745 Size == 0)
3746 return SDValue();
3747
3748 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3749 MachineFunction &MF = DAG.getMachineFunction();
3750 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3751
3752 // We can't bloat the constant pool too much, else the ConstantIslands pass
3753 // may fail to converge. If we haven't promoted this global yet (it may have
3754 // multiple uses), and promoting it would increase the constant pool size (Sz
3755 // > 4), ensure we have space to do so up to MaxTotal.
3756 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3757 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3758 ConstpoolPromotionMaxTotal)
3759 return SDValue();
3760
3761 // This is only valid if all users are in a single function; we can't clone
3762 // the constant in general. The LLVM IR unnamed_addr allows merging
3763 // constants, but not cloning them.
3764 //
3765 // We could potentially allow cloning if we could prove all uses of the
3766 // constant in the current function don't care about the address, like
3767 // printf format strings. But that isn't implemented for now.
3768 if (!allUsersAreInFunction(GVar, &F))
3769 return SDValue();
3770
3771 // We're going to inline this global. Pad it out if needed.
3772 if (RequiredPadding != 4) {
3773 StringRef S = CDAInit->getAsString();
3774
3775 SmallVector<uint8_t,16> V(S.size());
3776 std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3777 while (RequiredPadding--)
3778 V.push_back(0);
3779 Init = ConstantDataArray::get(*DAG.getContext(), V);
3780 }
3781
3782 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3783 SDValue CPAddr = DAG.getTargetConstantPool(CPVal, PtrVT, Align(4));
3784 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3785 AFI->markGlobalAsPromotedToConstantPool(GVar);
3786 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3787 PaddedSize - 4);
3788 }
3789 ++NumConstpoolPromoted;
3790 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3791}
3792
3793bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3794 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3795 if (!(GV = GA->getBaseObject()))
3796 return false;
3797 if (const auto *V = dyn_cast<GlobalVariable>(GV))
3798 return V->isConstant();
3799 return isa<Function>(GV);
3800}
3801
3802SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3803 SelectionDAG &DAG) const {
3804 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3805 default: llvm_unreachable("unknown object format")::llvm::llvm_unreachable_internal("unknown object format", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3805)
;
3806 case Triple::COFF:
3807 return LowerGlobalAddressWindows(Op, DAG);
3808 case Triple::ELF:
3809 return LowerGlobalAddressELF(Op, DAG);
3810 case Triple::MachO:
3811 return LowerGlobalAddressDarwin(Op, DAG);
3812 }
3813}
3814
3815SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3816 SelectionDAG &DAG) const {
3817 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3818 SDLoc dl(Op);
3819 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3820 const TargetMachine &TM = getTargetMachine();
3821 bool IsRO = isReadOnly(GV);
3822
3823 // promoteToConstantPool only if not generating XO text section
3824 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3825 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3826 return V;
3827
3828 if (isPositionIndependent()) {
3829 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3830 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3831 UseGOT_PREL ? ARMII::MO_GOT : 0);
3832 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3833 if (UseGOT_PREL)
3834 Result =
3835 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3836 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3837 return Result;
3838 } else if (Subtarget->isROPI() && IsRO) {
3839 // PC-relative.
3840 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3841 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3842 return Result;
3843 } else if (Subtarget->isRWPI() && !IsRO) {
3844 // SB-relative.
3845 SDValue RelAddr;
3846 if (Subtarget->useMovt()) {
3847 ++NumMovwMovt;
3848 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3849 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3850 } else { // use literal pool for address constant
3851 ARMConstantPoolValue *CPV =
3852 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3853 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3854 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3855 RelAddr = DAG.getLoad(
3856 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3857 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3858 }
3859 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3860 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3861 return Result;
3862 }
3863
3864 // If we have T2 ops, we can materialize the address directly via movt/movw
3865 // pair. This is always cheaper.
3866 if (Subtarget->useMovt()) {
3867 ++NumMovwMovt;
3868 // FIXME: Once remat is capable of dealing with instructions with register
3869 // operands, expand this into two nodes.
3870 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3871 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3872 } else {
3873 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, Align(4));
3874 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3875 return DAG.getLoad(
3876 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3877 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3878 }
3879}
3880
3881SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3882 SelectionDAG &DAG) const {
3883 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&(static_cast <bool> (!Subtarget->isROPI() &&
!Subtarget->isRWPI() && "ROPI/RWPI not currently supported for Darwin"
) ? void (0) : __assert_fail ("!Subtarget->isROPI() && !Subtarget->isRWPI() && \"ROPI/RWPI not currently supported for Darwin\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3884, __extension__ __PRETTY_FUNCTION__))
3884 "ROPI/RWPI not currently supported for Darwin")(static_cast <bool> (!Subtarget->isROPI() &&
!Subtarget->isRWPI() && "ROPI/RWPI not currently supported for Darwin"
) ? void (0) : __assert_fail ("!Subtarget->isROPI() && !Subtarget->isRWPI() && \"ROPI/RWPI not currently supported for Darwin\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3884, __extension__ __PRETTY_FUNCTION__))
;
3885 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3886 SDLoc dl(Op);
3887 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3888
3889 if (Subtarget->useMovt())
3890 ++NumMovwMovt;
3891
3892 // FIXME: Once remat is capable of dealing with instructions with register
3893 // operands, expand this into multiple nodes
3894 unsigned Wrapper =
3895 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3896
3897 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3898 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3899
3900 if (Subtarget->isGVIndirectSymbol(GV))
3901 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3902 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3903 return Result;
3904}
3905
3906SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3907 SelectionDAG &DAG) const {
3908 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported")(static_cast <bool> (Subtarget->isTargetWindows() &&
"non-Windows COFF is not supported") ? void (0) : __assert_fail
("Subtarget->isTargetWindows() && \"non-Windows COFF is not supported\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3908, __extension__ __PRETTY_FUNCTION__))
;
3909 assert(Subtarget->useMovt() &&(static_cast <bool> (Subtarget->useMovt() &&
"Windows on ARM expects to use movw/movt") ? void (0) : __assert_fail
("Subtarget->useMovt() && \"Windows on ARM expects to use movw/movt\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3910, __extension__ __PRETTY_FUNCTION__))
3910 "Windows on ARM expects to use movw/movt")(static_cast <bool> (Subtarget->useMovt() &&
"Windows on ARM expects to use movw/movt") ? void (0) : __assert_fail
("Subtarget->useMovt() && \"Windows on ARM expects to use movw/movt\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3910, __extension__ __PRETTY_FUNCTION__))
;
3911 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&(static_cast <bool> (!Subtarget->isROPI() &&
!Subtarget->isRWPI() && "ROPI/RWPI not currently supported for Windows"
) ? void (0) : __assert_fail ("!Subtarget->isROPI() && !Subtarget->isRWPI() && \"ROPI/RWPI not currently supported for Windows\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3912, __extension__ __PRETTY_FUNCTION__))
3912 "ROPI/RWPI not currently supported for Windows")(static_cast <bool> (!Subtarget->isROPI() &&
!Subtarget->isRWPI() && "ROPI/RWPI not currently supported for Windows"
) ? void (0) : __assert_fail ("!Subtarget->isROPI() && !Subtarget->isRWPI() && \"ROPI/RWPI not currently supported for Windows\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3912, __extension__ __PRETTY_FUNCTION__))
;
3913
3914 const TargetMachine &TM = getTargetMachine();
3915 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3916 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3917 if (GV->hasDLLImportStorageClass())
3918 TargetFlags = ARMII::MO_DLLIMPORT;
3919 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3920 TargetFlags = ARMII::MO_COFFSTUB;
3921 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3922 SDValue Result;
3923 SDLoc DL(Op);
3924
3925 ++NumMovwMovt;
3926
3927 // FIXME: Once remat is capable of dealing with instructions with register
3928 // operands, expand this into two nodes.
3929 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3930 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3931 TargetFlags));
3932 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3933 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3934 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3935 return Result;
3936}
3937
3938SDValue
3939ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3940 SDLoc dl(Op);
3941 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3942 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3943 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3944 Op.getOperand(1), Val);
3945}
3946
3947SDValue
3948ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3949 SDLoc dl(Op);
3950 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3951 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3952}
3953
3954SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3955 SelectionDAG &DAG) const {
3956 SDLoc dl(Op);
3957 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3958 Op.getOperand(0));
3959}
3960
3961SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3962 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3963 unsigned IntNo =
3964 cast<ConstantSDNode>(
3965 Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other))
3966 ->getZExtValue();
3967 switch (IntNo) {
3968 default:
3969 return SDValue(); // Don't custom lower most intrinsics.
3970 case Intrinsic::arm_gnu_eabi_mcount: {
3971 MachineFunction &MF = DAG.getMachineFunction();
3972 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3973 SDLoc dl(Op);
3974 SDValue Chain = Op.getOperand(0);
3975 // call "\01__gnu_mcount_nc"
3976 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3977 const uint32_t *Mask =
3978 ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3979 assert(Mask && "Missing call preserved mask for calling convention")(static_cast <bool> (Mask && "Missing call preserved mask for calling convention"
) ? void (0) : __assert_fail ("Mask && \"Missing call preserved mask for calling convention\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 3979, __extension__ __PRETTY_FUNCTION__))
;
3980 // Mark LR an implicit live-in.
3981 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3982 SDValue ReturnAddress =
3983 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3984 constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue};
3985 SDValue Callee =
3986 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3987 SDValue RegisterMask = DAG.getRegisterMask(Mask);
3988 if (Subtarget->isThumb())
3989 return SDValue(
3990 DAG.getMachineNode(
3991 ARM::tBL_PUSHLR, dl, ResultTys,
3992 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
3993 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
3994 0);
3995 return SDValue(
3996 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
3997 {ReturnAddress, Callee, RegisterMask, Chain}),
3998 0);
3999 }
4000 }
4001}
4002
4003SDValue
4004ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
4005 const ARMSubtarget *Subtarget) const {
4006 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4007 SDLoc dl(Op);
4008 switch (IntNo) {
4009 default: return SDValue(); // Don't custom lower most intrinsics.
4010 case Intrinsic::thread_pointer: {
4011 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4012 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
4013 }
4014 case Intrinsic::arm_cls: {
4015 const SDValue &Operand = Op.getOperand(1);
4016 const EVT VTy = Op.getValueType();
4017 SDValue SRA =
4018 DAG.getNode(ISD::SRA, dl, VTy, Operand, DAG.getConstant(31, dl, VTy));
4019 SDValue XOR = DAG.getNode(ISD::XOR, dl, VTy, SRA, Operand);
4020 SDValue SHL =
4021 DAG.getNode(ISD::SHL, dl, VTy, XOR, DAG.getConstant(1, dl, VTy));
4022 SDValue OR =
4023 DAG.getNode(ISD::OR, dl, VTy, SHL, DAG.getConstant(1, dl, VTy));
4024 SDValue Result = DAG.getNode(ISD::CTLZ, dl, VTy, OR);
4025 return Result;
4026 }
4027 case Intrinsic::arm_cls64: {
4028 // cls(x) = if cls(hi(x)) != 31 then cls(hi(x))
4029 // else 31 + clz(if hi(x) == 0 then lo(x) else not(lo(x)))
4030 const SDValue &Operand = Op.getOperand(1);
4031 const EVT VTy = Op.getValueType();
4032
4033 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
4034 DAG.getConstant(1, dl, VTy));
4035 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
4036 DAG.getConstant(0, dl, VTy));
4037 SDValue Constant0 = DAG.getConstant(0, dl, VTy);
4038 SDValue Constant1 = DAG.getConstant(1, dl, VTy);
4039 SDValue Constant31 = DAG.getConstant(31, dl, VTy);
4040 SDValue SRAHi = DAG.getNode(ISD::SRA, dl, VTy, Hi, Constant31);
4041 SDValue XORHi = DAG.getNode(ISD::XOR, dl, VTy, SRAHi, Hi);
4042 SDValue SHLHi = DAG.getNode(ISD::SHL, dl, VTy, XORHi, Constant1);
4043 SDValue ORHi = DAG.getNode(ISD::OR, dl, VTy, SHLHi, Constant1);
4044 SDValue CLSHi = DAG.getNode(ISD::CTLZ, dl, VTy, ORHi);
4045 SDValue CheckLo =
4046 DAG.getSetCC(dl, MVT::i1, CLSHi, Constant31, ISD::CondCode::SETEQ);
4047 SDValue HiIsZero =
4048 DAG.getSetCC(dl, MVT::i1, Hi, Constant0, ISD::CondCode::SETEQ);
4049 SDValue AdjustedLo =
4050 DAG.getSelect(dl, VTy, HiIsZero, Lo, DAG.getNOT(dl, Lo, VTy));
4051 SDValue CLZAdjustedLo = DAG.getNode(ISD::CTLZ, dl, VTy, AdjustedLo);
4052 SDValue Result =
4053 DAG.getSelect(dl, VTy, CheckLo,
4054 DAG.getNode(ISD::ADD, dl, VTy, CLZAdjustedLo, Constant31), CLSHi);
4055 return Result;
4056 }
4057 case Intrinsic::eh_sjlj_lsda: {
4058 MachineFunction &MF = DAG.getMachineFunction();
4059 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4060 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
4061 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4062 SDValue CPAddr;
4063 bool IsPositionIndependent = isPositionIndependent();
4064 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
4065 ARMConstantPoolValue *CPV =
4066 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
4067 ARMCP::CPLSDA, PCAdj);
4068 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
4069 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
4070 SDValue Result = DAG.getLoad(
4071 PtrVT, dl, DAG.getEntryNode(), CPAddr,
4072 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
4073
4074 if (IsPositionIndependent) {
4075 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
4076 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
4077 }
4078 return Result;
4079 }
4080 case Intrinsic::arm_neon_vabs:
4081 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
4082 Op.getOperand(1));
4083 case Intrinsic::arm_neon_vmulls:
4084 case Intrinsic::arm_neon_vmullu: {
4085 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
4086 ? ARMISD::VMULLs : ARMISD::VMULLu;
4087 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4088 Op.getOperand(1), Op.getOperand(2));
4089 }
4090 case Intrinsic::arm_neon_vminnm:
4091 case Intrinsic::arm_neon_vmaxnm: {
4092 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
4093 ? ISD::FMINNUM : ISD::FMAXNUM;
4094 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4095 Op.getOperand(1), Op.getOperand(2));
4096 }
4097 case Intrinsic::arm_neon_vminu:
4098 case Intrinsic::arm_neon_vmaxu: {
4099 if (Op.getValueType().isFloatingPoint())
4100 return SDValue();
4101 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
4102 ? ISD::UMIN : ISD::UMAX;
4103 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4104 Op.getOperand(1), Op.getOperand(2));
4105 }
4106 case Intrinsic::arm_neon_vmins:
4107 case Intrinsic::arm_neon_vmaxs: {
4108 // v{min,max}s is overloaded between signed integers and floats.
4109 if (!Op.getValueType().isFloatingPoint()) {
4110 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
4111 ? ISD::SMIN : ISD::SMAX;
4112 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4113 Op.getOperand(1), Op.getOperand(2));
4114 }
4115 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
4116 ? ISD::FMINIMUM : ISD::FMAXIMUM;
4117 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4118 Op.getOperand(1), Op.getOperand(2));
4119 }
4120 case Intrinsic::arm_neon_vtbl1:
4121 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
4122 Op.getOperand(1), Op.getOperand(2));
4123 case Intrinsic::arm_neon_vtbl2:
4124 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
4125 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4126 case Intrinsic::arm_mve_pred_i2v:
4127 case Intrinsic::arm_mve_pred_v2i:
4128 return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(),
4129 Op.getOperand(1));
4130 case Intrinsic::arm_mve_vreinterpretq:
4131 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(),
4132 Op.getOperand(1));
4133 case Intrinsic::arm_mve_lsll:
4134 return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(),
4135 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4136 case Intrinsic::arm_mve_asrl:
4137 return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(),
4138 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4139 }
4140}
4141
4142static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
4143 const ARMSubtarget *Subtarget) {
4144 SDLoc dl(Op);
4145 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
4146 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
4147 if (SSID == SyncScope::SingleThread)
4148 return Op;
4149
4150 if (!Subtarget->hasDataBarrier()) {
4151 // Some ARMv6 cpus can support data barriers with an mcr instruction.
4152 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
4153 // here.
4154 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&(static_cast <bool> (Subtarget->hasV6Ops() &&
!Subtarget->isThumb() && "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"
) ? void (0) : __assert_fail ("Subtarget->hasV6Ops() && !Subtarget->isThumb() && \"Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4155, __extension__ __PRETTY_FUNCTION__))
4155 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!")(static_cast <bool> (Subtarget->hasV6Ops() &&
!Subtarget->isThumb() && "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"
) ? void (0) : __assert_fail ("Subtarget->hasV6Ops() && !Subtarget->isThumb() && \"Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4155, __extension__ __PRETTY_FUNCTION__))
;
4156 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
4157 DAG.getConstant(0, dl, MVT::i32));
4158 }
4159
4160 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
4161 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
4162 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
4163 if (Subtarget->isMClass()) {
4164 // Only a full system barrier exists in the M-class architectures.
4165 Domain = ARM_MB::SY;
4166 } else if (Subtarget->preferISHSTBarriers() &&
4167 Ord == AtomicOrdering::Release) {
4168 // Swift happens to implement ISHST barriers in a way that's compatible with
4169 // Release semantics but weaker than ISH so we'd be fools not to use
4170 // it. Beware: other processors probably don't!
4171 Domain = ARM_MB::ISHST;
4172 }
4173
4174 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
4175 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
4176 DAG.getConstant(Domain, dl, MVT::i32));
4177}
4178
4179static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
4180 const ARMSubtarget *Subtarget) {
4181 // ARM pre v5TE and Thumb1 does not have preload instructions.
4182 if (!(Subtarget->isThumb2() ||
4183 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
4184 // Just preserve the chain.
4185 return Op.getOperand(0);
4186
4187 SDLoc dl(Op);
4188 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
4189 if (!isRead &&
4190 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
4191 // ARMv7 with MP extension has PLDW.
4192 return Op.getOperand(0);
4193
4194 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
4195 if (Subtarget->isThumb()) {
4196 // Invert the bits.
4197 isRead = ~isRead & 1;
4198 isData = ~isData & 1;
4199 }
4200
4201 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
4202 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
4203 DAG.getConstant(isData, dl, MVT::i32));
4204}
4205
4206static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
4207 MachineFunction &MF = DAG.getMachineFunction();
4208 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
4209
4210 // vastart just stores the address of the VarArgsFrameIndex slot into the
4211 // memory location argument.
4212 SDLoc dl(Op);
4213 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4214 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4215 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4216 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
4217 MachinePointerInfo(SV));
4218}
4219
4220SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
4221 CCValAssign &NextVA,
4222 SDValue &Root,
4223 SelectionDAG &DAG,
4224 const SDLoc &dl) const {
4225 MachineFunction &MF = DAG.getMachineFunction();
4226 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4227
4228 const TargetRegisterClass *RC;
4229 if (AFI->isThumb1OnlyFunction())
4230 RC = &ARM::tGPRRegClass;
4231 else
4232 RC = &ARM::GPRRegClass;
4233
4234 // Transform the arguments stored in physical registers into virtual ones.
4235 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4236 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4237
4238 SDValue ArgValue2;
4239 if (NextVA.isMemLoc()) {
4240 MachineFrameInfo &MFI = MF.getFrameInfo();
4241 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
4242
4243 // Create load node to retrieve arguments from the stack.
4244 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4245 ArgValue2 = DAG.getLoad(
4246 MVT::i32, dl, Root, FIN,
4247 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4248 } else {
4249 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
4250 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4251 }
4252 if (!Subtarget->isLittle())
4253 std::swap (ArgValue, ArgValue2);
4254 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
4255}
4256
4257// The remaining GPRs hold either the beginning of variable-argument
4258// data, or the beginning of an aggregate passed by value (usually
4259// byval). Either way, we allocate stack slots adjacent to the data
4260// provided by our caller, and store the unallocated registers there.
4261// If this is a variadic function, the va_list pointer will begin with
4262// these values; otherwise, this reassembles a (byval) structure that
4263// was split between registers and memory.
4264// Return: The frame index registers were stored into.
4265int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
4266 const SDLoc &dl, SDValue &Chain,
4267 const Value *OrigArg,
4268 unsigned InRegsParamRecordIdx,
4269 int ArgOffset, unsigned ArgSize) const {
4270 // Currently, two use-cases possible:
4271 // Case #1. Non-var-args function, and we meet first byval parameter.
4272 // Setup first unallocated register as first byval register;
4273 // eat all remained registers
4274 // (these two actions are performed by HandleByVal method).
4275 // Then, here, we initialize stack frame with
4276 // "store-reg" instructions.
4277 // Case #2. Var-args function, that doesn't contain byval parameters.
4278 // The same: eat all remained unallocated registers,
4279 // initialize stack frame.
4280
4281 MachineFunction &MF = DAG.getMachineFunction();
4282 MachineFrameInfo &MFI = MF.getFrameInfo();
4283 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4284 unsigned RBegin, REnd;
4285 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
4286 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
4287 } else {
4288 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4289 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
4290 REnd = ARM::R4;
4291 }
4292
4293 if (REnd != RBegin)
4294 ArgOffset = -4 * (ARM::R4 - RBegin);
4295
4296 auto PtrVT = getPointerTy(DAG.getDataLayout());
4297 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
4298 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
4299
4300 SmallVector<SDValue, 4> MemOps;
4301 const TargetRegisterClass *RC =
4302 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
4303
4304 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
4305 unsigned VReg = MF.addLiveIn(Reg, RC);
4306 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4307 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4308 MachinePointerInfo(OrigArg, 4 * i));
4309 MemOps.push_back(Store);
4310 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
4311 }
4312
4313 if (!MemOps.empty())
4314 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4315 return FrameIndex;
4316}
4317
4318// Setup stack frame, the va_list pointer will start from.
4319void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
4320 const SDLoc &dl, SDValue &Chain,
4321 unsigned ArgOffset,
4322 unsigned TotalArgRegsSaveSize,
4323 bool ForceMutable) const {
4324 MachineFunction &MF = DAG.getMachineFunction();
4325 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4326
4327 // Try to store any remaining integer argument regs
4328 // to their spots on the stack so that they may be loaded by dereferencing
4329 // the result of va_next.
4330 // If there is no regs to be stored, just point address after last
4331 // argument passed via stack.
4332 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
4333 CCInfo.getInRegsParamsCount(),
4334 CCInfo.getNextStackOffset(),
4335 std::max(4U, TotalArgRegsSaveSize));
4336 AFI->setVarArgsFrameIndex(FrameIndex);
4337}
4338
4339bool ARMTargetLowering::splitValueIntoRegisterParts(
4340 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4341 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
4342 bool IsABIRegCopy = CC.hasValue();
4343 EVT ValueVT = Val.getValueType();
4344 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) &&
4345 PartVT == MVT::f32) {
4346 unsigned ValueBits = ValueVT.getSizeInBits();
4347 unsigned PartBits = PartVT.getSizeInBits();
4348 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(ValueBits), Val);
4349 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::getIntegerVT(PartBits), Val);
4350 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
4351 Parts[0] = Val;
4352 return true;
4353 }
4354 return false;
4355}
4356
4357SDValue ARMTargetLowering::joinRegisterPartsIntoValue(
4358 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
4359 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
4360 bool IsABIRegCopy = CC.hasValue();
4361 if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) &&
4362 PartVT == MVT::f32) {
4363 unsigned ValueBits = ValueVT.getSizeInBits();
4364 unsigned PartBits = PartVT.getSizeInBits();
4365 SDValue Val = Parts[0];
4366
4367 Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(PartBits), Val);
4368 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::getIntegerVT(ValueBits), Val);
4369 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
4370 return Val;
4371 }
4372 return SDValue();
4373}
4374
4375SDValue ARMTargetLowering::LowerFormalArguments(
4376 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4377 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4378 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4379 MachineFunction &MF = DAG.getMachineFunction();
4380 MachineFrameInfo &MFI = MF.getFrameInfo();
4381
4382 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4383
4384 // Assign locations to all of the incoming arguments.
4385 SmallVector<CCValAssign, 16> ArgLocs;
4386 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4387 *DAG.getContext());
4388 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
4389
4390 SmallVector<SDValue, 16> ArgValues;
4391 SDValue ArgValue;
4392 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
4393 unsigned CurArgIdx = 0;
4394
4395 // Initially ArgRegsSaveSize is zero.
4396 // Then we increase this value each time we meet byval parameter.
4397 // We also increase this value in case of varargs function.
4398 AFI->setArgRegsSaveSize(0);
4399
4400 // Calculate the amount of stack space that we need to allocate to store
4401 // byval and variadic arguments that are passed in registers.
4402 // We need to know this before we allocate the first byval or variadic
4403 // argument, as they will be allocated a stack slot below the CFA (Canonical
4404 // Frame Address, the stack pointer at entry to the function).
4405 unsigned ArgRegBegin = ARM::R4;
4406 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4407 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
4408 break;
4409
4410 CCValAssign &VA = ArgLocs[i];
4411 unsigned Index = VA.getValNo();
4412 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
4413 if (!Flags.isByVal())
4414 continue;
4415
4416 assert(VA.isMemLoc() && "unexpected byval pointer in reg")(static_cast <bool> (VA.isMemLoc() && "unexpected byval pointer in reg"
) ? void (0) : __assert_fail ("VA.isMemLoc() && \"unexpected byval pointer in reg\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4416, __extension__ __PRETTY_FUNCTION__))
;
4417 unsigned RBegin, REnd;
4418 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
4419 ArgRegBegin = std::min(ArgRegBegin, RBegin);
4420
4421 CCInfo.nextInRegsParam();
4422 }
4423 CCInfo.rewindByValRegsInfo();
4424
4425 int lastInsIndex = -1;
4426 if (isVarArg && MFI.hasVAStart()) {
4427 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4428 if (RegIdx != array_lengthof(GPRArgRegs))
4429 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
4430 }
4431
4432 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
4433 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
4434 auto PtrVT = getPointerTy(DAG.getDataLayout());
4435
4436 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4437 CCValAssign &VA = ArgLocs[i];
4438 if (Ins[VA.getValNo()].isOrigArg()) {
4439 std::advance(CurOrigArg,
4440 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
4441 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
4442 }
4443 // Arguments stored in registers.
4444 if (VA.isRegLoc()) {
4445 EVT RegVT = VA.getLocVT();
4446
4447 if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
4448 // f64 and vector types are split up into multiple registers or
4449 // combinations of registers and stack slots.
4450 SDValue ArgValue1 =
4451 GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4452 VA = ArgLocs[++i]; // skip ahead to next loc
4453 SDValue ArgValue2;
4454 if (VA.isMemLoc()) {
4455 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
4456 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4457 ArgValue2 = DAG.getLoad(
4458 MVT::f64, dl, Chain, FIN,
4459 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4460 } else {
4461 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4462 }
4463 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
4464 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4465 ArgValue1, DAG.getIntPtrConstant(0, dl));
4466 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4467 ArgValue2, DAG.getIntPtrConstant(1, dl));
4468 } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
4469 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4470 } else {
4471 const TargetRegisterClass *RC;
4472
4473 if (RegVT == MVT::f16 || RegVT == MVT::bf16)
4474 RC = &ARM::HPRRegClass;
4475 else if (RegVT == MVT::f32)
4476 RC = &ARM::SPRRegClass;
4477 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16 ||
4478 RegVT == MVT::v4bf16)
4479 RC = &ARM::DPRRegClass;
4480 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16 ||
4481 RegVT == MVT::v8bf16)
4482 RC = &ARM::QPRRegClass;
4483 else if (RegVT == MVT::i32)
4484 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4485 : &ARM::GPRRegClass;
4486 else
4487 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering")::llvm::llvm_unreachable_internal("RegVT not supported by FORMAL_ARGUMENTS Lowering"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4487)
;
4488
4489 // Transform the arguments in physical registers into virtual ones.
4490 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4491 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4492
4493 // If this value is passed in r0 and has the returned attribute (e.g.
4494 // C++ 'structors), record this fact for later use.
4495 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4496 AFI->setPreservesR0();
4497 }
4498 }
4499
4500 // If this is an 8 or 16-bit value, it is really passed promoted
4501 // to 32 bits. Insert an assert[sz]ext to capture this, then
4502 // truncate to the right size.
4503 switch (VA.getLocInfo()) {
4504 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4504)
;
4505 case CCValAssign::Full: break;
4506 case CCValAssign::BCvt:
4507 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4508 break;
4509 case CCValAssign::SExt:
4510 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4511 DAG.getValueType(VA.getValVT()));
4512 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4513 break;
4514 case CCValAssign::ZExt:
4515 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4516 DAG.getValueType(VA.getValVT()));
4517 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4518 break;
4519 }
4520
4521 // f16 arguments have their size extended to 4 bytes and passed as if they
4522 // had been copied to the LSBs of a 32-bit register.
4523 // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
4524 if (VA.needsCustom() &&
4525 (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
4526 ArgValue = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), ArgValue);
4527
4528 InVals.push_back(ArgValue);
4529 } else { // VA.isRegLoc()
4530 // sanity check
4531 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4531, __extension__ __PRETTY_FUNCTION__))
;
4532 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered")(static_cast <bool> (VA.getValVT() != MVT::i64 &&
"i64 should already be lowered") ? void (0) : __assert_fail (
"VA.getValVT() != MVT::i64 && \"i64 should already be lowered\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4532, __extension__ __PRETTY_FUNCTION__))
;
4533
4534 int index = VA.getValNo();
4535
4536 // Some Ins[] entries become multiple ArgLoc[] entries.
4537 // Process them only once.
4538 if (index != lastInsIndex)
4539 {
4540 ISD::ArgFlagsTy Flags = Ins[index].Flags;
4541 // FIXME: For now, all byval parameter objects are marked mutable.
4542 // This can be changed with more analysis.
4543 // In case of tail call optimization mark all arguments mutable.
4544 // Since they could be overwritten by lowering of arguments in case of
4545 // a tail call.
4546 if (Flags.isByVal()) {
4547 assert(Ins[index].isOrigArg() &&(static_cast <bool> (Ins[index].isOrigArg() && "Byval arguments cannot be implicit"
) ? void (0) : __assert_fail ("Ins[index].isOrigArg() && \"Byval arguments cannot be implicit\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4548, __extension__ __PRETTY_FUNCTION__))
4548 "Byval arguments cannot be implicit")(static_cast <bool> (Ins[index].isOrigArg() && "Byval arguments cannot be implicit"
) ? void (0) : __assert_fail ("Ins[index].isOrigArg() && \"Byval arguments cannot be implicit\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4548, __extension__ __PRETTY_FUNCTION__))
;
4549 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4550
4551 int FrameIndex = StoreByValRegs(
4552 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4553 VA.getLocMemOffset(), Flags.getByValSize());
4554 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4555 CCInfo.nextInRegsParam();
4556 } else {
4557 unsigned FIOffset = VA.getLocMemOffset();
4558 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4559 FIOffset, true);
4560
4561 // Create load nodes to retrieve arguments from the stack.
4562 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4563 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4564 MachinePointerInfo::getFixedStack(
4565 DAG.getMachineFunction(), FI)));
4566 }
4567 lastInsIndex = index;
4568 }
4569 }
4570 }
4571
4572 // varargs
4573 if (isVarArg && MFI.hasVAStart()) {
4574 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset(),
4575 TotalArgRegsSaveSize);
4576 if (AFI->isCmseNSEntryFunction()) {
4577 DiagnosticInfoUnsupported Diag(
4578 DAG.getMachineFunction().getFunction(),
4579 "secure entry function must not be variadic", dl.getDebugLoc());
4580 DAG.getContext()->diagnose(Diag);
4581 }
4582 }
4583
4584 unsigned StackArgSize = CCInfo.getNextStackOffset();
4585 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4586 if (canGuaranteeTCO(CallConv, TailCallOpt)) {
4587 // The only way to guarantee a tail call is if the callee restores its
4588 // argument area, but it must also keep the stack aligned when doing so.
4589 const DataLayout &DL = DAG.getDataLayout();
4590 StackArgSize = alignTo(StackArgSize, DL.getStackAlignment());
4591
4592 AFI->setArgumentStackToRestore(StackArgSize);
4593 }
4594 AFI->setArgumentStackSize(StackArgSize);
4595
4596 if (CCInfo.getNextStackOffset() > 0 && AFI->isCmseNSEntryFunction()) {
4597 DiagnosticInfoUnsupported Diag(
4598 DAG.getMachineFunction().getFunction(),
4599 "secure entry function requires arguments on stack", dl.getDebugLoc());
4600 DAG.getContext()->diagnose(Diag);
4601 }
4602
4603 return Chain;
4604}
4605
4606/// isFloatingPointZero - Return true if this is +0.0.
4607static bool isFloatingPointZero(SDValue Op) {
4608 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4609 return CFP->getValueAPF().isPosZero();
4610 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4611 // Maybe this has already been legalized into the constant pool?
4612 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4613 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4614 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4615 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4616 return CFP->getValueAPF().isPosZero();
4617 }
4618 } else if (Op->getOpcode() == ISD::BITCAST &&
4619 Op->getValueType(0) == MVT::f64) {
4620 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4621 // created by LowerConstantFP().
4622 SDValue BitcastOp = Op->getOperand(0);
4623 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4624 isNullConstant(BitcastOp->getOperand(0)))
4625 return true;
4626 }
4627 return false;
4628}
4629
4630/// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4631/// the given operands.
4632SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4633 SDValue &ARMcc, SelectionDAG &DAG,
4634 const SDLoc &dl) const {
4635 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4636 unsigned C = RHSC->getZExtValue();
4637 if (!isLegalICmpImmediate((int32_t)C)) {
4638 // Constant does not fit, try adjusting it by one.
4639 switch (CC) {
4640 default: break;
4641 case ISD::SETLT:
4642 case ISD::SETGE:
4643 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4644 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4645 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4646 }
4647 break;
4648 case ISD::SETULT:
4649 case ISD::SETUGE:
4650 if (C != 0 && isLegalICmpImmediate(C-1)) {
4651 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4652 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4653 }
4654 break;
4655 case ISD::SETLE:
4656 case ISD::SETGT:
4657 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4658 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4659 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4660 }
4661 break;
4662 case ISD::SETULE:
4663 case ISD::SETUGT:
4664 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4665 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4666 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4667 }
4668 break;
4669 }
4670 }
4671 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4672 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4673 // In ARM and Thumb-2, the compare instructions can shift their second
4674 // operand.
4675 CC = ISD::getSetCCSwappedOperands(CC);
4676 std::swap(LHS, RHS);
4677 }
4678
4679 // Thumb1 has very limited immediate modes, so turning an "and" into a
4680 // shift can save multiple instructions.
4681 //
4682 // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4683 // into "((x << n) >> n)". But that isn't necessarily profitable on its
4684 // own. If it's the operand to an unsigned comparison with an immediate,
4685 // we can eliminate one of the shifts: we transform
4686 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4687 //
4688 // We avoid transforming cases which aren't profitable due to encoding
4689 // details:
4690 //
4691 // 1. C2 fits into the immediate field of a cmp, and the transformed version
4692 // would not; in that case, we're essentially trading one immediate load for
4693 // another.
4694 // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4695 // 3. C2 is zero; we have other code for this special case.
4696 //
4697 // FIXME: Figure out profitability for Thumb2; we usually can't save an
4698 // instruction, since the AND is always one instruction anyway, but we could
4699 // use narrow instructions in some cases.
4700 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4701 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4702 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4703 !isSignedIntSetCC(CC)) {
4704 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue();
4705 auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4706 uint64_t RHSV = RHSC->getZExtValue();
4707 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4708 unsigned ShiftBits = countLeadingZeros(Mask);
4709 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4710 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4711 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4712 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4713 }
4714 }
4715 }
4716
4717 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4718 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same
4719 // way a cmp would.
4720 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4721 // some tweaks to the heuristics for the previous and->shift transform.
4722 // FIXME: Optimize cases where the LHS isn't a shift.
4723 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4724 isa<ConstantSDNode>(RHS) &&
4725 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U &&
4726 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4727 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) {
4728 unsigned ShiftAmt =
4729 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1;
4730 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl,
4731 DAG.getVTList(MVT::i32, MVT::i32),
4732 LHS.getOperand(0),
4733 DAG.getConstant(ShiftAmt, dl, MVT::i32));
4734 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
4735 Shift.getValue(1), SDValue());
4736 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4737 return Chain.getValue(1);
4738 }
4739
4740 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4741
4742 // If the RHS is a constant zero then the V (overflow) flag will never be
4743 // set. This can allow us to simplify GE to PL or LT to MI, which can be
4744 // simpler for other passes (like the peephole optimiser) to deal with.
4745 if (isNullConstant(RHS)) {
4746 switch (CondCode) {
4747 default: break;
4748 case ARMCC::GE:
4749 CondCode = ARMCC::PL;
4750 break;
4751 case ARMCC::LT:
4752 CondCode = ARMCC::MI;
4753 break;
4754 }
4755 }
4756
4757 ARMISD::NodeType CompareType;
4758 switch (CondCode) {
4759 default:
4760 CompareType = ARMISD::CMP;
4761 break;
4762 case ARMCC::EQ:
4763 case ARMCC::NE:
4764 // Uses only Z Flag
4765 CompareType = ARMISD::CMPZ;
4766 break;
4767 }
4768 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4769 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4770}
4771
4772/// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4773SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4774 SelectionDAG &DAG, const SDLoc &dl,
4775 bool Signaling) const {
4776 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64)(static_cast <bool> (Subtarget->hasFP64() || RHS.getValueType
() != MVT::f64) ? void (0) : __assert_fail ("Subtarget->hasFP64() || RHS.getValueType() != MVT::f64"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4776, __extension__ __PRETTY_FUNCTION__))
;
4777 SDValue Cmp;
4778 if (!isFloatingPointZero(RHS))
4779 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP,
4780 dl, MVT::Glue, LHS, RHS);
4781 else
4782 Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0,
4783 dl, MVT::Glue, LHS);
4784 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4785}
4786
4787/// duplicateCmp - Glue values can have only one use, so this function
4788/// duplicates a comparison node.
4789SDValue
4790ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4791 unsigned Opc = Cmp.getOpcode();
4792 SDLoc DL(Cmp);
4793 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4794 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4795
4796 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation")(static_cast <bool> (Opc == ARMISD::FMSTAT && "unexpected comparison operation"
) ? void (0) : __assert_fail ("Opc == ARMISD::FMSTAT && \"unexpected comparison operation\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4796, __extension__ __PRETTY_FUNCTION__))
;
4797 Cmp = Cmp.getOperand(0);
4798 Opc = Cmp.getOpcode();
4799 if (Opc == ARMISD::CMPFP)
4800 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4801 else {
4802 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT")(static_cast <bool> (Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"
) ? void (0) : __assert_fail ("Opc == ARMISD::CMPFPw0 && \"unexpected operand of FMSTAT\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4802, __extension__ __PRETTY_FUNCTION__))
;
4803 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
4804 }
4805 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4806}
4807
4808// This function returns three things: the arithmetic computation itself
4809// (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
4810// comparison and the condition code define the case in which the arithmetic
4811// computation *does not* overflow.
4812std::pair<SDValue, SDValue>
4813ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4814 SDValue &ARMcc) const {
4815 assert(Op.getValueType() == MVT::i32 && "Unsupported value type")(static_cast <bool> (Op.getValueType() == MVT::i32 &&
"Unsupported value type") ? void (0) : __assert_fail ("Op.getValueType() == MVT::i32 && \"Unsupported value type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4815, __extension__ __PRETTY_FUNCTION__))
;
4816
4817 SDValue Value, OverflowCmp;
4818 SDValue LHS = Op.getOperand(0);
4819 SDValue RHS = Op.getOperand(1);
4820 SDLoc dl(Op);
4821
4822 // FIXME: We are currently always generating CMPs because we don't support
4823 // generating CMN through the backend. This is not as good as the natural
4824 // CMP case because it causes a register dependency and cannot be folded
4825 // later.
4826
4827 switch (Op.getOpcode()) {
4828 default:
4829 llvm_unreachable("Unknown overflow instruction!")::llvm::llvm_unreachable_internal("Unknown overflow instruction!"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4829)
;
4830 case ISD::SADDO:
4831 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4832 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4833 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4834 break;
4835 case ISD::UADDO:
4836 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4837 // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4838 // We do not use it in the USUBO case as Value may not be used.
4839 Value = DAG.getNode(ARMISD::ADDC, dl,
4840 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4841 .getValue(0);
4842 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4843 break;
4844 case ISD::SSUBO:
4845 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4846 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4847 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4848 break;
4849 case ISD::USUBO:
4850 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4851 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4852 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4853 break;
4854 case ISD::UMULO:
4855 // We generate a UMUL_LOHI and then check if the high word is 0.
4856 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4857 Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4858 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4859 LHS, RHS);
4860 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4861 DAG.getConstant(0, dl, MVT::i32));
4862 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4863 break;
4864 case ISD::SMULO:
4865 // We generate a SMUL_LOHI and then check if all the bits of the high word
4866 // are the same as the sign bit of the low word.
4867 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4868 Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4869 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4870 LHS, RHS);
4871 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4872 DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4873 Value.getValue(0),
4874 DAG.getConstant(31, dl, MVT::i32)));
4875 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4876 break;
4877 } // switch (...)
4878
4879 return std::make_pair(Value, OverflowCmp);
4880}
4881
4882SDValue
4883ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4884 // Let legalize expand this if it isn't a legal type yet.
4885 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4886 return SDValue();
4887
4888 SDValue Value, OverflowCmp;
4889 SDValue ARMcc;
4890 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4891 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4892 SDLoc dl(Op);
4893 // We use 0 and 1 as false and true values.
4894 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4895 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4896 EVT VT = Op.getValueType();
4897
4898 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4899 ARMcc, CCR, OverflowCmp);
4900
4901 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4902 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4903}
4904
4905static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4906 SelectionDAG &DAG) {
4907 SDLoc DL(BoolCarry);
4908 EVT CarryVT = BoolCarry.getValueType();
4909
4910 // This converts the boolean value carry into the carry flag by doing
4911 // ARMISD::SUBC Carry, 1
4912 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4913 DAG.getVTList(CarryVT, MVT::i32),
4914 BoolCarry, DAG.getConstant(1, DL, CarryVT));
4915 return Carry.getValue(1);
4916}
4917
4918static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4919 SelectionDAG &DAG) {
4920 SDLoc DL(Flags);
4921
4922 // Now convert the carry flag into a boolean carry. We do this
4923 // using ARMISD:ADDE 0, 0, Carry
4924 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4925 DAG.getConstant(0, DL, MVT::i32),
4926 DAG.getConstant(0, DL, MVT::i32), Flags);
4927}
4928
4929SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4930 SelectionDAG &DAG) const {
4931 // Let legalize expand this if it isn't a legal type yet.
4932 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4933 return SDValue();
4934
4935 SDValue LHS = Op.getOperand(0);
4936 SDValue RHS = Op.getOperand(1);
4937 SDLoc dl(Op);
4938
4939 EVT VT = Op.getValueType();
4940 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4941 SDValue Value;
4942 SDValue Overflow;
4943 switch (Op.getOpcode()) {
4944 default:
4945 llvm_unreachable("Unknown overflow instruction!")::llvm::llvm_unreachable_internal("Unknown overflow instruction!"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 4945)
;
4946 case ISD::UADDO:
4947 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4948 // Convert the carry flag into a boolean value.
4949 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4950 break;
4951 case ISD::USUBO: {
4952 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4953 // Convert the carry flag into a boolean value.
4954 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4955 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4956 // value. So compute 1 - C.
4957 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4958 DAG.getConstant(1, dl, MVT::i32), Overflow);
4959 break;
4960 }
4961 }
4962
4963 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4964}
4965
4966static SDValue LowerADDSUBSAT(SDValue Op, SelectionDAG &DAG,
4967 const ARMSubtarget *Subtarget) {
4968 EVT VT = Op.getValueType();
4969 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
4970 return SDValue();
4971 if (!VT.isSimple())
4972 return SDValue();
4973
4974 unsigned NewOpcode;
4975 switch (VT.getSimpleVT().SimpleTy) {
4976 default:
4977 return SDValue();
4978 case MVT::i8:
4979 switch (Op->getOpcode()) {
4980 case ISD::UADDSAT:
4981 NewOpcode = ARMISD::UQADD8b;
4982 break;
4983 case ISD::SADDSAT:
4984 NewOpcode = ARMISD::QADD8b;
4985 break;
4986 case ISD::USUBSAT:
4987 NewOpcode = ARMISD::UQSUB8b;
4988 break;
4989 case ISD::SSUBSAT:
4990 NewOpcode = ARMISD::QSUB8b;
4991 break;
4992 }
4993 break;
4994 case MVT::i16:
4995 switch (Op->getOpcode()) {
4996 case ISD::UADDSAT:
4997 NewOpcode = ARMISD::UQADD16b;
4998 break;
4999 case ISD::SADDSAT:
5000 NewOpcode = ARMISD::QADD16b;
5001 break;
5002 case ISD::USUBSAT:
5003 NewOpcode = ARMISD::UQSUB16b;
5004 break;
5005 case ISD::SSUBSAT:
5006 NewOpcode = ARMISD::QSUB16b;
5007 break;
5008 }
5009 break;
5010 }
5011
5012 SDLoc dl(Op);
5013 SDValue Add =
5014 DAG.getNode(NewOpcode, dl, MVT::i32,
5015 DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32),
5016 DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32));
5017 return DAG.getNode(ISD::TRUNCATE, dl, VT, Add);
5018}
5019
5020SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
5021 SDValue Cond = Op.getOperand(0);
5022 SDValue SelectTrue = Op.getOperand(1);
5023 SDValue SelectFalse = Op.getOperand(2);
5024 SDLoc dl(Op);
5025 unsigned Opc = Cond.getOpcode();
5026
5027 if (Cond.getResNo() == 1 &&
5028 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5029 Opc == ISD::USUBO)) {
5030 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5031 return SDValue();
5032
5033 SDValue Value, OverflowCmp;
5034 SDValue ARMcc;
5035 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5036 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5037 EVT VT = Op.getValueType();
5038
5039 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
5040 OverflowCmp, DAG);
5041 }
5042
5043 // Convert:
5044 //
5045 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
5046 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
5047 //
5048 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
5049 const ConstantSDNode *CMOVTrue =
5050 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
5051 const ConstantSDNode *CMOVFalse =
5052 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
5053
5054 if (CMOVTrue && CMOVFalse) {
5055 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
5056 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
5057
5058 SDValue True;
5059 SDValue False;
5060 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
5061 True = SelectTrue;
5062 False = SelectFalse;
5063 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
5064 True = SelectFalse;
5065 False = SelectTrue;
5066 }
5067
5068 if (True.getNode() && False.getNode()) {
5069 EVT VT = Op.getValueType();
5070 SDValue ARMcc = Cond.getOperand(2);
5071 SDValue CCR = Cond.getOperand(3);
5072 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
5073 assert(True.getValueType() == VT)(static_cast <bool> (True.getValueType() == VT) ? void (
0) : __assert_fail ("True.getValueType() == VT", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 5073, __extension__ __PRETTY_FUNCTION__))
;
5074 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
5075 }
5076 }
5077 }
5078
5079 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
5080 // undefined bits before doing a full-word comparison with zero.
5081 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
5082 DAG.getConstant(1, dl, Cond.getValueType()));
5083
5084 return DAG.getSelectCC(dl, Cond,
5085 DAG.getConstant(0, dl, Cond.getValueType()),
5086 SelectTrue, SelectFalse, ISD::SETNE);
5087}
5088
5089static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
5090 bool &swpCmpOps, bool &swpVselOps) {
5091 // Start by selecting the GE condition code for opcodes that return true for
5092 // 'equality'
5093 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
5094 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE)
5095 CondCode = ARMCC::GE;
5096
5097 // and GT for opcodes that return false for 'equality'.
5098 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
5099 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT)
5100 CondCode = ARMCC::GT;
5101
5102 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
5103 // to swap the compare operands.
5104 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
5105 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT)
5106 swpCmpOps = true;
5107
5108 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
5109 // If we have an unordered opcode, we need to swap the operands to the VSEL
5110 // instruction (effectively negating the condition).
5111 //
5112 // This also has the effect of swapping which one of 'less' or 'greater'
5113 // returns true, so we also swap the compare operands. It also switches
5114 // whether we return true for 'equality', so we compensate by picking the
5115 // opposite condition code to our original choice.
5116 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
5117 CC == ISD::SETUGT) {
5118 swpCmpOps = !swpCmpOps;
5119 swpVselOps = !swpVselOps;
5120 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
5121 }
5122
5123 // 'ordered' is 'anything but unordered', so use the VS condition code and
5124 // swap the VSEL operands.
5125 if (CC == ISD::SETO) {
5126 CondCode = ARMCC::VS;
5127 swpVselOps = true;
5128 }
5129
5130 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
5131 // code and swap the VSEL operands. Also do this if we don't care about the
5132 // unordered case.
5133 if (CC == ISD::SETUNE || CC == ISD::SETNE) {
5134 CondCode = ARMCC::EQ;
5135 swpVselOps = true;
5136 }
5137}
5138
5139SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
5140 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
5141 SDValue Cmp, SelectionDAG &DAG) const {
5142 if (!Subtarget->hasFP64() && VT == MVT::f64) {
5143 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
5144 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
5145 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
5146 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
5147
5148 SDValue TrueLow = TrueVal.getValue(0);
5149 SDValue TrueHigh = TrueVal.getValue(1);
5150 SDValue FalseLow = FalseVal.getValue(0);
5151 SDValue FalseHigh = FalseVal.getValue(1);
5152
5153 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
5154 ARMcc, CCR, Cmp);
5155 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
5156 ARMcc, CCR, duplicateCmp(Cmp, DAG));
5157
5158 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
5159 } else {
5160 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
5161 Cmp);
5162 }
5163}
5164
5165static bool isGTorGE(ISD::CondCode CC) {
5166 return CC == ISD::SETGT || CC == ISD::SETGE;
5167}
5168
5169static bool isLTorLE(ISD::CondCode CC) {
5170 return CC == ISD::SETLT || CC == ISD::SETLE;
5171}
5172
5173// See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
5174// All of these conditions (and their <= and >= counterparts) will do:
5175// x < k ? k : x
5176// x > k ? x : k
5177// k < x ? x : k
5178// k > x ? k : x
5179static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
5180 const SDValue TrueVal, const SDValue FalseVal,
5181 const ISD::CondCode CC, const SDValue K) {
5182 return (isGTorGE(CC) &&
5183 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
5184 (isLTorLE(CC) &&
5185 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
5186}
5187
5188// Check if two chained conditionals could be converted into SSAT or USAT.
5189//
5190// SSAT can replace a set of two conditional selectors that bound a number to an
5191// interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
5192//
5193// x < -k ? -k : (x > k ? k : x)
5194// x < -k ? -k : (x < k ? x : k)
5195// x > -k ? (x > k ? k : x) : -k
5196// x < k ? (x < -k ? -k : x) : k
5197// etc.
5198//
5199// LLVM canonicalizes these to either a min(max()) or a max(min())
5200// pattern. This function tries to match one of these and will return a SSAT
5201// node if successful.
5202//
5203// USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1
5204// is a power of 2.
5205static SDValue LowerSaturatingConditional(SDValue Op, SelectionDAG &DAG) {
5206 EVT VT = Op.getValueType();
5207 SDValue V1 = Op.getOperand(0);
5208 SDValue K1 = Op.getOperand(1);
5209 SDValue TrueVal1 = Op.getOperand(2);
5210 SDValue FalseVal1 = Op.getOperand(3);
5211 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5212
5213 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
5214 if (Op2.getOpcode() != ISD::SELECT_CC)
5215 return SDValue();
5216
5217 SDValue V2 = Op2.getOperand(0);
5218 SDValue K2 = Op2.getOperand(1);
5219 SDValue TrueVal2 = Op2.getOperand(2);
5220 SDValue FalseVal2 = Op2.getOperand(3);
5221 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
5222
5223 SDValue V1Tmp = V1;
5224 SDValue V2Tmp = V2;
5225
5226 // Check that the registers and the constants match a max(min()) or min(max())
5227 // pattern
5228 if (V1Tmp != TrueVal1 || V2Tmp != TrueVal2 || K1 != FalseVal1 ||
5229 K2 != FalseVal2 ||
5230 !((isGTorGE(CC1) && isLTorLE(CC2)) || (isLTorLE(CC1) && isGTorGE(CC2))))
5231 return SDValue();
5232
5233 // Check that the constant in the lower-bound check is
5234 // the opposite of the constant in the upper-bound check
5235 // in 1's complement.
5236 if (!isa<ConstantSDNode>(K1) || !isa<ConstantSDNode>(K2))
5237 return SDValue();
5238
5239 int64_t Val1 = cast<ConstantSDNode>(K1)->getSExtValue();
5240 int64_t Val2 = cast<ConstantSDNode>(K2)->getSExtValue();
5241 int64_t PosVal = std::max(Val1, Val2);
5242 int64_t NegVal = std::min(Val1, Val2);
5243
5244 if (!((Val1 > Val2 && isLTorLE(CC1)) || (Val1 < Val2 && isLTorLE(CC2))) ||
5245 !isPowerOf2_64(PosVal + 1))
5246 return SDValue();
5247
5248 // Handle the difference between USAT (unsigned) and SSAT (signed)
5249 // saturation
5250 // At this point, PosVal is guaranteed to be positive
5251 uint64_t K = PosVal;
5252 SDLoc dl(Op);
5253 if (Val1 == ~Val2)
5254 return DAG.getNode(ARMISD::SSAT, dl, VT, V2Tmp,
5255 DAG.getConstant(countTrailingOnes(K), dl, VT));
5256 if (NegVal == 0)
5257 return DAG.getNode(ARMISD::USAT, dl, VT, V2Tmp,
5258 DAG.getConstant(countTrailingOnes(K), dl, VT));
5259
5260 return SDValue();
5261}
5262
5263// Check if a condition of the type x < k ? k : x can be converted into a
5264// bit operation instead of conditional moves.
5265// Currently this is allowed given:
5266// - The conditions and values match up
5267// - k is 0 or -1 (all ones)
5268// This function will not check the last condition, thats up to the caller
5269// It returns true if the transformation can be made, and in such case
5270// returns x in V, and k in SatK.
5271static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
5272 SDValue &SatK)
5273{
5274 SDValue LHS = Op.getOperand(0);
5275 SDValue RHS = Op.getOperand(1);
5276 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5277 SDValue TrueVal = Op.getOperand(2);
5278 SDValue FalseVal = Op.getOperand(3);
5279
5280 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
5281 ? &RHS
5282 : nullptr;
5283
5284 // No constant operation in comparison, early out
5285 if (!K)
5286 return false;
5287
5288 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
5289 V = (KTmp == TrueVal) ? FalseVal : TrueVal;
5290 SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
5291
5292 // If the constant on left and right side, or variable on left and right,
5293 // does not match, early out
5294 if (*K != KTmp || V != VTmp)
5295 return false;
5296
5297 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
5298 SatK = *K;
5299 return true;
5300 }
5301
5302 return false;
5303}
5304
5305bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
5306 if (VT == MVT::f32)
5307 return !Subtarget->hasVFP2Base();
5308 if (VT == MVT::f64)
5309 return !Subtarget->hasFP64();
5310 if (VT == MVT::f16)
5311 return !Subtarget->hasFullFP16();
5312 return false;
5313}
5314
5315SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5316 EVT VT = Op.getValueType();
5317 SDLoc dl(Op);
5318
5319 // Try to convert two saturating conditional selects into a single SSAT
5320 if ((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2())
5321 if (SDValue SatValue = LowerSaturatingConditional(Op, DAG))
5322 return SatValue;
5323
5324 // Try to convert expressions of the form x < k ? k : x (and similar forms)
5325 // into more efficient bit operations, which is possible when k is 0 or -1
5326 // On ARM and Thumb-2 which have flexible operand 2 this will result in
5327 // single instructions. On Thumb the shift and the bit operation will be two
5328 // instructions.
5329 // Only allow this transformation on full-width (32-bit) operations
5330 SDValue LowerSatConstant;
5331 SDValue SatValue;
5332 if (VT == MVT::i32 &&
5333 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
5334 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
5335 DAG.getConstant(31, dl, VT));
5336 if (isNullConstant(LowerSatConstant)) {
5337 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
5338 DAG.getAllOnesConstant(dl, VT));
5339 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
5340 } else if (isAllOnesConstant(LowerSatConstant))
5341 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
5342 }
5343
5344 SDValue LHS = Op.getOperand(0);
5345 SDValue RHS = Op.getOperand(1);
5346 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5347 SDValue TrueVal = Op.getOperand(2);
5348 SDValue FalseVal = Op.getOperand(3);
5349 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
5350 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
5351
5352 if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal &&
5353 LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) {
5354 unsigned TVal = CTVal->getZExtValue();
5355 unsigned FVal = CFVal->getZExtValue();
5356 unsigned Opcode = 0;
5357
5358 if (TVal == ~FVal) {
5359 Opcode = ARMISD::CSINV;
5360 } else if (TVal == ~FVal + 1) {
5361 Opcode = ARMISD::CSNEG;
5362 } else if (TVal + 1 == FVal) {
5363 Opcode = ARMISD::CSINC;
5364 } else if (TVal == FVal + 1) {
5365 Opcode = ARMISD::CSINC;
5366 std::swap(TrueVal, FalseVal);
5367 std::swap(TVal, FVal);
5368 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5369 }
5370
5371 if (Opcode) {
5372 // If one of the constants is cheaper than another, materialise the
5373 // cheaper one and let the csel generate the other.
5374 if (Opcode != ARMISD::CSINC &&
5375 HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
5376 std::swap(TrueVal, FalseVal);
5377 std::swap(TVal, FVal);
5378 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5379 }
5380
5381 // Attempt to use ZR checking TVal is 0, possibly inverting the condition
5382 // to get there. CSINC not is invertable like the other two (~(~a) == a,
5383 // -(-a) == a, but (a+1)+1 != a).
5384 if (FVal == 0 && Opcode != ARMISD::CSINC) {
5385 std::swap(TrueVal, FalseVal);
5386 std::swap(TVal, FVal);
5387 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5388 }
5389
5390 // Drops F's value because we can get it by inverting/negating TVal.
5391 FalseVal = TrueVal;
5392
5393 SDValue ARMcc;
5394 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5395 EVT VT = TrueVal.getValueType();
5396 return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp);
5397 }
5398 }
5399
5400 if (isUnsupportedFloatingType(LHS.getValueType())) {
5401 DAG.getTargetLoweringInfo().softenSetCCOperands(
5402 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5403
5404 // If softenSetCCOperands only returned one value, we should compare it to
5405 // zero.
5406 if (!RHS.getNode()) {
5407 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5408 CC = ISD::SETNE;
5409 }
5410 }
5411
5412 if (LHS.getValueType() == MVT::i32) {
5413 // Try to generate VSEL on ARMv8.
5414 // The VSEL instruction can't use all the usual ARM condition
5415 // codes: it only has two bits to select the condition code, so it's
5416 // constrained to use only GE, GT, VS and EQ.
5417 //
5418 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
5419 // swap the operands of the previous compare instruction (effectively
5420 // inverting the compare condition, swapping 'less' and 'greater') and
5421 // sometimes need to swap the operands to the VSEL (which inverts the
5422 // condition in the sense of firing whenever the previous condition didn't)
5423 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
5424 TrueVal.getValueType() == MVT::f32 ||
5425 TrueVal.getValueType() == MVT::f64)) {
5426 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5427 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
5428 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
5429 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5430 std::swap(TrueVal, FalseVal);
5431 }
5432 }
5433
5434 SDValue ARMcc;
5435 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5436 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5437 // Choose GE over PL, which vsel does now support
5438 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
5439 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
5440 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5441 }
5442
5443 ARMCC::CondCodes CondCode, CondCode2;
5444 FPCCToARMCC(CC, CondCode, CondCode2);
5445
5446 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
5447 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
5448 // must use VSEL (limited condition codes), due to not having conditional f16
5449 // moves.
5450 if (Subtarget->hasFPARMv8Base() &&
5451 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
5452 (TrueVal.getValueType() == MVT::f16 ||
5453 TrueVal.getValueType() == MVT::f32 ||
5454 TrueVal.getValueType() == MVT::f64)) {
5455 bool swpCmpOps = false;
5456 bool swpVselOps = false;
5457 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
5458
5459 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
5460 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
5461 if (swpCmpOps)
5462 std::swap(LHS, RHS);
5463 if (swpVselOps)
5464 std::swap(TrueVal, FalseVal);
5465 }
5466 }
5467
5468 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5469 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5470 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5471 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5472 if (CondCode2 != ARMCC::AL) {
5473 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
5474 // FIXME: Needs another CMP because flag can have but one use.
5475 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
5476 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
5477 }
5478 return Result;
5479}
5480
5481/// canChangeToInt - Given the fp compare operand, return true if it is suitable
5482/// to morph to an integer compare sequence.
5483static bool canChangeToInt(SDValue Op, bool &SeenZero,
5484 const ARMSubtarget *Subtarget) {
5485 SDNode *N = Op.getNode();
5486 if (!N->hasOneUse())
5487 // Otherwise it requires moving the value from fp to integer registers.
5488 return false;
5489 if (!N->getNumValues())
5490 return false;
5491 EVT VT = Op.getValueType();
5492 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
5493 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
5494 // vmrs are very slow, e.g. cortex-a8.
5495 return false;
5496
5497 if (isFloatingPointZero(Op)) {
5498 SeenZero = true;
5499 return true;
5500 }
5501 return ISD::isNormalLoad(N);
5502}
5503
5504static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
5505 if (isFloatingPointZero(Op))
5506 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
5507
5508 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
5509 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
5510 Ld->getPointerInfo(), Ld->getAlignment(),
5511 Ld->getMemOperand()->getFlags());
5512
5513 llvm_unreachable("Unknown VFP cmp argument!")::llvm::llvm_unreachable_internal("Unknown VFP cmp argument!"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 5513)
;
5514}
5515
5516static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
5517 SDValue &RetVal1, SDValue &RetVal2) {
5518 SDLoc dl(Op);
5519
5520 if (isFloatingPointZero(Op)) {
5521 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
5522 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5523 return;
5524 }
5525
5526 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5527 SDValue Ptr = Ld->getBasePtr();
5528 RetVal1 =
5529 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5530 Ld->getAlignment(), Ld->getMemOperand()->getFlags());
5531
5532 EVT PtrType = Ptr.getValueType();
5533 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
5534 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5535 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5536 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5537 Ld->getPointerInfo().getWithOffset(4), NewAlign,
5538 Ld->getMemOperand()->getFlags());
5539 return;
5540 }
5541
5542 llvm_unreachable("Unknown VFP cmp argument!")::llvm::llvm_unreachable_internal("Unknown VFP cmp argument!"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 5542)
;
5543}
5544
5545/// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
5546/// f32 and even f64 comparisons to integer ones.
5547SDValue
5548ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5549 SDValue Chain = Op.getOperand(0);
5550 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5551 SDValue LHS = Op.getOperand(2);
5552 SDValue RHS = Op.getOperand(3);
5553 SDValue Dest = Op.getOperand(4);
5554 SDLoc dl(Op);
5555
5556 bool LHSSeenZero = false;
5557 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5558 bool RHSSeenZero = false;
5559 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5560 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5561 // If unsafe fp math optimization is enabled and there are no other uses of
5562 // the CMP operands, and the condition code is EQ or NE, we can optimize it
5563 // to an integer comparison.
5564 if (CC == ISD::SETOEQ)
5565 CC = ISD::SETEQ;
5566 else if (CC == ISD::SETUNE)
5567 CC = ISD::SETNE;
5568
5569 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5570 SDValue ARMcc;
5571 if (LHS.getValueType() == MVT::f32) {
5572 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5573 bitcastf32Toi32(LHS, DAG), Mask);
5574 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5575 bitcastf32Toi32(RHS, DAG), Mask);
5576 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5577 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5578 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5579 Chain, Dest, ARMcc, CCR, Cmp);
5580 }
5581
5582 SDValue LHS1, LHS2;
5583 SDValue RHS1, RHS2;
5584 expandf64Toi32(LHS, DAG, LHS1, LHS2);
5585 expandf64Toi32(RHS, DAG, RHS1, RHS2);
5586 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5587 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5588 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5589 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5590 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5591 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5592 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
5593 }
5594
5595 return SDValue();
5596}
5597
5598SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5599 SDValue Chain = Op.getOperand(0);
5600 SDValue Cond = Op.getOperand(1);
5601 SDValue Dest = Op.getOperand(2);
5602 SDLoc dl(Op);
5603
5604 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5605 // instruction.
5606 unsigned Opc = Cond.getOpcode();
5607 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5608 !Subtarget->isThumb1Only();
5609 if (Cond.getResNo() == 1 &&
5610 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5611 Opc == ISD::USUBO || OptimizeMul)) {
5612 // Only lower legal XALUO ops.
5613 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5614 return SDValue();
5615
5616 // The actual operation with overflow check.
5617 SDValue Value, OverflowCmp;
5618 SDValue ARMcc;
5619 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5620
5621 // Reverse the condition code.
5622 ARMCC::CondCodes CondCode =
5623 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5624 CondCode = ARMCC::getOppositeCondition(CondCode);
5625 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5626 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5627
5628 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5629 OverflowCmp);
5630 }
5631
5632 return SDValue();
5633}
5634
5635SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5636 SDValue Chain = Op.getOperand(0);
5637 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5638 SDValue LHS = Op.getOperand(2);
5639 SDValue RHS = Op.getOperand(3);
5640 SDValue Dest = Op.getOperand(4);
5641 SDLoc dl(Op);
5642
5643 if (isUnsupportedFloatingType(LHS.getValueType())) {
5644 DAG.getTargetLoweringInfo().softenSetCCOperands(
5645 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5646
5647 // If softenSetCCOperands only returned one value, we should compare it to
5648 // zero.
5649 if (!RHS.getNode()) {
5650 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5651 CC = ISD::SETNE;
5652 }
5653 }
5654
5655 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5656 // instruction.
5657 unsigned Opc = LHS.getOpcode();
5658 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5659 !Subtarget->isThumb1Only();
5660 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5661 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5662 Opc == ISD::USUBO || OptimizeMul) &&
5663 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5664 // Only lower legal XALUO ops.
5665 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5666 return SDValue();
5667
5668 // The actual operation with overflow check.
5669 SDValue Value, OverflowCmp;
5670 SDValue ARMcc;
5671 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5672
5673 if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5674 // Reverse the condition code.
5675 ARMCC::CondCodes CondCode =
5676 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5677 CondCode = ARMCC::getOppositeCondition(CondCode);
5678 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5679 }
5680 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5681
5682 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5683 OverflowCmp);
5684 }
5685
5686 if (LHS.getValueType() == MVT::i32) {
5687 SDValue ARMcc;
5688 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5689 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5690 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5691 Chain, Dest, ARMcc, CCR, Cmp);
5692 }
5693
5694 if (getTargetMachine().Options.UnsafeFPMath &&
5695 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
5696 CC == ISD::SETNE || CC == ISD::SETUNE)) {
5697 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5698 return Result;
5699 }
5700
5701 ARMCC::CondCodes CondCode, CondCode2;
5702 FPCCToARMCC(CC, CondCode, CondCode2);
5703
5704 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5705 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5706 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5707 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5708 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
5709 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5710 if (CondCode2 != ARMCC::AL) {
5711 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5712 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
5713 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5714 }
5715 return Res;
5716}
5717
5718SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5719 SDValue Chain = Op.getOperand(0);
5720 SDValue Table = Op.getOperand(1);
5721 SDValue Index = Op.getOperand(2);
5722 SDLoc dl(Op);
5723
5724 EVT PTy = getPointerTy(DAG.getDataLayout());
5725 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5726 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5727 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5728 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5729 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5730 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5731 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5732 // which does another jump to the destination. This also makes it easier
5733 // to translate it to TBB / TBH later (Thumb2 only).
5734 // FIXME: This might not work if the function is extremely large.
5735 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5736 Addr, Op.getOperand(2), JTI);
5737 }
5738 if (isPositionIndependent() || Subtarget->isROPI()) {
5739 Addr =
5740 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5741 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5742 Chain = Addr.getValue(1);
5743 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5744 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5745 } else {
5746 Addr =
5747 DAG.getLoad(PTy, dl, Chain, Addr,
5748 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5749 Chain = Addr.getValue(1);
5750 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5751 }
5752}
5753
5754static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5755 EVT VT = Op.getValueType();
5756 SDLoc dl(Op);
5757
5758 if (Op.getValueType().getVectorElementType() == MVT::i32) {
5759 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5760 return Op;
5761 return DAG.UnrollVectorOp(Op.getNode());
5762 }
5763
5764 const bool HasFullFP16 =
5765 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5766
5767 EVT NewTy;
5768 const EVT OpTy = Op.getOperand(0).getValueType();
5769 if (OpTy == MVT::v4f32)
5770 NewTy = MVT::v4i32;
5771 else if (OpTy == MVT::v4f16 && HasFullFP16)
5772 NewTy = MVT::v4i16;
5773 else if (OpTy == MVT::v8f16 && HasFullFP16)
5774 NewTy = MVT::v8i16;
5775 else
5776 llvm_unreachable("Invalid type for custom lowering!")::llvm::llvm_unreachable_internal("Invalid type for custom lowering!"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 5776)
;
5777
5778 if (VT != MVT::v4i16 && VT != MVT::v8i16)
5779 return DAG.UnrollVectorOp(Op.getNode());
5780
5781 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5782 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5783}
5784
5785SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5786 EVT VT = Op.getValueType();
5787 if (VT.isVector())
5788 return LowerVectorFP_TO_INT(Op, DAG);
5789
5790 bool IsStrict = Op->isStrictFPOpcode();
5791 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
5792
5793 if (isUnsupportedFloatingType(SrcVal.getValueType())) {
5794 RTLIB::Libcall LC;
5795 if (Op.getOpcode() == ISD::FP_TO_SINT ||
5796 Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
5797 LC = RTLIB::getFPTOSINT(SrcVal.getValueType(),
5798 Op.getValueType());
5799 else
5800 LC = RTLIB::getFPTOUINT(SrcVal.getValueType(),
5801 Op.getValueType());
5802 SDLoc Loc(Op);
5803 MakeLibCallOptions CallOptions;
5804 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
5805 SDValue Result;
5806 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
5807 CallOptions, Loc, Chain);
5808 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
5809 }
5810
5811 // FIXME: Remove this when we have strict fp instruction selection patterns
5812 if (IsStrict) {
5813 SDLoc Loc(Op);
5814 SDValue Result =
5815 DAG.getNode(Op.getOpcode() == ISD::STRICT_FP_TO_SINT ? ISD::FP_TO_SINT
5816 : ISD::FP_TO_UINT,
5817 Loc, Op.getValueType(), SrcVal);
5818 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
5819 }
5820
5821 return Op;
5822}
5823
5824static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5825 EVT VT = Op.getValueType();
5826 SDLoc dl(Op);
5827
5828 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5829 if (VT.getVectorElementType() == MVT::f32)
5830 return Op;
5831 return DAG.UnrollVectorOp(Op.getNode());
5832 }
5833
5834 assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||(static_cast <bool> ((Op.getOperand(0).getValueType() ==
MVT::v4i16 || Op.getOperand(0).getValueType() == MVT::v8i16)
&& "Invalid type for custom lowering!") ? void (0) :
__assert_fail ("(Op.getOperand(0).getValueType() == MVT::v4i16 || Op.getOperand(0).getValueType() == MVT::v8i16) && \"Invalid type for custom lowering!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 5836, __extension__ __PRETTY_FUNCTION__))
5835 Op.getOperand(0).getValueType() == MVT::v8i16) &&(static_cast <bool> ((Op.getOperand(0).getValueType() ==
MVT::v4i16 || Op.getOperand(0).getValueType() == MVT::v8i16)
&& "Invalid type for custom lowering!") ? void (0) :
__assert_fail ("(Op.getOperand(0).getValueType() == MVT::v4i16 || Op.getOperand(0).getValueType() == MVT::v8i16) && \"Invalid type for custom lowering!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 5836, __extension__ __PRETTY_FUNCTION__))
5836 "Invalid type for custom lowering!")(static_cast <bool> ((Op.getOperand(0).getValueType() ==
MVT::v4i16 || Op.getOperand(0).getValueType() == MVT::v8i16)
&& "Invalid type for custom lowering!") ? void (0) :
__assert_fail ("(Op.getOperand(0).getValueType() == MVT::v4i16 || Op.getOperand(0).getValueType() == MVT::v8i16) && \"Invalid type for custom lowering!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 5836, __extension__ __PRETTY_FUNCTION__))
;
5837
5838 const bool HasFullFP16 =
5839 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5840
5841 EVT DestVecType;
5842 if (VT == MVT::v4f32)
5843 DestVecType = MVT::v4i32;
5844 else if (VT == MVT::v4f16 && HasFullFP16)
5845 DestVecType = MVT::v4i16;
5846 else if (VT == MVT::v8f16 && HasFullFP16)
5847 DestVecType = MVT::v8i16;
5848 else
5849 return DAG.UnrollVectorOp(Op.getNode());
5850
5851 unsigned CastOpc;
5852 unsigned Opc;
5853 switch (Op.getOpcode()) {
5854 default: llvm_unreachable("Invalid opcode!")::llvm::llvm_unreachable_internal("Invalid opcode!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 5854)
;
5855 case ISD::SINT_TO_FP:
5856 CastOpc = ISD::SIGN_EXTEND;
5857 Opc = ISD::SINT_TO_FP;
5858 break;
5859 case ISD::UINT_TO_FP:
5860 CastOpc = ISD::ZERO_EXTEND;
5861 Opc = ISD::UINT_TO_FP;
5862 break;
5863 }
5864
5865 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5866 return DAG.getNode(Opc, dl, VT, Op);
5867}
5868
5869SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5870 EVT VT = Op.getValueType();
5871 if (VT.isVector())
5872 return LowerVectorINT_TO_FP(Op, DAG);
5873 if (isUnsupportedFloatingType(VT)) {
5874 RTLIB::Libcall LC;
5875 if (Op.getOpcode() == ISD::SINT_TO_FP)
5876 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5877 Op.getValueType());
5878 else
5879 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5880 Op.getValueType());
5881 MakeLibCallOptions CallOptions;
5882 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5883 CallOptions, SDLoc(Op)).first;
5884 }
5885
5886 return Op;
5887}
5888
5889SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5890 // Implement fcopysign with a fabs and a conditional fneg.
5891 SDValue Tmp0 = Op.getOperand(0);
5892 SDValue Tmp1 = Op.getOperand(1);
5893 SDLoc dl(Op);
5894 EVT VT = Op.getValueType();
5895 EVT SrcVT = Tmp1.getValueType();
5896 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5897 Tmp0.getOpcode() == ARMISD::VMOVDRR;
5898 bool UseNEON = !InGPR && Subtarget->hasNEON();
5899
5900 if (UseNEON) {
5901 // Use VBSL to copy the sign bit.
5902 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5903 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5904 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5905 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5906 if (VT == MVT::f64)
5907 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5908 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5909 DAG.getConstant(32, dl, MVT::i32));
5910 else /*if (VT == MVT::f32)*/
5911 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5912 if (SrcVT == MVT::f32) {
5913 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5914 if (VT == MVT::f64)
5915 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5916 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5917 DAG.getConstant(32, dl, MVT::i32));
5918 } else if (VT == MVT::f32)
5919 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5920 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5921 DAG.getConstant(32, dl, MVT::i32));
5922 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5923 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5924
5925 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
5926 dl, MVT::i32);
5927 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5928 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5929 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5930
5931 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5932 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5933 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5934 if (VT == MVT::f32) {
5935 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5936 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5937 DAG.getConstant(0, dl, MVT::i32));
5938 } else {
5939 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5940 }
5941
5942 return Res;
5943 }
5944
5945 // Bitcast operand 1 to i32.
5946 if (SrcVT == MVT::f64)
5947 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5948 Tmp1).getValue(1);
5949 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5950
5951 // Or in the signbit with integer operations.
5952 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5953 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5954 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5955 if (VT == MVT::f32) {
5956 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5957 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5958 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5959 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5960 }
5961
5962 // f64: Or the high part with signbit and then combine two parts.
5963 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5964 Tmp0);
5965 SDValue Lo = Tmp0.getValue(0);
5966 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5967 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5968 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5969}
5970
5971SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5972 MachineFunction &MF = DAG.getMachineFunction();
5973 MachineFrameInfo &MFI = MF.getFrameInfo();
5974 MFI.setReturnAddressIsTaken(true);
5975
5976 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5977 return SDValue();
5978
5979 EVT VT = Op.getValueType();
5980 SDLoc dl(Op);
5981 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5982 if (Depth) {
5983 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5984 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5985 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5986 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5987 MachinePointerInfo());
5988 }
5989
5990 // Return LR, which contains the return address. Mark it an implicit live-in.
5991 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5992 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5993}
5994
5995SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5996 const ARMBaseRegisterInfo &ARI =
5997 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5998 MachineFunction &MF = DAG.getMachineFunction();
5999 MachineFrameInfo &MFI = MF.getFrameInfo();
6000 MFI.setFrameAddressIsTaken(true);
6001
6002 EVT VT = Op.getValueType();
6003 SDLoc dl(Op); // FIXME probably not meaningful
6004 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6005 Register FrameReg = ARI.getFrameRegister(MF);
6006 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6007 while (Depth--)
6008 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
6009 MachinePointerInfo());
6010 return FrameAddr;
6011}
6012
6013// FIXME? Maybe this could be a TableGen attribute on some registers and
6014// this table could be generated automatically from RegInfo.
6015Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT,
6016 const MachineFunction &MF) const {
6017 Register Reg = StringSwitch<unsigned>(RegName)
6018 .Case("sp", ARM::SP)
6019 .Default(0);
6020 if (Reg)
6021 return Reg;
6022 report_fatal_error(Twine("Invalid register name \""
6023 + StringRef(RegName) + "\"."));
6024}
6025
6026// Result is 64 bit value so split into two 32 bit values and return as a
6027// pair of values.
6028static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
6029 SelectionDAG &DAG) {
6030 SDLoc DL(N);
6031
6032 // This function is only supposed to be called for i64 type destination.
6033 assert(N->getValueType(0) == MVT::i64(static_cast <bool> (N->getValueType(0) == MVT::i64 &&
"ExpandREAD_REGISTER called for non-i64 type result.") ? void
(0) : __assert_fail ("N->getValueType(0) == MVT::i64 && \"ExpandREAD_REGISTER called for non-i64 type result.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6034, __extension__ __PRETTY_FUNCTION__))
6034 && "ExpandREAD_REGISTER called for non-i64 type result.")(static_cast <bool> (N->getValueType(0) == MVT::i64 &&
"ExpandREAD_REGISTER called for non-i64 type result.") ? void
(0) : __assert_fail ("N->getValueType(0) == MVT::i64 && \"ExpandREAD_REGISTER called for non-i64 type result.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6034, __extension__ __PRETTY_FUNCTION__))
;
6035
6036 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
6037 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
6038 N->getOperand(0),
6039 N->getOperand(1));
6040
6041 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
6042 Read.getValue(1)));
6043 Results.push_back(Read.getOperand(0));
6044}
6045
6046/// \p BC is a bitcast that is about to be turned into a VMOVDRR.
6047/// When \p DstVT, the destination type of \p BC, is on the vector
6048/// register bank and the source of bitcast, \p Op, operates on the same bank,
6049/// it might be possible to combine them, such that everything stays on the
6050/// vector register bank.
6051/// \p return The node that would replace \p BT, if the combine
6052/// is possible.
6053static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
6054 SelectionDAG &DAG) {
6055 SDValue Op = BC->getOperand(0);
6056 EVT DstVT = BC->getValueType(0);
6057
6058 // The only vector instruction that can produce a scalar (remember,
6059 // since the bitcast was about to be turned into VMOVDRR, the source
6060 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
6061 // Moreover, we can do this combine only if there is one use.
6062 // Finally, if the destination type is not a vector, there is not
6063 // much point on forcing everything on the vector bank.
6064 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6065 !Op.hasOneUse())
6066 return SDValue();
6067
6068 // If the index is not constant, we will introduce an additional
6069 // multiply that will stick.
6070 // Give up in that case.
6071 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6072 if (!Index)
6073 return SDValue();
6074 unsigned DstNumElt = DstVT.getVectorNumElements();
6075
6076 // Compute the new index.
6077 const APInt &APIntIndex = Index->getAPIntValue();
6078 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
6079 NewIndex *= APIntIndex;
6080 // Check if the new constant index fits into i32.
6081 if (NewIndex.getBitWidth() > 32)
6082 return SDValue();
6083
6084 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
6085 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
6086 SDLoc dl(Op);
6087 SDValue ExtractSrc = Op.getOperand(0);
6088 EVT VecVT = EVT::getVectorVT(
6089 *DAG.getContext(), DstVT.getScalarType(),
6090 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
6091 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
6092 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
6093 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
6094}
6095
6096/// ExpandBITCAST - If the target supports VFP, this function is called to
6097/// expand a bit convert where either the source or destination type is i64 to
6098/// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
6099/// operand type is illegal (e.g., v2f32 for a target that doesn't support
6100/// vectors), since the legalizer won't know what to do with that.
6101SDValue ARMTargetLowering::ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
6102 const ARMSubtarget *Subtarget) const {
6103 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6104 SDLoc dl(N);
6105 SDValue Op = N->getOperand(0);
6106
6107 // This function is only supposed to be called for i16 and i64 types, either
6108 // as the source or destination of the bit convert.
6109 EVT SrcVT = Op.getValueType();
6110 EVT DstVT = N->getValueType(0);
6111
6112 if ((SrcVT == MVT::i16 || SrcVT == MVT::i32) &&
6113 (DstVT == MVT::f16 || DstVT == MVT::bf16))
6114 return MoveToHPR(SDLoc(N), DAG, MVT::i32, DstVT.getSimpleVT(),
6115 DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), MVT::i32, Op));
6116
6117 if ((DstVT == MVT::i16 || DstVT == MVT::i32) &&
6118 (SrcVT == MVT::f16 || SrcVT == MVT::bf16))
6119 return DAG.getNode(
6120 ISD::TRUNCATE, SDLoc(N), DstVT,
6121 MoveFromHPR(SDLoc(N), DAG, MVT::i32, SrcVT.getSimpleVT(), Op));
6122
6123 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
6124 return SDValue();
6125
6126 // Turn i64->f64 into VMOVDRR.
6127 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
6128 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
6129 // if we can combine the bitcast with its source.
6130 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
6131 return Val;
6132
6133 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
6134 DAG.getConstant(0, dl, MVT::i32));
6135 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
6136 DAG.getConstant(1, dl, MVT::i32));
6137 return DAG.getNode(ISD::BITCAST, dl, DstVT,
6138 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
6139 }
6140
6141 // Turn f64->i64 into VMOVRRD.
6142 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
6143 SDValue Cvt;
6144 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
6145 SrcVT.getVectorNumElements() > 1)
6146 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6147 DAG.getVTList(MVT::i32, MVT::i32),
6148 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
6149 else
6150 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6151 DAG.getVTList(MVT::i32, MVT::i32), Op);
6152 // Merge the pieces into a single i64 value.
6153 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
6154 }
6155
6156 return SDValue();
6157}
6158
6159/// getZeroVector - Returns a vector of specified type with all zero elements.
6160/// Zero vectors are used to represent vector negation and in those cases
6161/// will be implemented with the NEON VNEG instruction. However, VNEG does
6162/// not support i64 elements, so sometimes the zero vectors will need to be
6163/// explicitly constructed. Regardless, use a canonical VMOV to create the
6164/// zero vector.
6165static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6166 assert(VT.isVector() && "Expected a vector type")(static_cast <bool> (VT.isVector() && "Expected a vector type"
) ? void (0) : __assert_fail ("VT.isVector() && \"Expected a vector type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6166, __extension__ __PRETTY_FUNCTION__))
;
6167 // The canonical modified immediate encoding of a zero vector is....0!
6168 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
6169 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
6170 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
6171 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6172}
6173
6174/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6175/// i32 values and take a 2 x i32 value to shift plus a shift amount.
6176SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
6177 SelectionDAG &DAG) const {
6178 assert(Op.getNumOperands() == 3 && "Not a double-shift!")(static_cast <bool> (Op.getNumOperands() == 3 &&
"Not a double-shift!") ? void (0) : __assert_fail ("Op.getNumOperands() == 3 && \"Not a double-shift!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6178, __extension__ __PRETTY_FUNCTION__))
;
6179 EVT VT = Op.getValueType();
6180 unsigned VTBits = VT.getSizeInBits();
6181 SDLoc dl(Op);
6182 SDValue ShOpLo = Op.getOperand(0);
6183 SDValue ShOpHi = Op.getOperand(1);
6184 SDValue ShAmt = Op.getOperand(2);
6185 SDValue ARMcc;
6186 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6187 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6188
6189 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS)(static_cast <bool> (Op.getOpcode() == ISD::SRA_PARTS ||
Op.getOpcode() == ISD::SRL_PARTS) ? void (0) : __assert_fail
("Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6189, __extension__ __PRETTY_FUNCTION__))
;
6190
6191 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6192 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6193 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6194 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6195 DAG.getConstant(VTBits, dl, MVT::i32));
6196 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6197 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6198 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6199 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6200 ISD::SETGE, ARMcc, DAG, dl);
6201 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
6202 ARMcc, CCR, CmpLo);
6203
6204 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6205 SDValue HiBigShift = Opc == ISD::SRA
6206 ? DAG.getNode(Opc, dl, VT, ShOpHi,
6207 DAG.getConstant(VTBits - 1, dl, VT))
6208 : DAG.getConstant(0, dl, VT);
6209 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6210 ISD::SETGE, ARMcc, DAG, dl);
6211 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
6212 ARMcc, CCR, CmpHi);
6213
6214 SDValue Ops[2] = { Lo, Hi };
6215 return DAG.getMergeValues(Ops, dl);
6216}
6217
6218/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6219/// i32 values and take a 2 x i32 value to shift plus a shift amount.
6220SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
6221 SelectionDAG &DAG) const {
6222 assert(Op.getNumOperands() == 3 && "Not a double-shift!")(static_cast <bool> (Op.getNumOperands() == 3 &&
"Not a double-shift!") ? void (0) : __assert_fail ("Op.getNumOperands() == 3 && \"Not a double-shift!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6222, __extension__ __PRETTY_FUNCTION__))
;
6223 EVT VT = Op.getValueType();
6224 unsigned VTBits = VT.getSizeInBits();
6225 SDLoc dl(Op);
6226 SDValue ShOpLo = Op.getOperand(0);
6227 SDValue ShOpHi = Op.getOperand(1);
6228 SDValue ShAmt = Op.getOperand(2);
6229 SDValue ARMcc;
6230 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6231
6232 assert(Op.getOpcode() == ISD::SHL_PARTS)(static_cast <bool> (Op.getOpcode() == ISD::SHL_PARTS) ?
void (0) : __assert_fail ("Op.getOpcode() == ISD::SHL_PARTS"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6232, __extension__ __PRETTY_FUNCTION__))
;
6233 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6234 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6235 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6236 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6237 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6238
6239 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6240 DAG.getConstant(VTBits, dl, MVT::i32));
6241 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6242 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6243 ISD::SETGE, ARMcc, DAG, dl);
6244 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
6245 ARMcc, CCR, CmpHi);
6246
6247 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6248 ISD::SETGE, ARMcc, DAG, dl);
6249 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6250 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
6251 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
6252
6253 SDValue Ops[2] = { Lo, Hi };
6254 return DAG.getMergeValues(Ops, dl);
6255}
6256
6257SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6258 SelectionDAG &DAG) const {
6259 // The rounding mode is in bits 23:22 of the FPSCR.
6260 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
6261 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
6262 // so that the shift + and get folded into a bitfield extract.
6263 SDLoc dl(Op);
6264 SDValue Chain = Op.getOperand(0);
6265 SDValue Ops[] = {Chain,
6266 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)};
6267
6268 SDValue FPSCR =
6269 DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops);
6270 Chain = FPSCR.getValue(1);
6271 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
6272 DAG.getConstant(1U << 22, dl, MVT::i32));
6273 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
6274 DAG.getConstant(22, dl, MVT::i32));
6275 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
6276 DAG.getConstant(3, dl, MVT::i32));
6277 return DAG.getMergeValues({And, Chain}, dl);
6278}
6279
6280SDValue ARMTargetLowering::LowerSET_ROUNDING(SDValue Op,
6281 SelectionDAG &DAG) const {
6282 SDLoc DL(Op);
6283 SDValue Chain = Op->getOperand(0);
6284 SDValue RMValue = Op->getOperand(1);
6285
6286 // The rounding mode is in bits 23:22 of the FPSCR.
6287 // The llvm.set.rounding argument value to ARM rounding mode value mapping
6288 // is 0->3, 1->0, 2->1, 3->2. The formula we use to implement this is
6289 // ((arg - 1) & 3) << 22).
6290 //
6291 // It is expected that the argument of llvm.set.rounding is within the
6292 // segment [0, 3], so NearestTiesToAway (4) is not handled here. It is
6293 // responsibility of the code generated llvm.set.rounding to ensure this
6294 // condition.
6295
6296 // Calculate new value of FPSCR[23:22].
6297 RMValue = DAG.getNode(ISD::SUB, DL, MVT::i32, RMValue,
6298 DAG.getConstant(1, DL, MVT::i32));
6299 RMValue = DAG.getNode(ISD::AND, DL, MVT::i32, RMValue,
6300 DAG.getConstant(0x3, DL, MVT::i32));
6301 RMValue = DAG.getNode(ISD::SHL, DL, MVT::i32, RMValue,
6302 DAG.getConstant(ARM::RoundingBitsPos, DL, MVT::i32));
6303
6304 // Get current value of FPSCR.
6305 SDValue Ops[] = {Chain,
6306 DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)};
6307 SDValue FPSCR =
6308 DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops);
6309 Chain = FPSCR.getValue(1);
6310 FPSCR = FPSCR.getValue(0);
6311
6312 // Put new rounding mode into FPSCR[23:22].
6313 const unsigned RMMask = ~(ARM::Rounding::rmMask << ARM::RoundingBitsPos);
6314 FPSCR = DAG.getNode(ISD::AND, DL, MVT::i32, FPSCR,
6315 DAG.getConstant(RMMask, DL, MVT::i32));
6316 FPSCR = DAG.getNode(ISD::OR, DL, MVT::i32, FPSCR, RMValue);
6317 SDValue Ops2[] = {
6318 Chain, DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32), FPSCR};
6319 return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
6320}
6321
6322static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
6323 const ARMSubtarget *ST) {
6324 SDLoc dl(N);
6325 EVT VT = N->getValueType(0);
6326 if (VT.isVector() && ST->hasNEON()) {
6327
6328 // Compute the least significant set bit: LSB = X & -X
6329 SDValue X = N->getOperand(0);
6330 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
6331 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
6332
6333 EVT ElemTy = VT.getVectorElementType();
6334
6335 if (ElemTy == MVT::i8) {
6336 // Compute with: cttz(x) = ctpop(lsb - 1)
6337 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6338 DAG.getTargetConstant(1, dl, ElemTy));
6339 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6340 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6341 }
6342
6343 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
6344 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
6345 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
6346 unsigned NumBits = ElemTy.getSizeInBits();
6347 SDValue WidthMinus1 =
6348 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6349 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
6350 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
6351 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
6352 }
6353
6354 // Compute with: cttz(x) = ctpop(lsb - 1)
6355
6356 // Compute LSB - 1.
6357 SDValue Bits;
6358 if (ElemTy == MVT::i64) {
6359 // Load constant 0xffff'ffff'ffff'ffff to register.
6360 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6361 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
6362 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
6363 } else {
6364 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6365 DAG.getTargetConstant(1, dl, ElemTy));
6366 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6367 }
6368 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6369 }
6370
6371 if (!ST->hasV6T2Ops())
6372 return SDValue();
6373
6374 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
6375 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
6376}
6377
6378static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
6379 const ARMSubtarget *ST) {
6380 EVT VT = N->getValueType(0);
6381 SDLoc DL(N);
6382
6383 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.")(static_cast <bool> (ST->hasNEON() && "Custom ctpop lowering requires NEON."
) ? void (0) : __assert_fail ("ST->hasNEON() && \"Custom ctpop lowering requires NEON.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6383, __extension__ __PRETTY_FUNCTION__))
;
6384 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||(static_cast <bool> ((VT == MVT::v1i64 || VT == MVT::v2i64
|| VT == MVT::v2i32 || VT == MVT::v4i32 || VT == MVT::v4i16 ||
VT == MVT::v8i16) && "Unexpected type for custom ctpop lowering"
) ? void (0) : __assert_fail ("(VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && \"Unexpected type for custom ctpop lowering\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6386, __extension__ __PRETTY_FUNCTION__))
6385 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&(static_cast <bool> ((VT == MVT::v1i64 || VT == MVT::v2i64
|| VT == MVT::v2i32 || VT == MVT::v4i32 || VT == MVT::v4i16 ||
VT == MVT::v8i16) && "Unexpected type for custom ctpop lowering"
) ? void (0) : __assert_fail ("(VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && \"Unexpected type for custom ctpop lowering\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6386, __extension__ __PRETTY_FUNCTION__))
6386 "Unexpected type for custom ctpop lowering")(static_cast <bool> ((VT == MVT::v1i64 || VT == MVT::v2i64
|| VT == MVT::v2i32 || VT == MVT::v4i32 || VT == MVT::v4i16 ||
VT == MVT::v8i16) && "Unexpected type for custom ctpop lowering"
) ? void (0) : __assert_fail ("(VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && \"Unexpected type for custom ctpop lowering\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6386, __extension__ __PRETTY_FUNCTION__))
;
6387
6388 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6389 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6390 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
6391 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
6392
6393 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6394 unsigned EltSize = 8;
6395 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6396 while (EltSize != VT.getScalarSizeInBits()) {
6397 SmallVector<SDValue, 8> Ops;
6398 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
6399 TLI.getPointerTy(DAG.getDataLayout())));
6400 Ops.push_back(Res);
6401
6402 EltSize *= 2;
6403 NumElts /= 2;
6404 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
6405 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
6406 }
6407
6408 return Res;
6409}
6410
6411/// Getvshiftimm - Check if this is a valid build_vector for the immediate
6412/// operand of a vector shift operation, where all the elements of the
6413/// build_vector must have the same constant integer value.
6414static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6415 // Ignore bit_converts.
6416 while (Op.getOpcode() == ISD::BITCAST)
6417 Op = Op.getOperand(0);
6418 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6419 APInt SplatBits, SplatUndef;
6420 unsigned SplatBitSize;
6421 bool HasAnyUndefs;
6422 if (!BVN ||
6423 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6424 ElementBits) ||
6425 SplatBitSize > ElementBits)
6426 return false;
6427 Cnt = SplatBits.getSExtValue();
6428 return true;
6429}
6430
6431/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6432/// operand of a vector shift left operation. That value must be in the range:
6433/// 0 <= Value < ElementBits for a left shift; or
6434/// 0 <= Value <= ElementBits for a long left shift.
6435static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6436 assert(VT.isVector() && "vector shift count is not a vector type")(static_cast <bool> (VT.isVector() && "vector shift count is not a vector type"
) ? void (0) : __assert_fail ("VT.isVector() && \"vector shift count is not a vector type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6436, __extension__ __PRETTY_FUNCTION__))
;
6437 int64_t ElementBits = VT.getScalarSizeInBits();
6438 if (!getVShiftImm(Op, ElementBits, Cnt))
6439 return false;
6440 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6441}
6442
6443/// isVShiftRImm - Check if this is a valid build_vector for the immediate
6444/// operand of a vector shift right operation. For a shift opcode, the value
6445/// is positive, but for an intrinsic the value count must be negative. The
6446/// absolute value must be in the range:
6447/// 1 <= |Value| <= ElementBits for a right shift; or
6448/// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
6449static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6450 int64_t &Cnt) {
6451 assert(VT.isVector() && "vector shift count is not a vector type")(static_cast <bool> (VT.isVector() && "vector shift count is not a vector type"
) ? void (0) : __assert_fail ("VT.isVector() && \"vector shift count is not a vector type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6451, __extension__ __PRETTY_FUNCTION__))
;
6452 int64_t ElementBits = VT.getScalarSizeInBits();
6453 if (!getVShiftImm(Op, ElementBits, Cnt))
6454 return false;
6455 if (!isIntrinsic)
6456 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6457 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
6458 Cnt = -Cnt;
6459 return true;
6460 }
6461 return false;
6462}
6463
6464static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
6465 const ARMSubtarget *ST) {
6466 EVT VT = N->getValueType(0);
6467 SDLoc dl(N);
6468 int64_t Cnt;
6469
6470 if (!VT.isVector())
6471 return SDValue();
6472
6473 // We essentially have two forms here. Shift by an immediate and shift by a
6474 // vector register (there are also shift by a gpr, but that is just handled
6475 // with a tablegen pattern). We cannot easily match shift by an immediate in
6476 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
6477 // For shifting by a vector, we don't have VSHR, only VSHL (which can be
6478 // signed or unsigned, and a negative shift indicates a shift right).
6479 if (N->getOpcode() == ISD::SHL) {
6480 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
6481 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
6482 DAG.getConstant(Cnt, dl, MVT::i32));
6483 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
6484 N->getOperand(1));
6485 }
6486
6487 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&(static_cast <bool> ((N->getOpcode() == ISD::SRA || N
->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) && \"unexpected vector shift opcode\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6488, __extension__ __PRETTY_FUNCTION__))
6488 "unexpected vector shift opcode")(static_cast <bool> ((N->getOpcode() == ISD::SRA || N
->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) && \"unexpected vector shift opcode\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6488, __extension__ __PRETTY_FUNCTION__))
;
6489
6490 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
6491 unsigned VShiftOpc =
6492 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
6493 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
6494 DAG.getConstant(Cnt, dl, MVT::i32));
6495 }
6496
6497 // Other right shifts we don't have operations for (we use a shift left by a
6498 // negative number).
6499 EVT ShiftVT = N->getOperand(1).getValueType();
6500 SDValue NegatedCount = DAG.getNode(
6501 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
6502 unsigned VShiftOpc =
6503 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
6504 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
6505}
6506
6507static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
6508 const ARMSubtarget *ST) {
6509 EVT VT = N->getValueType(0);
6510 SDLoc dl(N);
6511
6512 // We can get here for a node like i32 = ISD::SHL i32, i64
6513 if (VT != MVT::i64)
6514 return SDValue();
6515
6516 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||(static_cast <bool> ((N->getOpcode() == ISD::SRL || N
->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SHL
) && "Unknown shift to lower!") ? void (0) : __assert_fail
("(N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SHL) && \"Unknown shift to lower!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6518, __extension__ __PRETTY_FUNCTION__))
6517 N->getOpcode() == ISD::SHL) &&(static_cast <bool> ((N->getOpcode() == ISD::SRL || N
->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SHL
) && "Unknown shift to lower!") ? void (0) : __assert_fail
("(N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SHL) && \"Unknown shift to lower!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6518, __extension__ __PRETTY_FUNCTION__))
6518 "Unknown shift to lower!")(static_cast <bool> ((N->getOpcode() == ISD::SRL || N
->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SHL
) && "Unknown shift to lower!") ? void (0) : __assert_fail
("(N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SHL) && \"Unknown shift to lower!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6518, __extension__ __PRETTY_FUNCTION__))
;
6519
6520 unsigned ShOpc = N->getOpcode();
6521 if (ST->hasMVEIntegerOps()) {
6522 SDValue ShAmt = N->getOperand(1);
6523 unsigned ShPartsOpc = ARMISD::LSLL;
6524 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
6525
6526 // If the shift amount is greater than 32 or has a greater bitwidth than 64
6527 // then do the default optimisation
6528 if (ShAmt->getValueType(0).getSizeInBits() > 64 ||
6529 (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32)))
6530 return SDValue();
6531
6532 // Extract the lower 32 bits of the shift amount if it's not an i32
6533 if (ShAmt->getValueType(0) != MVT::i32)
6534 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6535
6536 if (ShOpc == ISD::SRL) {
6537 if (!Con)
6538 // There is no t2LSRLr instruction so negate and perform an lsll if the
6539 // shift amount is in a register, emulating a right shift.
6540 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6541 DAG.getConstant(0, dl, MVT::i32), ShAmt);
6542 else
6543 // Else generate an lsrl on the immediate shift amount
6544 ShPartsOpc = ARMISD::LSRL;
6545 } else if (ShOpc == ISD::SRA)
6546 ShPartsOpc = ARMISD::ASRL;
6547
6548 // Lower 32 bits of the destination/source
6549 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6550 DAG.getConstant(0, dl, MVT::i32));
6551 // Upper 32 bits of the destination/source
6552 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6553 DAG.getConstant(1, dl, MVT::i32));
6554
6555 // Generate the shift operation as computed above
6556 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6557 ShAmt);
6558 // The upper 32 bits come from the second return value of lsll
6559 Hi = SDValue(Lo.getNode(), 1);
6560 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6561 }
6562
6563 // We only lower SRA, SRL of 1 here, all others use generic lowering.
6564 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6565 return SDValue();
6566
6567 // If we are in thumb mode, we don't have RRX.
6568 if (ST->isThumb1Only())
6569 return SDValue();
6570
6571 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
6572 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6573 DAG.getConstant(0, dl, MVT::i32));
6574 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6575 DAG.getConstant(1, dl, MVT::i32));
6576
6577 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
6578 // captures the result into a carry flag.
6579 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
6580 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
6581
6582 // The low part is an ARMISD::RRX operand, which shifts the carry in.
6583 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6584
6585 // Merge the pieces into a single i64 value.
6586 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6587}
6588
6589static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6590 const ARMSubtarget *ST) {
6591 bool Invert = false;
6592 bool Swap = false;
6593 unsigned Opc = ARMCC::AL;
6594
6595 SDValue Op0 = Op.getOperand(0);
6596 SDValue Op1 = Op.getOperand(1);
6597 SDValue CC = Op.getOperand(2);
6598 EVT VT = Op.getValueType();
6599 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6600 SDLoc dl(Op);
6601
6602 EVT CmpVT;
6603 if (ST->hasNEON())
6604 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6605 else {
6606 assert(ST->hasMVEIntegerOps() &&(static_cast <bool> (ST->hasMVEIntegerOps() &&
"No hardware support for integer vector comparison!") ? void
(0) : __assert_fail ("ST->hasMVEIntegerOps() && \"No hardware support for integer vector comparison!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6607, __extension__ __PRETTY_FUNCTION__))
6607 "No hardware support for integer vector comparison!")(static_cast <bool> (ST->hasMVEIntegerOps() &&
"No hardware support for integer vector comparison!") ? void
(0) : __assert_fail ("ST->hasMVEIntegerOps() && \"No hardware support for integer vector comparison!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6607, __extension__ __PRETTY_FUNCTION__))
;
6608
6609 if (Op.getValueType().getVectorElementType() != MVT::i1)
6610 return SDValue();
6611
6612 // Make sure we expand floating point setcc to scalar if we do not have
6613 // mve.fp, so that we can handle them from there.
6614 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6615 return SDValue();
6616
6617 CmpVT = VT;
6618 }
6619
6620 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6621 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6622 // Special-case integer 64-bit equality comparisons. They aren't legal,
6623 // but they can be lowered with a few vector instructions.
6624 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6625 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6626 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6627 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6628 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6629 DAG.getCondCode(ISD::SETEQ));
6630 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6631 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6632 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6633 if (SetCCOpcode == ISD::SETNE)
6634 Merged = DAG.getNOT(dl, Merged, CmpVT);
6635 Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6636 return Merged;
6637 }
6638
6639 if (CmpVT.getVectorElementType() == MVT::i64)
6640 // 64-bit comparisons are not legal in general.
6641 return SDValue();
6642
6643 if (Op1.getValueType().isFloatingPoint()) {
6644 switch (SetCCOpcode) {
6645 default: llvm_unreachable("Illegal FP comparison")::llvm::llvm_unreachable_internal("Illegal FP comparison", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6645)
;
6646 case ISD::SETUNE:
6647 case ISD::SETNE:
6648 if (ST->hasMVEFloatOps()) {
6649 Opc = ARMCC::NE; break;
6650 } else {
6651 Invert = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6652 }
6653 case ISD::SETOEQ:
6654 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6655 case ISD::SETOLT:
6656 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6657 case ISD::SETOGT:
6658 case ISD::SETGT: Opc = ARMCC::GT; break;
6659 case ISD::SETOLE:
6660 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6661 case ISD::SETOGE:
6662 case ISD::SETGE: Opc = ARMCC::GE; break;
6663 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6664 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6665 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6666 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6667 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6668 case ISD::SETONE: {
6669 // Expand this to (OLT | OGT).
6670 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6671 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6672 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6673 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6674 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6675 if (Invert)
6676 Result = DAG.getNOT(dl, Result, VT);
6677 return Result;
6678 }
6679 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6680 case ISD::SETO: {
6681 // Expand this to (OLT | OGE).
6682 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6683 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6684 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6685 DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6686 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6687 if (Invert)
6688 Result = DAG.getNOT(dl, Result, VT);
6689 return Result;
6690 }
6691 }
6692 } else {
6693 // Integer comparisons.
6694 switch (SetCCOpcode) {
6695 default: llvm_unreachable("Illegal integer comparison")::llvm::llvm_unreachable_internal("Illegal integer comparison"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6695)
;
6696 case ISD::SETNE:
6697 if (ST->hasMVEIntegerOps()) {
6698 Opc = ARMCC::NE; break;
6699 } else {
6700 Invert = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6701 }
6702 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6703 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6704 case ISD::SETGT: Opc = ARMCC::GT; break;
6705 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6706 case ISD::SETGE: Opc = ARMCC::GE; break;
6707 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6708 case ISD::SETUGT: Opc = ARMCC::HI; break;
6709 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
6710 case ISD::SETUGE: Opc = ARMCC::HS; break;
6711 }
6712
6713 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6714 if (ST->hasNEON() && Opc == ARMCC::EQ) {
6715 SDValue AndOp;
6716 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6717 AndOp = Op0;
6718 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6719 AndOp = Op1;
6720
6721 // Ignore bitconvert.
6722 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6723 AndOp = AndOp.getOperand(0);
6724
6725 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6726 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6727 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6728 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6729 if (!Invert)
6730 Result = DAG.getNOT(dl, Result, VT);
6731 return Result;
6732 }
6733 }
6734 }
6735
6736 if (Swap)
6737 std::swap(Op0, Op1);
6738
6739 // If one of the operands is a constant vector zero, attempt to fold the
6740 // comparison to a specialized compare-against-zero form.
6741 SDValue SingleOp;
6742 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6743 SingleOp = Op0;
6744 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
6745 if (Opc == ARMCC::GE)
6746 Opc = ARMCC::LE;
6747 else if (Opc == ARMCC::GT)
6748 Opc = ARMCC::LT;
6749 SingleOp = Op1;
6750 }
6751
6752 SDValue Result;
6753 if (SingleOp.getNode()) {
6754 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp,
6755 DAG.getConstant(Opc, dl, MVT::i32));
6756 } else {
6757 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6758 DAG.getConstant(Opc, dl, MVT::i32));
6759 }
6760
6761 Result = DAG.getSExtOrTrunc(Result, dl, VT);
6762
6763 if (Invert)
6764 Result = DAG.getNOT(dl, Result, VT);
6765
6766 return Result;
6767}
6768
6769static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6770 SDValue LHS = Op.getOperand(0);
6771 SDValue RHS = Op.getOperand(1);
6772 SDValue Carry = Op.getOperand(2);
6773 SDValue Cond = Op.getOperand(3);
6774 SDLoc DL(Op);
6775
6776 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.")(static_cast <bool> (LHS.getSimpleValueType().isInteger
() && "SETCCCARRY is integer only.") ? void (0) : __assert_fail
("LHS.getSimpleValueType().isInteger() && \"SETCCCARRY is integer only.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6776, __extension__ __PRETTY_FUNCTION__))
;
6777
6778 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
6779 // have to invert the carry first.
6780 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6781 DAG.getConstant(1, DL, MVT::i32), Carry);
6782 // This converts the boolean value carry into the carry flag.
6783 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6784
6785 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6786 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6787
6788 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6789 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6790 SDValue ARMcc = DAG.getConstant(
6791 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6792 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6793 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6794 Cmp.getValue(1), SDValue());
6795 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6796 CCR, Chain.getValue(1));
6797}
6798
6799/// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6800/// valid vector constant for a NEON or MVE instruction with a "modified
6801/// immediate" operand (e.g., VMOV). If so, return the encoded value.
6802static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6803 unsigned SplatBitSize, SelectionDAG &DAG,
6804 const SDLoc &dl, EVT &VT, EVT VectorVT,
6805 VMOVModImmType type) {
6806 unsigned OpCmode, Imm;
6807 bool is128Bits = VectorVT.is128BitVector();
6808
6809 // SplatBitSize is set to the smallest size that splats the vector, so a
6810 // zero vector will always have SplatBitSize == 8. However, NEON modified
6811 // immediate instructions others than VMOV do not support the 8-bit encoding
6812 // of a zero vector, and the default encoding of zero is supposed to be the
6813 // 32-bit version.
6814 if (SplatBits == 0)
6815 SplatBitSize = 32;
6816
6817 switch (SplatBitSize) {
6818 case 8:
6819 if (type != VMOVModImm)
6820 return SDValue();
6821 // Any 1-byte value is OK. Op=0, Cmode=1110.
6822 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big")(static_cast <bool> ((SplatBits & ~0xff) == 0 &&
"one byte splat value is too big") ? void (0) : __assert_fail
("(SplatBits & ~0xff) == 0 && \"one byte splat value is too big\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6822, __extension__ __PRETTY_FUNCTION__))
;
6823 OpCmode = 0xe;
6824 Imm = SplatBits;
6825 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6826 break;
6827
6828 case 16:
6829 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6830 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6831 if ((SplatBits & ~0xff) == 0) {
6832 // Value = 0x00nn: Op=x, Cmode=100x.
6833 OpCmode = 0x8;
6834 Imm = SplatBits;
6835 break;
6836 }
6837 if ((SplatBits & ~0xff00) == 0) {
6838 // Value = 0xnn00: Op=x, Cmode=101x.
6839 OpCmode = 0xa;
6840 Imm = SplatBits >> 8;
6841 break;
6842 }
6843 return SDValue();
6844
6845 case 32:
6846 // NEON's 32-bit VMOV supports splat values where:
6847 // * only one byte is nonzero, or
6848 // * the least significant byte is 0xff and the second byte is nonzero, or
6849 // * the least significant 2 bytes are 0xff and the third is nonzero.
6850 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6851 if ((SplatBits & ~0xff) == 0) {
6852 // Value = 0x000000nn: Op=x, Cmode=000x.
6853 OpCmode = 0;
6854 Imm = SplatBits;
6855 break;
6856 }
6857 if ((SplatBits & ~0xff00) == 0) {
6858 // Value = 0x0000nn00: Op=x, Cmode=001x.
6859 OpCmode = 0x2;
6860 Imm = SplatBits >> 8;
6861 break;
6862 }
6863 if ((SplatBits & ~0xff0000) == 0) {
6864 // Value = 0x00nn0000: Op=x, Cmode=010x.
6865 OpCmode = 0x4;
6866 Imm = SplatBits >> 16;
6867 break;
6868 }
6869 if ((SplatBits & ~0xff000000) == 0) {
6870 // Value = 0xnn000000: Op=x, Cmode=011x.
6871 OpCmode = 0x6;
6872 Imm = SplatBits >> 24;
6873 break;
6874 }
6875
6876 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6877 if (type == OtherModImm) return SDValue();
6878
6879 if ((SplatBits & ~0xffff) == 0 &&
6880 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6881 // Value = 0x0000nnff: Op=x, Cmode=1100.
6882 OpCmode = 0xc;
6883 Imm = SplatBits >> 8;
6884 break;
6885 }
6886
6887 // cmode == 0b1101 is not supported for MVE VMVN
6888 if (type == MVEVMVNModImm)
6889 return SDValue();
6890
6891 if ((SplatBits & ~0xffffff) == 0 &&
6892 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6893 // Value = 0x00nnffff: Op=x, Cmode=1101.
6894 OpCmode = 0xd;
6895 Imm = SplatBits >> 16;
6896 break;
6897 }
6898
6899 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6900 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6901 // VMOV.I32. A (very) minor optimization would be to replicate the value
6902 // and fall through here to test for a valid 64-bit splat. But, then the
6903 // caller would also need to check and handle the change in size.
6904 return SDValue();
6905
6906 case 64: {
6907 if (type != VMOVModImm)
6908 return SDValue();
6909 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6910 uint64_t BitMask = 0xff;
6911 unsigned ImmMask = 1;
6912 Imm = 0;
6913 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6914 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6915 Imm |= ImmMask;
6916 } else if ((SplatBits & BitMask) != 0) {
6917 return SDValue();
6918 }
6919 BitMask <<= 8;
6920 ImmMask <<= 1;
6921 }
6922
6923 if (DAG.getDataLayout().isBigEndian()) {
6924 // Reverse the order of elements within the vector.
6925 unsigned BytesPerElem = VectorVT.getScalarSizeInBits() / 8;
6926 unsigned Mask = (1 << BytesPerElem) - 1;
6927 unsigned NumElems = 8 / BytesPerElem;
6928 unsigned NewImm = 0;
6929 for (unsigned ElemNum = 0; ElemNum < NumElems; ++ElemNum) {
6930 unsigned Elem = ((Imm >> ElemNum * BytesPerElem) & Mask);
6931 NewImm |= Elem << (NumElems - ElemNum - 1) * BytesPerElem;
6932 }
6933 Imm = NewImm;
6934 }
6935
6936 // Op=1, Cmode=1110.
6937 OpCmode = 0x1e;
6938 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6939 break;
6940 }
6941
6942 default:
6943 llvm_unreachable("unexpected size for isVMOVModifiedImm")::llvm::llvm_unreachable_internal("unexpected size for isVMOVModifiedImm"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6943)
;
6944 }
6945
6946 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6947 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6948}
6949
6950SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6951 const ARMSubtarget *ST) const {
6952 EVT VT = Op.getValueType();
6953 bool IsDouble = (VT == MVT::f64);
6954 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6955 const APFloat &FPVal = CFP->getValueAPF();
6956
6957 // Prevent floating-point constants from using literal loads
6958 // when execute-only is enabled.
6959 if (ST->genExecuteOnly()) {
6960 // If we can represent the constant as an immediate, don't lower it
6961 if (isFPImmLegal(FPVal, VT))
6962 return Op;
6963 // Otherwise, construct as integer, and move to float register
6964 APInt INTVal = FPVal.bitcastToAPInt();
6965 SDLoc DL(CFP);
6966 switch (VT.getSimpleVT().SimpleTy) {
6967 default:
6968 llvm_unreachable("Unknown floating point type!")::llvm::llvm_unreachable_internal("Unknown floating point type!"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 6968)
;
6969 break;
6970 case MVT::f64: {
6971 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6972 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6973 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
6974 }
6975 case MVT::f32:
6976 return DAG.getNode(ARMISD::VMOVSR, DL, VT,
6977 DAG.getConstant(INTVal, DL, MVT::i32));
6978 }
6979 }
6980
6981 if (!ST->hasVFP3Base())
6982 return SDValue();
6983
6984 // Use the default (constant pool) lowering for double constants when we have
6985 // an SP-only FPU
6986 if (IsDouble && !Subtarget->hasFP64())
6987 return SDValue();
6988
6989 // Try splatting with a VMOV.f32...
6990 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
6991
6992 if (ImmVal != -1) {
6993 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6994 // We have code in place to select a valid ConstantFP already, no need to
6995 // do any mangling.
6996 return Op;
6997 }
6998
6999 // It's a float and we are trying to use NEON operations where
7000 // possible. Lower it to a splat followed by an extract.
7001 SDLoc DL(Op);
7002 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
7003 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
7004 NewVal);
7005 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
7006 DAG.getConstant(0, DL, MVT::i32));
7007 }
7008
7009 // The rest of our options are NEON only, make sure that's allowed before
7010 // proceeding..
7011 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
7012 return SDValue();
7013
7014 EVT VMovVT;
7015 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
7016
7017 // It wouldn't really be worth bothering for doubles except for one very
7018 // important value, which does happen to match: 0.0. So make sure we don't do
7019 // anything stupid.
7020 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
7021 return SDValue();
7022
7023 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
7024 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
7025 VMovVT, VT, VMOVModImm);
7026 if (NewVal != SDValue()) {
7027 SDLoc DL(Op);
7028 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
7029 NewVal);
7030 if (IsDouble)
7031 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
7032
7033 // It's a float: cast and extract a vector element.
7034 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
7035 VecConstant);
7036 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
7037 DAG.getConstant(0, DL, MVT::i32));
7038 }
7039
7040 // Finally, try a VMVN.i32
7041 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
7042 VT, VMVNModImm);
7043 if (NewVal != SDValue()) {
7044 SDLoc DL(Op);
7045 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
7046
7047 if (IsDouble)
7048 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
7049
7050 // It's a float: cast and extract a vector element.
7051 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
7052 VecConstant);
7053 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
7054 DAG.getConstant(0, DL, MVT::i32));
7055 }
7056
7057 return SDValue();
7058}
7059
7060// check if an VEXT instruction can handle the shuffle mask when the
7061// vector sources of the shuffle are the same.
7062static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
7063 unsigned NumElts = VT.getVectorNumElements();
7064
7065 // Assume that the first shuffle index is not UNDEF. Fail if it is.
7066 if (M[0] < 0)
7067 return false;
7068
7069 Imm = M[0];
7070
7071 // If this is a VEXT shuffle, the immediate value is the index of the first
7072 // element. The other shuffle indices must be the successive elements after
7073 // the first one.
7074 unsigned ExpectedElt = Imm;
7075 for (unsigned i = 1; i < NumElts; ++i) {
7076 // Increment the expected index. If it wraps around, just follow it
7077 // back to index zero and keep going.
7078 ++ExpectedElt;
7079 if (ExpectedElt == NumElts)
7080 ExpectedElt = 0;
7081
7082 if (M[i] < 0) continue; // ignore UNDEF indices
7083 if (ExpectedElt != static_cast<unsigned>(M[i]))
7084 return false;
7085 }
7086
7087 return true;
7088}
7089
7090static bool isVEXTMask(ArrayRef<int> M, EVT VT,
7091 bool &ReverseVEXT, unsigned &Imm) {
7092 unsigned NumElts = VT.getVectorNumElements();
7093 ReverseVEXT = false;
7094
7095 // Assume that the first shuffle index is not UNDEF. Fail if it is.
7096 if (M[0] < 0)
7097 return false;
7098
7099 Imm = M[0];
7100
7101 // If this is a VEXT shuffle, the immediate value is the index of the first
7102 // element. The other shuffle indices must be the successive elements after
7103 // the first one.
7104 unsigned ExpectedElt = Imm;
7105 for (unsigned i = 1; i < NumElts; ++i) {
7106 // Increment the expected index. If it wraps around, it may still be
7107 // a VEXT but the source vectors must be swapped.
7108 ExpectedElt += 1;
7109 if (ExpectedElt == NumElts * 2) {
7110 ExpectedElt = 0;
7111 ReverseVEXT = true;
7112 }
7113
7114 if (M[i] < 0) continue; // ignore UNDEF indices
7115 if (ExpectedElt != static_cast<unsigned>(M[i]))
7116 return false;
7117 }
7118
7119 // Adjust the index value if the source operands will be swapped.
7120 if (ReverseVEXT)
7121 Imm -= NumElts;
7122
7123 return true;
7124}
7125
7126static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
7127 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
7128 // range, then 0 is placed into the resulting vector. So pretty much any mask
7129 // of 8 elements can work here.
7130 return VT == MVT::v8i8 && M.size() == 8;
7131}
7132
7133static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
7134 unsigned Index) {
7135 if (Mask.size() == Elements * 2)
31
Assuming the condition is true
32
Taking true branch
7136 return Index / Elements;
33
Division by zero
7137 return Mask[Index] == 0 ? 0 : 1;
7138}
7139
7140// Checks whether the shuffle mask represents a vector transpose (VTRN) by
7141// checking that pairs of elements in the shuffle mask represent the same index
7142// in each vector, incrementing the expected index by 2 at each step.
7143// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
7144// v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
7145// v2={e,f,g,h}
7146// WhichResult gives the offset for each element in the mask based on which
7147// of the two results it belongs to.
7148//
7149// The transpose can be represented either as:
7150// result1 = shufflevector v1, v2, result1_shuffle_mask
7151// result2 = shufflevector v1, v2, result2_shuffle_mask
7152// where v1/v2 and the shuffle masks have the same number of elements
7153// (here WhichResult (see below) indicates which result is being checked)
7154//
7155// or as:
7156// results = shufflevector v1, v2, shuffle_mask
7157// where both results are returned in one vector and the shuffle mask has twice
7158// as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
7159// want to check the low half and high half of the shuffle mask as if it were
7160// the other case
7161static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7162 unsigned EltSz = VT.getScalarSizeInBits();
7163 if (EltSz == 64)
11
Assuming 'EltSz' is not equal to 64
12
Taking false branch
7164 return false;
7165
7166 unsigned NumElts = VT.getVectorNumElements();
13
Calling 'EVT::getVectorNumElements'
20
Returning from 'EVT::getVectorNumElements'
21
'NumElts' initialized here
7167 if (M.size() != NumElts && M.size() != NumElts*2)
22
Assuming the condition is false
7168 return false;
7169
7170 // If the mask is twice as long as the input vector then we need to check the
7171 // upper and lower parts of the mask with a matching value for WhichResult
7172 // FIXME: A mask with only even values will be rejected in case the first
7173 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
7174 // M[0] is used to determine WhichResult
7175 for (unsigned i = 0; i < M.size(); i += NumElts) {
23
Assuming the condition is true
24
Loop condition is true. Entering loop body
27
Assuming the condition is true
28
Loop condition is true. Entering loop body
7176 WhichResult = SelectPairHalf(NumElts, M, i);
29
Passing the value 0 via 1st parameter 'Elements'
30
Calling 'SelectPairHalf'
7177 for (unsigned j = 0; j < NumElts; j += 2) {
25
Assuming 'j' is >= 'NumElts'
26
Loop condition is false. Execution continues on line 7175
7178 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7179 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
7180 return false;
7181 }
7182 }
7183
7184 if (M.size() == NumElts*2)
7185 WhichResult = 0;
7186
7187 return true;
7188}
7189
7190/// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
7191/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7192/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
7193static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7194 unsigned EltSz = VT.getScalarSizeInBits();
7195 if (EltSz == 64)
7196 return false;
7197
7198 unsigned NumElts = VT.getVectorNumElements();
7199 if (M.size() != NumElts && M.size() != NumElts*2)
7200 return false;
7201
7202 for (unsigned i = 0; i < M.size(); i += NumElts) {
7203 WhichResult = SelectPairHalf(NumElts, M, i);
7204 for (unsigned j = 0; j < NumElts; j += 2) {
7205 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7206 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
7207 return false;
7208 }
7209 }
7210
7211 if (M.size() == NumElts*2)
7212 WhichResult = 0;
7213
7214 return true;
7215}
7216
7217// Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
7218// that the mask elements are either all even and in steps of size 2 or all odd
7219// and in steps of size 2.
7220// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
7221// v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
7222// v2={e,f,g,h}
7223// Requires similar checks to that of isVTRNMask with
7224// respect the how results are returned.
7225static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7226 unsigned EltSz = VT.getScalarSizeInBits();
7227 if (EltSz == 64)
7228 return false;
7229
7230 unsigned NumElts = VT.getVectorNumElements();
7231 if (M.size() != NumElts && M.size() != NumElts*2)
7232 return false;
7233
7234 for (unsigned i = 0; i < M.size(); i += NumElts) {
7235 WhichResult = SelectPairHalf(NumElts, M, i);
7236 for (unsigned j = 0; j < NumElts; ++j) {
7237 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
7238 return false;
7239 }
7240 }
7241
7242 if (M.size() == NumElts*2)
7243 WhichResult = 0;
7244
7245 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7246 if (VT.is64BitVector() && EltSz == 32)
7247 return false;
7248
7249 return true;
7250}
7251
7252/// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
7253/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7254/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
7255static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7256 unsigned EltSz = VT.getScalarSizeInBits();
7257 if (EltSz == 64)
7258 return false;
7259
7260 unsigned NumElts = VT.getVectorNumElements();
7261 if (M.size() != NumElts && M.size() != NumElts*2)
7262 return false;
7263
7264 unsigned Half = NumElts / 2;
7265 for (unsigned i = 0; i < M.size(); i += NumElts) {
7266 WhichResult = SelectPairHalf(NumElts, M, i);
7267 for (unsigned j = 0; j < NumElts; j += Half) {
7268 unsigned Idx = WhichResult;
7269 for (unsigned k = 0; k < Half; ++k) {
7270 int MIdx = M[i + j + k];
7271 if (MIdx >= 0 && (unsigned) MIdx != Idx)
7272 return false;
7273 Idx += 2;
7274 }
7275 }
7276 }
7277
7278 if (M.size() == NumElts*2)
7279 WhichResult = 0;
7280
7281 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7282 if (VT.is64BitVector() && EltSz == 32)
7283 return false;
7284
7285 return true;
7286}
7287
7288// Checks whether the shuffle mask represents a vector zip (VZIP) by checking
7289// that pairs of elements of the shufflemask represent the same index in each
7290// vector incrementing sequentially through the vectors.
7291// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
7292// v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
7293// v2={e,f,g,h}
7294// Requires similar checks to that of isVTRNMask with respect the how results
7295// are returned.
7296static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7297 unsigned EltSz = VT.getScalarSizeInBits();
7298 if (EltSz == 64)
7299 return false;
7300
7301 unsigned NumElts = VT.getVectorNumElements();
7302 if (M.size() != NumElts && M.size() != NumElts*2)
7303 return false;
7304
7305 for (unsigned i = 0; i < M.size(); i += NumElts) {
7306 WhichResult = SelectPairHalf(NumElts, M, i);
7307 unsigned Idx = WhichResult * NumElts / 2;
7308 for (unsigned j = 0; j < NumElts; j += 2) {
7309 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7310 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
7311 return false;
7312 Idx += 1;
7313 }
7314 }
7315
7316 if (M.size() == NumElts*2)
7317 WhichResult = 0;
7318
7319 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7320 if (VT.is64BitVector() && EltSz == 32)
7321 return false;
7322
7323 return true;
7324}
7325
7326/// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
7327/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7328/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
7329static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7330 unsigned EltSz = VT.getScalarSizeInBits();
7331 if (EltSz == 64)
7332 return false;
7333
7334 unsigned NumElts = VT.getVectorNumElements();
7335 if (M.size() != NumElts && M.size() != NumElts*2)
7336 return false;
7337
7338 for (unsigned i = 0; i < M.size(); i += NumElts) {
7339 WhichResult = SelectPairHalf(NumElts, M, i);
7340 unsigned Idx = WhichResult * NumElts / 2;
7341 for (unsigned j = 0; j < NumElts; j += 2) {
7342 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7343 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
7344 return false;
7345 Idx += 1;
7346 }
7347 }
7348
7349 if (M.size() == NumElts*2)
7350 WhichResult = 0;
7351
7352 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7353 if (VT.is64BitVector() && EltSz == 32)
7354 return false;
7355
7356 return true;
7357}
7358
7359/// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
7360/// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
7361static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
7362 unsigned &WhichResult,
7363 bool &isV_UNDEF) {
7364 isV_UNDEF = false;
7365 if (isVTRNMask(ShuffleMask, VT, WhichResult))
10
Calling 'isVTRNMask'
7366 return ARMISD::VTRN;
7367 if (isVUZPMask(ShuffleMask, VT, WhichResult))
7368 return ARMISD::VUZP;
7369 if (isVZIPMask(ShuffleMask, VT, WhichResult))
7370 return ARMISD::VZIP;
7371
7372 isV_UNDEF = true;
7373 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
7374 return ARMISD::VTRN;
7375 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7376 return ARMISD::VUZP;
7377 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7378 return ARMISD::VZIP;
7379
7380 return 0;
7381}
7382
7383/// \return true if this is a reverse operation on an vector.
7384static bool isReverseMask(ArrayRef<int> M, EVT VT) {
7385 unsigned NumElts = VT.getVectorNumElements();
7386 // Make sure the mask has the right size.
7387 if (NumElts != M.size())
7388 return false;
7389
7390 // Look for <15, ..., 3, -1, 1, 0>.
7391 for (unsigned i = 0; i != NumElts; ++i)
7392 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
7393 return false;
7394
7395 return true;
7396}
7397
7398static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top, bool SingleSource) {
7399 unsigned NumElts = VT.getVectorNumElements();
7400 // Make sure the mask has the right size.
7401 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7402 return false;
7403
7404 // If Top
7405 // Look for <0, N, 2, N+2, 4, N+4, ..>.
7406 // This inserts Input2 into Input1
7407 // else if not Top
7408 // Look for <0, N+1, 2, N+3, 4, N+5, ..>
7409 // This inserts Input1 into Input2
7410 unsigned Offset = Top ? 0 : 1;
7411 unsigned N = SingleSource ? 0 : NumElts;
7412 for (unsigned i = 0; i < NumElts; i += 2) {
7413 if (M[i] >= 0 && M[i] != (int)i)
7414 return false;
7415 if (M[i + 1] >= 0 && M[i + 1] != (int)(N + i + Offset))
7416 return false;
7417 }
7418
7419 return true;
7420}
7421
7422static bool isVMOVNTruncMask(ArrayRef<int> M, EVT ToVT, bool rev) {
7423 unsigned NumElts = ToVT.getVectorNumElements();
7424 if (NumElts != M.size())
7425 return false;
7426
7427 // Test if the Trunc can be convertable to a VMOVN with this shuffle. We are
7428 // looking for patterns of:
7429 // !rev: 0 N/2 1 N/2+1 2 N/2+2 ...
7430 // rev: N/2 0 N/2+1 1 N/2+2 2 ...
7431
7432 unsigned Off0 = rev ? NumElts / 2 : 0;
7433 unsigned Off1 = rev ? 0 : NumElts / 2;
7434 for (unsigned i = 0; i < NumElts; i += 2) {
7435 if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2))
7436 return false;
7437 if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2))
7438 return false;
7439 }
7440
7441 return true;
7442}
7443
7444// Reconstruct an MVE VCVT from a BuildVector of scalar fptrunc, all extracted
7445// from a pair of inputs. For example:
7446// BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7447// FP_ROUND(EXTRACT_ELT(Y, 0),
7448// FP_ROUND(EXTRACT_ELT(X, 1),
7449// FP_ROUND(EXTRACT_ELT(Y, 1), ...)
7450static SDValue LowerBuildVectorOfFPTrunc(SDValue BV, SelectionDAG &DAG,
7451 const ARMSubtarget *ST) {
7452 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!")(static_cast <bool> (BV.getOpcode() == ISD::BUILD_VECTOR
&& "Unknown opcode!") ? void (0) : __assert_fail ("BV.getOpcode() == ISD::BUILD_VECTOR && \"Unknown opcode!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 7452, __extension__ __PRETTY_FUNCTION__))
;
7453 if (!ST->hasMVEFloatOps())
7454 return SDValue();
7455
7456 SDLoc dl(BV);
7457 EVT VT = BV.getValueType();
7458 if (VT != MVT::v8f16)
7459 return SDValue();
7460
7461 // We are looking for a buildvector of fptrunc elements, where all the
7462 // elements are interleavingly extracted from two sources. Check the first two
7463 // items are valid enough and extract some info from them (they are checked
7464 // properly in the loop below).
7465 if (BV.getOperand(0).getOpcode() != ISD::FP_ROUND ||
7466 BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7467 BV.getOperand(0).getOperand(0).getConstantOperandVal(1) != 0)
7468 return SDValue();
7469 if (BV.getOperand(1).getOpcode() != ISD::FP_ROUND ||
7470 BV.getOperand(1).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7471 BV.getOperand(1).getOperand(0).getConstantOperandVal(1) != 0)
7472 return SDValue();
7473 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7474 SDValue Op1 = BV.getOperand(1).getOperand(0).getOperand(0);
7475 if (Op0.getValueType() != MVT::v4f32 || Op1.getValueType() != MVT::v4f32)
7476 return SDValue();
7477
7478 // Check all the values in the BuildVector line up with our expectations.
7479 for (unsigned i = 1; i < 4; i++) {
7480 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7481 return Trunc.getOpcode() == ISD::FP_ROUND &&
7482 Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7483 Trunc.getOperand(0).getOperand(0) == Op &&
7484 Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7485 };
7486 if (!Check(BV.getOperand(i * 2 + 0), Op0, i))
7487 return SDValue();
7488 if (!Check(BV.getOperand(i * 2 + 1), Op1, i))
7489 return SDValue();
7490 }
7491
7492 SDValue N1 = DAG.getNode(ARMISD::VCVTN, dl, VT, DAG.getUNDEF(VT), Op0,
7493 DAG.getConstant(0, dl, MVT::i32));
7494 return DAG.getNode(ARMISD::VCVTN, dl, VT, N1, Op1,
7495 DAG.getConstant(1, dl, MVT::i32));
7496}
7497
7498// Reconstruct an MVE VCVT from a BuildVector of scalar fpext, all extracted
7499// from a single input on alternating lanes. For example:
7500// BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7501// FP_ROUND(EXTRACT_ELT(X, 2),
7502// FP_ROUND(EXTRACT_ELT(X, 4), ...)
7503static SDValue LowerBuildVectorOfFPExt(SDValue BV, SelectionDAG &DAG,
7504 const ARMSubtarget *ST) {
7505 assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!")(static_cast <bool> (BV.getOpcode() == ISD::BUILD_VECTOR
&& "Unknown opcode!") ? void (0) : __assert_fail ("BV.getOpcode() == ISD::BUILD_VECTOR && \"Unknown opcode!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 7505, __extension__ __PRETTY_FUNCTION__))
;
7506 if (!ST->hasMVEFloatOps())
7507 return SDValue();
7508
7509 SDLoc dl(BV);
7510 EVT VT = BV.getValueType();
7511 if (VT != MVT::v4f32)
7512 return SDValue();
7513
7514 // We are looking for a buildvector of fptext elements, where all the
7515 // elements are alternating lanes from a single source. For example <0,2,4,6>
7516 // or <1,3,5,7>. Check the first two items are valid enough and extract some
7517 // info from them (they are checked properly in the loop below).
7518 if (BV.getOperand(0).getOpcode() != ISD::FP_EXTEND ||
7519 BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7520 return SDValue();
7521 SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7522 int Offset = BV.getOperand(0).getOperand(0).getConstantOperandVal(1);
7523 if (Op0.getValueType() != MVT::v8f16 || (Offset != 0 && Offset != 1))
7524 return SDValue();
7525
7526 // Check all the values in the BuildVector line up with our expectations.
7527 for (unsigned i = 1; i < 4; i++) {
7528 auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7529 return Trunc.getOpcode() == ISD::FP_EXTEND &&
7530 Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7531 Trunc.getOperand(0).getOperand(0) == Op &&
7532 Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7533 };
7534 if (!Check(BV.getOperand(i), Op0, 2 * i + Offset))
7535 return SDValue();
7536 }
7537
7538 return DAG.getNode(ARMISD::VCVTL, dl, VT, Op0,
7539 DAG.getConstant(Offset, dl, MVT::i32));
7540}
7541
7542// If N is an integer constant that can be moved into a register in one
7543// instruction, return an SDValue of such a constant (will become a MOV
7544// instruction). Otherwise return null.
7545static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
7546 const ARMSubtarget *ST, const SDLoc &dl) {
7547 uint64_t Val;
7548 if (!isa<ConstantSDNode>(N))
7549 return SDValue();
7550 Val = cast<ConstantSDNode>(N)->getZExtValue();
7551
7552 if (ST->isThumb1Only()) {
7553 if (Val <= 255 || ~Val <= 255)
7554 return DAG.getConstant(Val, dl, MVT::i32);
7555 } else {
7556 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
7557 return DAG.getConstant(Val, dl, MVT::i32);
7558 }
7559 return SDValue();
7560}
7561
7562static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
7563 const ARMSubtarget *ST) {
7564 SDLoc dl(Op);
7565 EVT VT = Op.getValueType();
7566
7567 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!")(static_cast <bool> (ST->hasMVEIntegerOps() &&
"LowerBUILD_VECTOR_i1 called without MVE!") ? void (0) : __assert_fail
("ST->hasMVEIntegerOps() && \"LowerBUILD_VECTOR_i1 called without MVE!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 7567, __extension__ __PRETTY_FUNCTION__))
;
7568
7569 unsigned NumElts = VT.getVectorNumElements();
7570 unsigned BoolMask;
7571 unsigned BitsPerBool;
7572 if (NumElts == 4) {
7573 BitsPerBool = 4;
7574 BoolMask = 0xf;
7575 } else if (NumElts == 8) {
7576 BitsPerBool = 2;
7577 BoolMask = 0x3;
7578 } else if (NumElts == 16) {
7579 BitsPerBool = 1;
7580 BoolMask = 0x1;
7581 } else
7582 return SDValue();
7583
7584 // If this is a single value copied into all lanes (a splat), we can just sign
7585 // extend that single value
7586 SDValue FirstOp = Op.getOperand(0);
7587 if (!isa<ConstantSDNode>(FirstOp) &&
7588 std::all_of(std::next(Op->op_begin()), Op->op_end(),
7589 [&FirstOp](SDUse &U) {
7590 return U.get().isUndef() || U.get() == FirstOp;
7591 })) {
7592 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp,
7593 DAG.getValueType(MVT::i1));
7594 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext);
7595 }
7596
7597 // First create base with bits set where known
7598 unsigned Bits32 = 0;
7599 for (unsigned i = 0; i < NumElts; ++i) {
7600 SDValue V = Op.getOperand(i);
7601 if (!isa<ConstantSDNode>(V) && !V.isUndef())
7602 continue;
7603 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue();
7604 if (BitSet)
7605 Bits32 |= BoolMask << (i * BitsPerBool);
7606 }
7607
7608 // Add in unknown nodes
7609 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
7610 DAG.getConstant(Bits32, dl, MVT::i32));
7611 for (unsigned i = 0; i < NumElts; ++i) {
7612 SDValue V = Op.getOperand(i);
7613 if (isa<ConstantSDNode>(V) || V.isUndef())
7614 continue;
7615 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
7616 DAG.getConstant(i, dl, MVT::i32));
7617 }
7618
7619 return Base;
7620}
7621
7622static SDValue LowerBUILD_VECTORToVIDUP(SDValue Op, SelectionDAG &DAG,
7623 const ARMSubtarget *ST) {
7624 if (!ST->hasMVEIntegerOps())
7625 return SDValue();
7626
7627 // We are looking for a buildvector where each element is Op[0] + i*N
7628 EVT VT = Op.getValueType();
7629 SDValue Op0 = Op.getOperand(0);
7630 unsigned NumElts = VT.getVectorNumElements();
7631
7632 // Get the increment value from operand 1
7633 SDValue Op1 = Op.getOperand(1);
7634 if (Op1.getOpcode() != ISD::ADD || Op1.getOperand(0) != Op0 ||
7635 !isa<ConstantSDNode>(Op1.getOperand(1)))
7636 return SDValue();
7637 unsigned N = Op1.getConstantOperandVal(1);
7638 if (N != 1 && N != 2 && N != 4 && N != 8)
7639 return SDValue();
7640
7641 // Check that each other operand matches
7642 for (unsigned I = 2; I < NumElts; I++) {
7643 SDValue OpI = Op.getOperand(I);
7644 if (OpI.getOpcode() != ISD::ADD || OpI.getOperand(0) != Op0 ||
7645 !isa<ConstantSDNode>(OpI.getOperand(1)) ||
7646 OpI.getConstantOperandVal(1) != I * N)
7647 return SDValue();
7648 }
7649
7650 SDLoc DL(Op);
7651 return DAG.getNode(ARMISD::VIDUP, DL, DAG.getVTList(VT, MVT::i32), Op0,
7652 DAG.getConstant(N, DL, MVT::i32));
7653}
7654
7655// If this is a case we can't handle, return null and let the default
7656// expansion code take care of it.
7657SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
7658 const ARMSubtarget *ST) const {
7659 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7660 SDLoc dl(Op);
7661 EVT VT = Op.getValueType();
7662
7663 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7664 return LowerBUILD_VECTOR_i1(Op, DAG, ST);
7665
7666 if (SDValue R = LowerBUILD_VECTORToVIDUP(Op, DAG, ST))
7667 return R;
7668
7669 APInt SplatBits, SplatUndef;
7670 unsigned SplatBitSize;
7671 bool HasAnyUndefs;
7672 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7673 if (SplatUndef.isAllOnesValue())
7674 return DAG.getUNDEF(VT);
7675
7676 if ((ST->hasNEON() && SplatBitSize <= 64) ||
7677 (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) {
7678 // Check if an immediate VMOV works.
7679 EVT VmovVT;
7680 SDValue Val =
7681 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
7682 SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm);
7683
7684 if (Val.getNode()) {
7685 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
7686 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7687 }
7688
7689 // Try an immediate VMVN.
7690 uint64_t NegatedImm = (~SplatBits).getZExtValue();
7691 Val = isVMOVModifiedImm(
7692 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT,
7693 VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7694 if (Val.getNode()) {
7695 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7696 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7697 }
7698
7699 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7700 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7701 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7702 if (ImmVal != -1) {
7703 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7704 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7705 }
7706 }
7707
7708 // If we are under MVE, generate a VDUP(constant), bitcast to the original
7709 // type.
7710 if (ST->hasMVEIntegerOps() &&
7711 (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32)) {
7712 EVT DupVT = SplatBitSize == 32 ? MVT::v4i32
7713 : SplatBitSize == 16 ? MVT::v8i16
7714 : MVT::v16i8;
7715 SDValue Const = DAG.getConstant(SplatBits.getZExtValue(), dl, MVT::i32);
7716 SDValue VDup = DAG.getNode(ARMISD::VDUP, dl, DupVT, Const);
7717 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, VDup);
7718 }
7719 }
7720 }
7721
7722 // Scan through the operands to see if only one value is used.
7723 //
7724 // As an optimisation, even if more than one value is used it may be more
7725 // profitable to splat with one value then change some lanes.
7726 //
7727 // Heuristically we decide to do this if the vector has a "dominant" value,
7728 // defined as splatted to more than half of the lanes.
7729 unsigned NumElts = VT.getVectorNumElements();
7730 bool isOnlyLowElement = true;
7731 bool usesOnlyOneValue = true;
7732 bool hasDominantValue = false;
7733 bool isConstant = true;
7734
7735 // Map of the number of times a particular SDValue appears in the
7736 // element list.
7737 DenseMap<SDValue, unsigned> ValueCounts;
7738 SDValue Value;
7739 for (unsigned i = 0; i < NumElts; ++i) {
7740 SDValue V = Op.getOperand(i);
7741 if (V.isUndef())
7742 continue;
7743 if (i > 0)
7744 isOnlyLowElement = false;
7745 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7746 isConstant = false;
7747
7748 ValueCounts.insert(std::make_pair(V, 0));
7749 unsigned &Count = ValueCounts[V];
7750
7751 // Is this value dominant? (takes up more than half of the lanes)
7752 if (++Count > (NumElts / 2)) {
7753 hasDominantValue = true;
7754 Value = V;
7755 }
7756 }
7757 if (ValueCounts.size() != 1)
7758 usesOnlyOneValue = false;
7759 if (!Value.getNode() && !ValueCounts.empty())
7760 Value = ValueCounts.begin()->first;
7761
7762 if (ValueCounts.empty())
7763 return DAG.getUNDEF(VT);
7764
7765 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7766 // Keep going if we are hitting this case.
7767 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
7768 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7769
7770 unsigned EltSize = VT.getScalarSizeInBits();
7771
7772 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
7773 // i32 and try again.
7774 if (hasDominantValue && EltSize <= 32) {
7775 if (!isConstant) {
7776 SDValue N;
7777
7778 // If we are VDUPing a value that comes directly from a vector, that will
7779 // cause an unnecessary move to and from a GPR, where instead we could
7780 // just use VDUPLANE. We can only do this if the lane being extracted
7781 // is at a constant index, as the VDUP from lane instructions only have
7782 // constant-index forms.
7783 ConstantSDNode *constIndex;
7784 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7785 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7786 // We need to create a new undef vector to use for the VDUPLANE if the
7787 // size of the vector from which we get the value is different than the
7788 // size of the vector that we need to create. We will insert the element
7789 // such that the register coalescer will remove unnecessary copies.
7790 if (VT != Value->getOperand(0).getValueType()) {
7791 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7792 VT.getVectorNumElements();
7793 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7794 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7795 Value, DAG.getConstant(index, dl, MVT::i32)),
7796 DAG.getConstant(index, dl, MVT::i32));
7797 } else
7798 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7799 Value->getOperand(0), Value->getOperand(1));
7800 } else
7801 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7802
7803 if (!usesOnlyOneValue) {
7804 // The dominant value was splatted as 'N', but we now have to insert
7805 // all differing elements.
7806 for (unsigned I = 0; I < NumElts; ++I) {
7807 if (Op.getOperand(I) == Value)
7808 continue;
7809 SmallVector<SDValue, 3> Ops;
7810 Ops.push_back(N);
7811 Ops.push_back(Op.getOperand(I));
7812 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7813 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7814 }
7815 }
7816 return N;
7817 }
7818 if (VT.getVectorElementType().isFloatingPoint()) {
7819 SmallVector<SDValue, 8> Ops;
7820 MVT FVT = VT.getVectorElementType().getSimpleVT();
7821 assert(FVT == MVT::f32 || FVT == MVT::f16)(static_cast <bool> (FVT == MVT::f32 || FVT == MVT::f16
) ? void (0) : __assert_fail ("FVT == MVT::f32 || FVT == MVT::f16"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 7821, __extension__ __PRETTY_FUNCTION__))
;
7822 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7823 for (unsigned i = 0; i < NumElts; ++i)
7824 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7825 Op.getOperand(i)));
7826 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7827 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7828 Val = LowerBUILD_VECTOR(Val, DAG, ST);
7829 if (Val.getNode())
7830 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7831 }
7832 if (usesOnlyOneValue) {
7833 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7834 if (isConstant && Val.getNode())
7835 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7836 }
7837 }
7838
7839 // If all elements are constants and the case above didn't get hit, fall back
7840 // to the default expansion, which will generate a load from the constant
7841 // pool.
7842 if (isConstant)
7843 return SDValue();
7844
7845 // Reconstruct the BUILDVECTOR to one of the legal shuffles (such as vext and
7846 // vmovn). Empirical tests suggest this is rarely worth it for vectors of
7847 // length <= 2.
7848 if (NumElts >= 4)
7849 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
7850 return shuffle;
7851
7852 // Attempt to turn a buildvector of scalar fptrunc's or fpext's back into
7853 // VCVT's
7854 if (SDValue VCVT = LowerBuildVectorOfFPTrunc(Op, DAG, Subtarget))
7855 return VCVT;
7856 if (SDValue VCVT = LowerBuildVectorOfFPExt(Op, DAG, Subtarget))
7857 return VCVT;
7858
7859 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7860 // If we haven't found an efficient lowering, try splitting a 128-bit vector
7861 // into two 64-bit vectors; we might discover a better way to lower it.
7862 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7863 EVT ExtVT = VT.getVectorElementType();
7864 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7865 SDValue Lower =
7866 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
7867 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7868 Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7869 SDValue Upper = DAG.getBuildVector(
7870 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
7871 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7872 Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7873 if (Lower && Upper)
7874 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7875 }
7876
7877 // Vectors with 32- or 64-bit elements can be built by directly assigning
7878 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
7879 // will be legalized.
7880 if (EltSize >= 32) {
7881 // Do the expansion with floating-point types, since that is what the VFP
7882 // registers are defined to use, and since i64 is not legal.
7883 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7884 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7885 SmallVector<SDValue, 8> Ops;
7886 for (unsigned i = 0; i < NumElts; ++i)
7887 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7888 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7889 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7890 }
7891
7892 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7893 // know the default expansion would otherwise fall back on something even
7894 // worse. For a vector with one or two non-undef values, that's
7895 // scalar_to_vector for the elements followed by a shuffle (provided the
7896 // shuffle is valid for the target) and materialization element by element
7897 // on the stack followed by a load for everything else.
7898 if (!isConstant && !usesOnlyOneValue) {
7899 SDValue Vec = DAG.getUNDEF(VT);
7900 for (unsigned i = 0 ; i < NumElts; ++i) {
7901 SDValue V = Op.getOperand(i);
7902 if (V.isUndef())
7903 continue;
7904 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7905 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7906 }
7907 return Vec;
7908 }
7909
7910 return SDValue();
7911}
7912
7913// Gather data to see if the operation can be modelled as a
7914// shuffle in combination with VEXTs.
7915SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7916 SelectionDAG &DAG) const {
7917 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!")(static_cast <bool> (Op.getOpcode() == ISD::BUILD_VECTOR
&& "Unknown opcode!") ? void (0) : __assert_fail ("Op.getOpcode() == ISD::BUILD_VECTOR && \"Unknown opcode!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 7917, __extension__ __PRETTY_FUNCTION__))
;
7918 SDLoc dl(Op);
7919 EVT VT = Op.getValueType();
7920 unsigned NumElts = VT.getVectorNumElements();
7921
7922 struct ShuffleSourceInfo {
7923 SDValue Vec;
7924 unsigned MinElt = std::numeric_limits<unsigned>::max();
7925 unsigned MaxElt = 0;
7926
7927 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7928 // be compatible with the shuffle we intend to construct. As a result
7929 // ShuffleVec will be some sliding window into the original Vec.
7930 SDValue ShuffleVec;
7931
7932 // Code should guarantee that element i in Vec starts at element "WindowBase
7933 // + i * WindowScale in ShuffleVec".
7934 int WindowBase = 0;
7935 int WindowScale = 1;
7936
7937 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7938
7939 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7940 };
7941
7942 // First gather all vectors used as an immediate source for this BUILD_VECTOR
7943 // node.
7944 SmallVector<ShuffleSourceInfo, 2> Sources;
7945 for (unsigned i = 0; i < NumElts; ++i) {
7946 SDValue V = Op.getOperand(i);
7947 if (V.isUndef())
7948 continue;
7949 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7950 // A shuffle can only come from building a vector from various
7951 // elements of other vectors.
7952 return SDValue();
7953 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7954 // Furthermore, shuffles require a constant mask, whereas extractelts
7955 // accept variable indices.
7956 return SDValue();
7957 }
7958
7959 // Add this element source to the list if it's not already there.
7960 SDValue SourceVec = V.getOperand(0);
7961 auto Source = llvm::find(Sources, SourceVec);
7962 if (Source == Sources.end())
7963 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7964
7965 // Update the minimum and maximum lane number seen.
7966 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7967 Source->MinElt = std::min(Source->MinElt, EltNo);
7968 Source->MaxElt = std::max(Source->MaxElt, EltNo);
7969 }
7970
7971 // Currently only do something sane when at most two source vectors
7972 // are involved.
7973 if (Sources.size() > 2)
7974 return SDValue();
7975
7976 // Find out the smallest element size among result and two sources, and use
7977 // it as element size to build the shuffle_vector.
7978 EVT SmallestEltTy = VT.getVectorElementType();
7979 for (auto &Source : Sources) {
7980 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7981 if (SrcEltTy.bitsLT(SmallestEltTy))
7982 SmallestEltTy = SrcEltTy;
7983 }
7984 unsigned ResMultiplier =
7985 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7986 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7987 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7988
7989 // If the source vector is too wide or too narrow, we may nevertheless be able
7990 // to construct a compatible shuffle either by concatenating it with UNDEF or
7991 // extracting a suitable range of elements.
7992 for (auto &Src : Sources) {
7993 EVT SrcVT = Src.ShuffleVec.getValueType();
7994
7995 uint64_t SrcVTSize = SrcVT.getFixedSizeInBits();
7996 uint64_t VTSize = VT.getFixedSizeInBits();
7997 if (SrcVTSize == VTSize)
7998 continue;
7999
8000 // This stage of the search produces a source with the same element type as
8001 // the original, but with a total width matching the BUILD_VECTOR output.
8002 EVT EltVT = SrcVT.getVectorElementType();
8003 unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
8004 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
8005
8006 if (SrcVTSize < VTSize) {
8007 if (2 * SrcVTSize != VTSize)
8008 return SDValue();
8009 // We can pad out the smaller vector for free, so if it's part of a
8010 // shuffle...
8011 Src.ShuffleVec =
8012 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
8013 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
8014 continue;
8015 }
8016
8017 if (SrcVTSize != 2 * VTSize)
8018 return SDValue();
8019
8020 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
8021 // Span too large for a VEXT to cope
8022 return SDValue();
8023 }
8024
8025 if (Src.MinElt >= NumSrcElts) {
8026 // The extraction can just take the second half
8027 Src.ShuffleVec =
8028 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8029 DAG.getConstant(NumSrcElts, dl, MVT::i32));
8030 Src.WindowBase = -NumSrcElts;
8031 } else if (Src.MaxElt < NumSrcElts) {
8032 // The extraction can just take the first half
8033 Src.ShuffleVec =
8034 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8035 DAG.getConstant(0, dl, MVT::i32));
8036 } else {
8037 // An actual VEXT is needed
8038 SDValue VEXTSrc1 =
8039 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8040 DAG.getConstant(0, dl, MVT::i32));
8041 SDValue VEXTSrc2 =
8042 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8043 DAG.getConstant(NumSrcElts, dl, MVT::i32));
8044
8045 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
8046 VEXTSrc2,
8047 DAG.getConstant(Src.MinElt, dl, MVT::i32));
8048 Src.WindowBase = -Src.MinElt;
8049 }
8050 }
8051
8052 // Another possible incompatibility occurs from the vector element types. We
8053 // can fix this by bitcasting the source vectors to the same type we intend
8054 // for the shuffle.
8055 for (auto &Src : Sources) {
8056 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
8057 if (SrcEltTy == SmallestEltTy)
8058 continue;
8059 assert(ShuffleVT.getVectorElementType() == SmallestEltTy)(static_cast <bool> (ShuffleVT.getVectorElementType() ==
SmallestEltTy) ? void (0) : __assert_fail ("ShuffleVT.getVectorElementType() == SmallestEltTy"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8059, __extension__ __PRETTY_FUNCTION__))
;
8060 Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec);
8061 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
8062 Src.WindowBase *= Src.WindowScale;
8063 }
8064
8065 // Final sanity check before we try to actually produce a shuffle.
8066 LLVM_DEBUG(for (auto Srcdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("arm-isel")) { for (auto Src : Sources) (static_cast <bool
> (Src.ShuffleVec.getValueType() == ShuffleVT) ? void (0) :
__assert_fail ("Src.ShuffleVec.getValueType() == ShuffleVT",
"/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8068, __extension__ __PRETTY_FUNCTION__));; } } while (false
)
8067 : Sources)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("arm-isel")) { for (auto Src : Sources) (static_cast <bool
> (Src.ShuffleVec.getValueType() == ShuffleVT) ? void (0) :
__assert_fail ("Src.ShuffleVec.getValueType() == ShuffleVT",
"/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8068, __extension__ __PRETTY_FUNCTION__));; } } while (false
)
8068 assert(Src.ShuffleVec.getValueType() == ShuffleVT);)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("arm-isel")) { for (auto Src : Sources) (static_cast <bool
> (Src.ShuffleVec.getValueType() == ShuffleVT) ? void (0) :
__assert_fail ("Src.ShuffleVec.getValueType() == ShuffleVT",
"/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8068, __extension__ __PRETTY_FUNCTION__));; } } while (false
)
;
8069
8070 // The stars all align, our next step is to produce the mask for the shuffle.
8071 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
8072 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
8073 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
8074 SDValue Entry = Op.getOperand(i);
8075 if (Entry.isUndef())
8076 continue;
8077
8078 auto Src = llvm::find(Sources, Entry.getOperand(0));
8079 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
8080
8081 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
8082 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
8083 // segment.
8084 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
8085 int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(),
8086 VT.getScalarSizeInBits());
8087 int LanesDefined = BitsDefined / BitsPerShuffleLane;
8088
8089 // This source is expected to fill ResMultiplier lanes of the final shuffle,
8090 // starting at the appropriate offset.
8091 int *LaneMask = &Mask[i * ResMultiplier];
8092
8093 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
8094 ExtractBase += NumElts * (Src - Sources.begin());
8095 for (int j = 0; j < LanesDefined; ++j)
8096 LaneMask[j] = ExtractBase + j;
8097 }
8098
8099
8100 // We can't handle more than two sources. This should have already
8101 // been checked before this point.
8102 assert(Sources.size() <= 2 && "Too many sources!")(static_cast <bool> (Sources.size() <= 2 && "Too many sources!"
) ? void (0) : __assert_fail ("Sources.size() <= 2 && \"Too many sources!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8102, __extension__ __PRETTY_FUNCTION__))
;
8103
8104 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
8105 for (unsigned i = 0; i < Sources.size(); ++i)
8106 ShuffleOps[i] = Sources[i].ShuffleVec;
8107
8108 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
8109 ShuffleOps[1], Mask, DAG);
8110 if (!Shuffle)
8111 return SDValue();
8112 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle);
8113}
8114
8115enum ShuffleOpCodes {
8116 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8117 OP_VREV,
8118 OP_VDUP0,
8119 OP_VDUP1,
8120 OP_VDUP2,
8121 OP_VDUP3,
8122 OP_VEXT1,
8123 OP_VEXT2,
8124 OP_VEXT3,
8125 OP_VUZPL, // VUZP, left result
8126 OP_VUZPR, // VUZP, right result
8127 OP_VZIPL, // VZIP, left result
8128 OP_VZIPR, // VZIP, right result
8129 OP_VTRNL, // VTRN, left result
8130 OP_VTRNR // VTRN, right result
8131};
8132
8133static bool isLegalMVEShuffleOp(unsigned PFEntry) {
8134 unsigned OpNum = (PFEntry >> 26) & 0x0F;
8135 switch (OpNum) {
8136 case OP_COPY:
8137 case OP_VREV:
8138 case OP_VDUP0:
8139 case OP_VDUP1:
8140 case OP_VDUP2:
8141 case OP_VDUP3:
8142 return true;
8143 }
8144 return false;
8145}
8146
8147/// isShuffleMaskLegal - Targets can use this to indicate that they only
8148/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8149/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8150/// are assumed to be legal.
8151bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
8152 if (VT.getVectorNumElements() == 4 &&
1
Assuming the condition is false
8153 (VT.is128BitVector() || VT.is64BitVector())) {
8154 unsigned PFIndexes[4];
8155 for (unsigned i = 0; i != 4; ++i) {
8156 if (M[i] < 0)
8157 PFIndexes[i] = 8;
8158 else
8159 PFIndexes[i] = M[i];
8160 }
8161
8162 // Compute the index in the perfect shuffle table.
8163 unsigned PFTableIndex =
8164 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8165 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8166 unsigned Cost = (PFEntry >> 30);
8167
8168 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
8169 return true;
8170 }
8171
8172 bool ReverseVEXT, isV_UNDEF;
8173 unsigned Imm, WhichResult;
8174
8175 unsigned EltSize = VT.getScalarSizeInBits();
8176 if (EltSize >= 32 ||
2
Assuming 'EltSize' is < 32
8177 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
3
Assuming the condition is false
8178 ShuffleVectorInst::isIdentityMask(M) ||
4
Assuming the condition is false
8179 isVREVMask(M, VT, 64) ||
5
Assuming the condition is false
8180 isVREVMask(M, VT, 32) ||
6
Assuming the condition is false
8181 isVREVMask(M, VT, 16))
7
Assuming the condition is false
8182 return true;
8183 else if (Subtarget->hasNEON() &&
8
Assuming the condition is true
8184 (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
8185 isVTBLMask(M, VT) ||
8186 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
9
Calling 'isNEONTwoResultShuffleMask'
8187 return true;
8188 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) &&
8189 isReverseMask(M, VT))
8190 return true;
8191 else if (Subtarget->hasMVEIntegerOps() &&
8192 (isVMOVNMask(M, VT, true, false) ||
8193 isVMOVNMask(M, VT, false, false) || isVMOVNMask(M, VT, true, true)))
8194 return true;
8195 else
8196 return false;
8197}
8198
8199/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8200/// the specified operations to build the shuffle.
8201static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8202 SDValue RHS, SelectionDAG &DAG,
8203 const SDLoc &dl) {
8204 unsigned OpNum = (PFEntry >> 26) & 0x0F;
8205 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8206 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
8207
8208 if (OpNum == OP_COPY) {
8209 if (LHSID == (1*9+2)*9+3) return LHS;
8210 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!")(static_cast <bool> (LHSID == ((4*9+5)*9+6)*9+7 &&
"Illegal OP_COPY!") ? void (0) : __assert_fail ("LHSID == ((4*9+5)*9+6)*9+7 && \"Illegal OP_COPY!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8210, __extension__ __PRETTY_FUNCTION__))
;
8211 return RHS;
8212 }
8213
8214 SDValue OpLHS, OpRHS;
8215 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8216 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8217 EVT VT = OpLHS.getValueType();
8218
8219 switch (OpNum) {
8220 default: llvm_unreachable("Unknown shuffle opcode!")::llvm::llvm_unreachable_internal("Unknown shuffle opcode!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8220)
;
8221 case OP_VREV:
8222 // VREV divides the vector in half and swaps within the half.
8223 if (VT.getVectorElementType() == MVT::i32 ||
8224 VT.getVectorElementType() == MVT::f32)
8225 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
8226 // vrev <4 x i16> -> VREV32
8227 if (VT.getVectorElementType() == MVT::i16 ||
8228 VT.getVectorElementType() == MVT::f16)
8229 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
8230 // vrev <4 x i8> -> VREV16
8231 assert(VT.getVectorElementType() == MVT::i8)(static_cast <bool> (VT.getVectorElementType() == MVT::
i8) ? void (0) : __assert_fail ("VT.getVectorElementType() == MVT::i8"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8231, __extension__ __PRETTY_FUNCTION__))
;
8232 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
8233 case OP_VDUP0:
8234 case OP_VDUP1:
8235 case OP_VDUP2:
8236 case OP_VDUP3:
8237 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
8238 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
8239 case OP_VEXT1:
8240 case OP_VEXT2:
8241 case OP_VEXT3:
8242 return DAG.getNode(ARMISD::VEXT, dl, VT,
8243 OpLHS, OpRHS,
8244 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
8245 case OP_VUZPL:
8246 case OP_VUZPR:
8247 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
8248 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
8249 case OP_VZIPL:
8250 case OP_VZIPR:
8251 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
8252 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
8253 case OP_VTRNL:
8254 case OP_VTRNR:
8255 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
8256 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
8257 }
8258}
8259
8260static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
8261 ArrayRef<int> ShuffleMask,
8262 SelectionDAG &DAG) {
8263 // Check to see if we can use the VTBL instruction.
8264 SDValue V1 = Op.getOperand(0);
8265 SDValue V2 = Op.getOperand(1);
8266 SDLoc DL(Op);
8267
8268 SmallVector<SDValue, 8> VTBLMask;
8269 for (ArrayRef<int>::iterator
8270 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
8271 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
8272
8273 if (V2.getNode()->isUndef())
8274 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
8275 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8276
8277 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
8278 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8279}
8280
8281static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
8282 SelectionDAG &DAG) {
8283 SDLoc DL(Op);
8284 SDValue OpLHS = Op.getOperand(0);
8285 EVT VT = OpLHS.getValueType();
8286
8287 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&(static_cast <bool> ((VT == MVT::v8i16 || VT == MVT::v16i8
) && "Expect an v8i16/v16i8 type") ? void (0) : __assert_fail
("(VT == MVT::v8i16 || VT == MVT::v16i8) && \"Expect an v8i16/v16i8 type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8288, __extension__ __PRETTY_FUNCTION__))
8288 "Expect an v8i16/v16i8 type")(static_cast <bool> ((VT == MVT::v8i16 || VT == MVT::v16i8
) && "Expect an v8i16/v16i8 type") ? void (0) : __assert_fail
("(VT == MVT::v8i16 || VT == MVT::v16i8) && \"Expect an v8i16/v16i8 type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8288, __extension__ __PRETTY_FUNCTION__))
;
8289 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
8290 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
8291 // extract the first 8 bytes into the top double word and the last 8 bytes
8292 // into the bottom double word. The v8i16 case is similar.
8293 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
8294 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
8295 DAG.getConstant(ExtractNum, DL, MVT::i32));
8296}
8297
8298static EVT getVectorTyFromPredicateVector(EVT VT) {
8299 switch (VT.getSimpleVT().SimpleTy) {
8300 case MVT::v4i1:
8301 return MVT::v4i32;
8302 case MVT::v8i1:
8303 return MVT::v8i16;
8304 case MVT::v16i1:
8305 return MVT::v16i8;
8306 default:
8307 llvm_unreachable("Unexpected vector predicate type")::llvm::llvm_unreachable_internal("Unexpected vector predicate type"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8307)
;
8308 }
8309}
8310
8311static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
8312 SelectionDAG &DAG) {
8313 // Converting from boolean predicates to integers involves creating a vector
8314 // of all ones or all zeroes and selecting the lanes based upon the real
8315 // predicate.
8316 SDValue AllOnes =
8317 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
8318 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
8319
8320 SDValue AllZeroes =
8321 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
8322 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
8323
8324 // Get full vector type from predicate type
8325 EVT NewVT = getVectorTyFromPredicateVector(VT);
8326
8327 SDValue RecastV1;
8328 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
8329 // this to a v16i1. This cannot be done with an ordinary bitcast because the
8330 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
8331 // since we know in hardware the sizes are really the same.
8332 if (VT != MVT::v16i1)
8333 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
8334 else
8335 RecastV1 = Pred;
8336
8337 // Select either all ones or zeroes depending upon the real predicate bits.
8338 SDValue PredAsVector =
8339 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
8340
8341 // Recast our new predicate-as-integer v16i8 vector into something
8342 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
8343 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
8344}
8345
8346static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
8347 const ARMSubtarget *ST) {
8348 EVT VT = Op.getValueType();
8349 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8350 ArrayRef<int> ShuffleMask = SVN->getMask();
8351
8352 assert(ST->hasMVEIntegerOps() &&(static_cast <bool> (ST->hasMVEIntegerOps() &&
"No support for vector shuffle of boolean predicates") ? void
(0) : __assert_fail ("ST->hasMVEIntegerOps() && \"No support for vector shuffle of boolean predicates\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8353, __extension__ __PRETTY_FUNCTION__))
8353 "No support for vector shuffle of boolean predicates")(static_cast <bool> (ST->hasMVEIntegerOps() &&
"No support for vector shuffle of boolean predicates") ? void
(0) : __assert_fail ("ST->hasMVEIntegerOps() && \"No support for vector shuffle of boolean predicates\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8353, __extension__ __PRETTY_FUNCTION__))
;
8354
8355 SDValue V1 = Op.getOperand(0);
8356 SDLoc dl(Op);
8357 if (isReverseMask(ShuffleMask, VT)) {
8358 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
8359 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
8360 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
8361 DAG.getConstant(16, dl, MVT::i32));
8362 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
8363 }
8364
8365 // Until we can come up with optimised cases for every single vector
8366 // shuffle in existence we have chosen the least painful strategy. This is
8367 // to essentially promote the boolean predicate to a 8-bit integer, where
8368 // each predicate represents a byte. Then we fall back on a normal integer
8369 // vector shuffle and convert the result back into a predicate vector. In
8370 // many cases the generated code might be even better than scalar code
8371 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
8372 // fields in a register into 8 other arbitrary 2-bit fields!
8373 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG);
8374 EVT NewVT = PredAsVector.getValueType();
8375
8376 // Do the shuffle!
8377 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector,
8378 DAG.getUNDEF(NewVT), ShuffleMask);
8379
8380 // Now return the result of comparing the shuffled vector with zero,
8381 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8382 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
8383 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8384}
8385
8386static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op,
8387 ArrayRef<int> ShuffleMask,
8388 SelectionDAG &DAG) {
8389 // Attempt to lower the vector shuffle using as many whole register movs as
8390 // possible. This is useful for types smaller than 32bits, which would
8391 // often otherwise become a series for grp movs.
8392 SDLoc dl(Op);
8393 EVT VT = Op.getValueType();
8394 if (VT.getScalarSizeInBits() >= 32)
8395 return SDValue();
8396
8397 assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&(static_cast <bool> ((VT == MVT::v8i16 || VT == MVT::v8f16
|| VT == MVT::v16i8) && "Unexpected vector type") ? void
(0) : __assert_fail ("(VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8398, __extension__ __PRETTY_FUNCTION__))
8398 "Unexpected vector type")(static_cast <bool> ((VT == MVT::v8i16 || VT == MVT::v8f16
|| VT == MVT::v16i8) && "Unexpected vector type") ? void
(0) : __assert_fail ("(VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8398, __extension__ __PRETTY_FUNCTION__))
;
8399 int NumElts = VT.getVectorNumElements();
8400 int QuarterSize = NumElts / 4;
8401 // The four final parts of the vector, as i32's
8402 SDValue Parts[4];
8403
8404 // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not
8405 // <u,u,u,u>), returning the vmov lane index
8406 auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) {
8407 // Detect which mov lane this would be from the first non-undef element.
8408 int MovIdx = -1;
8409 for (int i = 0; i < Length; i++) {
8410 if (ShuffleMask[Start + i] >= 0) {
8411 if (ShuffleMask[Start + i] % Length != i)
8412 return -1;
8413 MovIdx = ShuffleMask[Start + i] / Length;
8414 break;
8415 }
8416 }
8417 // If all items are undef, leave this for other combines
8418 if (MovIdx == -1)
8419 return -1;
8420 // Check the remaining values are the correct part of the same mov
8421 for (int i = 1; i < Length; i++) {
8422 if (ShuffleMask[Start + i] >= 0 &&
8423 (ShuffleMask[Start + i] / Length != MovIdx ||
8424 ShuffleMask[Start + i] % Length != i))
8425 return -1;
8426 }
8427 return MovIdx;
8428 };
8429
8430 for (int Part = 0; Part < 4; ++Part) {
8431 // Does this part look like a mov
8432 int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize);
8433 if (Elt != -1) {
8434 SDValue Input = Op->getOperand(0);
8435 if (Elt >= 4) {
8436 Input = Op->getOperand(1);
8437 Elt -= 4;
8438 }
8439 SDValue BitCast = DAG.getBitcast(MVT::v4f32, Input);
8440 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, BitCast,
8441 DAG.getConstant(Elt, dl, MVT::i32));
8442 }
8443 }
8444
8445 // Nothing interesting found, just return
8446 if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3])
8447 return SDValue();
8448
8449 // The other parts need to be built with the old shuffle vector, cast to a
8450 // v4i32 and extract_vector_elts
8451 if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) {
8452 SmallVector<int, 16> NewShuffleMask;
8453 for (int Part = 0; Part < 4; ++Part)
8454 for (int i = 0; i < QuarterSize; i++)
8455 NewShuffleMask.push_back(
8456 Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]);
8457 SDValue NewShuffle = DAG.getVectorShuffle(
8458 VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask);
8459 SDValue BitCast = DAG.getBitcast(MVT::v4f32, NewShuffle);
8460
8461 for (int Part = 0; Part < 4; ++Part)
8462 if (!Parts[Part])
8463 Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32,
8464 BitCast, DAG.getConstant(Part, dl, MVT::i32));
8465 }
8466 // Build a vector out of the various parts and bitcast it back to the original
8467 // type.
8468 SDValue NewVec = DAG.getNode(ARMISD::BUILD_VECTOR, dl, MVT::v4f32, Parts);
8469 return DAG.getBitcast(VT, NewVec);
8470}
8471
8472static SDValue LowerVECTOR_SHUFFLEUsingOneOff(SDValue Op,
8473 ArrayRef<int> ShuffleMask,
8474 SelectionDAG &DAG) {
8475 SDValue V1 = Op.getOperand(0);
8476 SDValue V2 = Op.getOperand(1);
8477 EVT VT = Op.getValueType();
8478 unsigned NumElts = VT.getVectorNumElements();
8479
8480 // An One-Off Identity mask is one that is mostly an identity mask from as
8481 // single source but contains a single element out-of-place, either from a
8482 // different vector or from another position in the same vector. As opposed to
8483 // lowering this via a ARMISD::BUILD_VECTOR we can generate an extract/insert
8484 // pair directly.
8485 auto isOneOffIdentityMask = [](ArrayRef<int> Mask, EVT VT, int BaseOffset,
8486 int &OffElement) {
8487 OffElement = -1;
8488 int NonUndef = 0;
8489 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
8490 if (Mask[i] == -1)
8491 continue;
8492 NonUndef++;
8493 if (Mask[i] != i + BaseOffset) {
8494 if (OffElement == -1)
8495 OffElement = i;
8496 else
8497 return false;
8498 }
8499 }
8500 return NonUndef > 2 && OffElement != -1;
8501 };
8502 int OffElement;
8503 SDValue VInput;
8504 if (isOneOffIdentityMask(ShuffleMask, VT, 0, OffElement))
8505 VInput = V1;
8506 else if (isOneOffIdentityMask(ShuffleMask, VT, NumElts, OffElement))
8507 VInput = V2;
8508 else
8509 return SDValue();
8510
8511 SDLoc dl(Op);
8512 EVT SVT = VT.getScalarType() == MVT::i8 || VT.getScalarType() == MVT::i16
8513 ? MVT::i32
8514 : VT.getScalarType();
8515 SDValue Elt = DAG.getNode(
8516 ISD::EXTRACT_VECTOR_ELT, dl, SVT,
8517 ShuffleMask[OffElement] < (int)NumElts ? V1 : V2,
8518 DAG.getVectorIdxConstant(ShuffleMask[OffElement] % NumElts, dl));
8519 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, VInput, Elt,
8520 DAG.getVectorIdxConstant(OffElement % NumElts, dl));
8521}
8522
8523static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
8524 const ARMSubtarget *ST) {
8525 SDValue V1 = Op.getOperand(0);
8526 SDValue V2 = Op.getOperand(1);
8527 SDLoc dl(Op);
8528 EVT VT = Op.getValueType();
8529 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8530 unsigned EltSize = VT.getScalarSizeInBits();
8531
8532 if (ST->hasMVEIntegerOps() && EltSize == 1)
8533 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
8534
8535 // Convert shuffles that are directly supported on NEON to target-specific
8536 // DAG nodes, instead of keeping them as shuffles and matching them again
8537 // during code selection. This is more efficient and avoids the possibility
8538 // of inconsistencies between legalization and selection.
8539 // FIXME: floating-point vectors should be canonicalized to integer vectors
8540 // of the same time so that they get CSEd properly.
8541 ArrayRef<int> ShuffleMask = SVN->getMask();
8542
8543 if (EltSize <= 32) {
8544 if (SVN->isSplat()) {
8545 int Lane = SVN->getSplatIndex();
8546 // If this is undef splat, generate it via "just" vdup, if possible.
8547 if (Lane == -1) Lane = 0;
8548
8549 // Test if V1 is a SCALAR_TO_VECTOR.
8550 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8551 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8552 }
8553 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
8554 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
8555 // reaches it).
8556 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
8557 !isa<ConstantSDNode>(V1.getOperand(0))) {
8558 bool IsScalarToVector = true;
8559 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
8560 if (!V1.getOperand(i).isUndef()) {
8561 IsScalarToVector = false;
8562 break;
8563 }
8564 if (IsScalarToVector)
8565 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8566 }
8567 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
8568 DAG.getConstant(Lane, dl, MVT::i32));
8569 }
8570
8571 bool ReverseVEXT = false;
8572 unsigned Imm = 0;
8573 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
8574 if (ReverseVEXT)
8575 std::swap(V1, V2);
8576 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
8577 DAG.getConstant(Imm, dl, MVT::i32));
8578 }
8579
8580 if (isVREVMask(ShuffleMask, VT, 64))
8581 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
8582 if (isVREVMask(ShuffleMask, VT, 32))
8583 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
8584 if (isVREVMask(ShuffleMask, VT, 16))
8585 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
8586
8587 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
8588 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
8589 DAG.getConstant(Imm, dl, MVT::i32));
8590 }
8591
8592 // Check for Neon shuffles that modify both input vectors in place.
8593 // If both results are used, i.e., if there are two shuffles with the same
8594 // source operands and with masks corresponding to both results of one of
8595 // these operations, DAG memoization will ensure that a single node is
8596 // used for both shuffles.
8597 unsigned WhichResult = 0;
8598 bool isV_UNDEF = false;
8599 if (ST->hasNEON()) {
8600 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8601 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
8602 if (isV_UNDEF)
8603 V2 = V1;
8604 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
8605 .getValue(WhichResult);
8606 }
8607 }
8608 if (ST->hasMVEIntegerOps()) {
8609 if (isVMOVNMask(ShuffleMask, VT, false, false))
8610 return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1,
8611 DAG.getConstant(0, dl, MVT::i32));
8612 if (isVMOVNMask(ShuffleMask, VT, true, false))
8613 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2,
8614 DAG.getConstant(1, dl, MVT::i32));
8615 if (isVMOVNMask(ShuffleMask, VT, true, true))
8616 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V1,
8617 DAG.getConstant(1, dl, MVT::i32));
8618 }
8619
8620 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
8621 // shuffles that produce a result larger than their operands with:
8622 // shuffle(concat(v1, undef), concat(v2, undef))
8623 // ->
8624 // shuffle(concat(v1, v2), undef)
8625 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
8626 //
8627 // This is useful in the general case, but there are special cases where
8628 // native shuffles produce larger results: the two-result ops.
8629 //
8630 // Look through the concat when lowering them:
8631 // shuffle(concat(v1, v2), undef)
8632 // ->
8633 // concat(VZIP(v1, v2):0, :1)
8634 //
8635 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
8636 SDValue SubV1 = V1->getOperand(0);
8637 SDValue SubV2 = V1->getOperand(1);
8638 EVT SubVT = SubV1.getValueType();
8639
8640 // We expect these to have been canonicalized to -1.
8641 assert(llvm::all_of(ShuffleMask, [&](int i) {(static_cast <bool> (llvm::all_of(ShuffleMask, [&](
int i) { return i < (int)VT.getVectorNumElements(); }) &&
"Unexpected shuffle index into UNDEF operand!") ? void (0) :
__assert_fail ("llvm::all_of(ShuffleMask, [&](int i) { return i < (int)VT.getVectorNumElements(); }) && \"Unexpected shuffle index into UNDEF operand!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8643, __extension__ __PRETTY_FUNCTION__))
8642 return i < (int)VT.getVectorNumElements();(static_cast <bool> (llvm::all_of(ShuffleMask, [&](
int i) { return i < (int)VT.getVectorNumElements(); }) &&
"Unexpected shuffle index into UNDEF operand!") ? void (0) :
__assert_fail ("llvm::all_of(ShuffleMask, [&](int i) { return i < (int)VT.getVectorNumElements(); }) && \"Unexpected shuffle index into UNDEF operand!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8643, __extension__ __PRETTY_FUNCTION__))
8643 }) && "Unexpected shuffle index into UNDEF operand!")(static_cast <bool> (llvm::all_of(ShuffleMask, [&](
int i) { return i < (int)VT.getVectorNumElements(); }) &&
"Unexpected shuffle index into UNDEF operand!") ? void (0) :
__assert_fail ("llvm::all_of(ShuffleMask, [&](int i) { return i < (int)VT.getVectorNumElements(); }) && \"Unexpected shuffle index into UNDEF operand!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8643, __extension__ __PRETTY_FUNCTION__))
;
8644
8645 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8646 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
8647 if (isV_UNDEF)
8648 SubV2 = SubV1;
8649 assert((WhichResult == 0) &&(static_cast <bool> ((WhichResult == 0) && "In-place shuffle of concat can only have one result!"
) ? void (0) : __assert_fail ("(WhichResult == 0) && \"In-place shuffle of concat can only have one result!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8650, __extension__ __PRETTY_FUNCTION__))
8650 "In-place shuffle of concat can only have one result!")(static_cast <bool> ((WhichResult == 0) && "In-place shuffle of concat can only have one result!"
) ? void (0) : __assert_fail ("(WhichResult == 0) && \"In-place shuffle of concat can only have one result!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8650, __extension__ __PRETTY_FUNCTION__))
;
8651 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
8652 SubV1, SubV2);
8653 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
8654 Res.getValue(1));
8655 }
8656 }
8657 }
8658
8659 if (ST->hasMVEIntegerOps() && EltSize <= 32)
8660 if (SDValue V = LowerVECTOR_SHUFFLEUsingOneOff(Op, ShuffleMask, DAG))
8661 return V;
8662
8663 // If the shuffle is not directly supported and it has 4 elements, use
8664 // the PerfectShuffle-generated table to synthesize it from other shuffles.
8665 unsigned NumElts = VT.getVectorNumElements();
8666 if (NumElts == 4) {
8667 unsigned PFIndexes[4];
8668 for (unsigned i = 0; i != 4; ++i) {
8669 if (ShuffleMask[i] < 0)
8670 PFIndexes[i] = 8;
8671 else
8672 PFIndexes[i] = ShuffleMask[i];
8673 }
8674
8675 // Compute the index in the perfect shuffle table.
8676 unsigned PFTableIndex =
8677 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8678 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8679 unsigned Cost = (PFEntry >> 30);
8680
8681 if (Cost <= 4) {
8682 if (ST->hasNEON())
8683 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8684 else if (isLegalMVEShuffleOp(PFEntry)) {
8685 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8686 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
8687 unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
8688 unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
8689 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
8690 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8691 }
8692 }
8693 }
8694
8695 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
8696 if (EltSize >= 32) {
8697 // Do the expansion with floating-point types, since that is what the VFP
8698 // registers are defined to use, and since i64 is not legal.
8699 EVT EltVT = EVT::getFloatingPointVT(EltSize);
8700 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
8701 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
8702 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
8703 SmallVector<SDValue, 8> Ops;
8704 for (unsigned i = 0; i < NumElts; ++i) {
8705 if (ShuffleMask[i] < 0)
8706 Ops.push_back(DAG.getUNDEF(EltVT));
8707 else
8708 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8709 ShuffleMask[i] < (int)NumElts ? V1 : V2,
8710 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
8711 dl, MVT::i32)));
8712 }
8713 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
8714 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8715 }
8716
8717 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
8718 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
8719
8720 if (ST->hasNEON() && VT == MVT::v8i8)
8721 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
8722 return NewOp;
8723
8724 if (ST->hasMVEIntegerOps())
8725 if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG))
8726 return NewOp;
8727
8728 return SDValue();
8729}
8730
8731static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8732 const ARMSubtarget *ST) {
8733 EVT VecVT = Op.getOperand(0).getValueType();
8734 SDLoc dl(Op);
8735
8736 assert(ST->hasMVEIntegerOps() &&(static_cast <bool> (ST->hasMVEIntegerOps() &&
"LowerINSERT_VECTOR_ELT_i1 called without MVE!") ? void (0) :
__assert_fail ("ST->hasMVEIntegerOps() && \"LowerINSERT_VECTOR_ELT_i1 called without MVE!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8737, __extension__ __PRETTY_FUNCTION__))
8737 "LowerINSERT_VECTOR_ELT_i1 called without MVE!")(static_cast <bool> (ST->hasMVEIntegerOps() &&
"LowerINSERT_VECTOR_ELT_i1 called without MVE!") ? void (0) :
__assert_fail ("ST->hasMVEIntegerOps() && \"LowerINSERT_VECTOR_ELT_i1 called without MVE!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8737, __extension__ __PRETTY_FUNCTION__))
;
8738
8739 SDValue Conv =
8740 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8741 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8742 unsigned LaneWidth =
8743 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8744 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
8745 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
8746 Op.getOperand(1), DAG.getValueType(MVT::i1));
8747 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
8748 DAG.getConstant(~Mask, dl, MVT::i32));
8749 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
8750}
8751
8752SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8753 SelectionDAG &DAG) const {
8754 // INSERT_VECTOR_ELT is legal only for immediate indexes.
8755 SDValue Lane = Op.getOperand(2);
8756 if (!isa<ConstantSDNode>(Lane))
8757 return SDValue();
8758
8759 SDValue Elt = Op.getOperand(1);
8760 EVT EltVT = Elt.getValueType();
8761
8762 if (Subtarget->hasMVEIntegerOps() &&
8763 Op.getValueType().getScalarSizeInBits() == 1)
8764 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
8765
8766 if (getTypeAction(*DAG.getContext(), EltVT) ==
8767 TargetLowering::TypePromoteFloat) {
8768 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
8769 // but the type system will try to do that if we don't intervene.
8770 // Reinterpret any such vector-element insertion as one with the
8771 // corresponding integer types.
8772
8773 SDLoc dl(Op);
8774
8775 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
8776 assert(getTypeAction(*DAG.getContext(), IEltVT) !=(static_cast <bool> (getTypeAction(*DAG.getContext(), IEltVT
) != TargetLowering::TypePromoteFloat) ? void (0) : __assert_fail
("getTypeAction(*DAG.getContext(), IEltVT) != TargetLowering::TypePromoteFloat"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8777, __extension__ __PRETTY_FUNCTION__))
8777 TargetLowering::TypePromoteFloat)(static_cast <bool> (getTypeAction(*DAG.getContext(), IEltVT
) != TargetLowering::TypePromoteFloat) ? void (0) : __assert_fail
("getTypeAction(*DAG.getContext(), IEltVT) != TargetLowering::TypePromoteFloat"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8777, __extension__ __PRETTY_FUNCTION__))
;
8778
8779 SDValue VecIn = Op.getOperand(0);
8780 EVT VecVT = VecIn.getValueType();
8781 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
8782 VecVT.getVectorNumElements());
8783
8784 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
8785 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
8786 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
8787 IVecIn, IElt, Lane);
8788 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
8789 }
8790
8791 return Op;
8792}
8793
8794static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8795 const ARMSubtarget *ST) {
8796 EVT VecVT = Op.getOperand(0).getValueType();
8797 SDLoc dl(Op);
8798
8799 assert(ST->hasMVEIntegerOps() &&(static_cast <bool> (ST->hasMVEIntegerOps() &&
"LowerINSERT_VECTOR_ELT_i1 called without MVE!") ? void (0) :
__assert_fail ("ST->hasMVEIntegerOps() && \"LowerINSERT_VECTOR_ELT_i1 called without MVE!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8800, __extension__ __PRETTY_FUNCTION__))
8800 "LowerINSERT_VECTOR_ELT_i1 called without MVE!")(static_cast <bool> (ST->hasMVEIntegerOps() &&
"LowerINSERT_VECTOR_ELT_i1 called without MVE!") ? void (0) :
__assert_fail ("ST->hasMVEIntegerOps() && \"LowerINSERT_VECTOR_ELT_i1 called without MVE!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8800, __extension__ __PRETTY_FUNCTION__))
;
8801
8802 SDValue Conv =
8803 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8804 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8805 unsigned LaneWidth =
8806 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8807 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
8808 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
8809 return Shift;
8810}
8811
8812static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
8813 const ARMSubtarget *ST) {
8814 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
8815 SDValue Lane = Op.getOperand(1);
8816 if (!isa<ConstantSDNode>(Lane))
8817 return SDValue();
8818
8819 SDValue Vec = Op.getOperand(0);
8820 EVT VT = Vec.getValueType();
8821
8822 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8823 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
8824
8825 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
8826 SDLoc dl(Op);
8827 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
8828 }
8829
8830 return Op;
8831}
8832
8833static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
8834 const ARMSubtarget *ST) {
8835 SDLoc dl(Op);
8836 assert(Op.getValueType().getScalarSizeInBits() == 1 &&(static_cast <bool> (Op.getValueType().getScalarSizeInBits
() == 1 && "Unexpected custom CONCAT_VECTORS lowering"
) ? void (0) : __assert_fail ("Op.getValueType().getScalarSizeInBits() == 1 && \"Unexpected custom CONCAT_VECTORS lowering\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8837, __extension__ __PRETTY_FUNCTION__))
8837 "Unexpected custom CONCAT_VECTORS lowering")(static_cast <bool> (Op.getValueType().getScalarSizeInBits
() == 1 && "Unexpected custom CONCAT_VECTORS lowering"
) ? void (0) : __assert_fail ("Op.getValueType().getScalarSizeInBits() == 1 && \"Unexpected custom CONCAT_VECTORS lowering\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8837, __extension__ __PRETTY_FUNCTION__))
;
8838 assert(isPowerOf2_32(Op.getNumOperands()) &&(static_cast <bool> (isPowerOf2_32(Op.getNumOperands())
&& "Unexpected custom CONCAT_VECTORS lowering") ? void
(0) : __assert_fail ("isPowerOf2_32(Op.getNumOperands()) && \"Unexpected custom CONCAT_VECTORS lowering\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8839, __extension__ __PRETTY_FUNCTION__))
8839 "Unexpected custom CONCAT_VECTORS lowering")(static_cast <bool> (isPowerOf2_32(Op.getNumOperands())
&& "Unexpected custom CONCAT_VECTORS lowering") ? void
(0) : __assert_fail ("isPowerOf2_32(Op.getNumOperands()) && \"Unexpected custom CONCAT_VECTORS lowering\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8839, __extension__ __PRETTY_FUNCTION__))
;
8840 assert(ST->hasMVEIntegerOps() &&(static_cast <bool> (ST->hasMVEIntegerOps() &&
"CONCAT_VECTORS lowering only supported for MVE") ? void (0)
: __assert_fail ("ST->hasMVEIntegerOps() && \"CONCAT_VECTORS lowering only supported for MVE\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8841, __extension__ __PRETTY_FUNCTION__))
8841 "CONCAT_VECTORS lowering only supported for MVE")(static_cast <bool> (ST->hasMVEIntegerOps() &&
"CONCAT_VECTORS lowering only supported for MVE") ? void (0)
: __assert_fail ("ST->hasMVEIntegerOps() && \"CONCAT_VECTORS lowering only supported for MVE\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8841, __extension__ __PRETTY_FUNCTION__))
;
8842
8843 auto ConcatPair = [&](SDValue V1, SDValue V2) {
8844 EVT Op1VT = V1.getValueType();
8845 EVT Op2VT = V2.getValueType();
8846 assert(Op1VT == Op2VT && "Operand types don't match!")(static_cast <bool> (Op1VT == Op2VT && "Operand types don't match!"
) ? void (0) : __assert_fail ("Op1VT == Op2VT && \"Operand types don't match!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8846, __extension__ __PRETTY_FUNCTION__))
;
8847 EVT VT = Op1VT.getDoubleNumVectorElementsVT(*DAG.getContext());
8848
8849 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8850 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
8851
8852 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
8853 // promoted to v8i16, etc.
8854 MVT ElType =
8855 getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8856 unsigned NumElts = 2 * Op1VT.getVectorNumElements();
8857
8858 // Extract the vector elements from Op1 and Op2 one by one and truncate them
8859 // to be the right size for the destination. For example, if Op1 is v4i1
8860 // then the promoted vector is v4i32. The result of concatentation gives a
8861 // v8i1, which when promoted is v8i16. That means each i32 element from Op1
8862 // needs truncating to i16 and inserting in the result.
8863 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
8864 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
8865 auto ExtractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
8866 EVT NewVT = NewV.getValueType();
8867 EVT ConcatVT = ConVec.getValueType();
8868 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
8869 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
8870 DAG.getIntPtrConstant(i, dl));
8871 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
8872 DAG.getConstant(j, dl, MVT::i32));
8873 }
8874 return ConVec;
8875 };
8876 unsigned j = 0;
8877 ConVec = ExtractInto(NewV1, ConVec, j);
8878 ConVec = ExtractInto(NewV2, ConVec, j);
8879
8880 // Now return the result of comparing the subvector with zero,
8881 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8882 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8883 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8884 };
8885
8886 // Concat each pair of subvectors and pack into the lower half of the array.
8887 SmallVector<SDValue> ConcatOps(Op->op_begin(), Op->op_end());
8888 while (ConcatOps.size() > 1) {
8889 for (unsigned I = 0, E = ConcatOps.size(); I != E; I += 2) {
8890 SDValue V1 = ConcatOps[I];
8891 SDValue V2 = ConcatOps[I + 1];
8892 ConcatOps[I / 2] = ConcatPair(V1, V2);
8893 }
8894 ConcatOps.resize(ConcatOps.size() / 2);
8895 }
8896 return ConcatOps[0];
8897}
8898
8899static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
8900 const ARMSubtarget *ST) {
8901 EVT VT = Op->getValueType(0);
8902 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8903 return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8904
8905 // The only time a CONCAT_VECTORS operation can have legal types is when
8906 // two 64-bit vectors are concatenated to a 128-bit vector.
8907 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&(static_cast <bool> (Op.getValueType().is128BitVector()
&& Op.getNumOperands() == 2 && "unexpected CONCAT_VECTORS"
) ? void (0) : __assert_fail ("Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && \"unexpected CONCAT_VECTORS\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8908, __extension__ __PRETTY_FUNCTION__))
8908 "unexpected CONCAT_VECTORS")(static_cast <bool> (Op.getValueType().is128BitVector()
&& Op.getNumOperands() == 2 && "unexpected CONCAT_VECTORS"
) ? void (0) : __assert_fail ("Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && \"unexpected CONCAT_VECTORS\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8908, __extension__ __PRETTY_FUNCTION__))
;
8909 SDLoc dl(Op);
8910 SDValue Val = DAG.getUNDEF(MVT::v2f64);
8911 SDValue Op0 = Op.getOperand(0);
8912 SDValue Op1 = Op.getOperand(1);
8913 if (!Op0.isUndef())
8914 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8915 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
8916 DAG.getIntPtrConstant(0, dl));
8917 if (!Op1.isUndef())
8918 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8919 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
8920 DAG.getIntPtrConstant(1, dl));
8921 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
8922}
8923
8924static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
8925 const ARMSubtarget *ST) {
8926 SDValue V1 = Op.getOperand(0);
8927 SDValue V2 = Op.getOperand(1);
8928 SDLoc dl(Op);
8929 EVT VT = Op.getValueType();
8930 EVT Op1VT = V1.getValueType();
8931 unsigned NumElts = VT.getVectorNumElements();
8932 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue();
8933
8934 assert(VT.getScalarSizeInBits() == 1 &&(static_cast <bool> (VT.getScalarSizeInBits() == 1 &&
"Unexpected custom EXTRACT_SUBVECTOR lowering") ? void (0) :
__assert_fail ("VT.getScalarSizeInBits() == 1 && \"Unexpected custom EXTRACT_SUBVECTOR lowering\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8935, __extension__ __PRETTY_FUNCTION__))
8935 "Unexpected custom EXTRACT_SUBVECTOR lowering")(static_cast <bool> (VT.getScalarSizeInBits() == 1 &&
"Unexpected custom EXTRACT_SUBVECTOR lowering") ? void (0) :
__assert_fail ("VT.getScalarSizeInBits() == 1 && \"Unexpected custom EXTRACT_SUBVECTOR lowering\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8935, __extension__ __PRETTY_FUNCTION__))
;
8936 assert(ST->hasMVEIntegerOps() &&(static_cast <bool> (ST->hasMVEIntegerOps() &&
"EXTRACT_SUBVECTOR lowering only supported for MVE") ? void (
0) : __assert_fail ("ST->hasMVEIntegerOps() && \"EXTRACT_SUBVECTOR lowering only supported for MVE\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8937, __extension__ __PRETTY_FUNCTION__))
8937 "EXTRACT_SUBVECTOR lowering only supported for MVE")(static_cast <bool> (ST->hasMVEIntegerOps() &&
"EXTRACT_SUBVECTOR lowering only supported for MVE") ? void (
0) : __assert_fail ("ST->hasMVEIntegerOps() && \"EXTRACT_SUBVECTOR lowering only supported for MVE\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8937, __extension__ __PRETTY_FUNCTION__))
;
8938
8939 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8940
8941 // We now have Op1 promoted to a vector of integers, where v8i1 gets
8942 // promoted to v8i16, etc.
8943
8944 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8945
8946 EVT SubVT = MVT::getVectorVT(ElType, NumElts);
8947 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
8948 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
8949 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
8950 DAG.getIntPtrConstant(i, dl));
8951 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8952 DAG.getConstant(j, dl, MVT::i32));
8953 }
8954
8955 // Now return the result of comparing the subvector with zero,
8956 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8957 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
8958 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8959}
8960
8961// Turn a truncate into a predicate (an i1 vector) into icmp(and(x, 1), 0).
8962static SDValue LowerTruncatei1(SDNode *N, SelectionDAG &DAG,
8963 const ARMSubtarget *ST) {
8964 assert(ST->hasMVEIntegerOps() && "Expected MVE!")(static_cast <bool> (ST->hasMVEIntegerOps() &&
"Expected MVE!") ? void (0) : __assert_fail ("ST->hasMVEIntegerOps() && \"Expected MVE!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8964, __extension__ __PRETTY_FUNCTION__))
;
8965 EVT VT = N->getValueType(0);
8966 assert((VT == MVT::v16i1 || VT == MVT::v8i1 || VT == MVT::v4i1) &&(static_cast <bool> ((VT == MVT::v16i1 || VT == MVT::v8i1
|| VT == MVT::v4i1) && "Expected a vector i1 type!")
? void (0) : __assert_fail ("(VT == MVT::v16i1 || VT == MVT::v8i1 || VT == MVT::v4i1) && \"Expected a vector i1 type!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8967, __extension__ __PRETTY_FUNCTION__))
8967 "Expected a vector i1 type!")(static_cast <bool> ((VT == MVT::v16i1 || VT == MVT::v8i1
|| VT == MVT::v4i1) && "Expected a vector i1 type!")
? void (0) : __assert_fail ("(VT == MVT::v16i1 || VT == MVT::v8i1 || VT == MVT::v4i1) && \"Expected a vector i1 type!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 8967, __extension__ __PRETTY_FUNCTION__))
;
8968 SDValue Op = N->getOperand(0);
8969 EVT FromVT = Op.getValueType();
8970 SDLoc DL(N);
8971
8972 SDValue And =
8973 DAG.getNode(ISD::AND, DL, FromVT, Op, DAG.getConstant(1, DL, FromVT));
8974 return DAG.getNode(ISD::SETCC, DL, VT, And, DAG.getConstant(0, DL, FromVT),
8975 DAG.getCondCode(ISD::SETNE));
8976}
8977
8978static SDValue LowerTruncate(SDNode *N, SelectionDAG &DAG,
8979 const ARMSubtarget *Subtarget) {
8980 if (!Subtarget->hasMVEIntegerOps())
8981 return SDValue();
8982
8983 EVT ToVT = N->getValueType(0);
8984 if (ToVT.getScalarType() == MVT::i1)
8985 return LowerTruncatei1(N, DAG, Subtarget);
8986
8987 // MVE does not have a single instruction to perform the truncation of a v4i32
8988 // into the lower half of a v8i16, in the same way that a NEON vmovn would.
8989 // Most of the instructions in MVE follow the 'Beats' system, where moving
8990 // values from different lanes is usually something that the instructions
8991 // avoid.
8992 //
8993 // Instead it has top/bottom instructions such as VMOVLT/B and VMOVNT/B,
8994 // which take a the top/bottom half of a larger lane and extend it (or do the
8995 // opposite, truncating into the top/bottom lane from a larger lane). Note
8996 // that because of the way we widen lanes, a v4i16 is really a v4i32 using the
8997 // bottom 16bits from each vector lane. This works really well with T/B
8998 // instructions, but that doesn't extend to v8i32->v8i16 where the lanes need
8999 // to move order.
9000 //
9001 // But truncates and sext/zext are always going to be fairly common from llvm.
9002 // We have several options for how to deal with them:
9003 // - Wherever possible combine them into an instruction that makes them
9004 // "free". This includes loads/stores, which can perform the trunc as part
9005 // of the memory operation. Or certain shuffles that can be turned into
9006 // VMOVN/VMOVL.
9007 // - Lane Interleaving to transform blocks surrounded by ext/trunc. So
9008 // trunc(mul(sext(a), sext(b))) may become
9009 // VMOVNT(VMUL(VMOVLB(a), VMOVLB(b)), VMUL(VMOVLT(a), VMOVLT(b))). (Which in
9010 // this case can use VMULL). This is performed in the
9011 // MVELaneInterleavingPass.
9012 // - Otherwise we have an option. By default we would expand the
9013 // zext/sext/trunc into a series of lane extract/inserts going via GPR
9014 // registers. One for each vector lane in the vector. This can obviously be
9015 // very expensive.
9016 // - The other option is to use the fact that loads/store can extend/truncate
9017 // to turn a trunc into two truncating stack stores and a stack reload. This
9018 // becomes 3 back-to-back memory operations, but at least that is less than
9019 // all the insert/extracts.
9020 //
9021 // In order to do the last, we convert certain trunc's into MVETRUNC, which
9022 // are either optimized where they can be, or eventually lowered into stack
9023 // stores/loads. This prevents us from splitting a v8i16 trunc into two stores
9024 // two early, where other instructions would be better, and stops us from
9025 // having to reconstruct multiple buildvector shuffles into loads/stores.
9026 if (ToVT != MVT::v8i16 && ToVT != MVT::v16i8)
9027 return SDValue();
9028 EVT FromVT = N->getOperand(0).getValueType();
9029 if (FromVT != MVT::v8i32 && FromVT != MVT::v16i16)
9030 return SDValue();
9031
9032 SDValue Lo, Hi;
9033 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
9034 SDLoc DL(N);
9035 return DAG.getNode(ARMISD::MVETRUNC, DL, ToVT, Lo, Hi);
9036}
9037
9038static SDValue LowerVectorExtend(SDNode *N, SelectionDAG &DAG,
9039 const ARMSubtarget *Subtarget) {
9040 if (!Subtarget->hasMVEIntegerOps())
9041 return SDValue();
9042
9043 // See LowerTruncate above for an explanation of MVEEXT/MVETRUNC.
9044
9045 EVT ToVT = N->getValueType(0);
9046 if (ToVT != MVT::v16i32 && ToVT != MVT::v8i32 && ToVT != MVT::v16i16)
9047 return SDValue();
9048 SDValue Op = N->getOperand(0);
9049 EVT FromVT = Op.getValueType();
9050 if (FromVT != MVT::v8i16 && FromVT != MVT::v16i8)
9051 return SDValue();
9052
9053 SDLoc DL(N);
9054 EVT ExtVT = ToVT.getHalfNumVectorElementsVT(*DAG.getContext());
9055 if (ToVT.getScalarType() == MVT::i32 && FromVT.getScalarType() == MVT::i8)
9056 ExtVT = MVT::v8i16;
9057
9058 unsigned Opcode =
9059 N->getOpcode() == ISD::SIGN_EXTEND ? ARMISD::MVESEXT : ARMISD::MVEZEXT;
9060 SDValue Ext = DAG.getNode(Opcode, DL, DAG.getVTList(ExtVT, ExtVT), Op);
9061 SDValue Ext1 = Ext.getValue(1);
9062
9063 if (ToVT.getScalarType() == MVT::i32 && FromVT.getScalarType() == MVT::i8) {
9064 Ext = DAG.getNode(N->getOpcode(), DL, MVT::v8i32, Ext);
9065 Ext1 = DAG.getNode(N->getOpcode(), DL, MVT::v8i32, Ext1);
9066 }
9067
9068 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Ext, Ext1);
9069}
9070
9071/// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
9072/// element has been zero/sign-extended, depending on the isSigned parameter,
9073/// from an integer type half its size.
9074static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
9075 bool isSigned) {
9076 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
9077 EVT VT = N->getValueType(0);
9078 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
9079 SDNode *BVN = N->getOperand(0).getNode();
9080 if (BVN->getValueType(0) != MVT::v4i32 ||
9081 BVN->getOpcode() != ISD::BUILD_VECTOR)
9082 return false;
9083 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9084 unsigned HiElt = 1 - LoElt;
9085 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
9086 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
9087 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
9088 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
9089 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
9090 return false;
9091 if (isSigned) {
9092 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
9093 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
9094 return true;
9095 } else {
9096 if (Hi0->isNullValue() && Hi1->isNullValue())
9097 return true;
9098 }
9099 return false;
9100 }
9101
9102 if (N->getOpcode() != ISD::BUILD_VECTOR)
9103 return false;
9104
9105 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9106 SDNode *Elt = N->getOperand(i).getNode();
9107 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
9108 unsigned EltSize = VT.getScalarSizeInBits();
9109 unsigned HalfSize = EltSize / 2;
9110 if (isSigned) {
9111 if (!isIntN(HalfSize, C->getSExtValue()))
9112 return false;
9113 } else {
9114 if (!isUIntN(HalfSize, C->getZExtValue()))
9115 return false;
9116 }
9117 continue;
9118 }
9119 return false;
9120 }
9121
9122 return true;
9123}
9124
9125/// isSignExtended - Check if a node is a vector value that is sign-extended
9126/// or a constant BUILD_VECTOR with sign-extended elements.
9127static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
9128 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
9129 return true;
9130 if (isExtendedBUILD_VECTOR(N, DAG, true))
9131 return true;
9132 return false;
9133}
9134
9135/// isZeroExtended - Check if a node is a vector value that is zero-extended (or
9136/// any-extended) or a constant BUILD_VECTOR with zero-extended elements.
9137static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
9138 if (N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND ||
9139 ISD::isZEXTLoad(N))
9140 return true;
9141 if (isExtendedBUILD_VECTOR(N, DAG, false))
9142 return true;
9143 return false;
9144}
9145
9146static EVT getExtensionTo64Bits(const EVT &OrigVT) {
9147 if (OrigVT.getSizeInBits() >= 64)
9148 return OrigVT;
9149
9150 assert(OrigVT.isSimple() && "Expecting a simple value type")(static_cast <bool> (OrigVT.isSimple() && "Expecting a simple value type"
) ? void (0) : __assert_fail ("OrigVT.isSimple() && \"Expecting a simple value type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9150, __extension__ __PRETTY_FUNCTION__))
;
9151
9152 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
9153 switch (OrigSimpleTy) {
9154 default: llvm_unreachable("Unexpected Vector Type")::llvm::llvm_unreachable_internal("Unexpected Vector Type", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9154)
;
9155 case MVT::v2i8:
9156 case MVT::v2i16:
9157 return MVT::v2i32;
9158 case MVT::v4i8:
9159 return MVT::v4i16;
9160 }
9161}
9162
9163/// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
9164/// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
9165/// We insert the required extension here to get the vector to fill a D register.
9166static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
9167 const EVT &OrigTy,
9168 const EVT &ExtTy,
9169 unsigned ExtOpcode) {
9170 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
9171 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
9172 // 64-bits we need to insert a new extension so that it will be 64-bits.
9173 assert(ExtTy.is128BitVector() && "Unexpected extension size")(static_cast <bool> (ExtTy.is128BitVector() && "Unexpected extension size"
) ? void (0) : __assert_fail ("ExtTy.is128BitVector() && \"Unexpected extension size\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9173, __extension__ __PRETTY_FUNCTION__))
;
9174 if (OrigTy.getSizeInBits() >= 64)
9175 return N;
9176
9177 // Must extend size to at least 64 bits to be used as an operand for VMULL.
9178 EVT NewVT = getExtensionTo64Bits(OrigTy);
9179
9180 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
9181}
9182
9183/// SkipLoadExtensionForVMULL - return a load of the original vector size that
9184/// does not do any sign/zero extension. If the original vector is less
9185/// than 64 bits, an appropriate extension will be added after the load to
9186/// reach a total size of 64 bits. We have to add the extension separately
9187/// because ARM does not have a sign/zero extending load for vectors.
9188static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
9189 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
9190
9191 // The load already has the right type.
9192 if (ExtendedTy == LD->getMemoryVT())
9193 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
9194 LD->getBasePtr(), LD->getPointerInfo(),
9195 LD->getAlignment(), LD->getMemOperand()->getFlags());
9196
9197 // We need to create a zextload/sextload. We cannot just create a load
9198 // followed by a zext/zext node because LowerMUL is also run during normal
9199 // operation legalization where we can't create illegal types.
9200 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
9201 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
9202 LD->getMemoryVT(), LD->getAlignment(),
9203 LD->getMemOperand()->getFlags());
9204}
9205
9206/// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
9207/// ANY_EXTEND, extending load, or BUILD_VECTOR with extended elements, return
9208/// the unextended value. The unextended vector should be 64 bits so that it can
9209/// be used as an operand to a VMULL instruction. If the original vector size
9210/// before extension is less than 64 bits we add a an extension to resize
9211/// the vector to 64 bits.
9212static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
9213 if (N->getOpcode() == ISD::SIGN_EXTEND ||
9214 N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND)
9215 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
9216 N->getOperand(0)->getValueType(0),
9217 N->getValueType(0),
9218 N->getOpcode());
9219
9220 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9221 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&(static_cast <bool> ((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad
(LD)) && "Expected extending load") ? void (0) : __assert_fail
("(ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && \"Expected extending load\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9222, __extension__ __PRETTY_FUNCTION__))
9222 "Expected extending load")(static_cast <bool> ((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad
(LD)) && "Expected extending load") ? void (0) : __assert_fail
("(ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && \"Expected extending load\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9222, __extension__ __PRETTY_FUNCTION__))
;
9223
9224 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
9225 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
9226 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9227 SDValue extLoad =
9228 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
9229 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
9230
9231 return newLoad;
9232 }
9233
9234 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
9235 // have been legalized as a BITCAST from v4i32.
9236 if (N->getOpcode() == ISD::BITCAST) {
9237 SDNode *BVN = N->getOperand(0).getNode();
9238 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&(static_cast <bool> (BVN->getOpcode() == ISD::BUILD_VECTOR
&& BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"
) ? void (0) : __assert_fail ("BVN->getOpcode() == ISD::BUILD_VECTOR && BVN->getValueType(0) == MVT::v4i32 && \"expected v4i32 BUILD_VECTOR\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9239, __extension__ __PRETTY_FUNCTION__))
9239 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR")(static_cast <bool> (BVN->getOpcode() == ISD::BUILD_VECTOR
&& BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"
) ? void (0) : __assert_fail ("BVN->getOpcode() == ISD::BUILD_VECTOR && BVN->getValueType(0) == MVT::v4i32 && \"expected v4i32 BUILD_VECTOR\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9239, __extension__ __PRETTY_FUNCTION__))
;
9240 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9241 return DAG.getBuildVector(
9242 MVT::v2i32, SDLoc(N),
9243 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
9244 }
9245 // Construct a new BUILD_VECTOR with elements truncated to half the size.
9246 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR")(static_cast <bool> (N->getOpcode() == ISD::BUILD_VECTOR
&& "expected BUILD_VECTOR") ? void (0) : __assert_fail
("N->getOpcode() == ISD::BUILD_VECTOR && \"expected BUILD_VECTOR\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9246, __extension__ __PRETTY_FUNCTION__))
;
9247 EVT VT = N->getValueType(0);
9248 unsigned EltSize = VT.getScalarSizeInBits() / 2;
9249 unsigned NumElts = VT.getVectorNumElements();
9250 MVT TruncVT = MVT::getIntegerVT(EltSize);
9251 SmallVector<SDValue, 8> Ops;
9252 SDLoc dl(N);
9253 for (unsigned i = 0; i != NumElts; ++i) {
9254 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
9255 const APInt &CInt = C->getAPIntValue();
9256 // Element types smaller than 32 bits are not legal, so use i32 elements.
9257 // The values are implicitly truncated so sext vs. zext doesn't matter.
9258 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
9259 }
9260 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
9261}
9262
9263static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
9264 unsigned Opcode = N->getOpcode();
9265 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
9266 SDNode *N0 = N->getOperand(0).getNode();
9267 SDNode *N1 = N->getOperand(1).getNode();
9268 return N0->hasOneUse() && N1->hasOneUse() &&
9269 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
9270 }
9271 return false;
9272}
9273
9274static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
9275 unsigned Opcode = N->getOpcode();
9276 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
9277 SDNode *N0 = N->getOperand(0).getNode();
9278 SDNode *N1 = N->getOperand(1).getNode();
9279 return N0->hasOneUse() && N1->hasOneUse() &&
9280 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
9281 }
9282 return false;
9283}
9284
9285static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
9286 // Multiplications are only custom-lowered for 128-bit vectors so that
9287 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
9288 EVT VT = Op.getValueType();
9289 assert(VT.is128BitVector() && VT.isInteger() &&(static_cast <bool> (VT.is128BitVector() && VT.
isInteger() && "unexpected type for custom-lowering ISD::MUL"
) ? void (0) : __assert_fail ("VT.is128BitVector() && VT.isInteger() && \"unexpected type for custom-lowering ISD::MUL\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9290, __extension__ __PRETTY_FUNCTION__))
9290 "unexpected type for custom-lowering ISD::MUL")(static_cast <bool> (VT.is128BitVector() && VT.
isInteger() && "unexpected type for custom-lowering ISD::MUL"
) ? void (0) : __assert_fail ("VT.is128BitVector() && VT.isInteger() && \"unexpected type for custom-lowering ISD::MUL\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9290, __extension__ __PRETTY_FUNCTION__))
;
9291 SDNode *N0 = Op.getOperand(0).getNode();
9292 SDNode *N1 = Op.getOperand(1).getNode();
9293 unsigned NewOpc = 0;
9294 bool isMLA = false;
9295 bool isN0SExt = isSignExtended(N0, DAG);
9296 bool isN1SExt = isSignExtended(N1, DAG);
9297 if (isN0SExt && isN1SExt)
9298 NewOpc = ARMISD::VMULLs;
9299 else {
9300 bool isN0ZExt = isZeroExtended(N0, DAG);
9301 bool isN1ZExt = isZeroExtended(N1, DAG);
9302 if (isN0ZExt && isN1ZExt)
9303 NewOpc = ARMISD::VMULLu;
9304 else if (isN1SExt || isN1ZExt) {
9305 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
9306 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
9307 if (isN1SExt && isAddSubSExt(N0, DAG)) {
9308 NewOpc = ARMISD::VMULLs;
9309 isMLA = true;
9310 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
9311 NewOpc = ARMISD::VMULLu;
9312 isMLA = true;
9313 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
9314 std::swap(N0, N1);
9315 NewOpc = ARMISD::VMULLu;
9316 isMLA = true;
9317 }
9318 }
9319
9320 if (!NewOpc) {
9321 if (VT == MVT::v2i64)
9322 // Fall through to expand this. It is not legal.
9323 return SDValue();
9324 else
9325 // Other vector multiplications are legal.
9326 return Op;
9327 }
9328 }
9329
9330 // Legalize to a VMULL instruction.
9331 SDLoc DL(Op);
9332 SDValue Op0;
9333 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
9334 if (!isMLA) {
9335 Op0 = SkipExtensionForVMULL(N0, DAG);
9336 assert(Op0.getValueType().is64BitVector() &&(static_cast <bool> (Op0.getValueType().is64BitVector()
&& Op1.getValueType().is64BitVector() && "unexpected types for extended operands to VMULL"
) ? void (0) : __assert_fail ("Op0.getValueType().is64BitVector() && Op1.getValueType().is64BitVector() && \"unexpected types for extended operands to VMULL\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9338, __extension__ __PRETTY_FUNCTION__))
9337 Op1.getValueType().is64BitVector() &&(static_cast <bool> (Op0.getValueType().is64BitVector()
&& Op1.getValueType().is64BitVector() && "unexpected types for extended operands to VMULL"
) ? void (0) : __assert_fail ("Op0.getValueType().is64BitVector() && Op1.getValueType().is64BitVector() && \"unexpected types for extended operands to VMULL\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9338, __extension__ __PRETTY_FUNCTION__))
9338 "unexpected types for extended operands to VMULL")(static_cast <bool> (Op0.getValueType().is64BitVector()
&& Op1.getValueType().is64BitVector() && "unexpected types for extended operands to VMULL"
) ? void (0) : __assert_fail ("Op0.getValueType().is64BitVector() && Op1.getValueType().is64BitVector() && \"unexpected types for extended operands to VMULL\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9338, __extension__ __PRETTY_FUNCTION__))
;
9339 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
9340 }
9341
9342 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
9343 // isel lowering to take advantage of no-stall back to back vmul + vmla.
9344 // vmull q0, d4, d6
9345 // vmlal q0, d5, d6
9346 // is faster than
9347 // vaddl q0, d4, d5
9348 // vmovl q1, d6
9349 // vmul q0, q0, q1
9350 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
9351 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
9352 EVT Op1VT = Op1.getValueType();
9353 return DAG.getNode(N0->getOpcode(), DL, VT,
9354 DAG.getNode(NewOpc, DL, VT,
9355 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
9356 DAG.getNode(NewOpc, DL, VT,
9357 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
9358}
9359
9360static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
9361 SelectionDAG &DAG) {
9362 // TODO: Should this propagate fast-math-flags?
9363
9364 // Convert to float
9365 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
9366 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
9367 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
9368 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
9369 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
9370 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
9371 // Get reciprocal estimate.
9372 // float4 recip = vrecpeq_f32(yf);
9373 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9374 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9375 Y);
9376 // Because char has a smaller range than uchar, we can actually get away
9377 // without any newton steps. This requires that we use a weird bias
9378 // of 0xb000, however (again, this has been exhaustively tested).
9379 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
9380 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
9381 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
9382 Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
9383 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
9384 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
9385 // Convert back to short.
9386 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
9387 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
9388 return X;
9389}
9390
9391static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
9392 SelectionDAG &DAG) {
9393 // TODO: Should this propagate fast-math-flags?
9394
9395 SDValue N2;
9396 // Convert to float.
9397 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
9398 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
9399 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
9400 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
9401 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
9402 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
9403
9404 // Use reciprocal estimate and one refinement step.
9405 // float4 recip = vrecpeq_f32(yf);
9406 // recip *= vrecpsq_f32(yf, recip);
9407 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9408 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9409 N1);
9410 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9411 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9412 N1, N2);
9413 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9414 // Because short has a smaller range than ushort, we can actually get away
9415 // with only a single newton step. This requires that we use a weird bias
9416 // of 89, however (again, this has been exhaustively tested).
9417 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
9418 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9419 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9420 N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
9421 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9422 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9423 // Convert back to integer and return.
9424 // return vmovn_s32(vcvt_s32_f32(result));
9425 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9426 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9427 return N0;
9428}
9429
9430static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
9431 const ARMSubtarget *ST) {
9432 EVT VT = Op.getValueType();
9433 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&(static_cast <bool> ((VT == MVT::v4i16 || VT == MVT::v8i8
) && "unexpected type for custom-lowering ISD::SDIV")
? void (0) : __assert_fail ("(VT == MVT::v4i16 || VT == MVT::v8i8) && \"unexpected type for custom-lowering ISD::SDIV\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9434, __extension__ __PRETTY_FUNCTION__))
9434 "unexpected type for custom-lowering ISD::SDIV")(static_cast <bool> ((VT == MVT::v4i16 || VT == MVT::v8i8
) && "unexpected type for custom-lowering ISD::SDIV")
? void (0) : __assert_fail ("(VT == MVT::v4i16 || VT == MVT::v8i8) && \"unexpected type for custom-lowering ISD::SDIV\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9434, __extension__ __PRETTY_FUNCTION__))
;
9435
9436 SDLoc dl(Op);
9437 SDValue N0 = Op.getOperand(0);
9438 SDValue N1 = Op.getOperand(1);
9439 SDValue N2, N3;
9440
9441 if (VT == MVT::v8i8) {
9442 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
9443 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
9444
9445 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9446 DAG.getIntPtrConstant(4, dl));
9447 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9448 DAG.getIntPtrConstant(4, dl));
9449 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9450 DAG.getIntPtrConstant(0, dl));
9451 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9452 DAG.getIntPtrConstant(0, dl));
9453
9454 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
9455 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
9456
9457 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9458 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9459
9460 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
9461 return N0;
9462 }
9463 return LowerSDIV_v4i16(N0, N1, dl, DAG);
9464}
9465
9466static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
9467 const ARMSubtarget *ST) {
9468 // TODO: Should this propagate fast-math-flags?
9469 EVT VT = Op.getValueType();
9470 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&(static_cast <bool> ((VT == MVT::v4i16 || VT == MVT::v8i8
) && "unexpected type for custom-lowering ISD::UDIV")
? void (0) : __assert_fail ("(VT == MVT::v4i16 || VT == MVT::v8i8) && \"unexpected type for custom-lowering ISD::UDIV\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9471, __extension__ __PRETTY_FUNCTION__))
9471 "unexpected type for custom-lowering ISD::UDIV")(static_cast <bool> ((VT == MVT::v4i16 || VT == MVT::v8i8
) && "unexpected type for custom-lowering ISD::UDIV")
? void (0) : __assert_fail ("(VT == MVT::v4i16 || VT == MVT::v8i8) && \"unexpected type for custom-lowering ISD::UDIV\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9471, __extension__ __PRETTY_FUNCTION__))
;
9472
9473 SDLoc dl(Op);
9474 SDValue N0 = Op.getOperand(0);
9475 SDValue N1 = Op.getOperand(1);
9476 SDValue N2, N3;
9477
9478 if (VT == MVT::v8i8) {
9479 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
9480 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
9481
9482 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9483 DAG.getIntPtrConstant(4, dl));
9484 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9485 DAG.getIntPtrConstant(4, dl));
9486 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9487 DAG.getIntPtrConstant(0, dl));
9488 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9489 DAG.getIntPtrConstant(0, dl));
9490
9491 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
9492 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
9493
9494 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9495 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9496
9497 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
9498 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
9499 MVT::i32),
9500 N0);
9501 return N0;
9502 }
9503
9504 // v4i16 sdiv ... Convert to float.
9505 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
9506 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
9507 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
9508 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
9509 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
9510 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
9511
9512 // Use reciprocal estimate and two refinement steps.
9513 // float4 recip = vrecpeq_f32(yf);
9514 // recip *= vrecpsq_f32(yf, recip);
9515 // recip *= vrecpsq_f32(yf, recip);
9516 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9517 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9518 BN1);
9519 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9520 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9521 BN1, N2);
9522 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9523 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9524 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9525 BN1, N2);
9526 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9527 // Simply multiplying by the reciprocal estimate can leave us a few ulps
9528 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
9529 // and that it will never cause us to return an answer too large).
9530 // float4 result = as_float4(as_int4(xf*recip) + 2);
9531 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9532 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9533 N1 = DAG.getConstant(2, dl, MVT::v4i32);
9534 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9535 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9536 // Convert back to integer and return.
9537 // return vmovn_u32(vcvt_s32_f32(result));
9538 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9539 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9540 return N0;
9541}
9542
9543static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
9544 SDNode *N = Op.getNode();
9545 EVT VT = N->getValueType(0);
9546 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9547
9548 SDValue Carry = Op.getOperand(2);
9549
9550 SDLoc DL(Op);
9551
9552 SDValue Result;
9553 if (Op.getOpcode() == ISD::ADDCARRY) {
9554 // This converts the boolean value carry into the carry flag.
9555 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
9556
9557 // Do the addition proper using the carry flag we wanted.
9558 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
9559 Op.getOperand(1), Carry);
9560
9561 // Now convert the carry flag into a boolean value.
9562 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
9563 } else {
9564 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
9565 // have to invert the carry first.
9566 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
9567 DAG.getConstant(1, DL, MVT::i32), Carry);
9568 // This converts the boolean value carry into the carry flag.
9569 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
9570
9571 // Do the subtraction proper using the carry flag we wanted.
9572 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
9573 Op.getOperand(1), Carry);
9574
9575 // Now convert the carry flag into a boolean value.
9576 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
9577 // But the carry returned by ARMISD::SUBE is not a borrow as expected
9578 // by ISD::SUBCARRY, so compute 1 - C.
9579 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
9580 DAG.getConstant(1, DL, MVT::i32), Carry);
9581 }
9582
9583 // Return both values.
9584 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
9585}
9586
9587SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
9588 assert(Subtarget->isTargetDarwin())(static_cast <bool> (Subtarget->isTargetDarwin()) ? void
(0) : __assert_fail ("Subtarget->isTargetDarwin()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9588, __extension__ __PRETTY_FUNCTION__))
;
9589
9590 // For iOS, we want to call an alternative entry point: __sincos_stret,
9591 // return values are passed via sret.
9592 SDLoc dl(Op);
9593 SDValue Arg = Op.getOperand(0);
9594 EVT ArgVT = Arg.getValueType();
9595 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9596 auto PtrVT = getPointerTy(DAG.getDataLayout());
9597
9598 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9599 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9600
9601 // Pair of floats / doubles used to pass the result.
9602 Type *RetTy = StructType::get(ArgTy, ArgTy);
9603 auto &DL = DAG.getDataLayout();
9604
9605 ArgListTy Args;
9606 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
9607 SDValue SRet;
9608 if (ShouldUseSRet) {
9609 // Create stack object for sret.
9610 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
9611 const Align StackAlign = DL.getPrefTypeAlign(RetTy);
9612 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
9613 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
9614
9615 ArgListEntry Entry;
9616 Entry.Node = SRet;
9617 Entry.Ty = RetTy->getPointerTo();
9618 Entry.IsSExt = false;
9619 Entry.IsZExt = false;
9620 Entry.IsSRet = true;
9621 Args.push_back(Entry);
9622 RetTy = Type::getVoidTy(*DAG.getContext());
9623 }
9624
9625 ArgListEntry Entry;
9626 Entry.Node = Arg;
9627 Entry.Ty = ArgTy;
9628 Entry.IsSExt = false;
9629 Entry.IsZExt = false;
9630 Args.push_back(Entry);
9631
9632 RTLIB::Libcall LC =
9633 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
9634 const char *LibcallName = getLibcallName(LC);
9635 CallingConv::ID CC = getLibcallCallingConv(LC);
9636 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
9637
9638 TargetLowering::CallLoweringInfo CLI(DAG);
9639 CLI.setDebugLoc(dl)
9640 .setChain(DAG.getEntryNode())
9641 .setCallee(CC, RetTy, Callee, std::move(Args))
9642 .setDiscardResult(ShouldUseSRet);
9643 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
9644
9645 if (!ShouldUseSRet)
9646 return CallResult.first;
9647
9648 SDValue LoadSin =
9649 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
9650
9651 // Address of cos field.
9652 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
9653 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
9654 SDValue LoadCos =
9655 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
9656
9657 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
9658 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
9659 LoadSin.getValue(0), LoadCos.getValue(0));
9660}
9661
9662SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
9663 bool Signed,
9664 SDValue &Chain) const {
9665 EVT VT = Op.getValueType();
9666 assert((VT == MVT::i32 || VT == MVT::i64) &&(static_cast <bool> ((VT == MVT::i32 || VT == MVT::i64)
&& "unexpected type for custom lowering DIV") ? void
(0) : __assert_fail ("(VT == MVT::i32 || VT == MVT::i64) && \"unexpected type for custom lowering DIV\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9667, __extension__ __PRETTY_FUNCTION__))
9667 "unexpected type for custom lowering DIV")(static_cast <bool> ((VT == MVT::i32 || VT == MVT::i64)
&& "unexpected type for custom lowering DIV") ? void
(0) : __assert_fail ("(VT == MVT::i32 || VT == MVT::i64) && \"unexpected type for custom lowering DIV\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9667, __extension__ __PRETTY_FUNCTION__))
;
9668 SDLoc dl(Op);
9669
9670 const auto &DL = DAG.getDataLayout();
9671 const auto &TLI = DAG.getTargetLoweringInfo();
9672
9673 const char *Name = nullptr;
9674 if (Signed)
9675 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
9676 else
9677 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
9678
9679 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
9680
9681 ARMTargetLowering::ArgListTy Args;
9682
9683 for (auto AI : {1, 0}) {
9684 ArgListEntry Arg;
9685 Arg.Node = Op.getOperand(AI);
9686 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
9687 Args.push_back(Arg);
9688 }
9689
9690 CallLoweringInfo CLI(DAG);
9691 CLI.setDebugLoc(dl)
9692 .setChain(Chain)
9693 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
9694 ES, std::move(Args));
9695
9696 return LowerCallTo(CLI).first;
9697}
9698
9699// This is a code size optimisation: return the original SDIV node to
9700// DAGCombiner when we don't want to expand SDIV into a sequence of
9701// instructions, and an empty node otherwise which will cause the
9702// SDIV to be expanded in DAGCombine.
9703SDValue
9704ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9705 SelectionDAG &DAG,
9706 SmallVectorImpl<SDNode *> &Created) const {
9707 // TODO: Support SREM
9708 if (N->getOpcode() != ISD::SDIV)
9709 return SDValue();
9710
9711 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
9712 const bool MinSize = ST.hasMinSize();
9713 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
9714 : ST.hasDivideInARMMode();
9715
9716 // Don't touch vector types; rewriting this may lead to scalarizing
9717 // the int divs.
9718 if (N->getOperand(0).getValueType().isVector())
9719 return SDValue();
9720
9721 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
9722 // hwdiv support for this to be really profitable.
9723 if (!(MinSize && HasDivide))
9724 return SDValue();
9725
9726 // ARM mode is a bit simpler than Thumb: we can handle large power
9727 // of 2 immediates with 1 mov instruction; no further checks required,
9728 // just return the sdiv node.
9729 if (!ST.isThumb())
9730 return SDValue(N, 0);
9731
9732 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
9733 // and thus lose the code size benefits of a MOVS that requires only 2.
9734 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
9735 // but as it's doing exactly this, it's not worth the trouble to get TTI.
9736 if (Divisor.sgt(128))
9737 return SDValue();
9738
9739 return SDValue(N, 0);
9740}
9741
9742SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
9743 bool Signed) const {
9744 assert(Op.getValueType() == MVT::i32 &&(static_cast <bool> (Op.getValueType() == MVT::i32 &&
"unexpected type for custom lowering DIV") ? void (0) : __assert_fail
("Op.getValueType() == MVT::i32 && \"unexpected type for custom lowering DIV\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9745, __extension__ __PRETTY_FUNCTION__))
9745 "unexpected type for custom lowering DIV")(static_cast <bool> (Op.getValueType() == MVT::i32 &&
"unexpected type for custom lowering DIV") ? void (0) : __assert_fail
("Op.getValueType() == MVT::i32 && \"unexpected type for custom lowering DIV\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9745, __extension__ __PRETTY_FUNCTION__))
;
9746 SDLoc dl(Op);
9747
9748 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
9749 DAG.getEntryNode(), Op.getOperand(1));
9750
9751 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9752}
9753
9754static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
9755 SDLoc DL(N);
9756 SDValue Op = N->getOperand(1);
9757 if (N->getValueType(0) == MVT::i32)
9758 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
9759 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9760 DAG.getConstant(0, DL, MVT::i32));
9761 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9762 DAG.getConstant(1, DL, MVT::i32));
9763 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
9764 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
9765}
9766
9767void ARMTargetLowering::ExpandDIV_Windows(
9768 SDValue Op, SelectionDAG &DAG, bool Signed,
9769 SmallVectorImpl<SDValue> &Results) const {
9770 const auto &DL = DAG.getDataLayout();
9771 const auto &TLI = DAG.getTargetLoweringInfo();
9772
9773 assert(Op.getValueType() == MVT::i64 &&(static_cast <bool> (Op.getValueType() == MVT::i64 &&
"unexpected type for custom lowering DIV") ? void (0) : __assert_fail
("Op.getValueType() == MVT::i64 && \"unexpected type for custom lowering DIV\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9774, __extension__ __PRETTY_FUNCTION__))
9774 "unexpected type for custom lowering DIV")(static_cast <bool> (Op.getValueType() == MVT::i64 &&
"unexpected type for custom lowering DIV") ? void (0) : __assert_fail
("Op.getValueType() == MVT::i64 && \"unexpected type for custom lowering DIV\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9774, __extension__ __PRETTY_FUNCTION__))
;
9775 SDLoc dl(Op);
9776
9777 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
9778
9779 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9780
9781 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
9782 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
9783 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
9784 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
9785
9786 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper));
9787}
9788
9789static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) {
9790 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
9791 EVT MemVT = LD->getMemoryVT();
9792 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&(static_cast <bool> ((MemVT == MVT::v4i1 || MemVT == MVT
::v8i1 || MemVT == MVT::v16i1) && "Expected a predicate type!"
) ? void (0) : __assert_fail ("(MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && \"Expected a predicate type!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9793, __extension__ __PRETTY_FUNCTION__))
9793 "Expected a predicate type!")(static_cast <bool> ((MemVT == MVT::v4i1 || MemVT == MVT
::v8i1 || MemVT == MVT::v16i1) && "Expected a predicate type!"
) ? void (0) : __assert_fail ("(MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && \"Expected a predicate type!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9793, __extension__ __PRETTY_FUNCTION__))
;
9794 assert(MemVT == Op.getValueType())(static_cast <bool> (MemVT == Op.getValueType()) ? void
(0) : __assert_fail ("MemVT == Op.getValueType()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9794, __extension__ __PRETTY_FUNCTION__))
;
9795 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&(static_cast <bool> (LD->getExtensionType() == ISD::
NON_EXTLOAD && "Expected a non-extending load") ? void
(0) : __assert_fail ("LD->getExtensionType() == ISD::NON_EXTLOAD && \"Expected a non-extending load\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9796, __extension__ __PRETTY_FUNCTION__))
9796 "Expected a non-extending load")(static_cast <bool> (LD->getExtensionType() == ISD::
NON_EXTLOAD && "Expected a non-extending load") ? void
(0) : __assert_fail ("LD->getExtensionType() == ISD::NON_EXTLOAD && \"Expected a non-extending load\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9796, __extension__ __PRETTY_FUNCTION__))
;
9797 assert(LD->isUnindexed() && "Expected a unindexed load")(static_cast <bool> (LD->isUnindexed() && "Expected a unindexed load"
) ? void (0) : __assert_fail ("LD->isUnindexed() && \"Expected a unindexed load\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9797, __extension__ __PRETTY_FUNCTION__))
;
9798
9799 // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit
9800 // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
9801 // need to make sure that 8/4 bits are actually loaded into the correct
9802 // place, which means loading the value and then shuffling the values into
9803 // the bottom bits of the predicate.
9804 // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
9805 // for BE).
9806 // Speaking of BE, apparently the rest of llvm will assume a reverse order to
9807 // a natural VMSR(load), so needs to be reversed.
9808
9809 SDLoc dl(Op);
9810 SDValue Load = DAG.getExtLoad(
9811 ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(),
9812 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
9813 LD->getMemOperand());
9814 SDValue Val = Load;
9815 if (DAG.getDataLayout().isBigEndian())
9816 Val = DAG.getNode(ISD::SRL, dl, MVT::i32,
9817 DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Load),
9818 DAG.getConstant(32 - MemVT.getSizeInBits(), dl, MVT::i32));
9819 SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Val);
9820 if (MemVT != MVT::v16i1)
9821 Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred,
9822 DAG.getConstant(0, dl, MVT::i32));
9823 return DAG.getMergeValues({Pred, Load.getValue(1)}, dl);
9824}
9825
9826void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results,
9827 SelectionDAG &DAG) const {
9828 LoadSDNode *LD = cast<LoadSDNode>(N);
9829 EVT MemVT = LD->getMemoryVT();
9830 assert(LD->isUnindexed() && "Loads should be unindexed at this point.")(static_cast <bool> (LD->isUnindexed() && "Loads should be unindexed at this point."
) ? void (0) : __assert_fail ("LD->isUnindexed() && \"Loads should be unindexed at this point.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9830, __extension__ __PRETTY_FUNCTION__))
;
9831
9832 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9833 !Subtarget->isThumb1Only() && LD->isVolatile()) {
9834 SDLoc dl(N);
9835 SDValue Result = DAG.getMemIntrinsicNode(
9836 ARMISD::LDRD, dl, DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}),
9837 {LD->getChain(), LD->getBasePtr()}, MemVT, LD->getMemOperand());
9838 SDValue Lo = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 0 : 1);
9839 SDValue Hi = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 1 : 0);
9840 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
9841 Results.append({Pair, Result.getValue(2)});
9842 }
9843}
9844
9845static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) {
9846 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9847 EVT MemVT = ST->getMemoryVT();
9848 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&(static_cast <bool> ((MemVT == MVT::v4i1 || MemVT == MVT
::v8i1 || MemVT == MVT::v16i1) && "Expected a predicate type!"
) ? void (0) : __assert_fail ("(MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && \"Expected a predicate type!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9849, __extension__ __PRETTY_FUNCTION__))
9849 "Expected a predicate type!")(static_cast <bool> ((MemVT == MVT::v4i1 || MemVT == MVT
::v8i1 || MemVT == MVT::v16i1) && "Expected a predicate type!"
) ? void (0) : __assert_fail ("(MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) && \"Expected a predicate type!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9849, __extension__ __PRETTY_FUNCTION__))
;
9850 assert(MemVT == ST->getValue().getValueType())(static_cast <bool> (MemVT == ST->getValue().getValueType
()) ? void (0) : __assert_fail ("MemVT == ST->getValue().getValueType()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9850, __extension__ __PRETTY_FUNCTION__))
;
9851 assert(!ST->isTruncatingStore() && "Expected a non-extending store")(static_cast <bool> (!ST->isTruncatingStore() &&
"Expected a non-extending store") ? void (0) : __assert_fail
("!ST->isTruncatingStore() && \"Expected a non-extending store\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9851, __extension__ __PRETTY_FUNCTION__))
;
9852 assert(ST->isUnindexed() && "Expected a unindexed store")(static_cast <bool> (ST->isUnindexed() && "Expected a unindexed store"
) ? void (0) : __assert_fail ("ST->isUnindexed() && \"Expected a unindexed store\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9852, __extension__ __PRETTY_FUNCTION__))
;
9853
9854 // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits
9855 // unset and a scalar store.
9856 SDLoc dl(Op);
9857 SDValue Build = ST->getValue();
9858 if (MemVT != MVT::v16i1) {
9859 SmallVector<SDValue, 16> Ops;
9860 for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++) {
9861 unsigned Elt = DAG.getDataLayout().isBigEndian()
9862 ? MemVT.getVectorNumElements() - I - 1
9863 : I;
9864 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build,
9865 DAG.getConstant(Elt, dl, MVT::i32)));
9866 }
9867 for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
9868 Ops.push_back(DAG.getUNDEF(MVT::i32));
9869 Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops);
9870 }
9871 SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build);
9872 if (MemVT == MVT::v16i1 && DAG.getDataLayout().isBigEndian())
9873 GRP = DAG.getNode(ISD::SRL, dl, MVT::i32,
9874 DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, GRP),
9875 DAG.getConstant(16, dl, MVT::i32));
9876 return DAG.getTruncStore(
9877 ST->getChain(), dl, GRP, ST->getBasePtr(),
9878 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
9879 ST->getMemOperand());
9880}
9881
9882static SDValue LowerSTORE(SDValue Op, SelectionDAG &DAG,
9883 const ARMSubtarget *Subtarget) {
9884 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9885 EVT MemVT = ST->getMemoryVT();
9886 assert(ST->isUnindexed() && "Stores should be unindexed at this point.")(static_cast <bool> (ST->isUnindexed() && "Stores should be unindexed at this point."
) ? void (0) : __assert_fail ("ST->isUnindexed() && \"Stores should be unindexed at this point.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9886, __extension__ __PRETTY_FUNCTION__))
;
9887
9888 if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9889 !Subtarget->isThumb1Only() && ST->isVolatile()) {
9890 SDNode *N = Op.getNode();
9891 SDLoc dl(N);
9892
9893 SDValue Lo = DAG.getNode(
9894 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9895 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 0 : 1, dl,
9896 MVT::i32));
9897 SDValue Hi = DAG.getNode(
9898 ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9899 DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 1 : 0, dl,
9900 MVT::i32));
9901
9902 return DAG.getMemIntrinsicNode(ARMISD::STRD, dl, DAG.getVTList(MVT::Other),
9903 {ST->getChain(), Lo, Hi, ST->getBasePtr()},
9904 MemVT, ST->getMemOperand());
9905 } else if (Subtarget->hasMVEIntegerOps() &&
9906 ((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9907 MemVT == MVT::v16i1))) {
9908 return LowerPredicateStore(Op, DAG);
9909 }
9910
9911 return SDValue();
9912}
9913
9914static bool isZeroVector(SDValue N) {
9915 return (ISD::isBuildVectorAllZeros(N.getNode()) ||
9916 (N->getOpcode() == ARMISD::VMOVIMM &&
9917 isNullConstant(N->getOperand(0))));
9918}
9919
9920static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) {
9921 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
9922 MVT VT = Op.getSimpleValueType();
9923 SDValue Mask = N->getMask();
9924 SDValue PassThru = N->getPassThru();
9925 SDLoc dl(Op);
9926
9927 if (isZeroVector(PassThru))
9928 return Op;
9929
9930 // MVE Masked loads use zero as the passthru value. Here we convert undef to
9931 // zero too, and other values are lowered to a select.
9932 SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
9933 DAG.getTargetConstant(0, dl, MVT::i32));
9934 SDValue NewLoad = DAG.getMaskedLoad(
9935 VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec,
9936 N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
9937 N->getExtensionType(), N->isExpandingLoad());
9938 SDValue Combo = NewLoad;
9939 bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST ||
9940 PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
9941 isZeroVector(PassThru->getOperand(0));
9942 if (!PassThru.isUndef() && !PassThruIsCastZero)
9943 Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
9944 return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl);
9945}
9946
9947static SDValue LowerVecReduce(SDValue Op, SelectionDAG &DAG,
9948 const ARMSubtarget *ST) {
9949 if (!ST->hasMVEIntegerOps())
9950 return SDValue();
9951
9952 SDLoc dl(Op);
9953 unsigned BaseOpcode = 0;
9954 switch (Op->getOpcode()) {
9955 default: llvm_unreachable("Expected VECREDUCE opcode")::llvm::llvm_unreachable_internal("Expected VECREDUCE opcode"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9955)
;
9956 case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break;
9957 case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break;
9958 case ISD::VECREDUCE_MUL: BaseOpcode = ISD::MUL; break;
9959 case ISD::VECREDUCE_AND: BaseOpcode = ISD::AND; break;
9960 case ISD::VECREDUCE_OR: BaseOpcode = ISD::OR; break;
9961 case ISD::VECREDUCE_XOR: BaseOpcode = ISD::XOR; break;
9962 case ISD::VECREDUCE_FMAX: BaseOpcode = ISD::FMAXNUM; break;
9963 case ISD::VECREDUCE_FMIN: BaseOpcode = ISD::FMINNUM; break;
9964 }
9965
9966 SDValue Op0 = Op->getOperand(0);
9967 EVT VT = Op0.getValueType();
9968 EVT EltVT = VT.getVectorElementType();
9969 unsigned NumElts = VT.getVectorNumElements();
9970 unsigned NumActiveLanes = NumElts;
9971
9972 assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 ||(static_cast <bool> ((NumActiveLanes == 16 || NumActiveLanes
== 8 || NumActiveLanes == 4 || NumActiveLanes == 2) &&
"Only expected a power 2 vector size") ? void (0) : __assert_fail
("(NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 || NumActiveLanes == 2) && \"Only expected a power 2 vector size\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9974, __extension__ __PRETTY_FUNCTION__))
9973 NumActiveLanes == 2) &&(static_cast <bool> ((NumActiveLanes == 16 || NumActiveLanes
== 8 || NumActiveLanes == 4 || NumActiveLanes == 2) &&
"Only expected a power 2 vector size") ? void (0) : __assert_fail
("(NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 || NumActiveLanes == 2) && \"Only expected a power 2 vector size\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9974, __extension__ __PRETTY_FUNCTION__))
9974 "Only expected a power 2 vector size")(static_cast <bool> ((NumActiveLanes == 16 || NumActiveLanes
== 8 || NumActiveLanes == 4 || NumActiveLanes == 2) &&
"Only expected a power 2 vector size") ? void (0) : __assert_fail
("(NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 || NumActiveLanes == 2) && \"Only expected a power 2 vector size\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 9974, __extension__ __PRETTY_FUNCTION__))
;
9975
9976 // Use Mul(X, Rev(X)) until 4 items remain. Going down to 4 vector elements
9977 // allows us to easily extract vector elements from the lanes.
9978 while (NumActiveLanes > 4) {
9979 unsigned RevOpcode = NumActiveLanes == 16 ? ARMISD::VREV16 : ARMISD::VREV32;
9980 SDValue Rev = DAG.getNode(RevOpcode, dl, VT, Op0);
9981 Op0 = DAG.getNode(BaseOpcode, dl, VT, Op0, Rev);
9982 NumActiveLanes /= 2;
9983 }
9984
9985 SDValue Res;
9986 if (NumActiveLanes == 4) {
9987 // The remaining 4 elements are summed sequentially
9988 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9989 DAG.getConstant(0 * NumElts / 4, dl, MVT::i32));
9990 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9991 DAG.getConstant(1 * NumElts / 4, dl, MVT::i32));
9992 SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9993 DAG.getConstant(2 * NumElts / 4, dl, MVT::i32));
9994 SDValue Ext3 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9995 DAG.getConstant(3 * NumElts / 4, dl, MVT::i32));
9996 SDValue Res0 = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
9997 SDValue Res1 = DAG.getNode(BaseOpcode, dl, EltVT, Ext2, Ext3, Op->getFlags());
9998 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res0, Res1, Op->getFlags());
9999 } else {
10000 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10001 DAG.getConstant(0, dl, MVT::i32));
10002 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10003 DAG.getConstant(1, dl, MVT::i32));
10004 Res = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
10005 }
10006
10007 // Result type may be wider than element type.
10008 if (EltVT != Op->getValueType(0))
10009 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Op->getValueType(0), Res);
10010 return Res;
10011}
10012
10013static SDValue LowerVecReduceF(SDValue Op, SelectionDAG &DAG,
10014 const ARMSubtarget *ST) {
10015 if (!ST->hasMVEFloatOps())
10016 return SDValue();
10017 return LowerVecReduce(Op, DAG, ST);
10018}
10019
10020static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
10021 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getSuccessOrdering()))
10022 // Acquire/Release load/store is not legal for targets without a dmb or
10023 // equivalent available.
10024 return SDValue();
10025
10026 // Monotonic load/store is legal for all targets.
10027 return Op;
10028}
10029
10030static void ReplaceREADCYCLECOUNTER(SDNode *N,
10031 SmallVectorImpl<SDValue> &Results,
10032 SelectionDAG &DAG,
10033 const ARMSubtarget *Subtarget) {
10034 SDLoc DL(N);
10035 // Under Power Management extensions, the cycle-count is:
10036 // mrc p15, #0, <Rt>, c9, c13, #0
10037 SDValue Ops[] = { N->getOperand(0), // Chain
10038 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
10039 DAG.getTargetConstant(15, DL, MVT::i32),
10040 DAG.getTargetConstant(0, DL, MVT::i32),
10041 DAG.getTargetConstant(9, DL, MVT::i32),
10042 DAG.getTargetConstant(13, DL, MVT::i32),
10043 DAG.getTargetConstant(0, DL, MVT::i32)
10044 };
10045
10046 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
10047 DAG.getVTList(MVT::i32, MVT::Other), Ops);
10048 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
10049 DAG.getConstant(0, DL, MVT::i32)));
10050 Results.push_back(Cycles32.getValue(1));
10051}
10052
10053static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
10054 SDLoc dl(V.getNode());
10055 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
10056 SDValue VHi = DAG.getAnyExtOrTrunc(
10057 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
10058 dl, MVT::i32);
10059 bool isBigEndian = DAG.getDataLayout().isBigEndian();
10060 if (isBigEndian)
10061 std::swap (VLo, VHi);
10062 SDValue RegClass =
10063 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
10064 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
10065 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
10066 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
10067 return SDValue(
10068 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
10069}
10070
10071static void ReplaceCMP_SWAP_64Results(SDNode *N,
10072 SmallVectorImpl<SDValue> & Results,
10073 SelectionDAG &DAG) {
10074 assert(N->getValueType(0) == MVT::i64 &&(static_cast <bool> (N->getValueType(0) == MVT::i64 &&
"AtomicCmpSwap on types less than 64 should be legal") ? void
(0) : __assert_fail ("N->getValueType(0) == MVT::i64 && \"AtomicCmpSwap on types less than 64 should be legal\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10075, __extension__ __PRETTY_FUNCTION__))
10075 "AtomicCmpSwap on types less than 64 should be legal")(static_cast <bool> (N->getValueType(0) == MVT::i64 &&
"AtomicCmpSwap on types less than 64 should be legal") ? void
(0) : __assert_fail ("N->getValueType(0) == MVT::i64 && \"AtomicCmpSwap on types less than 64 should be legal\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10075, __extension__ __PRETTY_FUNCTION__))
;
10076 SDValue Ops[] = {N->getOperand(1),
10077 createGPRPairNode(DAG, N->getOperand(2)),
10078 createGPRPairNode(DAG, N->getOperand(3)),
10079 N->getOperand(0)};
10080 SDNode *CmpSwap = DAG.getMachineNode(
10081 ARM::CMP_SWAP_64, SDLoc(N),
10082 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
10083
10084 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
10085 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
10086
10087 bool isBigEndian = DAG.getDataLayout().isBigEndian();
10088
10089 SDValue Lo =
10090 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
10091 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
10092 SDValue Hi =
10093 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
10094 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
10095 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi));
10096 Results.push_back(SDValue(CmpSwap, 2));
10097}
10098
10099SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const {
10100 SDLoc dl(Op);
10101 EVT VT = Op.getValueType();
10102 SDValue Chain = Op.getOperand(0);
10103 SDValue LHS = Op.getOperand(1);
10104 SDValue RHS = Op.getOperand(2);
10105 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
10106 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
10107
10108 // If we don't have instructions of this float type then soften to a libcall
10109 // and use SETCC instead.
10110 if (isUnsupportedFloatingType(LHS.getValueType())) {
10111 DAG.getTargetLoweringInfo().softenSetCCOperands(
10112 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS, Chain, IsSignaling);
10113 if (!RHS.getNode()) {
10114 RHS = DAG.getConstant(0, dl, LHS.getValueType());
10115 CC = ISD::SETNE;
10116 }
10117 SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS,
10118 DAG.getCondCode(CC));
10119 return DAG.getMergeValues({Result, Chain}, dl);
10120 }
10121
10122 ARMCC::CondCodes CondCode, CondCode2;
10123 FPCCToARMCC(CC, CondCode, CondCode2);
10124
10125 // FIXME: Chain is not handled correctly here. Currently the FPSCR is implicit
10126 // in CMPFP and CMPFPE, but instead it should be made explicit by these
10127 // instructions using a chain instead of glue. This would also fix the problem
10128 // here (and also in LowerSELECT_CC) where we generate two comparisons when
10129 // CondCode2 != AL.
10130 SDValue True = DAG.getConstant(1, dl, VT);
10131 SDValue False = DAG.getConstant(0, dl, VT);
10132 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
10133 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
10134 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
10135 SDValue Result = getCMOV(dl, VT, False, True, ARMcc, CCR, Cmp, DAG);
10136 if (CondCode2 != ARMCC::AL) {
10137 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
10138 Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
10139 Result = getCMOV(dl, VT, Result, True, ARMcc, CCR, Cmp, DAG);
10140 }
10141 return DAG.getMergeValues({Result, Chain}, dl);
10142}
10143
10144SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10145 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("arm-isel")) { dbgs() << "Lowering node: "; Op.dump();
} } while (false)
;
10146 switch (Op.getOpcode()) {
10147 default: llvm_unreachable("Don't know how to custom lower this!")::llvm::llvm_unreachable_internal("Don't know how to custom lower this!"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10147)
;
10148 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
10149 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10150 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10151 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10152 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10153 case ISD::SELECT: return LowerSELECT(Op, DAG);
10154 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
10155 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10156 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
10157 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
10158 case ISD::VASTART: return LowerVASTART(Op, DAG);
10159 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
10160 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
10161 case ISD::SINT_TO_FP:
10162 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
10163 case ISD::STRICT_FP_TO_SINT:
10164 case ISD::STRICT_FP_TO_UINT:
10165 case ISD::FP_TO_SINT:
10166 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
10167 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10168 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10169 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10170 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
10171 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
10172 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
10173 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
10174 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
10175 Subtarget);
10176 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
10177 case ISD::SHL:
10178 case ISD::SRL:
10179 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
10180 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
10181 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
10182 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
10183 case ISD::SRL_PARTS:
10184 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
10185 case ISD::CTTZ:
10186 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
10187 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
10188 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget);
10189 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
10190 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
10191 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
10192 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
10193 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
10194 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10195 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
10196 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
10197 case ISD::TRUNCATE: return LowerTruncate(Op.getNode(), DAG, Subtarget);
10198 case ISD::SIGN_EXTEND:
10199 case ISD::ZERO_EXTEND: return LowerVectorExtend(Op.getNode(), DAG, Subtarget);
10200 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
10201 case ISD::SET_ROUNDING: return LowerSET_ROUNDING(Op, DAG);
10202 case ISD::MUL: return LowerMUL(Op, DAG);
10203 case ISD::SDIV:
10204 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
10205 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
10206 return LowerSDIV(Op, DAG, Subtarget);
10207 case ISD::UDIV:
10208 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
10209 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
10210 return LowerUDIV(Op, DAG, Subtarget);
10211 case ISD::ADDCARRY:
10212 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG);
10213 case ISD::SADDO:
10214 case ISD::SSUBO:
10215 return LowerSignedALUO(Op, DAG);
10216 case ISD::UADDO:
10217 case ISD::USUBO:
10218 return LowerUnsignedALUO(Op, DAG);
10219 case ISD::SADDSAT:
10220 case ISD::SSUBSAT:
10221 case ISD::UADDSAT:
10222 case ISD::USUBSAT:
10223 return LowerADDSUBSAT(Op, DAG, Subtarget);
10224 case ISD::LOAD:
10225 return LowerPredicateLoad(Op, DAG);
10226 case ISD::STORE:
10227 return LowerSTORE(Op, DAG, Subtarget);
10228 case ISD::MLOAD:
10229 return LowerMLOAD(Op, DAG);
10230 case ISD::VECREDUCE_MUL:
10231 case ISD::VECREDUCE_AND:
10232 case ISD::VECREDUCE_OR:
10233 case ISD::VECREDUCE_XOR:
10234 return LowerVecReduce(Op, DAG, Subtarget);
10235 case ISD::VECREDUCE_FADD:
10236 case ISD::VECREDUCE_FMUL:
10237 case ISD::VECREDUCE_FMIN:
10238 case ISD::VECREDUCE_FMAX:
10239 return LowerVecReduceF(Op, DAG, Subtarget);
10240 case ISD::ATOMIC_LOAD:
10241 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
10242 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
10243 case ISD::SDIVREM:
10244 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
10245 case ISD::DYNAMIC_STACKALLOC:
10246 if (Subtarget->isTargetWindows())
10247 return LowerDYNAMIC_STACKALLOC(Op, DAG);
10248 llvm_unreachable("Don't know how to custom lower this!")::llvm::llvm_unreachable_internal("Don't know how to custom lower this!"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10248)
;
10249 case ISD::STRICT_FP_ROUND:
10250 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
10251 case ISD::STRICT_FP_EXTEND:
10252 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
10253 case ISD::STRICT_FSETCC:
10254 case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG);
10255 case ARMISD::WIN__DBZCHK: return SDValue();
10256 }
10257}
10258
10259static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
10260 SelectionDAG &DAG) {
10261 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10262 unsigned Opc = 0;
10263 if (IntNo == Intrinsic::arm_smlald)
10264 Opc = ARMISD::SMLALD;
10265 else if (IntNo == Intrinsic::arm_smlaldx)
10266 Opc = ARMISD::SMLALDX;
10267 else if (IntNo == Intrinsic::arm_smlsld)
10268 Opc = ARMISD::SMLSLD;
10269 else if (IntNo == Intrinsic::arm_smlsldx)
10270 Opc = ARMISD::SMLSLDX;
10271 else
10272 return;
10273
10274 SDLoc dl(N);
10275 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10276 N->getOperand(3),
10277 DAG.getConstant(0, dl, MVT::i32));
10278 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10279 N->getOperand(3),
10280 DAG.getConstant(1, dl, MVT::i32));
10281
10282 SDValue LongMul = DAG.getNode(Opc, dl,
10283 DAG.getVTList(MVT::i32, MVT::i32),
10284 N->getOperand(1), N->getOperand(2),
10285 Lo, Hi);
10286 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
10287 LongMul.getValue(0), LongMul.getValue(1)));
10288}
10289
10290/// ReplaceNodeResults - Replace the results of node with an illegal result
10291/// type with new values built out of custom code.
10292void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
10293 SmallVectorImpl<SDValue> &Results,
10294 SelectionDAG &DAG) const {
10295 SDValue Res;
10296 switch (N->getOpcode()) {
10297 default:
10298 llvm_unreachable("Don't know how to custom expand this!")::llvm::llvm_unreachable_internal("Don't know how to custom expand this!"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10298)
;
10299 case ISD::READ_REGISTER:
10300 ExpandREAD_REGISTER(N, Results, DAG);
10301 break;
10302 case ISD::BITCAST:
10303 Res = ExpandBITCAST(N, DAG, Subtarget);
10304 break;
10305 case ISD::SRL:
10306 case ISD::SRA:
10307 case ISD::SHL:
10308 Res = Expand64BitShift(N, DAG, Subtarget);
10309 break;
10310 case ISD::SREM:
10311 case ISD::UREM:
10312 Res = LowerREM(N, DAG);
10313 break;
10314 case ISD::SDIVREM:
10315 case ISD::UDIVREM:
10316 Res = LowerDivRem(SDValue(N, 0), DAG);
10317 assert(Res.getNumOperands() == 2 && "DivRem needs two values")(static_cast <bool> (Res.getNumOperands() == 2 &&
"DivRem needs two values") ? void (0) : __assert_fail ("Res.getNumOperands() == 2 && \"DivRem needs two values\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10317, __extension__ __PRETTY_FUNCTION__))
;
10318 Results.push_back(Res.getValue(0));
10319 Results.push_back(Res.getValue(1));
10320 return;
10321 case ISD::SADDSAT:
10322 case ISD::SSUBSAT:
10323 case ISD::UADDSAT:
10324 case ISD::USUBSAT:
10325 Res = LowerADDSUBSAT(SDValue(N, 0), DAG, Subtarget);
10326 break;
10327 case ISD::READCYCLECOUNTER:
10328 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
10329 return;
10330 case ISD::UDIV:
10331 case ISD::SDIV:
10332 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows")(static_cast <bool> (Subtarget->isTargetWindows() &&
"can only expand DIV on Windows") ? void (0) : __assert_fail
("Subtarget->isTargetWindows() && \"can only expand DIV on Windows\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10332, __extension__ __PRETTY_FUNCTION__))
;
10333 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
10334 Results);
10335 case ISD::ATOMIC_CMP_SWAP:
10336 ReplaceCMP_SWAP_64Results(N, Results, DAG);
10337 return;
10338 case ISD::INTRINSIC_WO_CHAIN:
10339 return ReplaceLongIntrinsic(N, Results, DAG);
10340 case ISD::ABS:
10341 lowerABS(N, Results, DAG);
10342 return ;
10343 case ISD::LOAD:
10344 LowerLOAD(N, Results, DAG);
10345 break;
10346 case ISD::TRUNCATE:
10347 Res = LowerTruncate(N, DAG, Subtarget);
10348 break;
10349 case ISD::SIGN_EXTEND:
10350 case ISD::ZERO_EXTEND:
10351 Res = LowerVectorExtend(N, DAG, Subtarget);
10352 break;
10353 }
10354 if (Res.getNode())
10355 Results.push_back(Res);
10356}
10357
10358//===----------------------------------------------------------------------===//
10359// ARM Scheduler Hooks
10360//===----------------------------------------------------------------------===//
10361
10362/// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
10363/// registers the function context.
10364void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
10365 MachineBasicBlock *MBB,
10366 MachineBasicBlock *DispatchBB,
10367 int FI) const {
10368 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&(static_cast <bool> (!Subtarget->isROPI() &&
!Subtarget->isRWPI() && "ROPI/RWPI not currently supported with SjLj"
) ? void (0) : __assert_fail ("!Subtarget->isROPI() && !Subtarget->isRWPI() && \"ROPI/RWPI not currently supported with SjLj\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10369, __extension__ __PRETTY_FUNCTION__))
10369 "ROPI/RWPI not currently supported with SjLj")(static_cast <bool> (!Subtarget->isROPI() &&
!Subtarget->isRWPI() && "ROPI/RWPI not currently supported with SjLj"
) ? void (0) : __assert_fail ("!Subtarget->isROPI() && !Subtarget->isRWPI() && \"ROPI/RWPI not currently supported with SjLj\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10369, __extension__ __PRETTY_FUNCTION__))
;
10370 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10371 DebugLoc dl = MI.getDebugLoc();
10372 MachineFunction *MF = MBB->getParent();
10373 MachineRegisterInfo *MRI = &MF->getRegInfo();
10374 MachineConstantPool *MCP = MF->getConstantPool();
10375 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
10376 const Function &F = MF->getFunction();
10377
10378 bool isThumb = Subtarget->isThumb();
10379 bool isThumb2 = Subtarget->isThumb2();
10380
10381 unsigned PCLabelId = AFI->createPICLabelUId();
10382 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
10383 ARMConstantPoolValue *CPV =
10384 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
10385 unsigned CPI = MCP->getConstantPoolIndex(CPV, Align(4));
10386
10387 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
10388 : &ARM::GPRRegClass;
10389
10390 // Grab constant pool and fixed stack memory operands.
10391 MachineMemOperand *CPMMO =
10392 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
10393 MachineMemOperand::MOLoad, 4, Align(4));
10394
10395 MachineMemOperand *FIMMOSt =
10396 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
10397 MachineMemOperand::MOStore, 4, Align(4));
10398
10399 // Load the address of the dispatch MBB into the jump buffer.
10400 if (isThumb2) {
10401 // Incoming value: jbuf
10402 // ldr.n r5, LCPI1_1
10403 // orr r5, r5, #1
10404 // add r5, pc
10405 // str r5, [$jbuf, #+4] ; &jbuf[1]
10406 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10407 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
10408 .addConstantPoolIndex(CPI)
10409 .addMemOperand(CPMMO)
10410 .add(predOps(ARMCC::AL));
10411 // Set the low bit because of thumb mode.
10412 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10413 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
10414 .addReg(NewVReg1, RegState::Kill)
10415 .addImm(0x01)
10416 .add(predOps(ARMCC::AL))
10417 .add(condCodeOp());
10418 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10419 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
10420 .addReg(NewVReg2, RegState::Kill)
10421 .addImm(PCLabelId);
10422 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
10423 .addReg(NewVReg3, RegState::Kill)
10424 .addFrameIndex(FI)
10425 .addImm(36) // &jbuf[1] :: pc
10426 .addMemOperand(FIMMOSt)
10427 .add(predOps(ARMCC::AL));
10428 } else if (isThumb) {
10429 // Incoming value: jbuf
10430 // ldr.n r1, LCPI1_4
10431 // add r1, pc
10432 // mov r2, #1
10433 // orrs r1, r2
10434 // add r2, $jbuf, #+4 ; &jbuf[1]
10435 // str r1, [r2]
10436 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10437 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
10438 .addConstantPoolIndex(CPI)
10439 .addMemOperand(CPMMO)
10440 .add(predOps(ARMCC::AL));
10441 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10442 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
10443 .addReg(NewVReg1, RegState::Kill)
10444 .addImm(PCLabelId);
10445 // Set the low bit because of thumb mode.
10446 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10447 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
10448 .addReg(ARM::CPSR, RegState::Define)
10449 .addImm(1)
10450 .add(predOps(ARMCC::AL));
10451 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10452 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
10453 .addReg(ARM::CPSR, RegState::Define)
10454 .addReg(NewVReg2, RegState::Kill)
10455 .addReg(NewVReg3, RegState::Kill)
10456 .add(predOps(ARMCC::AL));
10457 Register NewVReg5 = MRI->createVirtualRegister(TRC);
10458 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
10459 .addFrameIndex(FI)
10460 .addImm(36); // &jbuf[1] :: pc
10461 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
10462 .addReg(NewVReg4, RegState::Kill)
10463 .addReg(NewVReg5, RegState::Kill)
10464 .addImm(0)
10465 .addMemOperand(FIMMOSt)
10466 .add(predOps(ARMCC::AL));
10467 } else {
10468 // Incoming value: jbuf
10469 // ldr r1, LCPI1_1
10470 // add r1, pc, r1
10471 // str r1, [$jbuf, #+4] ; &jbuf[1]
10472 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10473 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
10474 .addConstantPoolIndex(CPI)
10475 .addImm(0)
10476 .addMemOperand(CPMMO)
10477 .add(predOps(ARMCC::AL));
10478 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10479 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
10480 .addReg(NewVReg1, RegState::Kill)
10481 .addImm(PCLabelId)
10482 .add(predOps(ARMCC::AL));
10483 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
10484 .addReg(NewVReg2, RegState::Kill)
10485 .addFrameIndex(FI)
10486 .addImm(36) // &jbuf[1] :: pc
10487 .addMemOperand(FIMMOSt)
10488 .add(predOps(ARMCC::AL));
10489 }
10490}
10491
10492void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
10493 MachineBasicBlock *MBB) const {
10494 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10495 DebugLoc dl = MI.getDebugLoc();
10496 MachineFunction *MF = MBB->getParent();
10497 MachineRegisterInfo *MRI = &MF->getRegInfo();
10498 MachineFrameInfo &MFI = MF->getFrameInfo();
10499 int FI = MFI.getFunctionContextIndex();
10500
10501 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
10502 : &ARM::GPRnopcRegClass;
10503
10504 // Get a mapping of the call site numbers to all of the landing pads they're
10505 // associated with.
10506 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
10507 unsigned MaxCSNum = 0;
10508 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
10509 ++BB) {
10510 if (!BB->isEHPad()) continue;
10511
10512 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
10513 // pad.
10514 for (MachineBasicBlock::iterator
10515 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
10516 if (!II->isEHLabel()) continue;
10517
10518 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
10519 if (!MF->hasCallSiteLandingPad(Sym)) continue;
10520
10521 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
10522 for (SmallVectorImpl<unsigned>::iterator
10523 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
10524 CSI != CSE; ++CSI) {
10525 CallSiteNumToLPad[*CSI].push_back(&*BB);
10526 MaxCSNum = std::max(MaxCSNum, *CSI);
10527 }
10528 break;
10529 }
10530 }
10531
10532 // Get an ordered list of the machine basic blocks for the jump table.
10533 std::vector<MachineBasicBlock*> LPadList;
10534 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
10535 LPadList.reserve(CallSiteNumToLPad.size());
10536 for (unsigned I = 1; I <= MaxCSNum; ++I) {
10537 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
10538 for (SmallVectorImpl<MachineBasicBlock*>::iterator
10539 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
10540 LPadList.push_back(*II);
10541 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
10542 }
10543 }
10544
10545 assert(!LPadList.empty() &&(static_cast <bool> (!LPadList.empty() && "No landing pad destinations for the dispatch jump table!"
) ? void (0) : __assert_fail ("!LPadList.empty() && \"No landing pad destinations for the dispatch jump table!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10546, __extension__ __PRETTY_FUNCTION__))
10546 "No landing pad destinations for the dispatch jump table!")(static_cast <bool> (!LPadList.empty() && "No landing pad destinations for the dispatch jump table!"
) ? void (0) : __assert_fail ("!LPadList.empty() && \"No landing pad destinations for the dispatch jump table!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10546, __extension__ __PRETTY_FUNCTION__))
;
10547
10548 // Create the jump table and associated information.
10549 MachineJumpTableInfo *JTI =
10550 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
10551 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
10552
10553 // Create the MBBs for the dispatch code.
10554
10555 // Shove the dispatch's address into the return slot in the function context.
10556 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
10557 DispatchBB->setIsEHPad();
10558
10559 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10560 unsigned trap_opcode;
10561 if (Subtarget->isThumb())
10562 trap_opcode = ARM::tTRAP;
10563 else
10564 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
10565
10566 BuildMI(TrapBB, dl, TII->get(trap_opcode));
10567 DispatchBB->addSuccessor(TrapBB);
10568
10569 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
10570 DispatchBB->addSuccessor(DispContBB);
10571
10572 // Insert and MBBs.
10573 MF->insert(MF->end(), DispatchBB);
10574 MF->insert(MF->end(), DispContBB);
10575 MF->insert(MF->end(), TrapBB);
10576
10577 // Insert code into the entry block that creates and registers the function
10578 // context.
10579 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
10580
10581 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
10582 MachinePointerInfo::getFixedStack(*MF, FI),
10583 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, Align(4));
10584
10585 MachineInstrBuilder MIB;
10586 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
10587
10588 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
10589 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
10590
10591 // Add a register mask with no preserved registers. This results in all
10592 // registers being marked as clobbered. This can't work if the dispatch block
10593 // is in a Thumb1 function and is linked with ARM code which uses the FP
10594 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
10595 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
10596
10597 bool IsPositionIndependent = isPositionIndependent();
10598 unsigned NumLPads = LPadList.size();
10599 if (Subtarget->isThumb2()) {
10600 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10601 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
10602 .addFrameIndex(FI)
10603 .addImm(4)
10604 .addMemOperand(FIMMOLd)
10605 .add(predOps(ARMCC::AL));
10606
10607 if (NumLPads < 256) {
10608 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
10609 .addReg(NewVReg1)
10610 .addImm(LPadList.size())
10611 .add(predOps(ARMCC::AL));
10612 } else {
10613 Register VReg1 = MRI->createVirtualRegister(TRC);
10614 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
10615 .addImm(NumLPads & 0xFFFF)
10616 .add(predOps(ARMCC::AL));
10617
10618 unsigned VReg2 = VReg1;
10619 if ((NumLPads & 0xFFFF0000) != 0) {
10620 VReg2 = MRI->createVirtualRegister(TRC);
10621 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
10622 .addReg(VReg1)
10623 .addImm(NumLPads >> 16)
10624 .add(predOps(ARMCC::AL));
10625 }
10626
10627 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
10628 .addReg(NewVReg1)
10629 .addReg(VReg2)
10630 .add(predOps(ARMCC::AL));
10631 }
10632
10633 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
10634 .addMBB(TrapBB)
10635 .addImm(ARMCC::HI)
10636 .addReg(ARM::CPSR);
10637
10638 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10639 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
10640 .addJumpTableIndex(MJTI)
10641 .add(predOps(ARMCC::AL));
10642
10643 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10644 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
10645 .addReg(NewVReg3, RegState::Kill)
10646 .addReg(NewVReg1)
10647 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
10648 .add(predOps(ARMCC::AL))
10649 .add(condCodeOp());
10650
10651 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
10652 .addReg(NewVReg4, RegState::Kill)
10653 .addReg(NewVReg1)
10654 .addJumpTableIndex(MJTI);
10655 } else if (Subtarget->isThumb()) {
10656 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10657 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
10658 .addFrameIndex(FI)
10659 .addImm(1)
10660 .addMemOperand(FIMMOLd)
10661 .add(predOps(ARMCC::AL));
10662
10663 if (NumLPads < 256) {
10664 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
10665 .addReg(NewVReg1)
10666 .addImm(NumLPads)
10667 .add(predOps(ARMCC::AL));
10668 } else {
10669 MachineConstantPool *ConstantPool = MF->getConstantPool();
10670 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10671 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
10672
10673 // MachineConstantPool wants an explicit alignment.
10674 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10675 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10676
10677 Register VReg1 = MRI->createVirtualRegister(TRC);
10678 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
10679 .addReg(VReg1, RegState::Define)
10680 .addConstantPoolIndex(Idx)
10681 .add(predOps(ARMCC::AL));
10682 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
10683 .addReg(NewVReg1)
10684 .addReg(VReg1)
10685 .add(predOps(ARMCC::AL));
10686 }
10687
10688 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
10689 .addMBB(TrapBB)
10690 .addImm(ARMCC::HI)
10691 .addReg(ARM::CPSR);
10692
10693 Register NewVReg2 = MRI->createVirtualRegister(TRC);
10694 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
10695 .addReg(ARM::CPSR, RegState::Define)
10696 .addReg(NewVReg1)
10697 .addImm(2)
10698 .add(predOps(ARMCC::AL));
10699
10700 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10701 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
10702 .addJumpTableIndex(MJTI)
10703 .add(predOps(ARMCC::AL));
10704
10705 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10706 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
10707 .addReg(ARM::CPSR, RegState::Define)
10708 .addReg(NewVReg2, RegState::Kill)
10709 .addReg(NewVReg3)
10710 .add(predOps(ARMCC::AL));
10711
10712 MachineMemOperand *JTMMOLd =
10713 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
10714 MachineMemOperand::MOLoad, 4, Align(4));
10715
10716 Register NewVReg5 = MRI->createVirtualRegister(TRC);
10717 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
10718 .addReg(NewVReg4, RegState::Kill)
10719 .addImm(0)
10720 .addMemOperand(JTMMOLd)
10721 .add(predOps(ARMCC::AL));
10722
10723 unsigned NewVReg6 = NewVReg5;
10724 if (IsPositionIndependent) {
10725 NewVReg6 = MRI->createVirtualRegister(TRC);
10726 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
10727 .addReg(ARM::CPSR, RegState::Define)
10728 .addReg(NewVReg5, RegState::Kill)
10729 .addReg(NewVReg3)
10730 .add(predOps(ARMCC::AL));
10731 }
10732
10733 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
10734 .addReg(NewVReg6, RegState::Kill)
10735 .addJumpTableIndex(MJTI);
10736 } else {
10737 Register NewVReg1 = MRI->createVirtualRegister(TRC);
10738 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
10739 .addFrameIndex(FI)
10740 .addImm(4)
10741 .addMemOperand(FIMMOLd)
10742 .add(predOps(ARMCC::AL));
10743
10744 if (NumLPads < 256) {
10745 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
10746 .addReg(NewVReg1)
10747 .addImm(NumLPads)
10748 .add(predOps(ARMCC::AL));
10749 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
10750 Register VReg1 = MRI->createVirtualRegister(TRC);
10751 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
10752 .addImm(NumLPads & 0xFFFF)
10753 .add(predOps(ARMCC::AL));
10754
10755 unsigned VReg2 = VReg1;
10756 if ((NumLPads & 0xFFFF0000) != 0) {
10757 VReg2 = MRI->createVirtualRegister(TRC);
10758 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
10759 .addReg(VReg1)
10760 .addImm(NumLPads >> 16)
10761 .add(predOps(ARMCC::AL));
10762 }
10763
10764 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
10765 .addReg(NewVReg1)
10766 .addReg(VReg2)
10767 .add(predOps(ARMCC::AL));
10768 } else {
10769 MachineConstantPool *ConstantPool = MF->getConstantPool();
10770 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10771 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
10772
10773 // MachineConstantPool wants an explicit alignment.
10774 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10775 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10776
10777 Register VReg1 = MRI->createVirtualRegister(TRC);
10778 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
10779 .addReg(VReg1, RegState::Define)
10780 .addConstantPoolIndex(Idx)
10781 .addImm(0)
10782 .add(predOps(ARMCC::AL));
10783 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
10784 .addReg(NewVReg1)
10785 .addReg(VReg1, RegState::Kill)
10786 .add(predOps(ARMCC::AL));
10787 }
10788
10789 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
10790 .addMBB(TrapBB)
10791 .addImm(ARMCC::HI)
10792 .addReg(ARM::CPSR);
10793
10794 Register NewVReg3 = MRI->createVirtualRegister(TRC);
10795 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
10796 .addReg(NewVReg1)
10797 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
10798 .add(predOps(ARMCC::AL))
10799 .add(condCodeOp());
10800 Register NewVReg4 = MRI->createVirtualRegister(TRC);
10801 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
10802 .addJumpTableIndex(MJTI)
10803 .add(predOps(ARMCC::AL));
10804
10805 MachineMemOperand *JTMMOLd =
10806 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
10807 MachineMemOperand::MOLoad, 4, Align(4));
10808 Register NewVReg5 = MRI->createVirtualRegister(TRC);
10809 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
10810 .addReg(NewVReg3, RegState::Kill)
10811 .addReg(NewVReg4)
10812 .addImm(0)
10813 .addMemOperand(JTMMOLd)
10814 .add(predOps(ARMCC::AL));
10815
10816 if (IsPositionIndependent) {
10817 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
10818 .addReg(NewVReg5, RegState::Kill)
10819 .addReg(NewVReg4)
10820 .addJumpTableIndex(MJTI);
10821 } else {
10822 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
10823 .addReg(NewVReg5, RegState::Kill)
10824 .addJumpTableIndex(MJTI);
10825 }
10826 }
10827
10828 // Add the jump table entries as successors to the MBB.
10829 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
10830 for (std::vector<MachineBasicBlock*>::iterator
10831 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
10832 MachineBasicBlock *CurMBB = *I;
10833 if (SeenMBBs.insert(CurMBB).second)
10834 DispContBB->addSuccessor(CurMBB);
10835 }
10836
10837 // N.B. the order the invoke BBs are processed in doesn't matter here.
10838 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
10839 SmallVector<MachineBasicBlock*, 64> MBBLPads;
10840 for (MachineBasicBlock *BB : InvokeBBs) {
10841
10842 // Remove the landing pad successor from the invoke block and replace it
10843 // with the new dispatch block.
10844 SmallVector<MachineBasicBlock*, 4> Successors(BB->successors());
10845 while (!Successors.empty()) {
10846 MachineBasicBlock *SMBB = Successors.pop_back_val();
10847 if (SMBB->isEHPad()) {
10848 BB->removeSuccessor(SMBB);
10849 MBBLPads.push_back(SMBB);
10850 }
10851 }
10852
10853 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
10854 BB->normalizeSuccProbs();
10855
10856 // Find the invoke call and mark all of the callee-saved registers as
10857 // 'implicit defined' so that they're spilled. This prevents code from
10858 // moving instructions to before the EH block, where they will never be
10859 // executed.
10860 for (MachineBasicBlock::reverse_iterator
10861 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
10862 if (!II->isCall()) continue;
10863
10864 DenseMap<unsigned, bool> DefRegs;
10865 for (MachineInstr::mop_iterator
10866 OI = II->operands_begin(), OE = II->operands_end();
10867 OI != OE; ++OI) {
10868 if (!OI->isReg()) continue;
10869 DefRegs[OI->getReg()] = true;
10870 }
10871
10872 MachineInstrBuilder MIB(*MF, &*II);
10873
10874 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
10875 unsigned Reg = SavedRegs[i];
10876 if (Subtarget->isThumb2() &&
10877 !ARM::tGPRRegClass.contains(Reg) &&
10878 !ARM::hGPRRegClass.contains(Reg))
10879 continue;
10880 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
10881 continue;
10882 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
10883 continue;
10884 if (!DefRegs[Reg])
10885 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
10886 }
10887
10888 break;
10889 }
10890 }
10891
10892 // Mark all former landing pads as non-landing pads. The dispatch is the only
10893 // landing pad now.
10894 for (SmallVectorImpl<MachineBasicBlock*>::iterator
10895 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
10896 (*I)->setIsEHPad(false);
10897
10898 // The instruction is gone now.
10899 MI.eraseFromParent();
10900}
10901
10902static
10903MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
10904 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
10905 E = MBB->succ_end(); I != E; ++I)
10906 if (*I != Succ)
10907 return *I;
10908 llvm_unreachable("Expecting a BB with two successors!")::llvm::llvm_unreachable_internal("Expecting a BB with two successors!"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10908)
;
10909}
10910
10911/// Return the load opcode for a given load size. If load size >= 8,
10912/// neon opcode will be returned.
10913static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
10914 if (LdSize >= 8)
10915 return LdSize == 16 ? ARM::VLD1q32wb_fixed
10916 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
10917 if (IsThumb1)
10918 return LdSize == 4 ? ARM::tLDRi
10919 : LdSize == 2 ? ARM::tLDRHi
10920 : LdSize == 1 ? ARM::tLDRBi : 0;
10921 if (IsThumb2)
10922 return LdSize == 4 ? ARM::t2LDR_POST
10923 : LdSize == 2 ? ARM::t2LDRH_POST
10924 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
10925 return LdSize == 4 ? ARM::LDR_POST_IMM
10926 : LdSize == 2 ? ARM::LDRH_POST
10927 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
10928}
10929
10930/// Return the store opcode for a given store size. If store size >= 8,
10931/// neon opcode will be returned.
10932static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
10933 if (StSize >= 8)
10934 return StSize == 16 ? ARM::VST1q32wb_fixed
10935 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
10936 if (IsThumb1)
10937 return StSize == 4 ? ARM::tSTRi
10938 : StSize == 2 ? ARM::tSTRHi
10939 : StSize == 1 ? ARM::tSTRBi : 0;
10940 if (IsThumb2)
10941 return StSize == 4 ? ARM::t2STR_POST
10942 : StSize == 2 ? ARM::t2STRH_POST
10943 : StSize == 1 ? ARM::t2STRB_POST : 0;
10944 return StSize == 4 ? ARM::STR_POST_IMM
10945 : StSize == 2 ? ARM::STRH_POST
10946 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
10947}
10948
10949/// Emit a post-increment load operation with given size. The instructions
10950/// will be added to BB at Pos.
10951static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
10952 const TargetInstrInfo *TII, const DebugLoc &dl,
10953 unsigned LdSize, unsigned Data, unsigned AddrIn,
10954 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
10955 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
10956 assert(LdOpc != 0 && "Should have a load opcode")(static_cast <bool> (LdOpc != 0 && "Should have a load opcode"
) ? void (0) : __assert_fail ("LdOpc != 0 && \"Should have a load opcode\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10956, __extension__ __PRETTY_FUNCTION__))
;
10957 if (LdSize >= 8) {
10958 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10959 .addReg(AddrOut, RegState::Define)
10960 .addReg(AddrIn)
10961 .addImm(0)
10962 .add(predOps(ARMCC::AL));
10963 } else if (IsThumb1) {
10964 // load + update AddrIn
10965 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10966 .addReg(AddrIn)
10967 .addImm(0)
10968 .add(predOps(ARMCC::AL));
10969 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
10970 .add(t1CondCodeOp())
10971 .addReg(AddrIn)
10972 .addImm(LdSize)
10973 .add(predOps(ARMCC::AL));
10974 } else if (IsThumb2) {
10975 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10976 .addReg(AddrOut, RegState::Define)
10977 .addReg(AddrIn)
10978 .addImm(LdSize)
10979 .add(predOps(ARMCC::AL));
10980 } else { // arm
10981 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10982 .addReg(AddrOut, RegState::Define)
10983 .addReg(AddrIn)
10984 .addReg(0)
10985 .addImm(LdSize)
10986 .add(predOps(ARMCC::AL));
10987 }
10988}
10989
10990/// Emit a post-increment store operation with given size. The instructions
10991/// will be added to BB at Pos.
10992static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
10993 const TargetInstrInfo *TII, const DebugLoc &dl,
10994 unsigned StSize, unsigned Data, unsigned AddrIn,
10995 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
10996 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
10997 assert(StOpc != 0 && "Should have a store opcode")(static_cast <bool> (StOpc != 0 && "Should have a store opcode"
) ? void (0) : __assert_fail ("StOpc != 0 && \"Should have a store opcode\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 10997, __extension__ __PRETTY_FUNCTION__))
;
10998 if (StSize >= 8) {
10999 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11000 .addReg(AddrIn)
11001 .addImm(0)
11002 .addReg(Data)
11003 .add(predOps(ARMCC::AL));
11004 } else if (IsThumb1) {
11005 // store + update AddrIn
11006 BuildMI(*BB, Pos, dl, TII->get(StOpc))
11007 .addReg(Data)
11008 .addReg(AddrIn)
11009 .addImm(0)
11010 .add(predOps(ARMCC::AL));
11011 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
11012 .add(t1CondCodeOp())
11013 .addReg(AddrIn)
11014 .addImm(StSize)
11015 .add(predOps(ARMCC::AL));
11016 } else if (IsThumb2) {
11017 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11018 .addReg(Data)
11019 .addReg(AddrIn)
11020 .addImm(StSize)
11021 .add(predOps(ARMCC::AL));
11022 } else { // arm
11023 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11024 .addReg(Data)
11025 .addReg(AddrIn)
11026 .addReg(0)
11027 .addImm(StSize)
11028 .add(predOps(ARMCC::AL));
11029 }
11030}
11031
11032MachineBasicBlock *
11033ARMTargetLowering::EmitStructByval(MachineInstr &MI,
11034 MachineBasicBlock *BB) const {
11035 // This pseudo instruction has 3 operands: dst, src, size
11036 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
11037 // Otherwise, we will generate unrolled scalar copies.
11038 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11039 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11040 MachineFunction::iterator It = ++BB->getIterator();
11041
11042 Register dest = MI.getOperand(0).getReg();
11043 Register src = MI.getOperand(1).getReg();
11044 unsigned SizeVal = MI.getOperand(2).getImm();
11045 unsigned Alignment = MI.getOperand(3).getImm();
11046 DebugLoc dl = MI.getDebugLoc();
11047
11048 MachineFunction *MF = BB->getParent();
11049 MachineRegisterInfo &MRI = MF->getRegInfo();
11050 unsigned UnitSize = 0;
11051 const TargetRegisterClass *TRC = nullptr;
11052 const TargetRegisterClass *VecTRC = nullptr;
11053
11054 bool IsThumb1 = Subtarget->isThumb1Only();
11055 bool IsThumb2 = Subtarget->isThumb2();
11056 bool IsThumb = Subtarget->isThumb();
11057
11058 if (Alignment & 1) {
11059 UnitSize = 1;
11060 } else if (Alignment & 2) {
11061 UnitSize = 2;
11062 } else {
11063 // Check whether we can use NEON instructions.
11064 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
11065 Subtarget->hasNEON()) {
11066 if ((Alignment % 16 == 0) && SizeVal >= 16)
11067 UnitSize = 16;
11068 else if ((Alignment % 8 == 0) && SizeVal >= 8)
11069 UnitSize = 8;
11070 }
11071 // Can't use NEON instructions.
11072 if (UnitSize == 0)
11073 UnitSize = 4;
11074 }
11075
11076 // Select the correct opcode and register class for unit size load/store
11077 bool IsNeon = UnitSize >= 8;
11078 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
11079 if (IsNeon)
11080 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
11081 : UnitSize == 8 ? &ARM::DPRRegClass
11082 : nullptr;
11083
11084 unsigned BytesLeft = SizeVal % UnitSize;
11085 unsigned LoopSize = SizeVal - BytesLeft;
11086
11087 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
11088 // Use LDR and STR to copy.
11089 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
11090 // [destOut] = STR_POST(scratch, destIn, UnitSize)
11091 unsigned srcIn = src;
11092 unsigned destIn = dest;
11093 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
11094 Register srcOut = MRI.createVirtualRegister(TRC);
11095 Register destOut = MRI.createVirtualRegister(TRC);
11096 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
11097 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
11098 IsThumb1, IsThumb2);
11099 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
11100 IsThumb1, IsThumb2);
11101 srcIn = srcOut;
11102 destIn = destOut;
11103 }
11104
11105 // Handle the leftover bytes with LDRB and STRB.
11106 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
11107 // [destOut] = STRB_POST(scratch, destIn, 1)
11108 for (unsigned i = 0; i < BytesLeft; i++) {
11109 Register srcOut = MRI.createVirtualRegister(TRC);
11110 Register destOut = MRI.createVirtualRegister(TRC);
11111 Register scratch = MRI.createVirtualRegister(TRC);
11112 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
11113 IsThumb1, IsThumb2);
11114 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
11115 IsThumb1, IsThumb2);
11116 srcIn = srcOut;
11117 destIn = destOut;
11118 }
11119 MI.eraseFromParent(); // The instruction is gone now.
11120 return BB;
11121 }
11122
11123 // Expand the pseudo op to a loop.
11124 // thisMBB:
11125 // ...
11126 // movw varEnd, # --> with thumb2
11127 // movt varEnd, #
11128 // ldrcp varEnd, idx --> without thumb2
11129 // fallthrough --> loopMBB
11130 // loopMBB:
11131 // PHI varPhi, varEnd, varLoop
11132 // PHI srcPhi, src, srcLoop
11133 // PHI destPhi, dst, destLoop
11134 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
11135 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
11136 // subs varLoop, varPhi, #UnitSize
11137 // bne loopMBB
11138 // fallthrough --> exitMBB
11139 // exitMBB:
11140 // epilogue to handle left-over bytes
11141 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
11142 // [destOut] = STRB_POST(scratch, destLoop, 1)
11143 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11144 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11145 MF->insert(It, loopMBB);
11146 MF->insert(It, exitMBB);
11147
11148 // Transfer the remainder of BB and its successor edges to exitMBB.
11149 exitMBB->splice(exitMBB->begin(), BB,
11150 std::next(MachineBasicBlock::iterator(MI)), BB->end());
11151 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11152
11153 // Load an immediate to varEnd.
11154 Register varEnd = MRI.createVirtualRegister(TRC);
11155 if (Subtarget->useMovt()) {
11156 unsigned Vtmp = varEnd;
11157 if ((LoopSize & 0xFFFF0000) != 0)
11158 Vtmp = MRI.createVirtualRegister(TRC);
11159 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
11160 .addImm(LoopSize & 0xFFFF)
11161 .add(predOps(ARMCC::AL));
11162
11163 if ((LoopSize & 0xFFFF0000) != 0)
11164 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
11165 .addReg(Vtmp)
11166 .addImm(LoopSize >> 16)
11167 .add(predOps(ARMCC::AL));
11168 } else {
11169 MachineConstantPool *ConstantPool = MF->getConstantPool();
11170 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
11171 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
11172
11173 // MachineConstantPool wants an explicit alignment.
11174 Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
11175 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
11176 MachineMemOperand *CPMMO =
11177 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
11178 MachineMemOperand::MOLoad, 4, Align(4));
11179
11180 if (IsThumb)
11181 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
11182 .addReg(varEnd, RegState::Define)
11183 .addConstantPoolIndex(Idx)
11184 .add(predOps(ARMCC::AL))
11185 .addMemOperand(CPMMO);
11186 else
11187 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
11188 .addReg(varEnd, RegState::Define)
11189 .addConstantPoolIndex(Idx)
11190 .addImm(0)
11191 .add(predOps(ARMCC::AL))
11192 .addMemOperand(CPMMO);
11193 }
11194 BB->addSuccessor(loopMBB);
11195
11196 // Generate the loop body:
11197 // varPhi = PHI(varLoop, varEnd)
11198 // srcPhi = PHI(srcLoop, src)
11199 // destPhi = PHI(destLoop, dst)
11200 MachineBasicBlock *entryBB = BB;
11201 BB = loopMBB;
11202 Register varLoop = MRI.createVirtualRegister(TRC);
11203 Register varPhi = MRI.createVirtualRegister(TRC);
11204 Register srcLoop = MRI.createVirtualRegister(TRC);
11205 Register srcPhi = MRI.createVirtualRegister(TRC);
11206 Register destLoop = MRI.createVirtualRegister(TRC);
11207 Register destPhi = MRI.createVirtualRegister(TRC);
11208
11209 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
11210 .addReg(varLoop).addMBB(loopMBB)
11211 .addReg(varEnd).addMBB(entryBB);
11212 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
11213 .addReg(srcLoop).addMBB(loopMBB)
11214 .addReg(src).addMBB(entryBB);
11215 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
11216 .addReg(destLoop).addMBB(loopMBB)
11217 .addReg(dest).addMBB(entryBB);
11218
11219 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
11220 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
11221 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
11222 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
11223 IsThumb1, IsThumb2);
11224 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
11225 IsThumb1, IsThumb2);
11226
11227 // Decrement loop variable by UnitSize.
11228 if (IsThumb1) {
11229 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
11230 .add(t1CondCodeOp())
11231 .addReg(varPhi)
11232 .addImm(UnitSize)
11233 .add(predOps(ARMCC::AL));
11234 } else {
11235 MachineInstrBuilder MIB =
11236 BuildMI(*BB, BB->end(), dl,
11237 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
11238 MIB.addReg(varPhi)
11239 .addImm(UnitSize)
11240 .add(predOps(ARMCC::AL))
11241 .add(condCodeOp());
11242 MIB->getOperand(5).setReg(ARM::CPSR);
11243 MIB->getOperand(5).setIsDef(true);
11244 }
11245 BuildMI(*BB, BB->end(), dl,
11246 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
11247 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
11248
11249 // loopMBB can loop back to loopMBB or fall through to exitMBB.
11250 BB->addSuccessor(loopMBB);
11251 BB->addSuccessor(exitMBB);
11252
11253 // Add epilogue to handle BytesLeft.
11254 BB = exitMBB;
11255 auto StartOfExit = exitMBB->begin();
11256
11257 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
11258 // [destOut] = STRB_POST(scratch, destLoop, 1)
11259 unsigned srcIn = srcLoop;
11260 unsigned destIn = destLoop;
11261 for (unsigned i = 0; i < BytesLeft; i++) {
11262 Register srcOut = MRI.createVirtualRegister(TRC);
11263 Register destOut = MRI.createVirtualRegister(TRC);
11264 Register scratch = MRI.createVirtualRegister(TRC);
11265 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
11266 IsThumb1, IsThumb2);
11267 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
11268 IsThumb1, IsThumb2);
11269 srcIn = srcOut;
11270 destIn = destOut;
11271 }
11272
11273 MI.eraseFromParent(); // The instruction is gone now.
11274 return BB;
11275}
11276
11277MachineBasicBlock *
11278ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
11279 MachineBasicBlock *MBB) const {
11280 const TargetMachine &TM = getTargetMachine();
11281 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
11282 DebugLoc DL = MI.getDebugLoc();
11283
11284 assert(Subtarget->isTargetWindows() &&(static_cast <bool> (Subtarget->isTargetWindows() &&
"__chkstk is only supported on Windows") ? void (0) : __assert_fail
("Subtarget->isTargetWindows() && \"__chkstk is only supported on Windows\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11285, __extension__ __PRETTY_FUNCTION__))
11285 "__chkstk is only supported on Windows")(static_cast <bool> (Subtarget->isTargetWindows() &&
"__chkstk is only supported on Windows") ? void (0) : __assert_fail
("Subtarget->isTargetWindows() && \"__chkstk is only supported on Windows\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11285, __extension__ __PRETTY_FUNCTION__))
;
11286 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode")(static_cast <bool> (Subtarget->isThumb2() &&
"Windows on ARM requires Thumb-2 mode") ? void (0) : __assert_fail
("Subtarget->isThumb2() && \"Windows on ARM requires Thumb-2 mode\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11286, __extension__ __PRETTY_FUNCTION__))
;
11287
11288 // __chkstk takes the number of words to allocate on the stack in R4, and
11289 // returns the stack adjustment in number of bytes in R4. This will not
11290 // clober any other registers (other than the obvious lr).
11291 //
11292 // Although, technically, IP should be considered a register which may be
11293 // clobbered, the call itself will not touch it. Windows on ARM is a pure
11294 // thumb-2 environment, so there is no interworking required. As a result, we
11295 // do not expect a veneer to be emitted by the linker, clobbering IP.
11296 //
11297 // Each module receives its own copy of __chkstk, so no import thunk is
11298 // required, again, ensuring that IP is not clobbered.
11299 //
11300 // Finally, although some linkers may theoretically provide a trampoline for
11301 // out of range calls (which is quite common due to a 32M range limitation of
11302 // branches for Thumb), we can generate the long-call version via
11303 // -mcmodel=large, alleviating the need for the trampoline which may clobber
11304 // IP.
11305
11306 switch (TM.getCodeModel()) {
11307 case CodeModel::Tiny:
11308 llvm_unreachable("Tiny code model not available on ARM.")::llvm::llvm_unreachable_internal("Tiny code model not available on ARM."
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11308)
;
11309 case CodeModel::Small:
11310 case CodeModel::Medium:
11311 case CodeModel::Kernel:
11312 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
11313 .add(predOps(ARMCC::AL))
11314 .addExternalSymbol("__chkstk")
11315 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
11316 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
11317 .addReg(ARM::R12,
11318 RegState::Implicit | RegState::Define | RegState::Dead)
11319 .addReg(ARM::CPSR,
11320 RegState::Implicit | RegState::Define | RegState::Dead);
11321 break;
11322 case CodeModel::Large: {
11323 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11324 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11325
11326 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
11327 .addExternalSymbol("__chkstk");
11328 BuildMI(*MBB, MI, DL, TII.get(gettBLXrOpcode(*MBB->getParent())))
11329 .add(predOps(ARMCC::AL))
11330 .addReg(Reg, RegState::Kill)
11331 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
11332 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
11333 .addReg(ARM::R12,
11334 RegState::Implicit | RegState::Define | RegState::Dead)
11335 .addReg(ARM::CPSR,
11336 RegState::Implicit | RegState::Define | RegState::Dead);
11337 break;
11338 }
11339 }
11340
11341 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
11342 .addReg(ARM::SP, RegState::Kill)
11343 .addReg(ARM::R4, RegState::Kill)
11344 .setMIFlags(MachineInstr::FrameSetup)
11345 .add(predOps(ARMCC::AL))
11346 .add(condCodeOp());
11347
11348 MI.eraseFromParent();
11349 return MBB;
11350}
11351
11352MachineBasicBlock *
11353ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
11354 MachineBasicBlock *MBB) const {
11355 DebugLoc DL = MI.getDebugLoc();
11356 MachineFunction *MF = MBB->getParent();
11357 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11358
11359 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
11360 MF->insert(++MBB->getIterator(), ContBB);
11361 ContBB->splice(ContBB->begin(), MBB,
11362 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11363 ContBB->transferSuccessorsAndUpdatePHIs(MBB);
11364 MBB->addSuccessor(ContBB);
11365
11366 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
11367 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
11368 MF->push_back(TrapBB);
11369 MBB->addSuccessor(TrapBB);
11370
11371 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
11372 .addReg(MI.getOperand(0).getReg())
11373 .addImm(0)
11374 .add(predOps(ARMCC::AL));
11375 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
11376 .addMBB(TrapBB)
11377 .addImm(ARMCC::EQ)
11378 .addReg(ARM::CPSR);
11379
11380 MI.eraseFromParent();
11381 return ContBB;
11382}
11383
11384// The CPSR operand of SelectItr might be missing a kill marker
11385// because there were multiple uses of CPSR, and ISel didn't know
11386// which to mark. Figure out whether SelectItr should have had a
11387// kill marker, and set it if it should. Returns the correct kill
11388// marker value.
11389static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
11390 MachineBasicBlock* BB,
11391 const TargetRegisterInfo* TRI) {
11392 // Scan forward through BB for a use/def of CPSR.
11393 MachineBasicBlock::iterator miI(std::next(SelectItr));
11394 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
11395 const MachineInstr& mi = *miI;
11396 if (mi.readsRegister(ARM::CPSR))
11397 return false;
11398 if (mi.definesRegister(ARM::CPSR))
11399 break; // Should have kill-flag - update below.
11400 }
11401
11402 // If we hit the end of the block, check whether CPSR is live into a
11403 // successor.
11404 if (miI == BB->end()) {
11405 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
11406 sEnd = BB->succ_end();
11407 sItr != sEnd; ++sItr) {
11408 MachineBasicBlock* succ = *sItr;
11409 if (succ->isLiveIn(ARM::CPSR))
11410 return false;
11411 }
11412 }
11413
11414 // We found a def, or hit the end of the basic block and CPSR wasn't live
11415 // out. SelectMI should have a kill flag on CPSR.
11416 SelectItr->addRegisterKilled(ARM::CPSR, TRI);
11417 return true;
11418}
11419
11420/// Adds logic in loop entry MBB to calculate loop iteration count and adds
11421/// t2WhileLoopSetup and t2WhileLoopStart to generate WLS loop
11422static Register genTPEntry(MachineBasicBlock *TpEntry,
11423 MachineBasicBlock *TpLoopBody,
11424 MachineBasicBlock *TpExit, Register OpSizeReg,
11425 const TargetInstrInfo *TII, DebugLoc Dl,
11426 MachineRegisterInfo &MRI) {
11427 // Calculates loop iteration count = ceil(n/16) = (n + 15) >> 4.
11428 Register AddDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11429 BuildMI(TpEntry, Dl, TII->get(ARM::t2ADDri), AddDestReg)
11430 .addUse(OpSizeReg)
11431 .addImm(15)
11432 .add(predOps(ARMCC::AL))
11433 .addReg(0);
11434
11435 Register LsrDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11436 BuildMI(TpEntry, Dl, TII->get(ARM::t2LSRri), LsrDestReg)
11437 .addUse(AddDestReg, RegState::Kill)
11438 .addImm(4)
11439 .add(predOps(ARMCC::AL))
11440 .addReg(0);
11441
11442 Register TotalIterationsReg = MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11443 BuildMI(TpEntry, Dl, TII->get(ARM::t2WhileLoopSetup), TotalIterationsReg)
11444 .addUse(LsrDestReg, RegState::Kill);
11445
11446 BuildMI(TpEntry, Dl, TII->get(ARM::t2WhileLoopStart))
11447 .addUse(TotalIterationsReg)
11448 .addMBB(TpExit);
11449
11450 BuildMI(TpEntry, Dl, TII->get(ARM::t2B))
11451 .addMBB(TpLoopBody)
11452 .add(predOps(ARMCC::AL));
11453
11454 return TotalIterationsReg;
11455}
11456
11457/// Adds logic in the loopBody MBB to generate MVE_VCTP, t2DoLoopDec and
11458/// t2DoLoopEnd. These are used by later passes to generate tail predicated
11459/// loops.
11460static void genTPLoopBody(MachineBasicBlock *TpLoopBody,
11461 MachineBasicBlock *TpEntry, MachineBasicBlock *TpExit,
11462 const TargetInstrInfo *TII, DebugLoc Dl,
11463 MachineRegisterInfo &MRI, Register OpSrcReg,
11464 Register OpDestReg, Register ElementCountReg,
11465 Register TotalIterationsReg, bool IsMemcpy) {
11466 // First insert 4 PHI nodes for: Current pointer to Src (if memcpy), Dest
11467 // array, loop iteration counter, predication counter.
11468
11469 Register SrcPhiReg, CurrSrcReg;
11470 if (IsMemcpy) {
11471 // Current position in the src array
11472 SrcPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11473 CurrSrcReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11474 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), SrcPhiReg)
11475 .addUse(OpSrcReg)
11476 .addMBB(TpEntry)
11477 .addUse(CurrSrcReg)
11478 .addMBB(TpLoopBody);
11479 }
11480
11481 // Current position in the dest array
11482 Register DestPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11483 Register CurrDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11484 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), DestPhiReg)
11485 .addUse(OpDestReg)
11486 .addMBB(TpEntry)
11487 .addUse(CurrDestReg)
11488 .addMBB(TpLoopBody);
11489
11490 // Current loop counter
11491 Register LoopCounterPhiReg = MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11492 Register RemainingLoopIterationsReg =
11493 MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11494 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), LoopCounterPhiReg)
11495 .addUse(TotalIterationsReg)
11496 .addMBB(TpEntry)
11497 .addUse(RemainingLoopIterationsReg)
11498 .addMBB(TpLoopBody);
11499
11500 // Predication counter
11501 Register PredCounterPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11502 Register RemainingElementsReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11503 BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), PredCounterPhiReg)
11504 .addUse(ElementCountReg)
11505 .addMBB(TpEntry)
11506 .addUse(RemainingElementsReg)
11507 .addMBB(TpLoopBody);
11508
11509 // Pass predication counter to VCTP
11510 Register VccrReg = MRI.createVirtualRegister(&ARM::VCCRRegClass);
11511 BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VCTP8), VccrReg)
11512 .addUse(PredCounterPhiReg)
11513 .addImm(ARMVCC::None)
11514 .addReg(0);
11515
11516 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2SUBri), RemainingElementsReg)
11517 .addUse(PredCounterPhiReg)
11518 .addImm(16)
11519 .add(predOps(ARMCC::AL))
11520 .addReg(0);
11521
11522 // VLDRB (only if memcpy) and VSTRB instructions, predicated using VPR
11523 Register SrcValueReg;
11524 if (IsMemcpy) {
11525 SrcValueReg = MRI.createVirtualRegister(&ARM::MQPRRegClass);
11526 BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VLDRBU8_post))
11527 .addDef(CurrSrcReg)
11528 .addDef(SrcValueReg)
11529 .addReg(SrcPhiReg)
11530 .addImm(16)
11531 .addImm(ARMVCC::Then)
11532 .addUse(VccrReg);
11533 } else
11534 SrcValueReg = OpSrcReg;
11535
11536 BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VSTRBU8_post))
11537 .addDef(CurrDestReg)
11538 .addUse(SrcValueReg)
11539 .addReg(DestPhiReg)
11540 .addImm(16)
11541 .addImm(ARMVCC::Then)
11542 .addUse(VccrReg);
11543
11544 // Add the pseudoInstrs for decrementing the loop counter and marking the
11545 // end:t2DoLoopDec and t2DoLoopEnd
11546 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2LoopDec), RemainingLoopIterationsReg)
11547 .addUse(LoopCounterPhiReg)
11548 .addImm(1);
11549
11550 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2LoopEnd))
11551 .addUse(RemainingLoopIterationsReg)
11552 .addMBB(TpLoopBody);
11553
11554 BuildMI(TpLoopBody, Dl, TII->get(ARM::t2B))
11555 .addMBB(TpExit)
11556 .add(predOps(ARMCC::AL));
11557}
11558
11559MachineBasicBlock *
11560ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11561 MachineBasicBlock *BB) const {
11562 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11563 DebugLoc dl = MI.getDebugLoc();
11564 bool isThumb2 = Subtarget->isThumb2();
11565 switch (MI.getOpcode()) {
11566 default: {
11567 MI.print(errs());
11568 llvm_unreachable("Unexpected instr type to insert")::llvm::llvm_unreachable_internal("Unexpected instr type to insert"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11568)
;
11569 }
11570
11571 // Thumb1 post-indexed loads are really just single-register LDMs.
11572 case ARM::tLDR_postidx: {
11573 MachineOperand Def(MI.getOperand(1));
11574 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
11575 .add(Def) // Rn_wb
11576 .add(MI.getOperand(2)) // Rn
11577 .add(MI.getOperand(3)) // PredImm
11578 .add(MI.getOperand(4)) // PredReg
11579 .add(MI.getOperand(0)) // Rt
11580 .cloneMemRefs(MI);
11581 MI.eraseFromParent();
11582 return BB;
11583 }
11584
11585 case ARM::MVE_MEMCPYLOOPINST:
11586 case ARM::MVE_MEMSETLOOPINST: {
11587
11588 // Transformation below expands MVE_MEMCPYLOOPINST/MVE_MEMSETLOOPINST Pseudo
11589 // into a Tail Predicated (TP) Loop. It adds the instructions to calculate
11590 // the iteration count =ceil(size_in_bytes/16)) in the TP entry block and
11591 // adds the relevant instructions in the TP loop Body for generation of a
11592 // WLSTP loop.
11593
11594 // Below is relevant portion of the CFG after the transformation.
11595 // The Machine Basic Blocks are shown along with branch conditions (in
11596 // brackets). Note that TP entry/exit MBBs depict the entry/exit of this
11597 // portion of the CFG and may not necessarily be the entry/exit of the
11598 // function.
11599
11600 // (Relevant) CFG after transformation:
11601 // TP entry MBB
11602 // |
11603 // |-----------------|
11604 // (n <= 0) (n > 0)
11605 // | |
11606 // | TP loop Body MBB<--|
11607 // | | |
11608 // \ |___________|
11609 // \ /
11610 // TP exit MBB
11611
11612 MachineFunction *MF = BB->getParent();
11613 MachineFunctionProperties &Properties = MF->getProperties();
11614 MachineRegisterInfo &MRI = MF->getRegInfo();
11615
11616 Register OpDestReg = MI.getOperand(0).getReg();
11617 Register OpSrcReg = MI.getOperand(1).getReg();
11618 Register OpSizeReg = MI.getOperand(2).getReg();
11619
11620 // Allocate the required MBBs and add to parent function.
11621 MachineBasicBlock *TpEntry = BB;
11622 MachineBasicBlock *TpLoopBody = MF->CreateMachineBasicBlock();
11623 MachineBasicBlock *TpExit;
11624
11625 MF->push_back(TpLoopBody);
11626
11627 // If any instructions are present in the current block after
11628 // MVE_MEMCPYLOOPINST or MVE_MEMSETLOOPINST, split the current block and
11629 // move the instructions into the newly created exit block. If there are no
11630 // instructions add an explicit branch to the FallThrough block and then
11631 // split.
11632 //
11633 // The split is required for two reasons:
11634 // 1) A terminator(t2WhileLoopStart) will be placed at that site.
11635 // 2) Since a TPLoopBody will be added later, any phis in successive blocks
11636 // need to be updated. splitAt() already handles this.
11637 TpExit = BB->splitAt(MI, false);
11638 if (TpExit == BB) {
11639 assert(BB->canFallThrough() && "Exit Block must be Fallthrough of the "(static_cast <bool> (BB->canFallThrough() &&
"Exit Block must be Fallthrough of the " "block containing memcpy/memset Pseudo"
) ? void (0) : __assert_fail ("BB->canFallThrough() && \"Exit Block must be Fallthrough of the \" \"block containing memcpy/memset Pseudo\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11640, __extension__ __PRETTY_FUNCTION__))
11640 "block containing memcpy/memset Pseudo")(static_cast <bool> (BB->canFallThrough() &&
"Exit Block must be Fallthrough of the " "block containing memcpy/memset Pseudo"
) ? void (0) : __assert_fail ("BB->canFallThrough() && \"Exit Block must be Fallthrough of the \" \"block containing memcpy/memset Pseudo\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11640, __extension__ __PRETTY_FUNCTION__))
;
11641 TpExit = BB->getFallThrough();
11642 BuildMI(BB, dl, TII->get(ARM::t2B))
11643 .addMBB(TpExit)
11644 .add(predOps(ARMCC::AL));
11645 TpExit = BB->splitAt(MI, false);
11646 }
11647
11648 // Add logic for iteration count
11649 Register TotalIterationsReg =
11650 genTPEntry(TpEntry, TpLoopBody, TpExit, OpSizeReg, TII, dl, MRI);
11651
11652 // Add the vectorized (and predicated) loads/store instructions
11653 bool IsMemcpy = MI.getOpcode() == ARM::MVE_MEMCPYLOOPINST;
11654 genTPLoopBody(TpLoopBody, TpEntry, TpExit, TII, dl, MRI, OpSrcReg,
11655 OpDestReg, OpSizeReg, TotalIterationsReg, IsMemcpy);
11656
11657 // Required to avoid conflict with the MachineVerifier during testing.
11658 Properties.reset(MachineFunctionProperties::Property::NoPHIs);
11659
11660 // Connect the blocks
11661 TpEntry->addSuccessor(TpLoopBody);
11662 TpLoopBody->addSuccessor(TpLoopBody);
11663 TpLoopBody->addSuccessor(TpExit);
11664
11665 // Reorder for a more natural layout
11666 TpLoopBody->moveAfter(TpEntry);
11667 TpExit->moveAfter(TpLoopBody);
11668
11669 // Finally, remove the memcpy Psuedo Instruction
11670 MI.eraseFromParent();
11671
11672 // Return the exit block as it may contain other instructions requiring a
11673 // custom inserter
11674 return TpExit;
11675 }
11676
11677 // The Thumb2 pre-indexed stores have the same MI operands, they just
11678 // define them differently in the .td files from the isel patterns, so
11679 // they need pseudos.
11680 case ARM::t2STR_preidx:
11681 MI.setDesc(TII->get(ARM::t2STR_PRE));
11682 return BB;
11683 case ARM::t2STRB_preidx:
11684 MI.setDesc(TII->get(ARM::t2STRB_PRE));
11685 return BB;
11686 case ARM::t2STRH_preidx:
11687 MI.setDesc(TII->get(ARM::t2STRH_PRE));
11688 return BB;
11689
11690 case ARM::STRi_preidx:
11691 case ARM::STRBi_preidx: {
11692 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
11693 : ARM::STRB_PRE_IMM;
11694 // Decode the offset.
11695 unsigned Offset = MI.getOperand(4).getImm();
11696 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
11697 Offset = ARM_AM::getAM2Offset(Offset);
11698 if (isSub)
11699 Offset = -Offset;
11700
11701 MachineMemOperand *MMO = *MI.memoperands_begin();
11702 BuildMI(*BB, MI, dl, TII->get(NewOpc))
11703 .add(MI.getOperand(0)) // Rn_wb
11704 .add(MI.getOperand(1)) // Rt
11705 .add(MI.getOperand(2)) // Rn
11706 .addImm(Offset) // offset (skip GPR==zero_reg)
11707 .add(MI.getOperand(5)) // pred
11708 .add(MI.getOperand(6))
11709 .addMemOperand(MMO);
11710 MI.eraseFromParent();
11711 return BB;
11712 }
11713 case ARM::STRr_preidx:
11714 case ARM::STRBr_preidx:
11715 case ARM::STRH_preidx: {
11716 unsigned NewOpc;
11717 switch (MI.getOpcode()) {
11718 default: llvm_unreachable("unexpected opcode!")::llvm::llvm_unreachable_internal("unexpected opcode!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11718)
;
11719 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
11720 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
11721 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
11722 }
11723 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
11724 for (unsigned i = 0; i < MI.getNumOperands(); ++i)
11725 MIB.add(MI.getOperand(i));
11726 MI.eraseFromParent();
11727 return BB;
11728 }
11729
11730 case ARM::tMOVCCr_pseudo: {
11731 // To "insert" a SELECT_CC instruction, we actually have to insert the
11732 // diamond control-flow pattern. The incoming instruction knows the
11733 // destination vreg to set, the condition code register to branch on, the
11734 // true/false values to select between, and a branch opcode to use.
11735 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11736 MachineFunction::iterator It = ++BB->getIterator();
11737
11738 // thisMBB:
11739 // ...
11740 // TrueVal = ...
11741 // cmpTY ccX, r1, r2
11742 // bCC copy1MBB
11743 // fallthrough --> copy0MBB
11744 MachineBasicBlock *thisMBB = BB;
11745 MachineFunction *F = BB->getParent();
11746 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11747 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11748 F->insert(It, copy0MBB);
11749 F->insert(It, sinkMBB);
11750
11751 // Check whether CPSR is live past the tMOVCCr_pseudo.
11752 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
11753 if (!MI.killsRegister(ARM::CPSR) &&
11754 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
11755 copy0MBB->addLiveIn(ARM::CPSR);
11756 sinkMBB->addLiveIn(ARM::CPSR);
11757 }
11758
11759 // Transfer the remainder of BB and its successor edges to sinkMBB.
11760 sinkMBB->splice(sinkMBB->begin(), BB,
11761 std::next(MachineBasicBlock::iterator(MI)), BB->end());
11762 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11763
11764 BB->addSuccessor(copy0MBB);
11765 BB->addSuccessor(sinkMBB);
11766
11767 BuildMI(BB, dl, TII->get(ARM::tBcc))
11768 .addMBB(sinkMBB)
11769 .addImm(MI.getOperand(3).getImm())
11770 .addReg(MI.getOperand(4).getReg());
11771
11772 // copy0MBB:
11773 // %FalseValue = ...
11774 // # fallthrough to sinkMBB
11775 BB = copy0MBB;
11776
11777 // Update machine-CFG edges
11778 BB->addSuccessor(sinkMBB);
11779
11780 // sinkMBB:
11781 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11782 // ...
11783 BB = sinkMBB;
11784 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
11785 .addReg(MI.getOperand(1).getReg())
11786 .addMBB(copy0MBB)
11787 .addReg(MI.getOperand(2).getReg())
11788 .addMBB(thisMBB);
11789
11790 MI.eraseFromParent(); // The pseudo instruction is gone now.
11791 return BB;
11792 }
11793
11794 case ARM::BCCi64:
11795 case ARM::BCCZi64: {
11796 // If there is an unconditional branch to the other successor, remove it.
11797 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
11798
11799 // Compare both parts that make up the double comparison separately for
11800 // equality.
11801 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
11802
11803 Register LHS1 = MI.getOperand(1).getReg();
11804 Register LHS2 = MI.getOperand(2).getReg();
11805 if (RHSisZero) {
11806 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
11807 .addReg(LHS1)
11808 .addImm(0)
11809 .add(predOps(ARMCC::AL));
11810 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
11811 .addReg(LHS2).addImm(0)
11812 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
11813 } else {
11814 Register RHS1 = MI.getOperand(3).getReg();
11815 Register RHS2 = MI.getOperand(4).getReg();
11816 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
11817 .addReg(LHS1)
11818 .addReg(RHS1)
11819 .add(predOps(ARMCC::AL));
11820 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
11821 .addReg(LHS2).addReg(RHS2)
11822 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
11823 }
11824
11825 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
11826 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
11827 if (MI.getOperand(0).getImm() == ARMCC::NE)
11828 std::swap(destMBB, exitMBB);
11829
11830 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
11831 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
11832 if (isThumb2)
11833 BuildMI(BB, dl, TII->get(ARM::t2B))
11834 .addMBB(exitMBB)
11835 .add(predOps(ARMCC::AL));
11836 else
11837 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
11838
11839 MI.eraseFromParent(); // The pseudo instruction is gone now.
11840 return BB;
11841 }
11842
11843 case ARM::Int_eh_sjlj_setjmp:
11844 case ARM::Int_eh_sjlj_setjmp_nofp:
11845 case ARM::tInt_eh_sjlj_setjmp:
11846 case ARM::t2Int_eh_sjlj_setjmp:
11847 case ARM::t2Int_eh_sjlj_setjmp_nofp:
11848 return BB;
11849
11850 case ARM::Int_eh_sjlj_setup_dispatch:
11851 EmitSjLjDispatchBlock(MI, BB);
11852 return BB;
11853
11854 case ARM::ABS:
11855 case ARM::t2ABS: {
11856 // To insert an ABS instruction, we have to insert the
11857 // diamond control-flow pattern. The incoming instruction knows the
11858 // source vreg to test against 0, the destination vreg to set,
11859 // the condition code register to branch on, the
11860 // true/false values to select between, and a branch opcode to use.
11861 // It transforms
11862 // V1 = ABS V0
11863 // into
11864 // V2 = MOVS V0
11865 // BCC (branch to SinkBB if V0 >= 0)
11866 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
11867 // SinkBB: V1 = PHI(V2, V3)
11868 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11869 MachineFunction::iterator BBI = ++BB->getIterator();
11870 MachineFunction *Fn = BB->getParent();
11871 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
11872 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
11873 Fn->insert(BBI, RSBBB);
11874 Fn->insert(BBI, SinkBB);
11875
11876 Register ABSSrcReg = MI.getOperand(1).getReg();
11877 Register ABSDstReg = MI.getOperand(0).getReg();
11878 bool ABSSrcKIll = MI.getOperand(1).isKill();
11879 bool isThumb2 = Subtarget->isThumb2();
11880 MachineRegisterInfo &MRI = Fn->getRegInfo();
11881 // In Thumb mode S must not be specified if source register is the SP or
11882 // PC and if destination register is the SP, so restrict register class
11883 Register NewRsbDstReg = MRI.createVirtualRegister(
11884 isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
11885
11886 // Transfer the remainder of BB and its successor edges to sinkMBB.
11887 SinkBB->splice(SinkBB->begin(), BB,
11888 std::next(MachineBasicBlock::iterator(MI)), BB->end());
11889 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
11890
11891 BB->addSuccessor(RSBBB);
11892 BB->addSuccessor(SinkBB);
11893
11894 // fall through to SinkMBB
11895 RSBBB->addSuccessor(SinkBB);
11896
11897 // insert a cmp at the end of BB
11898 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
11899 .addReg(ABSSrcReg)
11900 .addImm(0)
11901 .add(predOps(ARMCC::AL));
11902
11903 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
11904 BuildMI(BB, dl,
11905 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
11906 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
11907
11908 // insert rsbri in RSBBB
11909 // Note: BCC and rsbri will be converted into predicated rsbmi
11910 // by if-conversion pass
11911 BuildMI(*RSBBB, RSBBB->begin(), dl,
11912 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
11913 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
11914 .addImm(0)
11915 .add(predOps(ARMCC::AL))
11916 .add(condCodeOp());
11917
11918 // insert PHI in SinkBB,
11919 // reuse ABSDstReg to not change uses of ABS instruction
11920 BuildMI(*SinkBB, SinkBB->begin(), dl,
11921 TII->get(ARM::PHI), ABSDstReg)
11922 .addReg(NewRsbDstReg).addMBB(RSBBB)
11923 .addReg(ABSSrcReg).addMBB(BB);
11924
11925 // remove ABS instruction
11926 MI.eraseFromParent();
11927
11928 // return last added BB
11929 return SinkBB;
11930 }
11931 case ARM::COPY_STRUCT_BYVAL_I32:
11932 ++NumLoopByVals;
11933 return EmitStructByval(MI, BB);
11934 case ARM::WIN__CHKSTK:
11935 return EmitLowered__chkstk(MI, BB);
11936 case ARM::WIN__DBZCHK:
11937 return EmitLowered__dbzchk(MI, BB);
11938 }
11939}
11940
11941/// Attaches vregs to MEMCPY that it will use as scratch registers
11942/// when it is expanded into LDM/STM. This is done as a post-isel lowering
11943/// instead of as a custom inserter because we need the use list from the SDNode.
11944static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
11945 MachineInstr &MI, const SDNode *Node) {
11946 bool isThumb1 = Subtarget->isThumb1Only();
11947
11948 DebugLoc DL = MI.getDebugLoc();
11949 MachineFunction *MF = MI.getParent()->getParent();
11950 MachineRegisterInfo &MRI = MF->getRegInfo();
11951 MachineInstrBuilder MIB(*MF, MI);
11952
11953 // If the new dst/src is unused mark it as dead.
11954 if (!Node->hasAnyUseOfValue(0)) {
11955 MI.getOperand(0).setIsDead(true);
11956 }
11957 if (!Node->hasAnyUseOfValue(1)) {
11958 MI.getOperand(1).setIsDead(true);
11959 }
11960
11961 // The MEMCPY both defines and kills the scratch registers.
11962 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
11963 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
11964 : &ARM::GPRRegClass);
11965 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
11966 }
11967}
11968
11969void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11970 SDNode *Node) const {
11971 if (MI.getOpcode() == ARM::MEMCPY) {
11972 attachMEMCPYScratchRegs(Subtarget, MI, Node);
11973 return;
11974 }
11975
11976 const MCInstrDesc *MCID = &MI.getDesc();
11977 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
11978 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
11979 // operand is still set to noreg. If needed, set the optional operand's
11980 // register to CPSR, and remove the redundant implicit def.
11981 //
11982 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
11983
11984 // Rename pseudo opcodes.
11985 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
11986 unsigned ccOutIdx;
11987 if (NewOpc) {
11988 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
11989 MCID = &TII->get(NewOpc);
11990
11991 assert(MCID->getNumOperands() ==(static_cast <bool> (MCID->getNumOperands() == MI.getDesc
().getNumOperands() + 5 - MI.getDesc().getSize() && "converted opcode should be the same except for cc_out"
" (and, on Thumb1, pred)") ? void (0) : __assert_fail ("MCID->getNumOperands() == MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() && \"converted opcode should be the same except for cc_out\" \" (and, on Thumb1, pred)\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11994, __extension__ __PRETTY_FUNCTION__))
11992 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()(static_cast <bool> (MCID->getNumOperands() == MI.getDesc
().getNumOperands() + 5 - MI.getDesc().getSize() && "converted opcode should be the same except for cc_out"
" (and, on Thumb1, pred)") ? void (0) : __assert_fail ("MCID->getNumOperands() == MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() && \"converted opcode should be the same except for cc_out\" \" (and, on Thumb1, pred)\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11994, __extension__ __PRETTY_FUNCTION__))
11993 && "converted opcode should be the same except for cc_out"(static_cast <bool> (MCID->getNumOperands() == MI.getDesc
().getNumOperands() + 5 - MI.getDesc().getSize() && "converted opcode should be the same except for cc_out"
" (and, on Thumb1, pred)") ? void (0) : __assert_fail ("MCID->getNumOperands() == MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() && \"converted opcode should be the same except for cc_out\" \" (and, on Thumb1, pred)\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11994, __extension__ __PRETTY_FUNCTION__))
11994 " (and, on Thumb1, pred)")(static_cast <bool> (MCID->getNumOperands() == MI.getDesc
().getNumOperands() + 5 - MI.getDesc().getSize() && "converted opcode should be the same except for cc_out"
" (and, on Thumb1, pred)") ? void (0) : __assert_fail ("MCID->getNumOperands() == MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() && \"converted opcode should be the same except for cc_out\" \" (and, on Thumb1, pred)\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 11994, __extension__ __PRETTY_FUNCTION__))
;
11995
11996 MI.setDesc(*MCID);
11997
11998 // Add the optional cc_out operand
11999 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
12000
12001 // On Thumb1, move all input operands to the end, then add the predicate
12002 if (Subtarget->isThumb1Only()) {
12003 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
12004 MI.addOperand(MI.getOperand(1));
12005 MI.RemoveOperand(1);
12006 }
12007
12008 // Restore the ties
12009 for (unsigned i = MI.getNumOperands(); i--;) {
12010 const MachineOperand& op = MI.getOperand(i);
12011 if (op.isReg() && op.isUse()) {
12012 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
12013 if (DefIdx != -1)
12014 MI.tieOperands(DefIdx, i);
12015 }
12016 }
12017
12018 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
12019 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
12020 ccOutIdx = 1;
12021 } else
12022 ccOutIdx = MCID->getNumOperands() - 1;
12023 } else
12024 ccOutIdx = MCID->getNumOperands() - 1;
12025
12026 // Any ARM instruction that sets the 's' bit should specify an optional
12027 // "cc_out" operand in the last operand position.
12028 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
12029 assert(!NewOpc && "Optional cc_out operand required")(static_cast <bool> (!NewOpc && "Optional cc_out operand required"
) ? void (0) : __assert_fail ("!NewOpc && \"Optional cc_out operand required\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12029, __extension__ __PRETTY_FUNCTION__))
;
12030 return;
12031 }
12032 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
12033 // since we already have an optional CPSR def.
12034 bool definesCPSR = false;
12035 bool deadCPSR = false;
12036 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
12037 ++i) {
12038 const MachineOperand &MO = MI.getOperand(i);
12039 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
12040 definesCPSR = true;
12041 if (MO.isDead())
12042 deadCPSR = true;
12043 MI.RemoveOperand(i);
12044 break;
12045 }
12046 }
12047 if (!definesCPSR) {
12048 assert(!NewOpc && "Optional cc_out operand required")(static_cast <bool> (!NewOpc && "Optional cc_out operand required"
) ? void (0) : __assert_fail ("!NewOpc && \"Optional cc_out operand required\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12048, __extension__ __PRETTY_FUNCTION__))
;
12049 return;
12050 }
12051 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag")(static_cast <bool> (deadCPSR == !Node->hasAnyUseOfValue
(1) && "inconsistent dead flag") ? void (0) : __assert_fail
("deadCPSR == !Node->hasAnyUseOfValue(1) && \"inconsistent dead flag\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12051, __extension__ __PRETTY_FUNCTION__))
;
12052 if (deadCPSR) {
12053 assert(!MI.getOperand(ccOutIdx).getReg() &&(static_cast <bool> (!MI.getOperand(ccOutIdx).getReg() &&
"expect uninitialized optional cc_out operand") ? void (0) :
__assert_fail ("!MI.getOperand(ccOutIdx).getReg() && \"expect uninitialized optional cc_out operand\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12054, __extension__ __PRETTY_FUNCTION__))
12054 "expect uninitialized optional cc_out operand")(static_cast <bool> (!MI.getOperand(ccOutIdx).getReg() &&
"expect uninitialized optional cc_out operand") ? void (0) :
__assert_fail ("!MI.getOperand(ccOutIdx).getReg() && \"expect uninitialized optional cc_out operand\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12054, __extension__ __PRETTY_FUNCTION__))
;
12055 // Thumb1 instructions must have the S bit even if the CPSR is dead.
12056 if (!Subtarget->isThumb1Only())
12057 return;
12058 }
12059
12060 // If this instruction was defined with an optional CPSR def and its dag node
12061 // had a live implicit CPSR def, then activate the optional CPSR def.
12062 MachineOperand &MO = MI.getOperand(ccOutIdx);
12063 MO.setReg(ARM::CPSR);
12064 MO.setIsDef(true);
12065}
12066
12067//===----------------------------------------------------------------------===//
12068// ARM Optimization Hooks
12069//===----------------------------------------------------------------------===//
12070
12071// Helper function that checks if N is a null or all ones constant.
12072static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
12073 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
12074}
12075
12076// Return true if N is conditionally 0 or all ones.
12077// Detects these expressions where cc is an i1 value:
12078//
12079// (select cc 0, y) [AllOnes=0]
12080// (select cc y, 0) [AllOnes=0]
12081// (zext cc) [AllOnes=0]
12082// (sext cc) [AllOnes=0/1]
12083// (select cc -1, y) [AllOnes=1]
12084// (select cc y, -1) [AllOnes=1]
12085//
12086// Invert is set when N is the null/all ones constant when CC is false.
12087// OtherOp is set to the alternative value of N.
12088static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
12089 SDValue &CC, bool &Invert,
12090 SDValue &OtherOp,
12091 SelectionDAG &DAG) {
12092 switch (N->getOpcode()) {
12093 default: return false;
12094 case ISD::SELECT: {
12095 CC = N->getOperand(0);
12096 SDValue N1 = N->getOperand(1);
12097 SDValue N2 = N->getOperand(2);
12098 if (isZeroOrAllOnes(N1, AllOnes)) {
12099 Invert = false;
12100 OtherOp = N2;
12101 return true;
12102 }
12103 if (isZeroOrAllOnes(N2, AllOnes)) {
12104 Invert = true;
12105 OtherOp = N1;
12106 return true;
12107 }
12108 return false;
12109 }
12110 case ISD::ZERO_EXTEND:
12111 // (zext cc) can never be the all ones value.
12112 if (AllOnes)
12113 return false;
12114 LLVM_FALLTHROUGH[[gnu::fallthrough]];
12115 case ISD::SIGN_EXTEND: {
12116 SDLoc dl(N);
12117 EVT VT = N->getValueType(0);
12118 CC = N->getOperand(0);
12119 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
12120 return false;
12121 Invert = !AllOnes;
12122 if (AllOnes)
12123 // When looking for an AllOnes constant, N is an sext, and the 'other'
12124 // value is 0.
12125 OtherOp = DAG.getConstant(0, dl, VT);
12126 else if (N->getOpcode() == ISD::ZERO_EXTEND)
12127 // When looking for a 0 constant, N can be zext or sext.
12128 OtherOp = DAG.getConstant(1, dl, VT);
12129 else
12130 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
12131 VT);
12132 return true;
12133 }
12134 }
12135}
12136
12137// Combine a constant select operand into its use:
12138//
12139// (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
12140// (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
12141// (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
12142// (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
12143// (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
12144//
12145// The transform is rejected if the select doesn't have a constant operand that
12146// is null, or all ones when AllOnes is set.
12147//
12148// Also recognize sext/zext from i1:
12149//
12150// (add (zext cc), x) -> (select cc (add x, 1), x)
12151// (add (sext cc), x) -> (select cc (add x, -1), x)
12152//
12153// These transformations eventually create predicated instructions.
12154//
12155// @param N The node to transform.
12156// @param Slct The N operand that is a select.
12157// @param OtherOp The other N operand (x above).
12158// @param DCI Context.
12159// @param AllOnes Require the select constant to be all ones instead of null.
12160// @returns The new node, or SDValue() on failure.
12161static
12162SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
12163 TargetLowering::DAGCombinerInfo &DCI,
12164 bool AllOnes = false) {
12165 SelectionDAG &DAG = DCI.DAG;
12166 EVT VT = N->getValueType(0);
12167 SDValue NonConstantVal;
12168 SDValue CCOp;
12169 bool SwapSelectOps;
12170 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
12171 NonConstantVal, DAG))
12172 return SDValue();
12173
12174 // Slct is now know to be the desired identity constant when CC is true.
12175 SDValue TrueVal = OtherOp;
12176 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12177 OtherOp, NonConstantVal);
12178 // Unless SwapSelectOps says CC should be false.
12179 if (SwapSelectOps)
12180 std::swap(TrueVal, FalseVal);
12181
12182 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
12183 CCOp, TrueVal, FalseVal);
12184}
12185
12186// Attempt combineSelectAndUse on each operand of a commutative operator N.
12187static
12188SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
12189 TargetLowering::DAGCombinerInfo &DCI) {
12190 SDValue N0 = N->getOperand(0);
12191 SDValue N1 = N->getOperand(1);
12192 if (N0.getNode()->hasOneUse())
12193 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
12194 return Result;
12195 if (N1.getNode()->hasOneUse())
12196 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
12197 return Result;
12198 return SDValue();
12199}
12200
12201static bool IsVUZPShuffleNode(SDNode *N) {
12202 // VUZP shuffle node.
12203 if (N->getOpcode() == ARMISD::VUZP)
12204 return true;
12205
12206 // "VUZP" on i32 is an alias for VTRN.
12207 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
12208 return true;
12209
12210 return false;
12211}
12212
12213static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
12214 TargetLowering::DAGCombinerInfo &DCI,
12215 const ARMSubtarget *Subtarget) {
12216 // Look for ADD(VUZP.0, VUZP.1).
12217 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
12218 N0 == N1)
12219 return SDValue();
12220
12221 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
12222 if (!N->getValueType(0).is64BitVector())
12223 return SDValue();
12224
12225 // Generate vpadd.
12226 SelectionDAG &DAG = DCI.DAG;
12227 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12228 SDLoc dl(N);
12229 SDNode *Unzip = N0.getNode();
12230 EVT VT = N->getValueType(0);
12231
12232 SmallVector<SDValue, 8> Ops;
12233 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
12234 TLI.getPointerTy(DAG.getDataLayout())));
12235 Ops.push_back(Unzip->getOperand(0));
12236 Ops.push_back(Unzip->getOperand(1));
12237
12238 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
12239}
12240
12241static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
12242 TargetLowering::DAGCombinerInfo &DCI,
12243 const ARMSubtarget *Subtarget) {
12244 // Check for two extended operands.
12245 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
12246 N1.getOpcode() == ISD::SIGN_EXTEND) &&
12247 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
12248 N1.getOpcode() == ISD::ZERO_EXTEND))
12249 return SDValue();
12250
12251 SDValue N00 = N0.getOperand(0);
12252 SDValue N10 = N1.getOperand(0);
12253
12254 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
12255 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
12256 N00 == N10)
12257 return SDValue();
12258
12259 // We only recognize Q register paddl here; this can't be reached until
12260 // after type legalization.
12261 if (!N00.getValueType().is64BitVector() ||
12262 !N0.getValueType().is128BitVector())
12263 return SDValue();
12264
12265 // Generate vpaddl.
12266 SelectionDAG &DAG = DCI.DAG;
12267 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12268 SDLoc dl(N);
12269 EVT VT = N->getValueType(0);
12270
12271 SmallVector<SDValue, 8> Ops;
12272 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
12273 unsigned Opcode;
12274 if (N0.getOpcode() == ISD::SIGN_EXTEND)
12275 Opcode = Intrinsic::arm_neon_vpaddls;
12276 else
12277 Opcode = Intrinsic::arm_neon_vpaddlu;
12278 Ops.push_back(DAG.getConstant(Opcode, dl,
12279 TLI.getPointerTy(DAG.getDataLayout())));
12280 EVT ElemTy = N00.getValueType().getVectorElementType();
12281 unsigned NumElts = VT.getVectorNumElements();
12282 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
12283 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
12284 N00.getOperand(0), N00.getOperand(1));
12285 Ops.push_back(Concat);
12286
12287 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
12288}
12289
12290// FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
12291// an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
12292// much easier to match.
12293static SDValue
12294AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
12295 TargetLowering::DAGCombinerInfo &DCI,
12296 const ARMSubtarget *Subtarget) {
12297 // Only perform optimization if after legalize, and if NEON is available. We
12298 // also expected both operands to be BUILD_VECTORs.
12299 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
12300 || N0.getOpcode() != ISD::BUILD_VECTOR
12301 || N1.getOpcode() != ISD::BUILD_VECTOR)
12302 return SDValue();
12303
12304 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
12305 EVT VT = N->getValueType(0);
12306 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
12307 return SDValue();
12308
12309 // Check that the vector operands are of the right form.
12310 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
12311 // operands, where N is the size of the formed vector.
12312 // Each EXTRACT_VECTOR should have the same input vector and odd or even
12313 // index such that we have a pair wise add pattern.
12314
12315 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
12316 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12317 return SDValue();
12318 SDValue Vec = N0->getOperand(0)->getOperand(0);
12319 SDNode *V = Vec.getNode();
12320 unsigned nextIndex = 0;
12321
12322 // For each operands to the ADD which are BUILD_VECTORs,
12323 // check to see if each of their operands are an EXTRACT_VECTOR with
12324 // the same vector and appropriate index.
12325 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
12326 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
12327 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12328
12329 SDValue ExtVec0 = N0->getOperand(i);
12330 SDValue ExtVec1 = N1->getOperand(i);
12331
12332 // First operand is the vector, verify its the same.
12333 if (V != ExtVec0->getOperand(0).getNode() ||
12334 V != ExtVec1->getOperand(0).getNode())
12335 return SDValue();
12336
12337 // Second is the constant, verify its correct.
12338 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
12339 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
12340
12341 // For the constant, we want to see all the even or all the odd.
12342 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
12343 || C1->getZExtValue() != nextIndex+1)
12344 return SDValue();
12345
12346 // Increment index.
12347 nextIndex+=2;
12348 } else
12349 return SDValue();
12350 }
12351
12352 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
12353 // we're using the entire input vector, otherwise there's a size/legality
12354 // mismatch somewhere.
12355 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
12356 Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
12357 return SDValue();
12358
12359 // Create VPADDL node.
12360 SelectionDAG &DAG = DCI.DAG;
12361 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12362
12363 SDLoc dl(N);
12364
12365 // Build operand list.
12366 SmallVector<SDValue, 8> Ops;
12367 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
12368 TLI.getPointerTy(DAG.getDataLayout())));
12369
12370 // Input is the vector.
12371 Ops.push_back(Vec);
12372
12373 // Get widened type and narrowed type.
12374 MVT widenType;
12375 unsigned numElem = VT.getVectorNumElements();
12376
12377 EVT inputLaneType = Vec.getValueType().getVectorElementType();
12378 switch (inputLaneType.getSimpleVT().SimpleTy) {
12379 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
12380 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
12381 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
12382 default:
12383 llvm_unreachable("Invalid vector element type for padd optimization.")::llvm::llvm_unreachable_internal("Invalid vector element type for padd optimization."
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12383)
;
12384 }
12385
12386 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
12387 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
12388 return DAG.getNode(ExtOp, dl, VT, tmp);
12389}
12390
12391static SDValue findMUL_LOHI(SDValue V) {
12392 if (V->getOpcode() == ISD::UMUL_LOHI ||
12393 V->getOpcode() == ISD::SMUL_LOHI)
12394 return V;
12395 return SDValue();
12396}
12397
12398static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
12399 TargetLowering::DAGCombinerInfo &DCI,
12400 const ARMSubtarget *Subtarget) {
12401 if (!Subtarget->hasBaseDSP())
12402 return SDValue();
12403
12404 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
12405 // accumulates the product into a 64-bit value. The 16-bit values will
12406 // be sign extended somehow or SRA'd into 32-bit values
12407 // (addc (adde (mul 16bit, 16bit), lo), hi)
12408 SDValue Mul = AddcNode->getOperand(0);
12409 SDValue Lo = AddcNode->getOperand(1);
12410 if (Mul.getOpcode() != ISD::MUL) {
12411 Lo = AddcNode->getOperand(0);
12412 Mul = AddcNode->getOperand(1);
12413 if (Mul.getOpcode() != ISD::MUL)
12414 return SDValue();
12415 }
12416
12417 SDValue SRA = AddeNode->getOperand(0);
12418 SDValue Hi = AddeNode->getOperand(1);
12419 if (SRA.getOpcode() != ISD::SRA) {
12420 SRA = AddeNode->getOperand(1);
12421 Hi = AddeNode->getOperand(0);
12422 if (SRA.getOpcode() != ISD::SRA)
12423 return SDValue();
12424 }
12425 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
12426 if (Const->getZExtValue() != 31)
12427 return SDValue();
12428 } else
12429 return SDValue();
12430
12431 if (SRA.getOperand(0) != Mul)
12432 return SDValue();
12433
12434 SelectionDAG &DAG = DCI.DAG;
12435 SDLoc dl(AddcNode);
12436 unsigned Opcode = 0;
12437 SDValue Op0;
12438 SDValue Op1;
12439
12440 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
12441 Opcode = ARMISD::SMLALBB;
12442 Op0 = Mul.getOperand(0);
12443 Op1 = Mul.getOperand(1);
12444 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
12445 Opcode = ARMISD::SMLALBT;
12446 Op0 = Mul.getOperand(0);
12447 Op1 = Mul.getOperand(1).getOperand(0);
12448 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
12449 Opcode = ARMISD::SMLALTB;
12450 Op0 = Mul.getOperand(0).getOperand(0);
12451 Op1 = Mul.getOperand(1);
12452 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
12453 Opcode = ARMISD::SMLALTT;
12454 Op0 = Mul->getOperand(0).getOperand(0);
12455 Op1 = Mul->getOperand(1).getOperand(0);
12456 }
12457
12458 if (!Op0 || !Op1)
12459 return SDValue();
12460
12461 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
12462 Op0, Op1, Lo, Hi);
12463 // Replace the ADDs' nodes uses by the MLA node's values.
12464 SDValue HiMLALResult(SMLAL.getNode(), 1);
12465 SDValue LoMLALResult(SMLAL.getNode(), 0);
12466
12467 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
12468 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
12469
12470 // Return original node to notify the driver to stop replacing.
12471 SDValue resNode(AddcNode, 0);
12472 return resNode;
12473}
12474
12475static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
12476 TargetLowering::DAGCombinerInfo &DCI,
12477 const ARMSubtarget *Subtarget) {
12478 // Look for multiply add opportunities.
12479 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
12480 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
12481 // a glue link from the first add to the second add.
12482 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
12483 // a S/UMLAL instruction.
12484 // UMUL_LOHI
12485 // / :lo \ :hi
12486 // V \ [no multiline comment]
12487 // loAdd -> ADDC |
12488 // \ :carry /
12489 // V V
12490 // ADDE <- hiAdd
12491 //
12492 // In the special case where only the higher part of a signed result is used
12493 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
12494 // a constant with the exact value of 0x80000000, we recognize we are dealing
12495 // with a "rounded multiply and add" (or subtract) and transform it into
12496 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
12497
12498 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||(static_cast <bool> ((AddeSubeNode->getOpcode() == ARMISD
::ADDE || AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
"Expect an ADDE or SUBE") ? void (0) : __assert_fail ("(AddeSubeNode->getOpcode() == ARMISD::ADDE || AddeSubeNode->getOpcode() == ARMISD::SUBE) && \"Expect an ADDE or SUBE\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12500, __extension__ __PRETTY_FUNCTION__))
12499 AddeSubeNode->getOpcode() == ARMISD::SUBE) &&(static_cast <bool> ((AddeSubeNode->getOpcode() == ARMISD
::ADDE || AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
"Expect an ADDE or SUBE") ? void (0) : __assert_fail ("(AddeSubeNode->getOpcode() == ARMISD::ADDE || AddeSubeNode->getOpcode() == ARMISD::SUBE) && \"Expect an ADDE or SUBE\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12500, __extension__ __PRETTY_FUNCTION__))
12500 "Expect an ADDE or SUBE")(static_cast <bool> ((AddeSubeNode->getOpcode() == ARMISD
::ADDE || AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
"Expect an ADDE or SUBE") ? void (0) : __assert_fail ("(AddeSubeNode->getOpcode() == ARMISD::ADDE || AddeSubeNode->getOpcode() == ARMISD::SUBE) && \"Expect an ADDE or SUBE\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12500, __extension__ __PRETTY_FUNCTION__))
;
12501
12502 assert(AddeSubeNode->getNumOperands() == 3 &&(static_cast <bool> (AddeSubeNode->getNumOperands() ==
3 && AddeSubeNode->getOperand(2).getValueType() ==
MVT::i32 && "ADDE node has the wrong inputs") ? void
(0) : __assert_fail ("AddeSubeNode->getNumOperands() == 3 && AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && \"ADDE node has the wrong inputs\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12504, __extension__ __PRETTY_FUNCTION__))
12503 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&(static_cast <bool> (AddeSubeNode->getNumOperands() ==
3 && AddeSubeNode->getOperand(2).getValueType() ==
MVT::i32 && "ADDE node has the wrong inputs") ? void
(0) : __assert_fail ("AddeSubeNode->getNumOperands() == 3 && AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && \"ADDE node has the wrong inputs\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12504, __extension__ __PRETTY_FUNCTION__))
12504 "ADDE node has the wrong inputs")(static_cast <bool> (AddeSubeNode->getNumOperands() ==
3 && AddeSubeNode->getOperand(2).getValueType() ==
MVT::i32 && "ADDE node has the wrong inputs") ? void
(0) : __assert_fail ("AddeSubeNode->getNumOperands() == 3 && AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && \"ADDE node has the wrong inputs\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12504, __extension__ __PRETTY_FUNCTION__))
;
12505
12506 // Check that we are chained to the right ADDC or SUBC node.
12507 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
12508 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
12509 AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
12510 (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
12511 AddcSubcNode->getOpcode() != ARMISD::SUBC))
12512 return SDValue();
12513
12514 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
12515 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
12516
12517 // Check if the two operands are from the same mul_lohi node.
12518 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
12519 return SDValue();
12520
12521 assert(AddcSubcNode->getNumValues() == 2 &&(static_cast <bool> (AddcSubcNode->getNumValues() ==
2 && AddcSubcNode->getValueType(0) == MVT::i32 &&
"Expect ADDC with two result values. First: i32") ? void (0)
: __assert_fail ("AddcSubcNode->getNumValues() == 2 && AddcSubcNode->getValueType(0) == MVT::i32 && \"Expect ADDC with two result values. First: i32\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12523, __extension__ __PRETTY_FUNCTION__))
12522 AddcSubcNode->getValueType(0) == MVT::i32 &&(static_cast <bool> (AddcSubcNode->getNumValues() ==
2 && AddcSubcNode->getValueType(0) == MVT::i32 &&
"Expect ADDC with two result values. First: i32") ? void (0)
: __assert_fail ("AddcSubcNode->getNumValues() == 2 && AddcSubcNode->getValueType(0) == MVT::i32 && \"Expect ADDC with two result values. First: i32\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12523, __extension__ __PRETTY_FUNCTION__))
12523 "Expect ADDC with two result values. First: i32")(static_cast <bool> (AddcSubcNode->getNumValues() ==
2 && AddcSubcNode->getValueType(0) == MVT::i32 &&
"Expect ADDC with two result values. First: i32") ? void (0)
: __assert_fail ("AddcSubcNode->getNumValues() == 2 && AddcSubcNode->getValueType(0) == MVT::i32 && \"Expect ADDC with two result values. First: i32\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12523, __extension__ __PRETTY_FUNCTION__))
;
12524
12525 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
12526 // maybe a SMLAL which multiplies two 16-bit values.
12527 if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
12528 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
12529 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
12530 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
12531 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
12532 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
12533
12534 // Check for the triangle shape.
12535 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
12536 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
12537
12538 // Make sure that the ADDE/SUBE operands are not coming from the same node.
12539 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
12540 return SDValue();
12541
12542 // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
12543 bool IsLeftOperandMUL = false;
12544 SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
12545 if (MULOp == SDValue())
12546 MULOp = findMUL_LOHI(AddeSubeOp1);
12547 else
12548 IsLeftOperandMUL = true;
12549 if (MULOp == SDValue())
12550 return SDValue();
12551
12552 // Figure out the right opcode.
12553 unsigned Opc = MULOp->getOpcode();
12554 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
12555
12556 // Figure out the high and low input values to the MLAL node.
12557 SDValue *HiAddSub = nullptr;
12558 SDValue *LoMul = nullptr;
12559 SDValue *LowAddSub = nullptr;
12560
12561 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
12562 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
12563 return SDValue();
12564
12565 if (IsLeftOperandMUL)
12566 HiAddSub = &AddeSubeOp1;
12567 else
12568 HiAddSub = &AddeSubeOp0;
12569
12570 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
12571 // whose low result is fed to the ADDC/SUBC we are checking.
12572
12573 if (AddcSubcOp0 == MULOp.getValue(0)) {
12574 LoMul = &AddcSubcOp0;
12575 LowAddSub = &AddcSubcOp1;
12576 }
12577 if (AddcSubcOp1 == MULOp.getValue(0)) {
12578 LoMul = &AddcSubcOp1;
12579 LowAddSub = &AddcSubcOp0;
12580 }
12581
12582 if (!LoMul)
12583 return SDValue();
12584
12585 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
12586 // the replacement below will create a cycle.
12587 if (AddcSubcNode == HiAddSub->getNode() ||
12588 AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
12589 return SDValue();
12590
12591 // Create the merged node.
12592 SelectionDAG &DAG = DCI.DAG;
12593
12594 // Start building operand list.
12595 SmallVector<SDValue, 8> Ops;
12596 Ops.push_back(LoMul->getOperand(0));
12597 Ops.push_back(LoMul->getOperand(1));
12598
12599 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be
12600 // the case, we must be doing signed multiplication and only use the higher
12601 // part of the result of the MLAL, furthermore the LowAddSub must be a constant
12602 // addition or subtraction with the value of 0x800000.
12603 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
12604 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
12605 LowAddSub->getNode()->getOpcode() == ISD::Constant &&
12606 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
12607 0x80000000) {
12608 Ops.push_back(*HiAddSub);
12609 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
12610 FinalOpc = ARMISD::SMMLSR;
12611 } else {
12612 FinalOpc = ARMISD::SMMLAR;
12613 }
12614 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
12615 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
12616
12617 return SDValue(AddeSubeNode, 0);
12618 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
12619 // SMMLS is generated during instruction selection and the rest of this
12620 // function can not handle the case where AddcSubcNode is a SUBC.
12621 return SDValue();
12622
12623 // Finish building the operand list for {U/S}MLAL
12624 Ops.push_back(*LowAddSub);
12625 Ops.push_back(*HiAddSub);
12626
12627 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
12628 DAG.getVTList(MVT::i32, MVT::i32), Ops);
12629
12630 // Replace the ADDs' nodes uses by the MLA node's values.
12631 SDValue HiMLALResult(MLALNode.getNode(), 1);
12632 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
12633
12634 SDValue LoMLALResult(MLALNode.getNode(), 0);
12635 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
12636
12637 // Return original node to notify the driver to stop replacing.
12638 return SDValue(AddeSubeNode, 0);
12639}
12640
12641static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
12642 TargetLowering::DAGCombinerInfo &DCI,
12643 const ARMSubtarget *Subtarget) {
12644 // UMAAL is similar to UMLAL except that it adds two unsigned values.
12645 // While trying to combine for the other MLAL nodes, first search for the
12646 // chance to use UMAAL. Check if Addc uses a node which has already
12647 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
12648 // as the addend, and it's handled in PerformUMLALCombine.
12649
12650 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
12651 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
12652
12653 // Check that we have a glued ADDC node.
12654 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
12655 if (AddcNode->getOpcode() != ARMISD::ADDC)
12656 return SDValue();
12657
12658 // Find the converted UMAAL or quit if it doesn't exist.
12659 SDNode *UmlalNode = nullptr;
12660 SDValue AddHi;
12661 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
12662 UmlalNode = AddcNode->getOperand(0).getNode();
12663 AddHi = AddcNode->getOperand(1);
12664 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
12665 UmlalNode = AddcNode->getOperand(1).getNode();
12666 AddHi = AddcNode->getOperand(0);
12667 } else {
12668 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
12669 }
12670
12671 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
12672 // the ADDC as well as Zero.
12673 if (!isNullConstant(UmlalNode->getOperand(3)))
12674 return SDValue();
12675
12676 if ((isNullConstant(AddeNode->getOperand(0)) &&
12677 AddeNode->getOperand(1).getNode() == UmlalNode) ||
12678 (AddeNode->getOperand(0).getNode() == UmlalNode &&
12679 isNullConstant(AddeNode->getOperand(1)))) {
12680 SelectionDAG &DAG = DCI.DAG;
12681 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
12682 UmlalNode->getOperand(2), AddHi };
12683 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
12684 DAG.getVTList(MVT::i32, MVT::i32), Ops);
12685
12686 // Replace the ADDs' nodes uses by the UMAAL node's values.
12687 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
12688 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
12689
12690 // Return original node to notify the driver to stop replacing.
12691 return SDValue(AddeNode, 0);
12692 }
12693 return SDValue();
12694}
12695
12696static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
12697 const ARMSubtarget *Subtarget) {
12698 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
12699 return SDValue();
12700
12701 // Check that we have a pair of ADDC and ADDE as operands.
12702 // Both addends of the ADDE must be zero.
12703 SDNode* AddcNode = N->getOperand(2).getNode();
12704 SDNode* AddeNode = N->getOperand(3).getNode();
12705 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
12706 (AddeNode->getOpcode() == ARMISD::ADDE) &&
12707 isNullConstant(AddeNode->getOperand(0)) &&
12708 isNullConstant(AddeNode->getOperand(1)) &&
12709 (AddeNode->getOperand(2).getNode() == AddcNode))
12710 return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
12711 DAG.getVTList(MVT::i32, MVT::i32),
12712 {N->getOperand(0), N->getOperand(1),
12713 AddcNode->getOperand(0), AddcNode->getOperand(1)});
12714 else
12715 return SDValue();
12716}
12717
12718static SDValue PerformAddcSubcCombine(SDNode *N,
12719 TargetLowering::DAGCombinerInfo &DCI,
12720 const ARMSubtarget *Subtarget) {
12721 SelectionDAG &DAG(DCI.DAG);
12722
12723 if (N->getOpcode() == ARMISD::SUBC) {
12724 // (SUBC (ADDE 0, 0, C), 1) -> C
12725 SDValue LHS = N->getOperand(0);
12726 SDValue RHS = N->getOperand(1);
12727 if (LHS->getOpcode() == ARMISD::ADDE &&
12728 isNullConstant(LHS->getOperand(0)) &&
12729 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
12730 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
12731 }
12732 }
12733
12734 if (Subtarget->isThumb1Only()) {
12735 SDValue RHS = N->getOperand(1);
12736 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
12737 int32_t imm = C->getSExtValue();
12738 if (imm < 0 && imm > std::numeric_limits<int>::min()) {
12739 SDLoc DL(N);
12740 RHS = DAG.getConstant(-imm, DL, MVT::i32);
12741 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
12742 : ARMISD::ADDC;
12743 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
12744 }
12745 }
12746 }
12747
12748 return SDValue();
12749}
12750
12751static SDValue PerformAddeSubeCombine(SDNode *N,
12752 TargetLowering::DAGCombinerInfo &DCI,
12753 const ARMSubtarget *Subtarget) {
12754 if (Subtarget->isThumb1Only()) {
12755 SelectionDAG &DAG = DCI.DAG;
12756 SDValue RHS = N->getOperand(1);
12757 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
12758 int64_t imm = C->getSExtValue();
12759 if (imm < 0) {
12760 SDLoc DL(N);
12761
12762 // The with-carry-in form matches bitwise not instead of the negation.
12763 // Effectively, the inverse interpretation of the carry flag already
12764 // accounts for part of the negation.
12765 RHS = DAG.getConstant(~imm, DL, MVT::i32);
12766
12767 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
12768 : ARMISD::ADDE;
12769 return DAG.getNode(Opcode, DL, N->getVTList(),
12770 N->getOperand(0), RHS, N->getOperand(2));
12771 }
12772 }
12773 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
12774 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
12775 }
12776 return SDValue();
12777}
12778
12779static SDValue PerformSELECTCombine(SDNode *N,
12780 TargetLowering::DAGCombinerInfo &DCI,
12781 const ARMSubtarget *Subtarget) {
12782 if (!Subtarget->hasMVEIntegerOps())
12783 return SDValue();
12784
12785 SDLoc dl(N);
12786 SDValue SetCC;
12787 SDValue LHS;
12788 SDValue RHS;
12789 ISD::CondCode CC;
12790 SDValue TrueVal;
12791 SDValue FalseVal;
12792
12793 if (N->getOpcode() == ISD::SELECT &&
12794 N->getOperand(0)->getOpcode() == ISD::SETCC) {
12795 SetCC = N->getOperand(0);
12796 LHS = SetCC->getOperand(0);
12797 RHS = SetCC->getOperand(1);
12798 CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
12799 TrueVal = N->getOperand(1);
12800 FalseVal = N->getOperand(2);
12801 } else if (N->getOpcode() == ISD::SELECT_CC) {
12802 LHS = N->getOperand(0);
12803 RHS = N->getOperand(1);
12804 CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
12805 TrueVal = N->getOperand(2);
12806 FalseVal = N->getOperand(3);
12807 } else {
12808 return SDValue();
12809 }
12810
12811 unsigned int Opcode = 0;
12812 if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMIN ||
12813 FalseVal->getOpcode() == ISD::VECREDUCE_UMIN) &&
12814 (CC == ISD::SETULT || CC == ISD::SETUGT)) {
12815 Opcode = ARMISD::VMINVu;
12816 if (CC == ISD::SETUGT)
12817 std::swap(TrueVal, FalseVal);
12818 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMIN ||
12819 FalseVal->getOpcode() == ISD::VECREDUCE_SMIN) &&
12820 (CC == ISD::SETLT || CC == ISD::SETGT)) {
12821 Opcode = ARMISD::VMINVs;
12822 if (CC == ISD::SETGT)
12823 std::swap(TrueVal, FalseVal);
12824 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMAX ||
12825 FalseVal->getOpcode() == ISD::VECREDUCE_UMAX) &&
12826 (CC == ISD::SETUGT || CC == ISD::SETULT)) {
12827 Opcode = ARMISD::VMAXVu;
12828 if (CC == ISD::SETULT)
12829 std::swap(TrueVal, FalseVal);
12830 } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMAX ||
12831 FalseVal->getOpcode() == ISD::VECREDUCE_SMAX) &&
12832 (CC == ISD::SETGT || CC == ISD::SETLT)) {
12833 Opcode = ARMISD::VMAXVs;
12834 if (CC == ISD::SETLT)
12835 std::swap(TrueVal, FalseVal);
12836 } else
12837 return SDValue();
12838
12839 // Normalise to the right hand side being the vector reduction
12840 switch (TrueVal->getOpcode()) {
12841 case ISD::VECREDUCE_UMIN:
12842 case ISD::VECREDUCE_SMIN:
12843 case ISD::VECREDUCE_UMAX:
12844 case ISD::VECREDUCE_SMAX:
12845 std::swap(LHS, RHS);
12846 std::swap(TrueVal, FalseVal);
12847 break;
12848 }
12849
12850 EVT VectorType = FalseVal->getOperand(0).getValueType();
12851
12852 if (VectorType != MVT::v16i8 && VectorType != MVT::v8i16 &&
12853 VectorType != MVT::v4i32)
12854 return SDValue();
12855
12856 EVT VectorScalarType = VectorType.getVectorElementType();
12857
12858 // The values being selected must also be the ones being compared
12859 if (TrueVal != LHS || FalseVal != RHS)
12860 return SDValue();
12861
12862 EVT LeftType = LHS->getValueType(0);
12863 EVT RightType = RHS->getValueType(0);
12864
12865 // The types must match the reduced type too
12866 if (LeftType != VectorScalarType || RightType != VectorScalarType)
12867 return SDValue();
12868
12869 // Legalise the scalar to an i32
12870 if (VectorScalarType != MVT::i32)
12871 LHS = DCI.DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12872
12873 // Generate the reduction as an i32 for legalisation purposes
12874 auto Reduction =
12875 DCI.DAG.getNode(Opcode, dl, MVT::i32, LHS, RHS->getOperand(0));
12876
12877 // The result isn't actually an i32 so truncate it back to its original type
12878 if (VectorScalarType != MVT::i32)
12879 Reduction = DCI.DAG.getNode(ISD::TRUNCATE, dl, VectorScalarType, Reduction);
12880
12881 return Reduction;
12882}
12883
12884// A special combine for the vqdmulh family of instructions. This is one of the
12885// potential set of patterns that could patch this instruction. The base pattern
12886// you would expect to be min(max(ashr(mul(mul(sext(x), 2), sext(y)), 16))).
12887// This matches the different min(max(ashr(mul(mul(sext(x), sext(y)), 2), 16))),
12888// which llvm will have optimized to min(ashr(mul(sext(x), sext(y)), 15))) as
12889// the max is unnecessary.
12890static SDValue PerformVQDMULHCombine(SDNode *N, SelectionDAG &DAG) {
12891 EVT VT = N->getValueType(0);
12892 SDValue Shft;
12893 ConstantSDNode *Clamp;
12894
12895 if (!VT.isVector())
12896 return SDValue();
12897
12898 if (N->getOpcode() == ISD::SMIN) {
12899 Shft = N->getOperand(0);
12900 Clamp = isConstOrConstSplat(N->getOperand(1));
12901 } else if (N->getOpcode() == ISD::VSELECT) {
12902 // Detect a SMIN, which for an i64 node will be a vselect/setcc, not a smin.
12903 SDValue Cmp = N->getOperand(0);
12904 if (Cmp.getOpcode() != ISD::SETCC ||
12905 cast<CondCodeSDNode>(Cmp.getOperand(2))->get() != ISD::SETLT ||
12906 Cmp.getOperand(0) != N->getOperand(1) ||
12907 Cmp.getOperand(1) != N->getOperand(2))
12908 return SDValue();
12909 Shft = N->getOperand(1);
12910 Clamp = isConstOrConstSplat(N->getOperand(2));
12911 } else
12912 return SDValue();
12913
12914 if (!Clamp)
12915 return SDValue();
12916
12917 MVT ScalarType;
12918 int ShftAmt = 0;
12919 switch (Clamp->getSExtValue()) {
12920 case (1 << 7) - 1:
12921 ScalarType = MVT::i8;
12922 ShftAmt = 7;
12923 break;
12924 case (1 << 15) - 1:
12925 ScalarType = MVT::i16;
12926 ShftAmt = 15;
12927 break;
12928 case (1ULL << 31) - 1:
12929 ScalarType = MVT::i32;
12930 ShftAmt = 31;
12931 break;
12932 default:
12933 return SDValue();
12934 }
12935
12936 if (Shft.getOpcode() != ISD::SRA)
12937 return SDValue();
12938 ConstantSDNode *N1 = isConstOrConstSplat(Shft.getOperand(1));
12939 if (!N1 || N1->getSExtValue() != ShftAmt)
12940 return SDValue();
12941
12942 SDValue Mul = Shft.getOperand(0);
12943 if (Mul.getOpcode() != ISD::MUL)
12944 return SDValue();
12945
12946 SDValue Ext0 = Mul.getOperand(0);
12947 SDValue Ext1 = Mul.getOperand(1);
12948 if (Ext0.getOpcode() != ISD::SIGN_EXTEND ||
12949 Ext1.getOpcode() != ISD::SIGN_EXTEND)
12950 return SDValue();
12951 EVT VecVT = Ext0.getOperand(0).getValueType();
12952 if (!VecVT.isPow2VectorType() || VecVT.getVectorNumElements() == 1)
12953 return SDValue();
12954 if (Ext1.getOperand(0).getValueType() != VecVT ||
12955 VecVT.getScalarType() != ScalarType ||
12956 VT.getScalarSizeInBits() < ScalarType.getScalarSizeInBits() * 2)
12957 return SDValue();
12958
12959 SDLoc DL(Mul);
12960 unsigned LegalLanes = 128 / (ShftAmt + 1);
12961 EVT LegalVecVT = MVT::getVectorVT(ScalarType, LegalLanes);
12962 // For types smaller than legal vectors extend to be legal and only use needed
12963 // lanes.
12964 if (VecVT.getSizeInBits() < 128) {
12965 EVT ExtVecVT =
12966 MVT::getVectorVT(MVT::getIntegerVT(128 / VecVT.getVectorNumElements()),
12967 VecVT.getVectorNumElements());
12968 SDValue Inp0 =
12969 DAG.getNode(ISD::ANY_EXTEND, DL, ExtVecVT, Ext0.getOperand(0));
12970 SDValue Inp1 =
12971 DAG.getNode(ISD::ANY_EXTEND, DL, ExtVecVT, Ext1.getOperand(0));
12972 Inp0 = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, LegalVecVT, Inp0);
12973 Inp1 = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, LegalVecVT, Inp1);
12974 SDValue VQDMULH = DAG.getNode(ARMISD::VQDMULH, DL, LegalVecVT, Inp0, Inp1);
12975 SDValue Trunc = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, ExtVecVT, VQDMULH);
12976 Trunc = DAG.getNode(ISD::TRUNCATE, DL, VecVT, Trunc);
12977 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Trunc);
12978 }
12979
12980 // For larger types, split into legal sized chunks.
12981 assert(VecVT.getSizeInBits() % 128 == 0 && "Expected a power2 type")(static_cast <bool> (VecVT.getSizeInBits() % 128 == 0 &&
"Expected a power2 type") ? void (0) : __assert_fail ("VecVT.getSizeInBits() % 128 == 0 && \"Expected a power2 type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 12981, __extension__ __PRETTY_FUNCTION__))
;
12982 unsigned NumParts = VecVT.getSizeInBits() / 128;
12983 SmallVector<SDValue> Parts;
12984 for (unsigned I = 0; I < NumParts; ++I) {
12985 SDValue Inp0 =
12986 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, LegalVecVT, Ext0.getOperand(0),
12987 DAG.getVectorIdxConstant(I * LegalLanes, DL));
12988 SDValue Inp1 =
12989 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, LegalVecVT, Ext1.getOperand(0),
12990 DAG.getVectorIdxConstant(I * LegalLanes, DL));
12991 SDValue VQDMULH = DAG.getNode(ARMISD::VQDMULH, DL, LegalVecVT, Inp0, Inp1);
12992 Parts.push_back(VQDMULH);
12993 }
12994 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT,
12995 DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Parts));
12996}
12997
12998static SDValue PerformVSELECTCombine(SDNode *N,
12999 TargetLowering::DAGCombinerInfo &DCI,
13000 const ARMSubtarget *Subtarget) {
13001 if (!Subtarget->hasMVEIntegerOps())
13002 return SDValue();
13003
13004 if (SDValue V = PerformVQDMULHCombine(N, DCI.DAG))
13005 return V;
13006
13007 // Transforms vselect(not(cond), lhs, rhs) into vselect(cond, rhs, lhs).
13008 //
13009 // We need to re-implement this optimization here as the implementation in the
13010 // Target-Independent DAGCombiner does not handle the kind of constant we make
13011 // (it calls isConstOrConstSplat with AllowTruncation set to false - and for
13012 // good reason, allowing truncation there would break other targets).
13013 //
13014 // Currently, this is only done for MVE, as it's the only target that benefits
13015 // from this transformation (e.g. VPNOT+VPSEL becomes a single VPSEL).
13016 if (N->getOperand(0).getOpcode() != ISD::XOR)
13017 return SDValue();
13018 SDValue XOR = N->getOperand(0);
13019
13020 // Check if the XOR's RHS is either a 1, or a BUILD_VECTOR of 1s.
13021 // It is important to check with truncation allowed as the BUILD_VECTORs we
13022 // generate in those situations will truncate their operands.
13023 ConstantSDNode *Const =
13024 isConstOrConstSplat(XOR->getOperand(1), /*AllowUndefs*/ false,
13025 /*AllowTruncation*/ true);
13026 if (!Const || !Const->isOne())
13027 return SDValue();
13028
13029 // Rewrite into vselect(cond, rhs, lhs).
13030 SDValue Cond = XOR->getOperand(0);
13031 SDValue LHS = N->getOperand(1);
13032 SDValue RHS = N->getOperand(2);
13033 EVT Type = N->getValueType(0);
13034 return DCI.DAG.getNode(ISD::VSELECT, SDLoc(N), Type, Cond, RHS, LHS);
13035}
13036
13037static SDValue PerformABSCombine(SDNode *N,
13038 TargetLowering::DAGCombinerInfo &DCI,
13039 const ARMSubtarget *Subtarget) {
13040 SDValue res;
13041 SelectionDAG &DAG = DCI.DAG;
13042 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13043
13044 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
13045 return SDValue();
13046
13047 if (!TLI.expandABS(N, res, DAG))
13048 return SDValue();
13049
13050 return res;
13051}
13052
13053/// PerformADDECombine - Target-specific dag combine transform from
13054/// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
13055/// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
13056static SDValue PerformADDECombine(SDNode *N,
13057 TargetLowering::DAGCombinerInfo &DCI,
13058 const ARMSubtarget *Subtarget) {
13059 // Only ARM and Thumb2 support UMLAL/SMLAL.
13060 if (Subtarget->isThumb1Only())
13061 return PerformAddeSubeCombine(N, DCI, Subtarget);
13062
13063 // Only perform the checks after legalize when the pattern is available.
13064 if (DCI.isBeforeLegalize()) return SDValue();
13065
13066 return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
13067}
13068
13069/// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
13070/// operands N0 and N1. This is a helper for PerformADDCombine that is
13071/// called with the default operands, and if that fails, with commuted
13072/// operands.
13073static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
13074 TargetLowering::DAGCombinerInfo &DCI,
13075 const ARMSubtarget *Subtarget){
13076 // Attempt to create vpadd for this add.
13077 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
13078 return Result;
13079
13080 // Attempt to create vpaddl for this add.
13081 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
13082 return Result;
13083 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
13084 Subtarget))
13085 return Result;
13086
13087 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
13088 if (N0.getNode()->hasOneUse())
13089 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
13090 return Result;
13091 return SDValue();
13092}
13093
13094static SDValue TryDistrubutionADDVecReduce(SDNode *N, SelectionDAG &DAG) {
13095 EVT VT = N->getValueType(0);
13096 SDValue N0 = N->getOperand(0);
13097 SDValue N1 = N->getOperand(1);
13098 SDLoc dl(N);
13099
13100 auto IsVecReduce = [](SDValue Op) {
13101 switch (Op.getOpcode()) {
13102 case ISD::VECREDUCE_ADD:
13103 case ARMISD::VADDVs:
13104 case ARMISD::VADDVu:
13105 case ARMISD::VMLAVs:
13106 case ARMISD::VMLAVu:
13107 return true;
13108 }
13109 return false;
13110 };
13111
13112 auto DistrubuteAddAddVecReduce = [&](SDValue N0, SDValue N1) {
13113 // Distribute add(X, add(vecreduce(Y), vecreduce(Z))) ->
13114 // add(add(X, vecreduce(Y)), vecreduce(Z))
13115 // to make better use of vaddva style instructions.
13116 if (VT == MVT::i32 && N1.getOpcode() == ISD::ADD && !IsVecReduce(N0) &&
13117 IsVecReduce(N1.getOperand(0)) && IsVecReduce(N1.getOperand(1)) &&
13118 !isa<ConstantSDNode>(N0)) {
13119 SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, N0, N1.getOperand(0));
13120 return DAG.getNode(ISD::ADD, dl, VT, Add0, N1.getOperand(1));
13121 }
13122 // And turn add(add(A, reduce(B)), add(C, reduce(D))) ->
13123 // add(add(add(A, C), reduce(B)), reduce(D))
13124 if (VT == MVT::i32 && N0.getOpcode() == ISD::ADD &&
13125 N1.getOpcode() == ISD::ADD) {
13126 unsigned N0RedOp = 0;
13127 if (!IsVecReduce(N0.getOperand(N0RedOp))) {
13128 N0RedOp = 1;
13129 if (!IsVecReduce(N0.getOperand(N0RedOp)))
13130 return SDValue();
13131 }
13132
13133 unsigned N1RedOp = 0;
13134 if (!IsVecReduce(N1.getOperand(N1RedOp)))
13135 N1RedOp = 1;
13136 if (!IsVecReduce(N1.getOperand(N1RedOp)))
13137 return SDValue();
13138
13139 SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, N0.getOperand(1 - N0RedOp),
13140 N1.getOperand(1 - N1RedOp));
13141 SDValue Add1 =
13142 DAG.getNode(ISD::ADD, dl, VT, Add0, N0.getOperand(N0RedOp));
13143 return DAG.getNode(ISD::ADD, dl, VT, Add1, N1.getOperand(N1RedOp));
13144 }
13145 return SDValue();
13146 };
13147 if (SDValue R = DistrubuteAddAddVecReduce(N0, N1))
13148 return R;
13149 if (SDValue R = DistrubuteAddAddVecReduce(N1, N0))
13150 return R;
13151
13152 // Distribute add(vecreduce(load(Y)), vecreduce(load(Z)))
13153 // Or add(add(X, vecreduce(load(Y))), vecreduce(load(Z)))
13154 // by ascending load offsets. This can help cores prefetch if the order of
13155 // loads is more predictable.
13156 auto DistrubuteVecReduceLoad = [&](SDValue N0, SDValue N1, bool IsForward) {
13157 // Check if two reductions are known to load data where one is before/after
13158 // another. Return negative if N0 loads data before N1, positive if N1 is
13159 // before N0 and 0 otherwise if nothing is known.
13160 auto IsKnownOrderedLoad = [&](SDValue N0, SDValue N1) {
13161 // Look through to the first operand of a MUL, for the VMLA case.
13162 // Currently only looks at the first operand, in the hope they are equal.
13163 if (N0.getOpcode() == ISD::MUL)
13164 N0 = N0.getOperand(0);
13165 if (N1.getOpcode() == ISD::MUL)
13166 N1 = N1.getOperand(0);
13167
13168 // Return true if the two operands are loads to the same object and the
13169 // offset of the first is known to be less than the offset of the second.
13170 LoadSDNode *Load0 = dyn_cast<LoadSDNode>(N0);
13171 LoadSDNode *Load1 = dyn_cast<LoadSDNode>(N1);
13172 if (!Load0 || !Load1 || Load0->getChain() != Load1->getChain() ||
13173 !Load0->isSimple() || !Load1->isSimple() || Load0->isIndexed() ||
13174 Load1->isIndexed())
13175 return 0;
13176
13177 auto BaseLocDecomp0 = BaseIndexOffset::match(Load0, DAG);
13178 auto BaseLocDecomp1 = BaseIndexOffset::match(Load1, DAG);
13179
13180 if (!BaseLocDecomp0.getBase() ||
13181 BaseLocDecomp0.getBase() != BaseLocDecomp1.getBase() ||
13182 !BaseLocDecomp0.hasValidOffset() || !BaseLocDecomp1.hasValidOffset())
13183 return 0;
13184 if (BaseLocDecomp0.getOffset() < BaseLocDecomp1.getOffset())
13185 return -1;
13186 if (BaseLocDecomp0.getOffset() > BaseLocDecomp1.getOffset())
13187 return 1;
13188 return 0;
13189 };
13190
13191 SDValue X;
13192 if (N0.getOpcode() == ISD::ADD) {
13193 if (IsVecReduce(N0.getOperand(0)) && IsVecReduce(N0.getOperand(1))) {
13194 int IsBefore = IsKnownOrderedLoad(N0.getOperand(0).getOperand(0),
13195 N0.getOperand(1).getOperand(0));
13196 if (IsBefore < 0) {
13197 X = N0.getOperand(0);
13198 N0 = N0.getOperand(1);
13199 } else if (IsBefore > 0) {
13200 X = N0.getOperand(1);
13201 N0 = N0.getOperand(0);
13202 } else
13203 return SDValue();
13204 } else if (IsVecReduce(N0.getOperand(0))) {
13205 X = N0.getOperand(1);
13206 N0 = N0.getOperand(0);
13207 } else if (IsVecReduce(N0.getOperand(1))) {
13208 X = N0.getOperand(0);
13209 N0 = N0.getOperand(1);
13210 } else
13211 return SDValue();
13212 } else if (IsForward && IsVecReduce(N0) && IsVecReduce(N1) &&
13213 IsKnownOrderedLoad(N0.getOperand(0), N1.getOperand(0)) < 0) {
13214 // Note this is backward to how you would expect. We create
13215 // add(reduce(load + 16), reduce(load + 0)) so that the
13216 // add(reduce(load+16), X) is combined into VADDVA(X, load+16)), leaving
13217 // the X as VADDV(load + 0)
13218 return DAG.getNode(ISD::ADD, dl, VT, N1, N0);
13219 } else
13220 return SDValue();
13221
13222 if (!IsVecReduce(N0) || !IsVecReduce(N1))
13223 return SDValue();
13224
13225 if (IsKnownOrderedLoad(N1.getOperand(0), N0.getOperand(0)) >= 0)
13226 return SDValue();
13227
13228 // Switch from add(add(X, N0), N1) to add(add(X, N1), N0)
13229 SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, X, N1);
13230 return DAG.getNode(ISD::ADD, dl, VT, Add0, N0);
13231 };
13232 if (SDValue R = DistrubuteVecReduceLoad(N0, N1, true))
13233 return R;
13234 if (SDValue R = DistrubuteVecReduceLoad(N1, N0, false))
13235 return R;
13236 return SDValue();
13237}
13238
13239static SDValue PerformADDVecReduce(SDNode *N, SelectionDAG &DAG,
13240 const ARMSubtarget *Subtarget) {
13241 if (!Subtarget->hasMVEIntegerOps())
13242 return SDValue();
13243
13244 if (SDValue R = TryDistrubutionADDVecReduce(N, DAG))
13245 return R;
13246
13247 EVT VT = N->getValueType(0);
13248 SDValue N0 = N->getOperand(0);
13249 SDValue N1 = N->getOperand(1);
13250 SDLoc dl(N);
13251
13252 if (VT != MVT::i64)
13253 return SDValue();
13254
13255 // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this
13256 // will look like:
13257 // t1: i32,i32 = ARMISD::VADDLVs x
13258 // t2: i64 = build_pair t1, t1:1
13259 // t3: i64 = add t2, y
13260 // Otherwise we try to push the add up above VADDLVAx, to potentially allow
13261 // the add to be simplified seperately.
13262 // We also need to check for sext / zext and commutitive adds.
13263 auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA,
13264 SDValue NB) {
13265 if (NB->getOpcode() != ISD::BUILD_PAIR)
13266 return SDValue();
13267 SDValue VecRed = NB->getOperand(0);
13268 if ((VecRed->getOpcode() != Opcode && VecRed->getOpcode() != OpcodeA) ||
13269 VecRed.getResNo() != 0 ||
13270 NB->getOperand(1) != SDValue(VecRed.getNode(), 1))
13271 return SDValue();
13272
13273 if (VecRed->getOpcode() == OpcodeA) {
13274 // add(NA, VADDLVA(Inp), Y) -> VADDLVA(add(NA, Inp), Y)
13275 SDValue Inp = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
13276 VecRed.getOperand(0), VecRed.getOperand(1));
13277 NA = DAG.getNode(ISD::ADD, dl, MVT::i64, Inp, NA);
13278 }
13279
13280 SmallVector<SDValue, 4> Ops;
13281 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA,
13282 DAG.getConstant(0, dl, MVT::i32)));
13283 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA,
13284 DAG.getConstant(1, dl, MVT::i32)));
13285 unsigned S = VecRed->getOpcode() == OpcodeA ? 2 : 0;
13286 for (unsigned I = S, E = VecRed.getNumOperands(); I < E; I++)
13287 Ops.push_back(VecRed->getOperand(I));
13288 SDValue Red =
13289 DAG.getNode(OpcodeA, dl, DAG.getVTList({MVT::i32, MVT::i32}), Ops);
13290 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Red,
13291 SDValue(Red.getNode(), 1));
13292 };
13293
13294 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1))
13295 return M;
13296 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1))
13297 return M;
13298 if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0))
13299 return M;
13300 if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0))
13301 return M;
13302 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1))
13303 return M;
13304 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1))
13305 return M;
13306 if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0))
13307 return M;
13308 if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0))
13309 return M;
13310 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1))
13311 return M;
13312 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1))
13313 return M;
13314 if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0))
13315 return M;
13316 if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0))
13317 return M;
13318 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N0, N1))
13319 return M;
13320 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N0, N1))
13321 return M;
13322 if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N1, N0))
13323 return M;
13324 if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N1, N0))
13325 return M;
13326 return SDValue();
13327}
13328
13329bool
13330ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
13331 CombineLevel Level) const {
13332 if (Level == BeforeLegalizeTypes)
13333 return true;
13334
13335 if (N->getOpcode() != ISD::SHL)
13336 return true;
13337
13338 if (Subtarget->isThumb1Only()) {
13339 // Avoid making expensive immediates by commuting shifts. (This logic
13340 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
13341 // for free.)
13342 if (N->getOpcode() != ISD::SHL)
13343 return true;
13344 SDValue N1 = N->getOperand(0);
13345 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
13346 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
13347 return true;
13348 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
13349 if (Const->getAPIntValue().ult(256))
13350 return false;
13351 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
13352 Const->getAPIntValue().sgt(-256))
13353 return false;
13354 }
13355 return true;
13356 }
13357
13358 // Turn off commute-with-shift transform after legalization, so it doesn't
13359 // conflict with PerformSHLSimplify. (We could try to detect when
13360 // PerformSHLSimplify would trigger more precisely, but it isn't
13361 // really necessary.)
13362 return false;
13363}
13364
13365bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
13366 const SDNode *N, CombineLevel Level) const {
13367 if (!Subtarget->isThumb1Only())
13368 return true;
13369
13370 if (Level == BeforeLegalizeTypes)
13371 return true;
13372
13373 return false;
13374}
13375
13376bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
13377 if (!Subtarget->hasNEON()) {
13378 if (Subtarget->isThumb1Only())
13379 return VT.getScalarSizeInBits() <= 32;
13380 return true;
13381 }
13382 return VT.isScalarInteger();
13383}
13384
13385static SDValue PerformSHLSimplify(SDNode *N,
13386 TargetLowering::DAGCombinerInfo &DCI,
13387 const ARMSubtarget *ST) {
13388 // Allow the generic combiner to identify potential bswaps.
13389 if (DCI.isBeforeLegalize())
13390 return SDValue();
13391
13392 // DAG combiner will fold:
13393 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
13394 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
13395 // Other code patterns that can be also be modified have the following form:
13396 // b + ((a << 1) | 510)
13397 // b + ((a << 1) & 510)
13398 // b + ((a << 1) ^ 510)
13399 // b + ((a << 1) + 510)
13400
13401 // Many instructions can perform the shift for free, but it requires both
13402 // the operands to be registers. If c1 << c2 is too large, a mov immediate
13403 // instruction will needed. So, unfold back to the original pattern if:
13404 // - if c1 and c2 are small enough that they don't require mov imms.
13405 // - the user(s) of the node can perform an shl
13406
13407 // No shifted operands for 16-bit instructions.
13408 if (ST->isThumb() && ST->isThumb1Only())
13409 return SDValue();
13410
13411 // Check that all the users could perform the shl themselves.
13412 for (auto U : N->uses()) {
13413 switch(U->getOpcode()) {
13414 default:
13415 return SDValue();
13416 case ISD::SUB:
13417 case ISD::ADD:
13418 case ISD::AND:
13419 case ISD::OR:
13420 case ISD::XOR:
13421 case ISD::SETCC:
13422 case ARMISD::CMP:
13423 // Check that the user isn't already using a constant because there
13424 // aren't any instructions that support an immediate operand and a
13425 // shifted operand.
13426 if (isa<ConstantSDNode>(U->getOperand(0)) ||
13427 isa<ConstantSDNode>(U->getOperand(1)))
13428 return SDValue();
13429
13430 // Check that it's not already using a shift.
13431 if (U->getOperand(0).getOpcode() == ISD::SHL ||
13432 U->getOperand(1).getOpcode() == ISD::SHL)
13433 return SDValue();
13434 break;
13435 }
13436 }
13437
13438 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
13439 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
13440 return SDValue();
13441
13442 if (N->getOperand(0).getOpcode() != ISD::SHL)
13443 return SDValue();
13444
13445 SDValue SHL = N->getOperand(0);
13446
13447 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
13448 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
13449 if (!C1ShlC2 || !C2)
13450 return SDValue();
13451
13452 APInt C2Int = C2->getAPIntValue();
13453 APInt C1Int = C1ShlC2->getAPIntValue();
13454
13455 // Check that performing a lshr will not lose any information.
13456 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
13457 C2Int.getBitWidth() - C2->getZExtValue());
13458 if ((C1Int & Mask) != C1Int)
13459 return SDValue();
13460
13461 // Shift the first constant.
13462 C1Int.lshrInPlace(C2Int);
13463
13464 // The immediates are encoded as an 8-bit value that can be rotated.
13465 auto LargeImm = [](const APInt &Imm) {
13466 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
13467 return Imm.getBitWidth() - Zeros > 8;
13468 };
13469
13470 if (LargeImm(C1Int) || LargeImm(C2Int))
13471 return SDValue();
13472
13473 SelectionDAG &DAG = DCI.DAG;
13474 SDLoc dl(N);
13475 SDValue X = SHL.getOperand(0);
13476 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
13477 DAG.getConstant(C1Int, dl, MVT::i32));
13478 // Shift left to compensate for the lshr of C1Int.
13479 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
13480
13481 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("arm-isel")) { dbgs() << "Simplify shl use:\n"; SHL.getOperand
(0).dump(); SHL.dump(); N->dump(); } } while (false)
13482 SHL.dump(); N->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("arm-isel")) { dbgs() << "Simplify shl use:\n"; SHL.getOperand
(0).dump(); SHL.dump(); N->dump(); } } while (false)
;
13483 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("arm-isel")) { dbgs() << "Into:\n"; X.dump(); BinOp.dump
(); Res.dump(); } } while (false)
;
13484 return Res;
13485}
13486
13487
13488/// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
13489///
13490static SDValue PerformADDCombine(SDNode *N,
13491 TargetLowering::DAGCombinerInfo &DCI,
13492 const ARMSubtarget *Subtarget) {
13493 SDValue N0 = N->getOperand(0);
13494 SDValue N1 = N->getOperand(1);
13495
13496 // Only works one way, because it needs an immediate operand.
13497 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
13498 return Result;
13499
13500 if (SDValue Result = PerformADDVecReduce(N, DCI.DAG, Subtarget))
13501 return Result;
13502
13503 // First try with the default operand order.
13504 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
13505 return Result;
13506
13507 // If that didn't work, try again with the operands commuted.
13508 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
13509}
13510
13511// Combine (sub 0, (csinc X, Y, CC)) -> (csinv -X, Y, CC)
13512// providing -X is as cheap as X (currently, just a constant).
13513static SDValue PerformSubCSINCCombine(SDNode *N, SelectionDAG &DAG) {
13514 if (N->getValueType(0) != MVT::i32 || !isNullConstant(N->getOperand(0)))
13515 return SDValue();
13516 SDValue CSINC = N->getOperand(1);
13517 if (CSINC.getOpcode() != ARMISD::CSINC || !CSINC.hasOneUse())
13518 return SDValue();
13519
13520 ConstantSDNode *X = dyn_cast<ConstantSDNode>(CSINC.getOperand(0));
13521 if (!X)
13522 return SDValue();
13523
13524 return DAG.getNode(ARMISD::CSINV, SDLoc(N), MVT::i32,
13525 DAG.getNode(ISD::SUB, SDLoc(N), MVT::i32, N->getOperand(0),
13526 CSINC.getOperand(0)),
13527 CSINC.getOperand(1), CSINC.getOperand(2),
13528 CSINC.getOperand(3));
13529}
13530
13531/// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
13532///
13533static SDValue PerformSUBCombine(SDNode *N,
13534 TargetLowering::DAGCombinerInfo &DCI,
13535 const ARMSubtarget *Subtarget) {
13536 SDValue N0 = N->getOperand(0);
13537 SDValue N1 = N->getOperand(1);
13538
13539 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
13540 if (N1.getNode()->hasOneUse())
13541 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
13542 return Result;
13543
13544 if (SDValue R = PerformSubCSINCCombine(N, DCI.DAG))
13545 return R;
13546
13547 if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector())
13548 return SDValue();
13549
13550 // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x))
13551 // so that we can readily pattern match more mve instructions which can use
13552 // a scalar operand.
13553 SDValue VDup = N->getOperand(1);
13554 if (VDup->getOpcode() != ARMISD::VDUP)
13555 return SDValue();
13556
13557 SDValue VMov = N->getOperand(0);
13558 if (VMov->getOpcode() == ISD::BITCAST)
13559 VMov = VMov->getOperand(0);
13560
13561 if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov))
13562 return SDValue();
13563
13564 SDLoc dl(N);
13565 SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32,
13566 DCI.DAG.getConstant(0, dl, MVT::i32),
13567 VDup->getOperand(0));
13568 return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate);
13569}
13570
13571/// PerformVMULCombine
13572/// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
13573/// special multiplier accumulator forwarding.
13574/// vmul d3, d0, d2
13575/// vmla d3, d1, d2
13576/// is faster than
13577/// vadd d3, d0, d1
13578/// vmul d3, d3, d2
13579// However, for (A + B) * (A + B),
13580// vadd d2, d0, d1
13581// vmul d3, d0, d2
13582// vmla d3, d1, d2
13583// is slower than
13584// vadd d2, d0, d1
13585// vmul d3, d2, d2
13586static SDValue PerformVMULCombine(SDNode *N,
13587 TargetLowering::DAGCombinerInfo &DCI,
13588 const ARMSubtarget *Subtarget) {
13589 if (!Subtarget->hasVMLxForwarding())
13590 return SDValue();
13591
13592 SelectionDAG &DAG = DCI.DAG;
13593 SDValue N0 = N->getOperand(0);
13594 SDValue N1 = N->getOperand(1);
13595 unsigned Opcode = N0.getOpcode();
13596 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
13597 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
13598 Opcode = N1.getOpcode();
13599 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
13600 Opcode != ISD::FADD && Opcode != ISD::FSUB)
13601 return SDValue();
13602 std::swap(N0, N1);
13603 }
13604
13605 if (N0 == N1)
13606 return SDValue();
13607
13608 EVT VT = N->getValueType(0);
13609 SDLoc DL(N);
13610 SDValue N00 = N0->getOperand(0);
13611 SDValue N01 = N0->getOperand(1);
13612 return DAG.getNode(Opcode, DL, VT,
13613 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
13614 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
13615}
13616
13617static SDValue PerformMVEVMULLCombine(SDNode *N, SelectionDAG &DAG,
13618 const ARMSubtarget *Subtarget) {
13619 EVT VT = N->getValueType(0);
13620 if (VT != MVT::v2i64)
13621 return SDValue();
13622
13623 SDValue N0 = N->getOperand(0);
13624 SDValue N1 = N->getOperand(1);
13625
13626 auto IsSignExt = [&](SDValue Op) {
13627 if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG)
13628 return SDValue();
13629 EVT VT = cast<VTSDNode>(Op->getOperand(1))->getVT();
13630 if (VT.getScalarSizeInBits() == 32)
13631 return Op->getOperand(0);
13632 return SDValue();
13633 };
13634 auto IsZeroExt = [&](SDValue Op) {
13635 // Zero extends are a little more awkward. At the point we are matching
13636 // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask.
13637 // That might be before of after a bitcast depending on how the and is
13638 // placed. Because this has to look through bitcasts, it is currently only
13639 // supported on LE.
13640 if (!Subtarget->isLittle())
13641 return SDValue();
13642
13643 SDValue And = Op;
13644 if (And->getOpcode() == ISD::BITCAST)
13645 And = And->getOperand(0);
13646 if (And->getOpcode() != ISD::AND)
13647 return SDValue();
13648 SDValue Mask = And->getOperand(1);
13649 if (Mask->getOpcode() == ISD::BITCAST)
13650 Mask = Mask->getOperand(0);
13651
13652 if (Mask->getOpcode() != ISD::BUILD_VECTOR ||
13653 Mask.getValueType() != MVT::v4i32)
13654 return SDValue();
13655 if (isAllOnesConstant(Mask->getOperand(0)) &&
13656 isNullConstant(Mask->getOperand(1)) &&
13657 isAllOnesConstant(Mask->getOperand(2)) &&
13658 isNullConstant(Mask->getOperand(3)))
13659 return And->getOperand(0);
13660 return SDValue();
13661 };
13662
13663 SDLoc dl(N);
13664 if (SDValue Op0 = IsSignExt(N0)) {
13665 if (SDValue Op1 = IsSignExt(N1)) {
13666 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
13667 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
13668 return DAG.getNode(ARMISD::VMULLs, dl, VT, New0a, New1a);
13669 }
13670 }
13671 if (SDValue Op0 = IsZeroExt(N0)) {
13672 if (SDValue Op1 = IsZeroExt(N1)) {
13673 SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
13674 SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
13675 return DAG.getNode(ARMISD::VMULLu, dl, VT, New0a, New1a);
13676 }
13677 }
13678
13679 return SDValue();
13680}
13681
13682static SDValue PerformMULCombine(SDNode *N,
13683 TargetLowering::DAGCombinerInfo &DCI,
13684 const ARMSubtarget *Subtarget) {
13685 SelectionDAG &DAG = DCI.DAG;
13686
13687 EVT VT = N->getValueType(0);
13688 if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64)
13689 return PerformMVEVMULLCombine(N, DAG, Subtarget);
13690
13691 if (Subtarget->isThumb1Only())
13692 return SDValue();
13693
13694 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13695 return SDValue();
13696
13697 if (VT.is64BitVector() || VT.is128BitVector())
13698 return PerformVMULCombine(N, DCI, Subtarget);
13699 if (VT != MVT::i32)
13700 return SDValue();
13701
13702 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13703 if (!C)
13704 return SDValue();
13705
13706 int64_t MulAmt = C->getSExtValue();
13707 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
13708
13709 ShiftAmt = ShiftAmt & (32 - 1);
13710 SDValue V = N->getOperand(0);
13711 SDLoc DL(N);
13712
13713 SDValue Res;
13714 MulAmt >>= ShiftAmt;
13715
13716 if (MulAmt >= 0) {
13717 if (isPowerOf2_32(MulAmt - 1)) {
13718 // (mul x, 2^N + 1) => (add (shl x, N), x)
13719 Res = DAG.getNode(ISD::ADD, DL, VT,
13720 V,
13721 DAG.getNode(ISD::SHL, DL, VT,
13722 V,
13723 DAG.getConstant(Log2_32(MulAmt - 1), DL,
13724 MVT::i32)));
13725 } else if (isPowerOf2_32(MulAmt + 1)) {
13726 // (mul x, 2^N - 1) => (sub (shl x, N), x)
13727 Res = DAG.getNode(ISD::SUB, DL, VT,
13728 DAG.getNode(ISD::SHL, DL, VT,
13729 V,
13730 DAG.getConstant(Log2_32(MulAmt + 1), DL,
13731 MVT::i32)),
13732 V);
13733 } else
13734 return SDValue();
13735 } else {
13736 uint64_t MulAmtAbs = -MulAmt;
13737 if (isPowerOf2_32(MulAmtAbs + 1)) {
13738 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
13739 Res = DAG.getNode(ISD::SUB, DL, VT,
13740 V,
13741 DAG.getNode(ISD::SHL, DL, VT,
13742 V,
13743 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
13744 MVT::i32)));
13745 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
13746 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
13747 Res = DAG.getNode(ISD::ADD, DL, VT,
13748 V,
13749 DAG.getNode(ISD::SHL, DL, VT,
13750 V,
13751 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
13752 MVT::i32)));
13753 Res = DAG.getNode(ISD::SUB, DL, VT,
13754 DAG.getConstant(0, DL, MVT::i32), Res);
13755 } else
13756 return SDValue();
13757 }
13758
13759 if (ShiftAmt != 0)
13760 Res = DAG.getNode(ISD::SHL, DL, VT,
13761 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
13762
13763 // Do not add new nodes to DAG combiner worklist.
13764 DCI.CombineTo(N, Res, false);
13765 return SDValue();
13766}
13767
13768static SDValue CombineANDShift(SDNode *N,
13769 TargetLowering::DAGCombinerInfo &DCI,
13770 const ARMSubtarget *Subtarget) {
13771 // Allow DAGCombine to pattern-match before we touch the canonical form.
13772 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13773 return SDValue();
13774
13775 if (N->getValueType(0) != MVT::i32)
13776 return SDValue();
13777
13778 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13779 if (!N1C)
13780 return SDValue();
13781
13782 uint32_t C1 = (uint32_t)N1C->getZExtValue();
13783 // Don't transform uxtb/uxth.
13784 if (C1 == 255 || C1 == 65535)
13785 return SDValue();
13786
13787 SDNode *N0 = N->getOperand(0).getNode();
13788 if (!N0->hasOneUse())
13789 return SDValue();
13790
13791 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
13792 return SDValue();
13793
13794 bool LeftShift = N0->getOpcode() == ISD::SHL;
13795
13796 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13797 if (!N01C)
13798 return SDValue();
13799
13800 uint32_t C2 = (uint32_t)N01C->getZExtValue();
13801 if (!C2 || C2 >= 32)
13802 return SDValue();
13803
13804 // Clear irrelevant bits in the mask.
13805 if (LeftShift)
13806 C1 &= (-1U << C2);
13807 else
13808 C1 &= (-1U >> C2);
13809
13810 SelectionDAG &DAG = DCI.DAG;
13811 SDLoc DL(N);
13812
13813 // We have a pattern of the form "(and (shl x, c2) c1)" or
13814 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
13815 // transform to a pair of shifts, to save materializing c1.
13816
13817 // First pattern: right shift, then mask off leading bits.
13818 // FIXME: Use demanded bits?
13819 if (!LeftShift && isMask_32(C1)) {
13820 uint32_t C3 = countLeadingZeros(C1);
13821 if (C2 < C3) {
13822 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
13823 DAG.getConstant(C3 - C2, DL, MVT::i32));
13824 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
13825 DAG.getConstant(C3, DL, MVT::i32));
13826 }
13827 }
13828
13829 // First pattern, reversed: left shift, then mask off trailing bits.
13830 if (LeftShift && isMask_32(~C1)) {
13831 uint32_t C3 = countTrailingZeros(C1);
13832 if (C2 < C3) {
13833 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
13834 DAG.getConstant(C3 - C2, DL, MVT::i32));
13835 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
13836 DAG.getConstant(C3, DL, MVT::i32));
13837 }
13838 }
13839
13840 // Second pattern: left shift, then mask off leading bits.
13841 // FIXME: Use demanded bits?
13842 if (LeftShift && isShiftedMask_32(C1)) {
13843 uint32_t Trailing = countTrailingZeros(C1);
13844 uint32_t C3 = countLeadingZeros(C1);
13845 if (Trailing == C2 && C2 + C3 < 32) {
13846 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
13847 DAG.getConstant(C2 + C3, DL, MVT::i32));
13848 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
13849 DAG.getConstant(C3, DL, MVT::i32));
13850 }
13851 }
13852
13853 // Second pattern, reversed: right shift, then mask off trailing bits.
13854 // FIXME: Handle other patterns of known/demanded bits.
13855 if (!LeftShift && isShiftedMask_32(C1)) {
13856 uint32_t Leading = countLeadingZeros(C1);
13857 uint32_t C3 = countTrailingZeros(C1);
13858 if (Leading == C2 && C2 + C3 < 32) {
13859 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
13860 DAG.getConstant(C2 + C3, DL, MVT::i32));
13861 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
13862 DAG.getConstant(C3, DL, MVT::i32));
13863 }
13864 }
13865
13866 // FIXME: Transform "(and (shl x, c2) c1)" ->
13867 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
13868 // c1.
13869 return SDValue();
13870}
13871
13872static SDValue PerformANDCombine(SDNode *N,
13873 TargetLowering::DAGCombinerInfo &DCI,
13874 const ARMSubtarget *Subtarget) {
13875 // Attempt to use immediate-form VBIC
13876 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
13877 SDLoc dl(N);
13878 EVT VT = N->getValueType(0);
13879 SelectionDAG &DAG = DCI.DAG;
13880
13881 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) || VT == MVT::v4i1 ||
13882 VT == MVT::v8i1 || VT == MVT::v16i1)
13883 return SDValue();
13884
13885 APInt SplatBits, SplatUndef;
13886 unsigned SplatBitSize;
13887 bool HasAnyUndefs;
13888 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
13889 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
13890 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
13891 SplatBitSize == 64) {
13892 EVT VbicVT;
13893 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
13894 SplatUndef.getZExtValue(), SplatBitSize,
13895 DAG, dl, VbicVT, VT, OtherModImm);
13896 if (Val.getNode()) {
13897 SDValue Input =
13898 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
13899 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
13900 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
13901 }
13902 }
13903 }
13904
13905 if (!Subtarget->isThumb1Only()) {
13906 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
13907 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
13908 return Result;
13909
13910 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
13911 return Result;
13912 }
13913
13914 if (Subtarget->isThumb1Only())
13915 if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
13916 return Result;
13917
13918 return SDValue();
13919}
13920
13921// Try combining OR nodes to SMULWB, SMULWT.
13922static SDValue PerformORCombineToSMULWBT(SDNode *OR,
13923 TargetLowering::DAGCombinerInfo &DCI,
13924 const ARMSubtarget *Subtarget) {
13925 if (!Subtarget->hasV6Ops() ||
13926 (Subtarget->isThumb() &&
13927 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
13928 return SDValue();
13929
13930 SDValue SRL = OR->getOperand(0);
13931 SDValue SHL = OR->getOperand(1);
13932
13933 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
13934 SRL = OR->getOperand(1);
13935 SHL = OR->getOperand(0);
13936 }
13937 if (!isSRL16(SRL) || !isSHL16(SHL))
13938 return SDValue();
13939
13940 // The first operands to the shifts need to be the two results from the
13941 // same smul_lohi node.
13942 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
13943 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
13944 return SDValue();
13945
13946 SDNode *SMULLOHI = SRL.getOperand(0).getNode();
13947 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
13948 SHL.getOperand(0) != SDValue(SMULLOHI, 1))
13949 return SDValue();
13950
13951 // Now we have:
13952 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
13953 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
13954 // For SMUWB the 16-bit value will signed extended somehow.
13955 // For SMULWT only the SRA is required.
13956 // Check both sides of SMUL_LOHI
13957 SDValue OpS16 = SMULLOHI->getOperand(0);
13958 SDValue OpS32 = SMULLOHI->getOperand(1);
13959
13960 SelectionDAG &DAG = DCI.DAG;
13961 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
13962 OpS16 = OpS32;
13963 OpS32 = SMULLOHI->getOperand(0);
13964 }
13965
13966 SDLoc dl(OR);
13967 unsigned Opcode = 0;
13968 if (isS16(OpS16, DAG))
13969 Opcode = ARMISD::SMULWB;
13970 else if (isSRA16(OpS16)) {
13971 Opcode = ARMISD::SMULWT;
13972 OpS16 = OpS16->getOperand(0);
13973 }
13974 else
13975 return SDValue();
13976
13977 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
13978 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
13979 return SDValue(OR, 0);
13980}
13981
13982static SDValue PerformORCombineToBFI(SDNode *N,
13983 TargetLowering::DAGCombinerInfo &DCI,
13984 const ARMSubtarget *Subtarget) {
13985 // BFI is only available on V6T2+
13986 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
13987 return SDValue();
13988
13989 EVT VT = N->getValueType(0);
13990 SDValue N0 = N->getOperand(0);
13991 SDValue N1 = N->getOperand(1);
13992 SelectionDAG &DAG = DCI.DAG;
13993 SDLoc DL(N);
13994 // 1) or (and A, mask), val => ARMbfi A, val, mask
13995 // iff (val & mask) == val
13996 //
13997 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
13998 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
13999 // && mask == ~mask2
14000 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
14001 // && ~mask == mask2
14002 // (i.e., copy a bitfield value into another bitfield of the same width)
14003
14004 if (VT != MVT::i32)
14005 return SDValue();
14006
14007 SDValue N00 = N0.getOperand(0);
14008
14009 // The value and the mask need to be constants so we can verify this is
14010 // actually a bitfield set. If the mask is 0xffff, we can do better
14011 // via a movt instruction, so don't use BFI in that case.
14012 SDValue MaskOp = N0.getOperand(1);
14013 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
14014 if (!MaskC)
14015 return SDValue();
14016 unsigned Mask = MaskC->getZExtValue();
14017 if (Mask == 0xffff)
14018 return SDValue();
14019 SDValue Res;
14020 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
14021 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14022 if (N1C) {
14023 unsigned Val = N1C->getZExtValue();
14024 if ((Val & ~Mask) != Val)
14025 return SDValue();
14026
14027 if (ARM::isBitFieldInvertedMask(Mask)) {
14028 Val >>= countTrailingZeros(~Mask);
14029
14030 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
14031 DAG.getConstant(Val, DL, MVT::i32),
14032 DAG.getConstant(Mask, DL, MVT::i32));
14033
14034 DCI.CombineTo(N, Res, false);
14035 // Return value from the original node to inform the combiner than N is
14036 // now dead.
14037 return SDValue(N, 0);
14038 }
14039 } else if (N1.getOpcode() == ISD::AND) {
14040 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
14041 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
14042 if (!N11C)
14043 return SDValue();
14044 unsigned Mask2 = N11C->getZExtValue();
14045
14046 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
14047 // as is to match.
14048 if (ARM::isBitFieldInvertedMask(Mask) &&
14049 (Mask == ~Mask2)) {
14050 // The pack halfword instruction works better for masks that fit it,
14051 // so use that when it's available.
14052 if (Subtarget->hasDSP() &&
14053 (Mask == 0xffff || Mask == 0xffff0000))
14054 return SDValue();
14055 // 2a
14056 unsigned amt = countTrailingZeros(Mask2);
14057 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
14058 DAG.getConstant(amt, DL, MVT::i32));
14059 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
14060 DAG.getConstant(Mask, DL, MVT::i32));
14061 DCI.CombineTo(N, Res, false);
14062 // Return value from the original node to inform the combiner than N is
14063 // now dead.
14064 return SDValue(N, 0);
14065 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
14066 (~Mask == Mask2)) {
14067 // The pack halfword instruction works better for masks that fit it,
14068 // so use that when it's available.
14069 if (Subtarget->hasDSP() &&
14070 (Mask2 == 0xffff || Mask2 == 0xffff0000))
14071 return SDValue();
14072 // 2b
14073 unsigned lsb = countTrailingZeros(Mask);
14074 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
14075 DAG.getConstant(lsb, DL, MVT::i32));
14076 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
14077 DAG.getConstant(Mask2, DL, MVT::i32));
14078 DCI.CombineTo(N, Res, false);
14079 // Return value from the original node to inform the combiner than N is
14080 // now dead.
14081 return SDValue(N, 0);
14082 }
14083 }
14084
14085 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
14086 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
14087 ARM::isBitFieldInvertedMask(~Mask)) {
14088 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
14089 // where lsb(mask) == #shamt and masked bits of B are known zero.
14090 SDValue ShAmt = N00.getOperand(1);
14091 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
14092 unsigned LSB = countTrailingZeros(Mask);
14093 if (ShAmtC != LSB)
14094 return SDValue();
14095
14096 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
14097 DAG.getConstant(~Mask, DL, MVT::i32));
14098
14099 DCI.CombineTo(N, Res, false);
14100 // Return value from the original node to inform the combiner than N is
14101 // now dead.
14102 return SDValue(N, 0);
14103 }
14104
14105 return SDValue();
14106}
14107
14108static bool isValidMVECond(unsigned CC, bool IsFloat) {
14109 switch (CC) {
14110 case ARMCC::EQ:
14111 case ARMCC::NE:
14112 case ARMCC::LE:
14113 case ARMCC::GT:
14114 case ARMCC::GE:
14115 case ARMCC::LT:
14116 return true;
14117 case ARMCC::HS:
14118 case ARMCC::HI:
14119 return !IsFloat;
14120 default:
14121 return false;
14122 };
14123}
14124
14125static ARMCC::CondCodes getVCMPCondCode(SDValue N) {
14126 if (N->getOpcode() == ARMISD::VCMP)
14127 return (ARMCC::CondCodes)N->getConstantOperandVal(2);
14128 else if (N->getOpcode() == ARMISD::VCMPZ)
14129 return (ARMCC::CondCodes)N->getConstantOperandVal(1);
14130 else
14131 llvm_unreachable("Not a VCMP/VCMPZ!")::llvm::llvm_unreachable_internal("Not a VCMP/VCMPZ!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 14131)
;
14132}
14133
14134static bool CanInvertMVEVCMP(SDValue N) {
14135 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N));
14136 return isValidMVECond(CC, N->getOperand(0).getValueType().isFloatingPoint());
14137}
14138
14139static SDValue PerformORCombine_i1(SDNode *N, SelectionDAG &DAG,
14140 const ARMSubtarget *Subtarget) {
14141 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
14142 // together with predicates
14143 EVT VT = N->getValueType(0);
14144 SDLoc DL(N);
14145 SDValue N0 = N->getOperand(0);
14146 SDValue N1 = N->getOperand(1);
14147
14148 auto IsFreelyInvertable = [&](SDValue V) {
14149 if (V->getOpcode() == ARMISD::VCMP || V->getOpcode() == ARMISD::VCMPZ)
14150 return CanInvertMVEVCMP(V);
14151 return false;
14152 };
14153
14154 // At least one operand must be freely invertable.
14155 if (!(IsFreelyInvertable(N0) || IsFreelyInvertable(N1)))
14156 return SDValue();
14157
14158 SDValue NewN0 = DAG.getLogicalNOT(DL, N0, VT);
14159 SDValue NewN1 = DAG.getLogicalNOT(DL, N1, VT);
14160 SDValue And = DAG.getNode(ISD::AND, DL, VT, NewN0, NewN1);
14161 return DAG.getLogicalNOT(DL, And, VT);
14162}
14163
14164/// PerformORCombine - Target-specific dag combine xforms for ISD::OR
14165static SDValue PerformORCombine(SDNode *N,
14166 TargetLowering::DAGCombinerInfo &DCI,
14167 const ARMSubtarget *Subtarget) {
14168 // Attempt to use immediate-form VORR
14169 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
14170 SDLoc dl(N);
14171 EVT VT = N->getValueType(0);
14172 SelectionDAG &DAG = DCI.DAG;
14173
14174 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14175 return SDValue();
14176
14177 if (Subtarget->hasMVEIntegerOps() &&
14178 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1))
14179 return PerformORCombine_i1(N, DAG, Subtarget);
14180
14181 APInt SplatBits, SplatUndef;
14182 unsigned SplatBitSize;
14183 bool HasAnyUndefs;
14184 if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
14185 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
14186 if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
14187 SplatBitSize == 64) {
14188 EVT VorrVT;
14189 SDValue Val =
14190 isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
14191 SplatBitSize, DAG, dl, VorrVT, VT, OtherModImm);
14192 if (Val.getNode()) {
14193 SDValue Input =
14194 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
14195 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
14196 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
14197 }
14198 }
14199 }
14200
14201 if (!Subtarget->isThumb1Only()) {
14202 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
14203 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
14204 return Result;
14205 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
14206 return Result;
14207 }
14208
14209 SDValue N0 = N->getOperand(0);
14210 SDValue N1 = N->getOperand(1);
14211
14212 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
14213 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
14214 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14215
14216 // The code below optimizes (or (and X, Y), Z).
14217 // The AND operand needs to have a single user to make these optimizations
14218 // profitable.
14219 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
14220 return SDValue();
14221
14222 APInt SplatUndef;
14223 unsigned SplatBitSize;
14224 bool HasAnyUndefs;
14225
14226 APInt SplatBits0, SplatBits1;
14227 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
14228 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
14229 // Ensure that the second operand of both ands are constants
14230 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
14231 HasAnyUndefs) && !HasAnyUndefs) {
14232 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
14233 HasAnyUndefs) && !HasAnyUndefs) {
14234 // Ensure that the bit width of the constants are the same and that
14235 // the splat arguments are logical inverses as per the pattern we
14236 // are trying to simplify.
14237 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
14238 SplatBits0 == ~SplatBits1) {
14239 // Canonicalize the vector type to make instruction selection
14240 // simpler.
14241 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
14242 SDValue Result = DAG.getNode(ARMISD::VBSP, dl, CanonicalVT,
14243 N0->getOperand(1),
14244 N0->getOperand(0),
14245 N1->getOperand(0));
14246 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
14247 }
14248 }
14249 }
14250 }
14251
14252 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
14253 // reasonable.
14254 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
14255 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
14256 return Res;
14257 }
14258
14259 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14260 return Result;
14261
14262 return SDValue();
14263}
14264
14265static SDValue PerformXORCombine(SDNode *N,
14266 TargetLowering::DAGCombinerInfo &DCI,
14267 const ARMSubtarget *Subtarget) {
14268 EVT VT = N->getValueType(0);
14269 SelectionDAG &DAG = DCI.DAG;
14270
14271 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14272 return SDValue();
14273
14274 if (!Subtarget->isThumb1Only()) {
14275 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
14276 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
14277 return Result;
14278
14279 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14280 return Result;
14281 }
14282
14283 if (Subtarget->hasMVEIntegerOps()) {
14284 // fold (xor(vcmp/z, 1)) into a vcmp with the opposite condition.
14285 SDValue N0 = N->getOperand(0);
14286 SDValue N1 = N->getOperand(1);
14287 const TargetLowering *TLI = Subtarget->getTargetLowering();
14288 if (TLI->isConstTrueVal(N1.getNode()) &&
14289 (N0->getOpcode() == ARMISD::VCMP || N0->getOpcode() == ARMISD::VCMPZ)) {
14290 if (CanInvertMVEVCMP(N0)) {
14291 SDLoc DL(N0);
14292 ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N0));
14293
14294 SmallVector<SDValue, 4> Ops;
14295 Ops.push_back(N0->getOperand(0));
14296 if (N0->getOpcode() == ARMISD::VCMP)
14297 Ops.push_back(N0->getOperand(1));
14298 Ops.push_back(DAG.getConstant(CC, DL, MVT::i32));
14299 return DAG.getNode(N0->getOpcode(), DL, N0->getValueType(0), Ops);
14300 }
14301 }
14302 }
14303
14304 return SDValue();
14305}
14306
14307// ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
14308// and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
14309// their position in "to" (Rd).
14310static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
14311 assert(N->getOpcode() == ARMISD::BFI)(static_cast <bool> (N->getOpcode() == ARMISD::BFI) ?
void (0) : __assert_fail ("N->getOpcode() == ARMISD::BFI"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 14311, __extension__ __PRETTY_FUNCTION__))
;
14312
14313 SDValue From = N->getOperand(1);
14314 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
14315 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
14316
14317 // If the Base came from a SHR #C, we can deduce that it is really testing bit
14318 // #C in the base of the SHR.
14319 if (From->getOpcode() == ISD::SRL &&
14320 isa<ConstantSDNode>(From->getOperand(1))) {
14321 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
14322 assert(Shift.getLimitedValue() < 32 && "Shift too large!")(static_cast <bool> (Shift.getLimitedValue() < 32 &&
"Shift too large!") ? void (0) : __assert_fail ("Shift.getLimitedValue() < 32 && \"Shift too large!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 14322, __extension__ __PRETTY_FUNCTION__))
;
14323 FromMask <<= Shift.getLimitedValue(31);
14324 From = From->getOperand(0);
14325 }
14326
14327 return From;
14328}
14329
14330// If A and B contain one contiguous set of bits, does A | B == A . B?
14331//
14332// Neither A nor B must be zero.
14333static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
14334 unsigned LastActiveBitInA = A.countTrailingZeros();
14335 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
14336 return LastActiveBitInA - 1 == FirstActiveBitInB;
14337}
14338
14339static SDValue FindBFIToCombineWith(SDNode *N) {
14340 // We have a BFI in N. Find a BFI it can combine with, if one exists.
14341 APInt ToMask, FromMask;
14342 SDValue From = ParseBFI(N, ToMask, FromMask);
14343 SDValue To = N->getOperand(0);
14344
14345 SDValue V = To;
14346 if (V.getOpcode() != ARMISD::BFI)
14347 return SDValue();
14348
14349 APInt NewToMask, NewFromMask;
14350 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
14351 if (NewFrom != From)
14352 return SDValue();
14353
14354 // Do the written bits conflict with any we've seen so far?
14355 if ((NewToMask & ToMask).getBoolValue())
14356 // Conflicting bits.
14357 return SDValue();
14358
14359 // Are the new bits contiguous when combined with the old bits?
14360 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
14361 BitsProperlyConcatenate(FromMask, NewFromMask))
14362 return V;
14363 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
14364 BitsProperlyConcatenate(NewFromMask, FromMask))
14365 return V;
14366
14367 return SDValue();
14368}
14369
14370static SDValue PerformBFICombine(SDNode *N, SelectionDAG &DAG) {
14371 SDValue N0 = N->getOperand(0);
14372 SDValue N1 = N->getOperand(1);
14373
14374 if (N1.getOpcode() == ISD::AND) {
14375 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
14376 // the bits being cleared by the AND are not demanded by the BFI.
14377 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
14378 if (!N11C)
14379 return SDValue();
14380 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
14381 unsigned LSB = countTrailingZeros(~InvMask);
14382 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
14383 assert(Width <(static_cast <bool> (Width < static_cast<unsigned
>(std::numeric_limits<unsigned>::digits) && "undefined behavior"
) ? void (0) : __assert_fail ("Width < static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && \"undefined behavior\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 14385, __extension__ __PRETTY_FUNCTION__))
14384 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&(static_cast <bool> (Width < static_cast<unsigned
>(std::numeric_limits<unsigned>::digits) && "undefined behavior"
) ? void (0) : __assert_fail ("Width < static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && \"undefined behavior\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 14385, __extension__ __PRETTY_FUNCTION__))
14385 "undefined behavior")(static_cast <bool> (Width < static_cast<unsigned
>(std::numeric_limits<unsigned>::digits) && "undefined behavior"
) ? void (0) : __assert_fail ("Width < static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && \"undefined behavior\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 14385, __extension__ __PRETTY_FUNCTION__))
;
14386 unsigned Mask = (1u << Width) - 1;
14387 unsigned Mask2 = N11C->getZExtValue();
14388 if ((Mask & (~Mask2)) == 0)
14389 return DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
14390 N->getOperand(0), N1.getOperand(0), N->getOperand(2));
14391 return SDValue();
14392 }
14393
14394 // Look for another BFI to combine with.
14395 if (SDValue CombineBFI = FindBFIToCombineWith(N)) {
14396 // We've found a BFI.
14397 APInt ToMask1, FromMask1;
14398 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
14399
14400 APInt ToMask2, FromMask2;
14401 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
14402 assert(From1 == From2)(static_cast <bool> (From1 == From2) ? void (0) : __assert_fail
("From1 == From2", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 14402, __extension__ __PRETTY_FUNCTION__))
;
14403 (void)From2;
14404
14405 // Create a new BFI, combining the two together.
14406 APInt NewFromMask = FromMask1 | FromMask2;
14407 APInt NewToMask = ToMask1 | ToMask2;
14408
14409 EVT VT = N->getValueType(0);
14410 SDLoc dl(N);
14411
14412 if (NewFromMask[0] == 0)
14413 From1 = DAG.getNode(
14414 ISD::SRL, dl, VT, From1,
14415 DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
14416 return DAG.getNode(ARMISD::BFI, dl, VT, CombineBFI.getOperand(0), From1,
14417 DAG.getConstant(~NewToMask, dl, VT));
14418 }
14419
14420 // Reassociate BFI(BFI (A, B, M1), C, M2) to BFI(BFI (A, C, M2), B, M1) so
14421 // that lower bit insertions are performed first, providing that M1 and M2
14422 // do no overlap. This can allow multiple BFI instructions to be combined
14423 // together by the other folds above.
14424 if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
14425 APInt ToMask1 = ~N->getConstantOperandAPInt(2);
14426 APInt ToMask2 = ~N0.getConstantOperandAPInt(2);
14427
14428 if (!N0.hasOneUse() || (ToMask1 & ToMask2) != 0 ||
14429 ToMask1.countLeadingZeros() < ToMask2.countLeadingZeros())
14430 return SDValue();
14431
14432 EVT VT = N->getValueType(0);
14433 SDLoc dl(N);
14434 SDValue BFI1 = DAG.getNode(ARMISD::BFI, dl, VT, N0.getOperand(0),
14435 N->getOperand(1), N->getOperand(2));
14436 return DAG.getNode(ARMISD::BFI, dl, VT, BFI1, N0.getOperand(1),
14437 N0.getOperand(2));
14438 }
14439
14440 return SDValue();
14441}
14442
14443/// PerformVMOVRRDCombine - Target-specific dag combine xforms for
14444/// ARMISD::VMOVRRD.
14445static SDValue PerformVMOVRRDCombine(SDNode *N,
14446 TargetLowering::DAGCombinerInfo &DCI,
14447 const ARMSubtarget *Subtarget) {
14448 // vmovrrd(vmovdrr x, y) -> x,y
14449 SDValue InDouble = N->getOperand(0);
14450 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
14451 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
14452
14453 // vmovrrd(load f64) -> (load i32), (load i32)
14454 SDNode *InNode = InDouble.getNode();
14455 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
14456 InNode->getValueType(0) == MVT::f64 &&
14457 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
14458 !cast<LoadSDNode>(InNode)->isVolatile()) {
14459 // TODO: Should this be done for non-FrameIndex operands?
14460 LoadSDNode *LD = cast<LoadSDNode>(InNode);
14461
14462 SelectionDAG &DAG = DCI.DAG;
14463 SDLoc DL(LD);
14464 SDValue BasePtr = LD->getBasePtr();
14465 SDValue NewLD1 =
14466 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
14467 LD->getAlignment(), LD->getMemOperand()->getFlags());
14468
14469 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
14470 DAG.getConstant(4, DL, MVT::i32));
14471
14472 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
14473 LD->getPointerInfo().getWithOffset(4),
14474 std::min(4U, LD->getAlignment()),
14475 LD->getMemOperand()->getFlags());
14476
14477 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
14478 if (DCI.DAG.getDataLayout().isBigEndian())
14479 std::swap (NewLD1, NewLD2);
14480 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
14481 return Result;
14482 }
14483
14484 // VMOVRRD(extract(..(build_vector(a, b, c, d)))) -> a,b or c,d
14485 // VMOVRRD(extract(insert_vector(insert_vector(.., a, l1), b, l2))) -> a,b
14486 if (InDouble.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
14487 isa<ConstantSDNode>(InDouble.getOperand(1))) {
14488 SDValue BV = InDouble.getOperand(0);
14489 // Look up through any nop bitcasts and vector_reg_casts. bitcasts may
14490 // change lane order under big endian.
14491 bool BVSwap = BV.getOpcode() == ISD::BITCAST;
14492 while (
14493 (BV.getOpcode() == ISD::BITCAST ||
14494 BV.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
14495 (BV.getValueType() == MVT::v2f64 || BV.getValueType() == MVT::v2i64)) {
14496 BVSwap = BV.getOpcode() == ISD::BITCAST;
14497 BV = BV.getOperand(0);
14498 }
14499 if (BV.getValueType() != MVT::v4i32)
14500 return SDValue();
14501
14502 // Handle buildvectors, pulling out the correct lane depending on
14503 // endianness.
14504 unsigned Offset = InDouble.getConstantOperandVal(1) == 1 ? 2 : 0;
14505 if (BV.getOpcode() == ISD::BUILD_VECTOR) {
14506 SDValue Op0 = BV.getOperand(Offset);
14507 SDValue Op1 = BV.getOperand(Offset + 1);
14508 if (!Subtarget->isLittle() && BVSwap)
14509 std::swap(Op0, Op1);
14510
14511 return DCI.DAG.getMergeValues({Op0, Op1}, SDLoc(N));
14512 }
14513
14514 // A chain of insert_vectors, grabbing the correct value of the chain of
14515 // inserts.
14516 SDValue Op0, Op1;
14517 while (BV.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14518 if (isa<ConstantSDNode>(BV.getOperand(2))) {
14519 if (BV.getConstantOperandVal(2) == Offset)
14520 Op0 = BV.getOperand(1);
14521 if (BV.getConstantOperandVal(2) == Offset + 1)
14522 Op1 = BV.getOperand(1);
14523 }
14524 BV = BV.getOperand(0);
14525 }
14526 if (!Subtarget->isLittle() && BVSwap)
14527 std::swap(Op0, Op1);
14528 if (Op0 && Op1)
14529 return DCI.DAG.getMergeValues({Op0, Op1}, SDLoc(N));
14530 }
14531
14532 return SDValue();
14533}
14534
14535/// PerformVMOVDRRCombine - Target-specific dag combine xforms for
14536/// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
14537static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
14538 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
14539 SDValue Op0 = N->getOperand(0);
14540 SDValue Op1 = N->getOperand(1);
14541 if (Op0.getOpcode() == ISD::BITCAST)
14542 Op0 = Op0.getOperand(0);
14543 if (Op1.getOpcode() == ISD::BITCAST)
14544 Op1 = Op1.getOperand(0);
14545 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
14546 Op0.getNode() == Op1.getNode() &&
14547 Op0.getResNo() == 0 && Op1.getResNo() == 1)
14548 return DAG.getNode(ISD::BITCAST, SDLoc(N),
14549 N->getValueType(0), Op0.getOperand(0));
14550 return SDValue();
14551}
14552
14553static SDValue PerformVMOVhrCombine(SDNode *N,
14554 TargetLowering::DAGCombinerInfo &DCI) {
14555 SDValue Op0 = N->getOperand(0);
14556
14557 // VMOVhr (VMOVrh (X)) -> X
14558 if (Op0->getOpcode() == ARMISD::VMOVrh)
14559 return Op0->getOperand(0);
14560
14561 // FullFP16: half values are passed in S-registers, and we don't
14562 // need any of the bitcast and moves:
14563 //
14564 // t2: f32,ch = CopyFromReg t0, Register:f32 %0
14565 // t5: i32 = bitcast t2
14566 // t18: f16 = ARMISD::VMOVhr t5
14567 if (Op0->getOpcode() == ISD::BITCAST) {
14568 SDValue Copy = Op0->getOperand(0);
14569 if (Copy.getValueType() == MVT::f32 &&
14570 Copy->getOpcode() == ISD::CopyFromReg) {
14571 SDValue Ops[] = {Copy->getOperand(0), Copy->getOperand(1)};
14572 SDValue NewCopy =
14573 DCI.DAG.getNode(ISD::CopyFromReg, SDLoc(N), N->getValueType(0), Ops);
14574 return NewCopy;
14575 }
14576 }
14577
14578 // fold (VMOVhr (load x)) -> (load (f16*)x)
14579 if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(Op0)) {
14580 if (LN0->hasOneUse() && LN0->isUnindexed() &&
14581 LN0->getMemoryVT() == MVT::i16) {
14582 SDValue Load =
14583 DCI.DAG.getLoad(N->getValueType(0), SDLoc(N), LN0->getChain(),
14584 LN0->getBasePtr(), LN0->getMemOperand());
14585 DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
14586 DCI.DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Load.getValue(1));
14587 return Load;
14588 }
14589 }
14590
14591 // Only the bottom 16 bits of the source register are used.
14592 APInt DemandedMask = APInt::getLowBitsSet(32, 16);
14593 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
14594 if (TLI.SimplifyDemandedBits(Op0, DemandedMask, DCI))
14595 return SDValue(N, 0);
14596
14597 return SDValue();
14598}
14599
14600static SDValue PerformVMOVrhCombine(SDNode *N, SelectionDAG &DAG) {
14601 SDValue N0 = N->getOperand(0);
14602 EVT VT = N->getValueType(0);
14603
14604 // fold (VMOVrh (fpconst x)) -> const x
14605 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N0)) {
14606 APFloat V = C->getValueAPF();
14607 return DAG.getConstant(V.bitcastToAPInt().getZExtValue(), SDLoc(N), VT);
14608 }
14609
14610 // fold (VMOVrh (load x)) -> (zextload (i16*)x)
14611 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
14612 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
14613
14614 SDValue Load =
14615 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, LN0->getChain(),
14616 LN0->getBasePtr(), MVT::i16, LN0->getMemOperand());
14617 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
14618 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
14619 return Load;
14620 }
14621
14622 // Fold VMOVrh(extract(x, n)) -> vgetlaneu(x, n)
14623 if (N0->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
14624 isa<ConstantSDNode>(N0->getOperand(1)))
14625 return DAG.getNode(ARMISD::VGETLANEu, SDLoc(N), VT, N0->getOperand(0),
14626 N0->getOperand(1));
14627
14628 return SDValue();
14629}
14630
14631/// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
14632/// are normal, non-volatile loads. If so, it is profitable to bitcast an
14633/// i64 vector to have f64 elements, since the value can then be loaded
14634/// directly into a VFP register.
14635static bool hasNormalLoadOperand(SDNode *N) {
14636 unsigned NumElts = N->getValueType(0).getVectorNumElements();
14637 for (unsigned i = 0; i < NumElts; ++i) {
14638 SDNode *Elt = N->getOperand(i).getNode();
14639 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
14640 return true;
14641 }
14642 return false;
14643}
14644
14645/// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
14646/// ISD::BUILD_VECTOR.
14647static SDValue PerformBUILD_VECTORCombine(SDNode *N,
14648 TargetLowering::DAGCombinerInfo &DCI,
14649 const ARMSubtarget *Subtarget) {
14650 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
14651 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
14652 // into a pair of GPRs, which is fine when the value is used as a scalar,
14653 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
14654 SelectionDAG &DAG = DCI.DAG;
14655 if (N->getNumOperands() == 2)
14656 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
14657 return RV;
14658
14659 // Load i64 elements as f64 values so that type legalization does not split
14660 // them up into i32 values.
14661 EVT VT = N->getValueType(0);
14662 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
14663 return SDValue();
14664 SDLoc dl(N);
14665 SmallVector<SDValue, 8> Ops;
14666 unsigned NumElts = VT.getVectorNumElements();
14667 for (unsigned i = 0; i < NumElts; ++i) {
14668 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
14669 Ops.push_back(V);
14670 // Make the DAGCombiner fold the bitcast.
14671 DCI.AddToWorklist(V.getNode());
14672 }
14673 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
14674 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
14675 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
14676}
14677
14678/// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
14679static SDValue
14680PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
14681 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
14682 // At that time, we may have inserted bitcasts from integer to float.
14683 // If these bitcasts have survived DAGCombine, change the lowering of this
14684 // BUILD_VECTOR in something more vector friendly, i.e., that does not
14685 // force to use floating point types.
14686
14687 // Make sure we can change the type of the vector.
14688 // This is possible iff:
14689 // 1. The vector is only used in a bitcast to a integer type. I.e.,
14690 // 1.1. Vector is used only once.
14691 // 1.2. Use is a bit convert to an integer type.
14692 // 2. The size of its operands are 32-bits (64-bits are not legal).
14693 EVT VT = N->getValueType(0);
14694 EVT EltVT = VT.getVectorElementType();
14695
14696 // Check 1.1. and 2.
14697 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
14698 return SDValue();
14699
14700 // By construction, the input type must be float.
14701 assert(EltVT == MVT::f32 && "Unexpected type!")(static_cast <bool> (EltVT == MVT::f32 && "Unexpected type!"
) ? void (0) : __assert_fail ("EltVT == MVT::f32 && \"Unexpected type!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 14701, __extension__ __PRETTY_FUNCTION__))
;
14702
14703 // Check 1.2.
14704 SDNode *Use = *N->use_begin();
14705 if (Use->getOpcode() != ISD::BITCAST ||
14706 Use->getValueType(0).isFloatingPoint())
14707 return SDValue();
14708
14709 // Check profitability.
14710 // Model is, if more than half of the relevant operands are bitcast from
14711 // i32, turn the build_vector into a sequence of insert_vector_elt.
14712 // Relevant operands are everything that is not statically
14713 // (i.e., at compile time) bitcasted.
14714 unsigned NumOfBitCastedElts = 0;
14715 unsigned NumElts = VT.getVectorNumElements();
14716 unsigned NumOfRelevantElts = NumElts;
14717 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
14718 SDValue Elt = N->getOperand(Idx);
14719 if (Elt->getOpcode() == ISD::BITCAST) {
14720 // Assume only bit cast to i32 will go away.
14721 if (Elt->getOperand(0).getValueType() == MVT::i32)
14722 ++NumOfBitCastedElts;
14723 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
14724 // Constants are statically casted, thus do not count them as
14725 // relevant operands.
14726 --NumOfRelevantElts;
14727 }
14728
14729 // Check if more than half of the elements require a non-free bitcast.
14730 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
14731 return SDValue();
14732
14733 SelectionDAG &DAG = DCI.DAG;
14734 // Create the new vector type.
14735 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
14736 // Check if the type is legal.
14737 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14738 if (!TLI.isTypeLegal(VecVT))
14739 return SDValue();
14740
14741 // Combine:
14742 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
14743 // => BITCAST INSERT_VECTOR_ELT
14744 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
14745 // (BITCAST EN), N.
14746 SDValue Vec = DAG.getUNDEF(VecVT);
14747 SDLoc dl(N);
14748 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
14749 SDValue V = N->getOperand(Idx);
14750 if (V.isUndef())
14751 continue;
14752 if (V.getOpcode() == ISD::BITCAST &&
14753 V->getOperand(0).getValueType() == MVT::i32)
14754 // Fold obvious case.
14755 V = V.getOperand(0);
14756 else {
14757 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
14758 // Make the DAGCombiner fold the bitcasts.
14759 DCI.AddToWorklist(V.getNode());
14760 }
14761 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
14762 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
14763 }
14764 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
14765 // Make the DAGCombiner fold the bitcasts.
14766 DCI.AddToWorklist(Vec.getNode());
14767 return Vec;
14768}
14769
14770static SDValue
14771PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
14772 EVT VT = N->getValueType(0);
14773 SDValue Op = N->getOperand(0);
14774 SDLoc dl(N);
14775
14776 // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x)
14777 if (Op->getOpcode() == ARMISD::PREDICATE_CAST) {
14778 // If the valuetypes are the same, we can remove the cast entirely.
14779 if (Op->getOperand(0).getValueType() == VT)
14780 return Op->getOperand(0);
14781 return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
14782 }
14783
14784 // Turn pred_cast(xor x, -1) into xor(pred_cast x, -1), in order to produce
14785 // more VPNOT which might get folded as else predicates.
14786 if (Op.getValueType() == MVT::i32 && isBitwiseNot(Op)) {
14787 SDValue X =
14788 DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
14789 SDValue C = DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
14790 DCI.DAG.getConstant(65535, dl, MVT::i32));
14791 return DCI.DAG.getNode(ISD::XOR, dl, VT, X, C);
14792 }
14793
14794 // Only the bottom 16 bits of the source register are used.
14795 if (Op.getValueType() == MVT::i32) {
14796 APInt DemandedMask = APInt::getLowBitsSet(32, 16);
14797 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
14798 if (TLI.SimplifyDemandedBits(Op, DemandedMask, DCI))
14799 return SDValue(N, 0);
14800 }
14801 return SDValue();
14802}
14803
14804static SDValue PerformVECTOR_REG_CASTCombine(SDNode *N, SelectionDAG &DAG,
14805 const ARMSubtarget *ST) {
14806 EVT VT = N->getValueType(0);
14807 SDValue Op = N->getOperand(0);
14808 SDLoc dl(N);
14809
14810 // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST
14811 if (ST->isLittle())
14812 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14813
14814 // VECTOR_REG_CAST undef -> undef
14815 if (Op.isUndef())
14816 return DAG.getUNDEF(VT);
14817
14818 // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x)
14819 if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) {
14820 // If the valuetypes are the same, we can remove the cast entirely.
14821 if (Op->getOperand(0).getValueType() == VT)
14822 return Op->getOperand(0);
14823 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0));
14824 }
14825
14826 return SDValue();
14827}
14828
14829static SDValue PerformVCMPCombine(SDNode *N, SelectionDAG &DAG,
14830 const ARMSubtarget *Subtarget) {
14831 if (!Subtarget->hasMVEIntegerOps())
14832 return SDValue();
14833
14834 EVT VT = N->getValueType(0);
14835 SDValue Op0 = N->getOperand(0);
14836 SDValue Op1 = N->getOperand(1);
14837 ARMCC::CondCodes Cond =
14838 (ARMCC::CondCodes)cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
14839 SDLoc dl(N);
14840
14841 // vcmp X, 0, cc -> vcmpz X, cc
14842 if (isZeroVector(Op1))
14843 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0, N->getOperand(2));
14844
14845 unsigned SwappedCond = getSwappedCondition(Cond);
14846 if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) {
14847 // vcmp 0, X, cc -> vcmpz X, reversed(cc)
14848 if (isZeroVector(Op0))
14849 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1,
14850 DAG.getConstant(SwappedCond, dl, MVT::i32));
14851 // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc)
14852 if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP)
14853 return DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0,
14854 DAG.getConstant(SwappedCond, dl, MVT::i32));
14855 }
14856
14857 return SDValue();
14858}
14859
14860/// PerformInsertEltCombine - Target-specific dag combine xforms for
14861/// ISD::INSERT_VECTOR_ELT.
14862static SDValue PerformInsertEltCombine(SDNode *N,
14863 TargetLowering::DAGCombinerInfo &DCI) {
14864 // Bitcast an i64 load inserted into a vector to f64.
14865 // Otherwise, the i64 value will be legalized to a pair of i32 values.
14866 EVT VT = N->getValueType(0);
14867 SDNode *Elt = N->getOperand(1).getNode();
14868 if (VT.getVectorElementType() != MVT::i64 ||
14869 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
14870 return SDValue();
14871
14872 SelectionDAG &DAG = DCI.DAG;
14873 SDLoc dl(N);
14874 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
14875 VT.getVectorNumElements());
14876 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
14877 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
14878 // Make the DAGCombiner fold the bitcasts.
14879 DCI.AddToWorklist(Vec.getNode());
14880 DCI.AddToWorklist(V.getNode());
14881 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
14882 Vec, V, N->getOperand(2));
14883 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
14884}
14885
14886// Convert a pair of extracts from the same base vector to a VMOVRRD. Either
14887// directly or bitcast to an integer if the original is a float vector.
14888// extract(x, n); extract(x, n+1) -> VMOVRRD(extract v2f64 x, n/2)
14889// bitcast(extract(x, n)); bitcast(extract(x, n+1)) -> VMOVRRD(extract x, n/2)
14890static SDValue
14891PerformExtractEltToVMOVRRD(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
14892 EVT VT = N->getValueType(0);
14893 SDLoc dl(N);
14894
14895 if (!DCI.isAfterLegalizeDAG() || VT != MVT::i32 ||
14896 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(MVT::f64))
14897 return SDValue();
14898
14899 SDValue Ext = SDValue(N, 0);
14900 if (Ext.getOpcode() == ISD::BITCAST &&
14901 Ext.getOperand(0).getValueType() == MVT::f32)
14902 Ext = Ext.getOperand(0);
14903 if (Ext.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14904 !isa<ConstantSDNode>(Ext.getOperand(1)) ||
14905 Ext.getConstantOperandVal(1) % 2 != 0)
14906 return SDValue();
14907 if (Ext->use_size() == 1 &&
14908 (Ext->use_begin()->getOpcode() == ISD::SINT_TO_FP ||
14909 Ext->use_begin()->getOpcode() == ISD::UINT_TO_FP))
14910 return SDValue();
14911
14912 SDValue Op0 = Ext.getOperand(0);
14913 EVT VecVT = Op0.getValueType();
14914 unsigned Lane = Ext.getConstantOperandVal(1);
14915 if (VecVT.getVectorNumElements() != 4)
14916 return SDValue();
14917
14918 // Find another extract, of Lane + 1
14919 auto OtherIt = find_if(Op0->uses(), [&](SDNode *V) {
14920 return V->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
14921 isa<ConstantSDNode>(V->getOperand(1)) &&
14922 V->getConstantOperandVal(1) == Lane + 1;
14923 });
14924 if (OtherIt == Op0->uses().end())
14925 return SDValue();
14926
14927 // For float extracts, we need to be converting to a i32 for both vector
14928 // lanes.
14929 SDValue OtherExt(*OtherIt, 0);
14930 if (OtherExt.getValueType() != MVT::i32) {
14931 if (OtherExt->use_size() != 1 ||
14932 OtherExt->use_begin()->getOpcode() != ISD::BITCAST ||
14933 OtherExt->use_begin()->getValueType(0) != MVT::i32)
14934 return SDValue();
14935 OtherExt = SDValue(*OtherExt->use_begin(), 0);
14936 }
14937
14938 // Convert the type to a f64 and extract with a VMOVRRD.
14939 SDValue F64 = DCI.DAG.getNode(
14940 ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
14941 DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v2f64, Op0),
14942 DCI.DAG.getConstant(Ext.getConstantOperandVal(1) / 2, dl, MVT::i32));
14943 SDValue VMOVRRD =
14944 DCI.DAG.getNode(ARMISD::VMOVRRD, dl, {MVT::i32, MVT::i32}, F64);
14945
14946 DCI.CombineTo(OtherExt.getNode(), SDValue(VMOVRRD.getNode(), 1));
14947 return VMOVRRD;
14948}
14949
14950static SDValue PerformExtractEltCombine(SDNode *N,
14951 TargetLowering::DAGCombinerInfo &DCI,
14952 const ARMSubtarget *ST) {
14953 SDValue Op0 = N->getOperand(0);
14954 EVT VT = N->getValueType(0);
14955 SDLoc dl(N);
14956
14957 // extract (vdup x) -> x
14958 if (Op0->getOpcode() == ARMISD::VDUP) {
14959 SDValue X = Op0->getOperand(0);
14960 if (VT == MVT::f16 && X.getValueType() == MVT::i32)
14961 return DCI.DAG.getNode(ARMISD::VMOVhr, dl, VT, X);
14962 if (VT == MVT::i32 && X.getValueType() == MVT::f16)
14963 return DCI.DAG.getNode(ARMISD::VMOVrh, dl, VT, X);
14964 if (VT == MVT::f32 && X.getValueType() == MVT::i32)
14965 return DCI.DAG.getNode(ISD::BITCAST, dl, VT, X);
14966
14967 while (X.getValueType() != VT && X->getOpcode() == ISD::BITCAST)
14968 X = X->getOperand(0);
14969 if (X.getValueType() == VT)
14970 return X;
14971 }
14972
14973 // extract ARM_BUILD_VECTOR -> x
14974 if (Op0->getOpcode() == ARMISD::BUILD_VECTOR &&
14975 isa<ConstantSDNode>(N->getOperand(1)) &&
14976 N->getConstantOperandVal(1) < Op0.getNumOperands()) {
14977 return Op0.getOperand(N->getConstantOperandVal(1));
14978 }
14979
14980 // extract(bitcast(BUILD_VECTOR(VMOVDRR(a, b), ..))) -> a or b
14981 if (Op0.getValueType() == MVT::v4i32 &&
14982 isa<ConstantSDNode>(N->getOperand(1)) &&
14983 Op0.getOpcode() == ISD::BITCAST &&
14984 Op0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
14985 Op0.getOperand(0).getValueType() == MVT::v2f64) {
14986 SDValue BV = Op0.getOperand(0);
14987 unsigned Offset = N->getConstantOperandVal(1);
14988 SDValue MOV = BV.getOperand(Offset < 2 ? 0 : 1);
14989 if (MOV.getOpcode() == ARMISD::VMOVDRR)
14990 return MOV.getOperand(ST->isLittle() ? Offset % 2 : 1 - Offset % 2);
14991 }
14992
14993 // extract x, n; extract x, n+1 -> VMOVRRD x
14994 if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI))
14995 return R;
14996
14997 // extract (MVETrunc(x)) -> extract x
14998 if (Op0->getOpcode() == ARMISD::MVETRUNC) {
14999 unsigned Idx = N->getConstantOperandVal(1);
15000 unsigned Vec =
15001 Idx / Op0->getOperand(0).getValueType().getVectorNumElements();
15002 unsigned SubIdx =
15003 Idx % Op0->getOperand(0).getValueType().getVectorNumElements();
15004 return DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Op0.getOperand(Vec),
15005 DCI.DAG.getConstant(SubIdx, dl, MVT::i32));
15006 }
15007
15008 return SDValue();
15009}
15010
15011static SDValue PerformSignExtendInregCombine(SDNode *N, SelectionDAG &DAG) {
15012 SDValue Op = N->getOperand(0);
15013 EVT VT = N->getValueType(0);
15014
15015 // sext_inreg(VGETLANEu) -> VGETLANEs
15016 if (Op.getOpcode() == ARMISD::VGETLANEu &&
15017 cast<VTSDNode>(N->getOperand(1))->getVT() ==
15018 Op.getOperand(0).getValueType().getScalarType())
15019 return DAG.getNode(ARMISD::VGETLANEs, SDLoc(N), VT, Op.getOperand(0),
15020 Op.getOperand(1));
15021
15022 return SDValue();
15023}
15024
15025// When lowering complex nodes that we recognize, like VQDMULH and MULH, we
15026// can end up with shuffle(binop(shuffle, shuffle)), that can be simplified to
15027// binop as the shuffles cancel out.
15028static SDValue FlattenVectorShuffle(ShuffleVectorSDNode *N, SelectionDAG &DAG) {
15029 EVT VT = N->getValueType(0);
15030 if (!N->getOperand(1).isUndef() || N->getOperand(0).getValueType() != VT)
15031 return SDValue();
15032 SDValue Op = N->getOperand(0);
15033
15034 // Looking for binary operators that will have been folded from
15035 // truncates/extends.
15036 switch (Op.getOpcode()) {
15037 case ARMISD::VQDMULH:
15038 case ISD::MULHS:
15039 case ISD::MULHU:
15040 case ISD::ABDS:
15041 case ISD::ABDU:
15042 break;
15043 default:
15044 return SDValue();
15045 }
15046
15047 ShuffleVectorSDNode *Op0 = dyn_cast<ShuffleVectorSDNode>(Op.getOperand(0));
15048 ShuffleVectorSDNode *Op1 = dyn_cast<ShuffleVectorSDNode>(Op.getOperand(1));
15049 if (!Op0 || !Op1 || !Op0->getOperand(1).isUndef() ||
15050 !Op1->getOperand(1).isUndef() || Op0->getMask() != Op1->getMask() ||
15051 Op0->getOperand(0).getValueType() != VT)
15052 return SDValue();
15053
15054 // Check the mask turns into an identity shuffle.
15055 ArrayRef<int> NMask = N->getMask();
15056 ArrayRef<int> OpMask = Op0->getMask();
15057 for (int i = 0, e = NMask.size(); i != e; i++) {
15058 if (NMask[i] > 0 && OpMask[NMask[i]] > 0 && OpMask[NMask[i]] != i)
15059 return SDValue();
15060 }
15061
15062 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
15063 Op0->getOperand(0), Op1->getOperand(0));
15064}
15065
15066static SDValue
15067PerformInsertSubvectorCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15068 SDValue Vec = N->getOperand(0);
15069 SDValue SubVec = N->getOperand(1);
15070 uint64_t IdxVal = N->getConstantOperandVal(2);
15071 EVT VecVT = Vec.getValueType();
15072 EVT SubVT = SubVec.getValueType();
15073
15074 // Only do this for legal fixed vector types.
15075 if (!VecVT.isFixedLengthVector() ||
15076 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(VecVT) ||
15077 !DCI.DAG.getTargetLoweringInfo().isTypeLegal(SubVT))
15078 return SDValue();
15079
15080 // Ignore widening patterns.
15081 if (IdxVal == 0 && Vec.isUndef())
15082 return SDValue();
15083
15084 // Subvector must be half the width and an "aligned" insertion.
15085 unsigned NumSubElts = SubVT.getVectorNumElements();
15086 if ((SubVT.getSizeInBits() * 2) != VecVT.getSizeInBits() ||
15087 (IdxVal != 0 && IdxVal != NumSubElts))
15088 return SDValue();
15089
15090 // Fold insert_subvector -> concat_vectors
15091 // insert_subvector(Vec,Sub,lo) -> concat_vectors(Sub,extract(Vec,hi))
15092 // insert_subvector(Vec,Sub,hi) -> concat_vectors(extract(Vec,lo),Sub)
15093 SDLoc DL(N);
15094 SDValue Lo, Hi;
15095 if (IdxVal == 0) {
15096 Lo = SubVec;
15097 Hi = DCI.DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
15098 DCI.DAG.getVectorIdxConstant(NumSubElts, DL));
15099 } else {
15100 Lo = DCI.DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
15101 DCI.DAG.getVectorIdxConstant(0, DL));
15102 Hi = SubVec;
15103 }
15104 return DCI.DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Lo, Hi);
15105}
15106
15107// shuffle(MVETrunc(x, y)) -> VMOVN(x, y)
15108static SDValue PerformShuffleVMOVNCombine(ShuffleVectorSDNode *N,
15109 SelectionDAG &DAG) {
15110 SDValue Trunc = N->getOperand(0);
15111 EVT VT = Trunc.getValueType();
15112 if (Trunc.getOpcode() != ARMISD::MVETRUNC || !N->getOperand(1).isUndef())
15113 return SDValue();
15114
15115 SDLoc DL(Trunc);
15116 if (isVMOVNTruncMask(N->getMask(), VT, 0))
15117 return DAG.getNode(
15118 ARMISD::VMOVN, DL, VT,
15119 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(0)),
15120 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(1)),
15121 DAG.getConstant(1, DL, MVT::i32));
15122 else if (isVMOVNTruncMask(N->getMask(), VT, 1))
15123 return DAG.getNode(
15124 ARMISD::VMOVN, DL, VT,
15125 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(1)),
15126 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(0)),
15127 DAG.getConstant(1, DL, MVT::i32));
15128 return SDValue();
15129}
15130
15131/// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
15132/// ISD::VECTOR_SHUFFLE.
15133static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
15134 if (SDValue R = FlattenVectorShuffle(cast<ShuffleVectorSDNode>(N), DAG))
15135 return R;
15136 if (SDValue R = PerformShuffleVMOVNCombine(cast<ShuffleVectorSDNode>(N), DAG))
15137 return R;
15138
15139 // The LLVM shufflevector instruction does not require the shuffle mask
15140 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
15141 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
15142 // operands do not match the mask length, they are extended by concatenating
15143 // them with undef vectors. That is probably the right thing for other
15144 // targets, but for NEON it is better to concatenate two double-register
15145 // size vector operands into a single quad-register size vector. Do that
15146 // transformation here:
15147 // shuffle(concat(v1, undef), concat(v2, undef)) ->
15148 // shuffle(concat(v1, v2), undef)
15149 SDValue Op0 = N->getOperand(0);
15150 SDValue Op1 = N->getOperand(1);
15151 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
15152 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
15153 Op0.getNumOperands() != 2 ||
15154 Op1.getNumOperands() != 2)
15155 return SDValue();
15156 SDValue Concat0Op1 = Op0.getOperand(1);
15157 SDValue Concat1Op1 = Op1.getOperand(1);
15158 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
15159 return SDValue();
15160 // Skip the transformation if any of the types are illegal.
15161 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15162 EVT VT = N->getValueType(0);
15163 if (!TLI.isTypeLegal(VT) ||
15164 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
15165 !TLI.isTypeLegal(Concat1Op1.getValueType()))
15166 return SDValue();
15167
15168 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
15169 Op0.getOperand(0), Op1.getOperand(0));
15170 // Translate the shuffle mask.
15171 SmallVector<int, 16> NewMask;
15172 unsigned NumElts = VT.getVectorNumElements();
15173 unsigned HalfElts = NumElts/2;
15174 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15175 for (unsigned n = 0; n < NumElts; ++n) {
15176 int MaskElt = SVN->getMaskElt(n);
15177 int NewElt = -1;
15178 if (MaskElt < (int)HalfElts)
15179 NewElt = MaskElt;
15180 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
15181 NewElt = HalfElts + MaskElt - NumElts;
15182 NewMask.push_back(NewElt);
15183 }
15184 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
15185 DAG.getUNDEF(VT), NewMask);
15186}
15187
15188/// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
15189/// NEON load/store intrinsics, and generic vector load/stores, to merge
15190/// base address updates.
15191/// For generic load/stores, the memory type is assumed to be a vector.
15192/// The caller is assumed to have checked legality.
15193static SDValue CombineBaseUpdate(SDNode *N,
15194 TargetLowering::DAGCombinerInfo &DCI) {
15195 SelectionDAG &DAG = DCI.DAG;
15196 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
15197 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
15198 const bool isStore = N->getOpcode() == ISD::STORE;
15199 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
15200 SDValue Addr = N->getOperand(AddrOpIdx);
15201 MemSDNode *MemN = cast<MemSDNode>(N);
15202 SDLoc dl(N);
15203
15204 // Search for a use of the address operand that is an increment.
15205 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
15206 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
15207 SDNode *User = *UI;
15208 if (User->getOpcode() != ISD::ADD ||
15209 UI.getUse().getResNo() != Addr.getResNo())
15210 continue;
15211
15212 // Check that the add is independent of the load/store. Otherwise, folding
15213 // it would create a cycle. We can avoid searching through Addr as it's a
15214 // predecessor to both.
15215 SmallPtrSet<const SDNode *, 32> Visited;
15216 SmallVector<const SDNode *, 16> Worklist;
15217 Visited.insert(Addr.getNode());
15218 Worklist.push_back(N);
15219 Worklist.push_back(User);
15220 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
15221 SDNode::hasPredecessorHelper(User, Visited, Worklist))
15222 continue;
15223
15224 // Find the new opcode for the updating load/store.
15225 bool isLoadOp = true;
15226 bool isLaneOp = false;
15227 // Workaround for vst1x and vld1x intrinsics which do not have alignment
15228 // as an operand.
15229 bool hasAlignment = true;
15230 unsigned NewOpc = 0;
15231 unsigned NumVecs = 0;
15232 if (isIntrinsic) {
15233 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
15234 switch (IntNo) {
15235 default: llvm_unreachable("unexpected intrinsic for Neon base update")::llvm::llvm_unreachable_internal("unexpected intrinsic for Neon base update"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 15235)
;
15236 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
15237 NumVecs = 1; break;
15238 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
15239 NumVecs = 2; break;
15240 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
15241 NumVecs = 3; break;
15242 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
15243 NumVecs = 4; break;
15244 case Intrinsic::arm_neon_vld1x2: NewOpc = ARMISD::VLD1x2_UPD;
15245 NumVecs = 2; hasAlignment = false; break;
15246 case Intrinsic::arm_neon_vld1x3: NewOpc = ARMISD::VLD1x3_UPD;
15247 NumVecs = 3; hasAlignment = false; break;
15248 case Intrinsic::arm_neon_vld1x4: NewOpc = ARMISD::VLD1x4_UPD;
15249 NumVecs = 4; hasAlignment = false; break;
15250 case Intrinsic::arm_neon_vld2dup: NewOpc = ARMISD::VLD2DUP_UPD;
15251 NumVecs = 2; break;
15252 case Intrinsic::arm_neon_vld3dup: NewOpc = ARMISD::VLD3DUP_UPD;
15253 NumVecs = 3; break;
15254 case Intrinsic::arm_neon_vld4dup: NewOpc = ARMISD::VLD4DUP_UPD;
15255 NumVecs = 4; break;
15256 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
15257 NumVecs = 2; isLaneOp = true; break;
15258 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
15259 NumVecs = 3; isLaneOp = true; break;
15260 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
15261 NumVecs = 4; isLaneOp = true; break;
15262 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
15263 NumVecs = 1; isLoadOp = false; break;
15264 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
15265 NumVecs = 2; isLoadOp = false; break;
15266 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
15267 NumVecs = 3; isLoadOp = false; break;
15268 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
15269 NumVecs = 4; isLoadOp = false; break;
15270 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
15271 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
15272 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
15273 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
15274 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
15275 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
15276 case Intrinsic::arm_neon_vst1x2: NewOpc = ARMISD::VST1x2_UPD;
15277 NumVecs = 2; isLoadOp = false; hasAlignment = false; break;
15278 case Intrinsic::arm_neon_vst1x3: NewOpc = ARMISD::VST1x3_UPD;
15279 NumVecs = 3; isLoadOp = false; hasAlignment = false; break;
15280 case Intrinsic::arm_neon_vst1x4: NewOpc = ARMISD::VST1x4_UPD;
15281 NumVecs = 4; isLoadOp = false; hasAlignment = false; break;
15282 }
15283 } else {
15284 isLaneOp = true;
15285 switch (N->getOpcode()) {
15286 default: llvm_unreachable("unexpected opcode for Neon base update")::llvm::llvm_unreachable_internal("unexpected opcode for Neon base update"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 15286)
;
15287 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
15288 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
15289 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
15290 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
15291 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
15292 NumVecs = 1; isLaneOp = false; break;
15293 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
15294 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
15295 }
15296 }
15297
15298 // Find the size of memory referenced by the load/store.
15299 EVT VecTy;
15300 if (isLoadOp) {
15301 VecTy = N->getValueType(0);
15302 } else if (isIntrinsic) {
15303 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
15304 } else {
15305 assert(isStore && "Node has to be a load, a store, or an intrinsic!")(static_cast <bool> (isStore && "Node has to be a load, a store, or an intrinsic!"
) ? void (0) : __assert_fail ("isStore && \"Node has to be a load, a store, or an intrinsic!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 15305, __extension__ __PRETTY_FUNCTION__))
;
15306 VecTy = N->getOperand(1).getValueType();
15307 }
15308
15309 bool isVLDDUPOp =
15310 NewOpc == ARMISD::VLD1DUP_UPD || NewOpc == ARMISD::VLD2DUP_UPD ||
15311 NewOpc == ARMISD::VLD3DUP_UPD || NewOpc == ARMISD::VLD4DUP_UPD;
15312
15313 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
15314 if (isLaneOp || isVLDDUPOp)
15315 NumBytes /= VecTy.getVectorNumElements();
15316
15317 // If the increment is a constant, it must match the memory ref size.
15318 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
15319 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
15320 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
15321 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
15322 // separate instructions that make it harder to use a non-constant update.
15323 continue;
15324 }
15325
15326 // OK, we found an ADD we can fold into the base update.
15327 // Now, create a _UPD node, taking care of not breaking alignment.
15328
15329 EVT AlignedVecTy = VecTy;
15330 unsigned Alignment = MemN->getAlignment();
15331
15332 // If this is a less-than-standard-aligned load/store, change the type to
15333 // match the standard alignment.
15334 // The alignment is overlooked when selecting _UPD variants; and it's
15335 // easier to introduce bitcasts here than fix that.
15336 // There are 3 ways to get to this base-update combine:
15337 // - intrinsics: they are assumed to be properly aligned (to the standard
15338 // alignment of the memory type), so we don't need to do anything.
15339 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
15340 // intrinsics, so, likewise, there's nothing to do.
15341 // - generic load/store instructions: the alignment is specified as an
15342 // explicit operand, rather than implicitly as the standard alignment
15343 // of the memory type (like the intrisics). We need to change the
15344 // memory type to match the explicit alignment. That way, we don't
15345 // generate non-standard-aligned ARMISD::VLDx nodes.
15346 if (isa<LSBaseSDNode>(N)) {
15347 if (Alignment == 0)
15348 Alignment = 1;
15349 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
15350 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
15351 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.")(static_cast <bool> (NumVecs == 1 && "Unexpected multi-element generic load/store."
) ? void (0) : __assert_fail ("NumVecs == 1 && \"Unexpected multi-element generic load/store.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 15351, __extension__ __PRETTY_FUNCTION__))
;
15352 assert(!isLaneOp && "Unexpected generic load/store lane.")(static_cast <bool> (!isLaneOp && "Unexpected generic load/store lane."
) ? void (0) : __assert_fail ("!isLaneOp && \"Unexpected generic load/store lane.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 15352, __extension__ __PRETTY_FUNCTION__))
;
15353 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
15354 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
15355 }
15356 // Don't set an explicit alignment on regular load/stores that we want
15357 // to transform to VLD/VST 1_UPD nodes.
15358 // This matches the behavior of regular load/stores, which only get an
15359 // explicit alignment if the MMO alignment is larger than the standard
15360 // alignment of the memory type.
15361 // Intrinsics, however, always get an explicit alignment, set to the
15362 // alignment of the MMO.
15363 Alignment = 1;
15364 }
15365
15366 // Create the new updating load/store node.
15367 // First, create an SDVTList for the new updating node's results.
15368 EVT Tys[6];
15369 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
15370 unsigned n;
15371 for (n = 0; n < NumResultVecs; ++n)
15372 Tys[n] = AlignedVecTy;
15373 Tys[n++] = MVT::i32;
15374 Tys[n] = MVT::Other;
15375 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
15376
15377 // Then, gather the new node's operands.
15378 SmallVector<SDValue, 8> Ops;
15379 Ops.push_back(N->getOperand(0)); // incoming chain
15380 Ops.push_back(N->getOperand(AddrOpIdx));
15381 Ops.push_back(Inc);
15382
15383 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
15384 // Try to match the intrinsic's signature
15385 Ops.push_back(StN->getValue());
15386 } else {
15387 // Loads (and of course intrinsics) match the intrinsics' signature,
15388 // so just add all but the alignment operand.
15389 unsigned LastOperand =
15390 hasAlignment ? N->getNumOperands() - 1 : N->getNumOperands();
15391 for (unsigned i = AddrOpIdx + 1; i < LastOperand; ++i)
15392 Ops.push_back(N->getOperand(i));
15393 }
15394
15395 // For all node types, the alignment operand is always the last one.
15396 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
15397
15398 // If this is a non-standard-aligned STORE, the penultimate operand is the
15399 // stored value. Bitcast it to the aligned type.
15400 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
15401 SDValue &StVal = Ops[Ops.size()-2];
15402 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
15403 }
15404
15405 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
15406 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
15407 MemN->getMemOperand());
15408
15409 // Update the uses.
15410 SmallVector<SDValue, 5> NewResults;
15411 for (unsigned i = 0; i < NumResultVecs; ++i)
15412 NewResults.push_back(SDValue(UpdN.getNode(), i));
15413
15414 // If this is an non-standard-aligned LOAD, the first result is the loaded
15415 // value. Bitcast it to the expected result type.
15416 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
15417 SDValue &LdVal = NewResults[0];
15418 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
15419 }
15420
15421 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
15422 DCI.CombineTo(N, NewResults);
15423 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
15424
15425 break;
15426 }
15427 return SDValue();
15428}
15429
15430static SDValue PerformVLDCombine(SDNode *N,
15431 TargetLowering::DAGCombinerInfo &DCI) {
15432 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15433 return SDValue();
15434
15435 return CombineBaseUpdate(N, DCI);
15436}
15437
15438static SDValue PerformMVEVLDCombine(SDNode *N,
15439 TargetLowering::DAGCombinerInfo &DCI) {
15440 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15441 return SDValue();
15442
15443 SelectionDAG &DAG = DCI.DAG;
15444 SDValue Addr = N->getOperand(2);
15445 MemSDNode *MemN = cast<MemSDNode>(N);
15446 SDLoc dl(N);
15447
15448 // For the stores, where there are multiple intrinsics we only actually want
15449 // to post-inc the last of the them.
15450 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
15451 if (IntNo == Intrinsic::arm_mve_vst2q &&
15452 cast<ConstantSDNode>(N->getOperand(5))->getZExtValue() != 1)
15453 return SDValue();
15454 if (IntNo == Intrinsic::arm_mve_vst4q &&
15455 cast<ConstantSDNode>(N->getOperand(7))->getZExtValue() != 3)
15456 return SDValue();
15457
15458 // Search for a use of the address operand that is an increment.
15459 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
15460 UE = Addr.getNode()->use_end();
15461 UI != UE; ++UI) {
15462 SDNode *User = *UI;
15463 if (User->getOpcode() != ISD::ADD ||
15464 UI.getUse().getResNo() != Addr.getResNo())
15465 continue;
15466
15467 // Check that the add is independent of the load/store. Otherwise, folding
15468 // it would create a cycle. We can avoid searching through Addr as it's a
15469 // predecessor to both.
15470 SmallPtrSet<const SDNode *, 32> Visited;
15471 SmallVector<const SDNode *, 16> Worklist;
15472 Visited.insert(Addr.getNode());
15473 Worklist.push_back(N);
15474 Worklist.push_back(User);
15475 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
15476 SDNode::hasPredecessorHelper(User, Visited, Worklist))
15477 continue;
15478
15479 // Find the new opcode for the updating load/store.
15480 bool isLoadOp = true;
15481 unsigned NewOpc = 0;
15482 unsigned NumVecs = 0;
15483 switch (IntNo) {
15484 default:
15485 llvm_unreachable("unexpected intrinsic for MVE VLDn combine")::llvm::llvm_unreachable_internal("unexpected intrinsic for MVE VLDn combine"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 15485)
;
15486 case Intrinsic::arm_mve_vld2q:
15487 NewOpc = ARMISD::VLD2_UPD;
15488 NumVecs = 2;
15489 break;
15490 case Intrinsic::arm_mve_vld4q:
15491 NewOpc = ARMISD::VLD4_UPD;
15492 NumVecs = 4;
15493 break;
15494 case Intrinsic::arm_mve_vst2q:
15495 NewOpc = ARMISD::VST2_UPD;
15496 NumVecs = 2;
15497 isLoadOp = false;
15498 break;
15499 case Intrinsic::arm_mve_vst4q:
15500 NewOpc = ARMISD::VST4_UPD;
15501 NumVecs = 4;
15502 isLoadOp = false;
15503 break;
15504 }
15505
15506 // Find the size of memory referenced by the load/store.
15507 EVT VecTy;
15508 if (isLoadOp) {
15509 VecTy = N->getValueType(0);
15510 } else {
15511 VecTy = N->getOperand(3).getValueType();
15512 }
15513
15514 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
15515
15516 // If the increment is a constant, it must match the memory ref size.
15517 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
15518 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
15519 if (!CInc || CInc->getZExtValue() != NumBytes)
15520 continue;
15521
15522 // Create the new updating load/store node.
15523 // First, create an SDVTList for the new updating node's results.
15524 EVT Tys[6];
15525 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
15526 unsigned n;
15527 for (n = 0; n < NumResultVecs; ++n)
15528 Tys[n] = VecTy;
15529 Tys[n++] = MVT::i32;
15530 Tys[n] = MVT::Other;
15531 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
15532
15533 // Then, gather the new node's operands.
15534 SmallVector<SDValue, 8> Ops;
15535 Ops.push_back(N->getOperand(0)); // incoming chain
15536 Ops.push_back(N->getOperand(2)); // ptr
15537 Ops.push_back(Inc);
15538
15539 for (unsigned i = 3; i < N->getNumOperands(); ++i)
15540 Ops.push_back(N->getOperand(i));
15541
15542 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy,
15543 MemN->getMemOperand());
15544
15545 // Update the uses.
15546 SmallVector<SDValue, 5> NewResults;
15547 for (unsigned i = 0; i < NumResultVecs; ++i)
15548 NewResults.push_back(SDValue(UpdN.getNode(), i));
15549
15550 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
15551 DCI.CombineTo(N, NewResults);
15552 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
15553
15554 break;
15555 }
15556
15557 return SDValue();
15558}
15559
15560/// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
15561/// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
15562/// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
15563/// return true.
15564static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15565 SelectionDAG &DAG = DCI.DAG;
15566 EVT VT = N->getValueType(0);
15567 // vldN-dup instructions only support 64-bit vectors for N > 1.
15568 if (!VT.is64BitVector())
15569 return false;
15570
15571 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
15572 SDNode *VLD = N->getOperand(0).getNode();
15573 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
15574 return false;
15575 unsigned NumVecs = 0;
15576 unsigned NewOpc = 0;
15577 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
15578 if (IntNo == Intrinsic::arm_neon_vld2lane) {
15579 NumVecs = 2;
15580 NewOpc = ARMISD::VLD2DUP;
15581 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
15582 NumVecs = 3;
15583 NewOpc = ARMISD::VLD3DUP;
15584 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
15585 NumVecs = 4;
15586 NewOpc = ARMISD::VLD4DUP;
15587 } else {
15588 return false;
15589 }
15590
15591 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
15592 // numbers match the load.
15593 unsigned VLDLaneNo =
15594 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
15595 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
15596 UI != UE; ++UI) {
15597 // Ignore uses of the chain result.
15598 if (UI.getUse().getResNo() == NumVecs)
15599 continue;
15600 SDNode *User = *UI;
15601 if (User->getOpcode() != ARMISD::VDUPLANE ||
15602 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
15603 return false;
15604 }
15605
15606 // Create the vldN-dup node.
15607 EVT Tys[5];
15608 unsigned n;
15609 for (n = 0; n < NumVecs; ++n)
15610 Tys[n] = VT;
15611 Tys[n] = MVT::Other;
15612 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
15613 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
15614 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
15615 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
15616 Ops, VLDMemInt->getMemoryVT(),
15617 VLDMemInt->getMemOperand());
15618
15619 // Update the uses.
15620 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
15621 UI != UE; ++UI) {
15622 unsigned ResNo = UI.getUse().getResNo();
15623 // Ignore uses of the chain result.
15624 if (ResNo == NumVecs)
15625 continue;
15626 SDNode *User = *UI;
15627 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
15628 }
15629
15630 // Now the vldN-lane intrinsic is dead except for its chain result.
15631 // Update uses of the chain.
15632 std::vector<SDValue> VLDDupResults;
15633 for (unsigned n = 0; n < NumVecs; ++n)
15634 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
15635 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
15636 DCI.CombineTo(VLD, VLDDupResults);
15637
15638 return true;
15639}
15640
15641/// PerformVDUPLANECombine - Target-specific dag combine xforms for
15642/// ARMISD::VDUPLANE.
15643static SDValue PerformVDUPLANECombine(SDNode *N,
15644 TargetLowering::DAGCombinerInfo &DCI,
15645 const ARMSubtarget *Subtarget) {
15646 SDValue Op = N->getOperand(0);
15647 EVT VT = N->getValueType(0);
15648
15649 // On MVE, we just convert the VDUPLANE to a VDUP with an extract.
15650 if (Subtarget->hasMVEIntegerOps()) {
15651 EVT ExtractVT = VT.getVectorElementType();
15652 // We need to ensure we are creating a legal type.
15653 if (!DCI.DAG.getTargetLoweringInfo().isTypeLegal(ExtractVT))
15654 ExtractVT = MVT::i32;
15655 SDValue Extract = DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), ExtractVT,
15656 N->getOperand(0), N->getOperand(1));
15657 return DCI.DAG.getNode(ARMISD::VDUP, SDLoc(N), VT, Extract);
15658 }
15659
15660 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
15661 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
15662 if (CombineVLDDUP(N, DCI))
15663 return SDValue(N, 0);
15664
15665 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
15666 // redundant. Ignore bit_converts for now; element sizes are checked below.
15667 while (Op.getOpcode() == ISD::BITCAST)
15668 Op = Op.getOperand(0);
15669 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
15670 return SDValue();
15671
15672 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
15673 unsigned EltSize = Op.getScalarValueSizeInBits();
15674 // The canonical VMOV for a zero vector uses a 32-bit element size.
15675 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15676 unsigned EltBits;
15677 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
15678 EltSize = 8;
15679 if (EltSize > VT.getScalarSizeInBits())
15680 return SDValue();
15681
15682 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
15683}
15684
15685/// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
15686static SDValue PerformVDUPCombine(SDNode *N, SelectionDAG &DAG,
15687 const ARMSubtarget *Subtarget) {
15688 SDValue Op = N->getOperand(0);
15689 SDLoc dl(N);
15690
15691 if (Subtarget->hasMVEIntegerOps()) {
15692 // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will
15693 // need to come from a GPR.
15694 if (Op.getValueType() == MVT::f32)
15695 return DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
15696 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op));
15697 else if (Op.getValueType() == MVT::f16)
15698 return DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
15699 DAG.getNode(ARMISD::VMOVrh, dl, MVT::i32, Op));
15700 }
15701
15702 if (!Subtarget->hasNEON())
15703 return SDValue();
15704
15705 // Match VDUP(LOAD) -> VLD1DUP.
15706 // We match this pattern here rather than waiting for isel because the
15707 // transform is only legal for unindexed loads.
15708 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
15709 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
15710 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
15711 SDValue Ops[] = {LD->getOperand(0), LD->getOperand(1),
15712 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32)};
15713 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
15714 SDValue VLDDup =
15715 DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, Ops,
15716 LD->getMemoryVT(), LD->getMemOperand());
15717 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
15718 return VLDDup;
15719 }
15720
15721 return SDValue();
15722}
15723
15724static SDValue PerformLOADCombine(SDNode *N,
15725 TargetLowering::DAGCombinerInfo &DCI) {
15726 EVT VT = N->getValueType(0);
15727
15728 // If this is a legal vector load, try to combine it into a VLD1_UPD.
15729 if (ISD::isNormalLoad(N) && VT.isVector() &&
15730 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
15731 return CombineBaseUpdate(N, DCI);
15732
15733 return SDValue();
15734}
15735
15736// Optimize trunc store (of multiple scalars) to shuffle and store. First,
15737// pack all of the elements in one place. Next, store to memory in fewer
15738// chunks.
15739static SDValue PerformTruncatingStoreCombine(StoreSDNode *St,
15740 SelectionDAG &DAG) {
15741 SDValue StVal = St->getValue();
15742 EVT VT = StVal.getValueType();
15743 if (!St->isTruncatingStore() || !VT.isVector())
15744 return SDValue();
15745 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15746 EVT StVT = St->getMemoryVT();
15747 unsigned NumElems = VT.getVectorNumElements();
15748 assert(StVT != VT && "Cannot truncate to the same type")(static_cast <bool> (StVT != VT && "Cannot truncate to the same type"
) ? void (0) : __assert_fail ("StVT != VT && \"Cannot truncate to the same type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 15748, __extension__ __PRETTY_FUNCTION__))
;
15749 unsigned FromEltSz = VT.getScalarSizeInBits();
15750 unsigned ToEltSz = StVT.getScalarSizeInBits();
15751
15752 // From, To sizes and ElemCount must be pow of two
15753 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz))
15754 return SDValue();
15755
15756 // We are going to use the original vector elt for storing.
15757 // Accumulated smaller vector elements must be a multiple of the store size.
15758 if (0 != (NumElems * FromEltSz) % ToEltSz)
15759 return SDValue();
15760
15761 unsigned SizeRatio = FromEltSz / ToEltSz;
15762 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits())(static_cast <bool> (SizeRatio * NumElems * ToEltSz == VT
.getSizeInBits()) ? void (0) : __assert_fail ("SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 15762, __extension__ __PRETTY_FUNCTION__))
;
15763
15764 // Create a type on which we perform the shuffle.
15765 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
15766 NumElems * SizeRatio);
15767 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits())(static_cast <bool> (WideVecVT.getSizeInBits() == VT.getSizeInBits
()) ? void (0) : __assert_fail ("WideVecVT.getSizeInBits() == VT.getSizeInBits()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 15767, __extension__ __PRETTY_FUNCTION__))
;
15768
15769 SDLoc DL(St);
15770 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
15771 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15772 for (unsigned i = 0; i < NumElems; ++i)
15773 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1
15774 : i * SizeRatio;
15775
15776 // Can't shuffle using an illegal type.
15777 if (!TLI.isTypeLegal(WideVecVT))
15778 return SDValue();
15779
15780 SDValue Shuff = DAG.getVectorShuffle(
15781 WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec);
15782 // At this point all of the data is stored at the bottom of the
15783 // register. We now need to save it to mem.
15784
15785 // Find the largest store unit
15786 MVT StoreType = MVT::i8;
15787 for (MVT Tp : MVT::integer_valuetypes()) {
15788 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
15789 StoreType = Tp;
15790 }
15791 // Didn't find a legal store type.
15792 if (!TLI.isTypeLegal(StoreType))
15793 return SDValue();
15794
15795 // Bitcast the original vector into a vector of store-size units
15796 EVT StoreVecVT =
15797 EVT::getVectorVT(*DAG.getContext(), StoreType,
15798 VT.getSizeInBits() / EVT(StoreType).getSizeInBits());
15799 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits())(static_cast <bool> (StoreVecVT.getSizeInBits() == VT.getSizeInBits
()) ? void (0) : __assert_fail ("StoreVecVT.getSizeInBits() == VT.getSizeInBits()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 15799, __extension__ __PRETTY_FUNCTION__))
;
15800 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
15801 SmallVector<SDValue, 8> Chains;
15802 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
15803 TLI.getPointerTy(DAG.getDataLayout()));
15804 SDValue BasePtr = St->getBasePtr();
15805
15806 // Perform one or more big stores into memory.
15807 unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits();
15808 for (unsigned I = 0; I < E; I++) {
15809 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType,
15810 ShuffWide, DAG.getIntPtrConstant(I, DL));
15811 SDValue Ch =
15812 DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(),
15813 St->getAlignment(), St->getMemOperand()->getFlags());
15814 BasePtr =
15815 DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment);
15816 Chains.push_back(Ch);
15817 }
15818 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
15819}
15820
15821// Try taking a single vector store from an fpround (which would otherwise turn
15822// into an expensive buildvector) and splitting it into a series of narrowing
15823// stores.
15824static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St,
15825 SelectionDAG &DAG) {
15826 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
15827 return SDValue();
15828 SDValue Trunc = St->getValue();
15829 if (Trunc->getOpcode() != ISD::FP_ROUND)
15830 return SDValue();
15831 EVT FromVT = Trunc->getOperand(0).getValueType();
15832 EVT ToVT = Trunc.getValueType();
15833 if (!ToVT.isVector())
15834 return SDValue();
15835 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements())(static_cast <bool> (FromVT.getVectorNumElements() == ToVT
.getVectorNumElements()) ? void (0) : __assert_fail ("FromVT.getVectorNumElements() == ToVT.getVectorNumElements()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 15835, __extension__ __PRETTY_FUNCTION__))
;
15836 EVT ToEltVT = ToVT.getVectorElementType();
15837 EVT FromEltVT = FromVT.getVectorElementType();
15838
15839 if (FromEltVT != MVT::f32 || ToEltVT != MVT::f16)
15840 return SDValue();
15841
15842 unsigned NumElements = 4;
15843 if (FromVT.getVectorNumElements() % NumElements != 0)
15844 return SDValue();
15845
15846 // Test if the Trunc will be convertable to a VMOVN with a shuffle, and if so
15847 // use the VMOVN over splitting the store. We are looking for patterns of:
15848 // !rev: 0 N 1 N+1 2 N+2 ...
15849 // rev: N 0 N+1 1 N+2 2 ...
15850 // The shuffle may either be a single source (in which case N = NumElts/2) or
15851 // two inputs extended with concat to the same size (in which case N =
15852 // NumElts).
15853 auto isVMOVNShuffle = [&](ShuffleVectorSDNode *SVN, bool Rev) {
15854 ArrayRef<int> M = SVN->getMask();
15855 unsigned NumElts = ToVT.getVectorNumElements();
15856 if (SVN->getOperand(1).isUndef())
15857 NumElts /= 2;
15858
15859 unsigned Off0 = Rev ? NumElts : 0;
15860 unsigned Off1 = Rev ? 0 : NumElts;
15861
15862 for (unsigned I = 0; I < NumElts; I += 2) {
15863 if (M[I] >= 0 && M[I] != (int)(Off0 + I / 2))
15864 return false;
15865 if (M[I + 1] >= 0 && M[I + 1] != (int)(Off1 + I / 2))
15866 return false;
15867 }
15868
15869 return true;
15870 };
15871
15872 if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Trunc.getOperand(0)))
15873 if (isVMOVNShuffle(Shuffle, false) || isVMOVNShuffle(Shuffle, true))
15874 return SDValue();
15875
15876 LLVMContext &C = *DAG.getContext();
15877 SDLoc DL(St);
15878 // Details about the old store
15879 SDValue Ch = St->getChain();
15880 SDValue BasePtr = St->getBasePtr();
15881 Align Alignment = St->getOriginalAlign();
15882 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
15883 AAMDNodes AAInfo = St->getAAInfo();
15884
15885 // We split the store into slices of NumElements. fp16 trunc stores are vcvt
15886 // and then stored as truncating integer stores.
15887 EVT NewFromVT = EVT::getVectorVT(C, FromEltVT, NumElements);
15888 EVT NewToVT = EVT::getVectorVT(
15889 C, EVT::getIntegerVT(C, ToEltVT.getSizeInBits()), NumElements);
15890
15891 SmallVector<SDValue, 4> Stores;
15892 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
15893 unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8;
15894 SDValue NewPtr =
15895 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset));
15896
15897 SDValue Extract =
15898 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0),
15899 DAG.getConstant(i * NumElements, DL, MVT::i32));
15900
15901 SDValue FPTrunc =
15902 DAG.getNode(ARMISD::VCVTN, DL, MVT::v8f16, DAG.getUNDEF(MVT::v8f16),
15903 Extract, DAG.getConstant(0, DL, MVT::i32));
15904 Extract = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v4i32, FPTrunc);
15905
15906 SDValue Store = DAG.getTruncStore(
15907 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
15908 NewToVT, Alignment.value(), MMOFlags, AAInfo);
15909 Stores.push_back(Store);
15910 }
15911 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
15912}
15913
15914// Try taking a single vector store from an MVETRUNC (which would otherwise turn
15915// into an expensive buildvector) and splitting it into a series of narrowing
15916// stores.
15917static SDValue PerformSplittingMVETruncToNarrowingStores(StoreSDNode *St,
15918 SelectionDAG &DAG) {
15919 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
15920 return SDValue();
15921 SDValue Trunc = St->getValue();
15922 if (Trunc->getOpcode() != ARMISD::MVETRUNC)
15923 return SDValue();
15924 EVT FromVT = Trunc->getOperand(0).getValueType();
15925 EVT ToVT = Trunc.getValueType();
15926
15927 LLVMContext &C = *DAG.getContext();
15928 SDLoc DL(St);
15929 // Details about the old store
15930 SDValue Ch = St->getChain();
15931 SDValue BasePtr = St->getBasePtr();
15932 Align Alignment = St->getOriginalAlign();
15933 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
15934 AAMDNodes AAInfo = St->getAAInfo();
15935
15936 EVT NewToVT = EVT::getVectorVT(C, ToVT.getVectorElementType(),
15937 FromVT.getVectorNumElements());
15938
15939 SmallVector<SDValue, 4> Stores;
15940 for (unsigned i = 0; i < Trunc.getNumOperands(); i++) {
15941 unsigned NewOffset =
15942 i * FromVT.getVectorNumElements() * ToVT.getScalarSizeInBits() / 8;
15943 SDValue NewPtr =
15944 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset));
15945
15946 SDValue Extract = Trunc.getOperand(i);
15947 SDValue Store = DAG.getTruncStore(
15948 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
15949 NewToVT, Alignment.value(), MMOFlags, AAInfo);
15950 Stores.push_back(Store);
15951 }
15952 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
15953}
15954
15955// Given a floating point store from an extracted vector, with an integer
15956// VGETLANE that already exists, store the existing VGETLANEu directly. This can
15957// help reduce fp register pressure, doesn't require the fp extract and allows
15958// use of more integer post-inc stores not available with vstr.
15959static SDValue PerformExtractFpToIntStores(StoreSDNode *St, SelectionDAG &DAG) {
15960 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
15961 return SDValue();
15962 SDValue Extract = St->getValue();
15963 EVT VT = Extract.getValueType();
15964 // For now only uses f16. This may be useful for f32 too, but that will
15965 // be bitcast(extract), not the VGETLANEu we currently check here.
15966 if (VT != MVT::f16 || Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15967 return SDValue();
15968
15969 SDNode *GetLane =
15970 DAG.getNodeIfExists(ARMISD::VGETLANEu, DAG.getVTList(MVT::i32),
15971 {Extract.getOperand(0), Extract.getOperand(1)});
15972 if (!GetLane)
15973 return SDValue();
15974
15975 LLVMContext &C = *DAG.getContext();
15976 SDLoc DL(St);
15977 // Create a new integer store to replace the existing floating point version.
15978 SDValue Ch = St->getChain();
15979 SDValue BasePtr = St->getBasePtr();
15980 Align Alignment = St->getOriginalAlign();
15981 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
15982 AAMDNodes AAInfo = St->getAAInfo();
15983 EVT NewToVT = EVT::getIntegerVT(C, VT.getSizeInBits());
15984 SDValue Store = DAG.getTruncStore(Ch, DL, SDValue(GetLane, 0), BasePtr,
15985 St->getPointerInfo(), NewToVT,
15986 Alignment.value(), MMOFlags, AAInfo);
15987
15988 return Store;
15989}
15990
15991/// PerformSTORECombine - Target-specific dag combine xforms for
15992/// ISD::STORE.
15993static SDValue PerformSTORECombine(SDNode *N,
15994 TargetLowering::DAGCombinerInfo &DCI,
15995 const ARMSubtarget *Subtarget) {
15996 StoreSDNode *St = cast<StoreSDNode>(N);
15997 if (St->isVolatile())
15998 return SDValue();
15999 SDValue StVal = St->getValue();
16000 EVT VT = StVal.getValueType();
16001
16002 if (Subtarget->hasNEON())
16003 if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG))
16004 return Store;
16005
16006 if (Subtarget->hasMVEIntegerOps()) {
16007 if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG))
16008 return NewToken;
16009 if (SDValue NewChain = PerformExtractFpToIntStores(St, DCI.DAG))
16010 return NewChain;
16011 if (SDValue NewToken =
16012 PerformSplittingMVETruncToNarrowingStores(St, DCI.DAG))
16013 return NewToken;
16014 }
16015
16016 if (!ISD::isNormalStore(St))
16017 return SDValue();
16018
16019 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
16020 // ARM stores of arguments in the same cache line.
16021 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
16022 StVal.getNode()->hasOneUse()) {
16023 SelectionDAG &DAG = DCI.DAG;
16024 bool isBigEndian = DAG.getDataLayout().isBigEndian();
16025 SDLoc DL(St);
16026 SDValue BasePtr = St->getBasePtr();
16027 SDValue NewST1 = DAG.getStore(
16028 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
16029 BasePtr, St->getPointerInfo(), St->getOriginalAlign(),
16030 St->getMemOperand()->getFlags());
16031
16032 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
16033 DAG.getConstant(4, DL, MVT::i32));
16034 return DAG.getStore(NewST1.getValue(0), DL,
16035 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
16036 OffsetPtr, St->getPointerInfo().getWithOffset(4),
16037 St->getOriginalAlign(),
16038 St->getMemOperand()->getFlags());
16039 }
16040
16041 if (StVal.getValueType() == MVT::i64 &&
16042 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
16043
16044 // Bitcast an i64 store extracted from a vector to f64.
16045 // Otherwise, the i64 value will be legalized to a pair of i32 values.
16046 SelectionDAG &DAG = DCI.DAG;
16047 SDLoc dl(StVal);
16048 SDValue IntVec = StVal.getOperand(0);
16049 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
16050 IntVec.getValueType().getVectorNumElements());
16051 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
16052 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
16053 Vec, StVal.getOperand(1));
16054 dl = SDLoc(N);
16055 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
16056 // Make the DAGCombiner fold the bitcasts.
16057 DCI.AddToWorklist(Vec.getNode());
16058 DCI.AddToWorklist(ExtElt.getNode());
16059 DCI.AddToWorklist(V.getNode());
16060 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
16061 St->getPointerInfo(), St->getAlignment(),
16062 St->getMemOperand()->getFlags(), St->getAAInfo());
16063 }
16064
16065 // If this is a legal vector store, try to combine it into a VST1_UPD.
16066 if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() &&
16067 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
16068 return CombineBaseUpdate(N, DCI);
16069
16070 return SDValue();
16071}
16072
16073/// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
16074/// can replace combinations of VMUL and VCVT (floating-point to integer)
16075/// when the VMUL has a constant operand that is a power of 2.
16076///
16077/// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
16078/// vmul.f32 d16, d17, d16
16079/// vcvt.s32.f32 d16, d16
16080/// becomes:
16081/// vcvt.s32.f32 d16, d16, #3
16082static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
16083 const ARMSubtarget *Subtarget) {
16084 if (!Subtarget->hasNEON())
16085 return SDValue();
16086
16087 SDValue Op = N->getOperand(0);
16088 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
16089 Op.getOpcode() != ISD::FMUL)
16090 return SDValue();
16091
16092 SDValue ConstVec = Op->getOperand(1);
16093 if (!isa<BuildVectorSDNode>(ConstVec))
16094 return SDValue();
16095
16096 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
16097 uint32_t FloatBits = FloatTy.getSizeInBits();
16098 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
16099 uint32_t IntBits = IntTy.getSizeInBits();
16100 unsigned NumLanes = Op.getValueType().getVectorNumElements();
16101 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
16102 // These instructions only exist converting from f32 to i32. We can handle
16103 // smaller integers by generating an extra truncate, but larger ones would
16104 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
16105 // these intructions only support v2i32/v4i32 types.
16106 return SDValue();
16107 }
16108
16109 BitVector UndefElements;
16110 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
16111 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
16112 if (C == -1 || C == 0 || C > 32)
16113 return SDValue();
16114
16115 SDLoc dl(N);
16116 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
16117 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
16118 Intrinsic::arm_neon_vcvtfp2fxu;
16119 SDValue FixConv = DAG.getNode(
16120 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
16121 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
16122 DAG.getConstant(C, dl, MVT::i32));
16123
16124 if (IntBits < FloatBits)
16125 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
16126
16127 return FixConv;
16128}
16129
16130/// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
16131/// can replace combinations of VCVT (integer to floating-point) and VDIV
16132/// when the VDIV has a constant operand that is a power of 2.
16133///
16134/// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
16135/// vcvt.f32.s32 d16, d16
16136/// vdiv.f32 d16, d17, d16
16137/// becomes:
16138/// vcvt.f32.s32 d16, d16, #3
16139static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
16140 const ARMSubtarget *Subtarget) {
16141 if (!Subtarget->hasNEON())
16142 return SDValue();
16143
16144 SDValue Op = N->getOperand(0);
16145 unsigned OpOpcode = Op.getNode()->getOpcode();
16146 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
16147 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
16148 return SDValue();
16149
16150 SDValue ConstVec = N->getOperand(1);
16151 if (!isa<BuildVectorSDNode>(ConstVec))
16152 return SDValue();
16153
16154 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
16155 uint32_t FloatBits = FloatTy.getSizeInBits();
16156 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
16157 uint32_t IntBits = IntTy.getSizeInBits();
16158 unsigned NumLanes = Op.getValueType().getVectorNumElements();
16159 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
16160 // These instructions only exist converting from i32 to f32. We can handle
16161 // smaller integers by generating an extra extend, but larger ones would
16162 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
16163 // these intructions only support v2i32/v4i32 types.
16164 return SDValue();
16165 }
16166
16167 BitVector UndefElements;
16168 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
16169 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
16170 if (C == -1 || C == 0 || C > 32)
16171 return SDValue();
16172
16173 SDLoc dl(N);
16174 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
16175 SDValue ConvInput = Op.getOperand(0);
16176 if (IntBits < FloatBits)
16177 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
16178 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
16179 ConvInput);
16180
16181 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
16182 Intrinsic::arm_neon_vcvtfxu2fp;
16183 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
16184 Op.getValueType(),
16185 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
16186 ConvInput, DAG.getConstant(C, dl, MVT::i32));
16187}
16188
16189static SDValue PerformVECREDUCE_ADDCombine(SDNode *N, SelectionDAG &DAG,
16190 const ARMSubtarget *ST) {
16191 if (!ST->hasMVEIntegerOps())
16192 return SDValue();
16193
16194 assert(N->getOpcode() == ISD::VECREDUCE_ADD)(static_cast <bool> (N->getOpcode() == ISD::VECREDUCE_ADD
) ? void (0) : __assert_fail ("N->getOpcode() == ISD::VECREDUCE_ADD"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16194, __extension__ __PRETTY_FUNCTION__))
;
16195 EVT ResVT = N->getValueType(0);
16196 SDValue N0 = N->getOperand(0);
16197 SDLoc dl(N);
16198
16199 // Try to turn vecreduce_add(add(x, y)) into vecreduce(x) + vecreduce(y)
16200 if (ResVT == MVT::i32 && N0.getOpcode() == ISD::ADD &&
16201 (N0.getValueType() == MVT::v4i32 || N0.getValueType() == MVT::v8i16 ||
16202 N0.getValueType() == MVT::v16i8)) {
16203 SDValue Red0 = DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, N0.getOperand(0));
16204 SDValue Red1 = DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, N0.getOperand(1));
16205 return DAG.getNode(ISD::ADD, dl, ResVT, Red0, Red1);
16206 }
16207
16208 // We are looking for something that will have illegal types if left alone,
16209 // but that we can convert to a single instruction under MVE. For example
16210 // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A
16211 // or
16212 // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B
16213
16214 // The legal cases are:
16215 // VADDV u/s 8/16/32
16216 // VMLAV u/s 8/16/32
16217 // VADDLV u/s 32
16218 // VMLALV u/s 16/32
16219
16220 // If the input vector is smaller than legal (v4i8/v4i16 for example) we can
16221 // extend it and use v4i32 instead.
16222 auto ExtTypeMatches = [](SDValue A, ArrayRef<MVT> ExtTypes) {
16223 EVT AVT = A.getValueType();
16224 return any_of(ExtTypes, [&](MVT Ty) {
16225 return AVT.getVectorNumElements() == Ty.getVectorNumElements() &&
16226 AVT.bitsLE(Ty);
16227 });
16228 };
16229 auto ExtendIfNeeded = [&](SDValue A, unsigned ExtendCode) {
16230 EVT AVT = A.getValueType();
16231 if (!AVT.is128BitVector())
16232 A = DAG.getNode(ExtendCode, dl,
16233 AVT.changeVectorElementType(MVT::getIntegerVT(
16234 128 / AVT.getVectorMinNumElements())),
16235 A);
16236 return A;
16237 };
16238 auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) {
16239 if (ResVT != RetTy || N0->getOpcode() != ExtendCode)
16240 return SDValue();
16241 SDValue A = N0->getOperand(0);
16242 if (ExtTypeMatches(A, ExtTypes))
16243 return ExtendIfNeeded(A, ExtendCode);
16244 return SDValue();
16245 };
16246 auto IsPredVADDV = [&](MVT RetTy, unsigned ExtendCode,
16247 ArrayRef<MVT> ExtTypes, SDValue &Mask) {
16248 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
16249 !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode()))
16250 return SDValue();
16251 Mask = N0->getOperand(0);
16252 SDValue Ext = N0->getOperand(1);
16253 if (Ext->getOpcode() != ExtendCode)
16254 return SDValue();
16255 SDValue A = Ext->getOperand(0);
16256 if (ExtTypeMatches(A, ExtTypes))
16257 return ExtendIfNeeded(A, ExtendCode);
16258 return SDValue();
16259 };
16260 auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
16261 SDValue &A, SDValue &B) {
16262 // For a vmla we are trying to match a larger pattern:
16263 // ExtA = sext/zext A
16264 // ExtB = sext/zext B
16265 // Mul = mul ExtA, ExtB
16266 // vecreduce.add Mul
16267 // There might also be en extra extend between the mul and the addreduce, so
16268 // long as the bitwidth is high enough to make them equivalent (for example
16269 // original v8i16 might be mul at v8i32 and the reduce happens at v8i64).
16270 if (ResVT != RetTy)
16271 return false;
16272 SDValue Mul = N0;
16273 if (Mul->getOpcode() == ExtendCode &&
16274 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
16275 ResVT.getScalarSizeInBits())
16276 Mul = Mul->getOperand(0);
16277 if (Mul->getOpcode() != ISD::MUL)
16278 return false;
16279 SDValue ExtA = Mul->getOperand(0);
16280 SDValue ExtB = Mul->getOperand(1);
16281 if (ExtA->getOpcode() != ExtendCode || ExtB->getOpcode() != ExtendCode)
16282 return false;
16283 A = ExtA->getOperand(0);
16284 B = ExtB->getOperand(0);
16285 if (ExtTypeMatches(A, ExtTypes) && ExtTypeMatches(B, ExtTypes)) {
16286 A = ExtendIfNeeded(A, ExtendCode);
16287 B = ExtendIfNeeded(B, ExtendCode);
16288 return true;
16289 }
16290 return false;
16291 };
16292 auto IsPredVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
16293 SDValue &A, SDValue &B, SDValue &Mask) {
16294 // Same as the pattern above with a select for the zero predicated lanes
16295 // ExtA = sext/zext A
16296 // ExtB = sext/zext B
16297 // Mul = mul ExtA, ExtB
16298 // N0 = select Mask, Mul, 0
16299 // vecreduce.add N0
16300 if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
16301 !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode()))
16302 return false;
16303 Mask = N0->getOperand(0);
16304 SDValue Mul = N0->getOperand(1);
16305 if (Mul->getOpcode() == ExtendCode &&
16306 Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
16307 ResVT.getScalarSizeInBits())
16308 Mul = Mul->getOperand(0);
16309 if (Mul->getOpcode() != ISD::MUL)
16310 return false;
16311 SDValue ExtA = Mul->getOperand(0);
16312 SDValue ExtB = Mul->getOperand(1);
16313 if (ExtA->getOpcode() != ExtendCode || ExtB->getOpcode() != ExtendCode)
16314 return false;
16315 A = ExtA->getOperand(0);
16316 B = ExtB->getOperand(0);
16317 if (ExtTypeMatches(A, ExtTypes) && ExtTypeMatches(B, ExtTypes)) {
16318 A = ExtendIfNeeded(A, ExtendCode);
16319 B = ExtendIfNeeded(B, ExtendCode);
16320 return true;
16321 }
16322 return false;
16323 };
16324 auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) {
16325 // Split illegal MVT::v16i8->i64 vector reductions into two legal v8i16->i64
16326 // reductions. The operands are extended with MVEEXT, but as they are
16327 // reductions the lane orders do not matter. MVEEXT may be combined with
16328 // loads to produce two extending loads, or else they will be expanded to
16329 // VREV/VMOVL.
16330 EVT VT = Ops[0].getValueType();
16331 if (VT == MVT::v16i8) {
16332 assert((Opcode == ARMISD::VMLALVs || Opcode == ARMISD::VMLALVu) &&(static_cast <bool> ((Opcode == ARMISD::VMLALVs || Opcode
== ARMISD::VMLALVu) && "Unexpected illegal long reduction opcode"
) ? void (0) : __assert_fail ("(Opcode == ARMISD::VMLALVs || Opcode == ARMISD::VMLALVu) && \"Unexpected illegal long reduction opcode\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16333, __extension__ __PRETTY_FUNCTION__))
16333 "Unexpected illegal long reduction opcode")(static_cast <bool> ((Opcode == ARMISD::VMLALVs || Opcode
== ARMISD::VMLALVu) && "Unexpected illegal long reduction opcode"
) ? void (0) : __assert_fail ("(Opcode == ARMISD::VMLALVs || Opcode == ARMISD::VMLALVu) && \"Unexpected illegal long reduction opcode\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16333, __extension__ __PRETTY_FUNCTION__))
;
16334 bool IsUnsigned = Opcode == ARMISD::VMLALVu;
16335
16336 SDValue Ext0 =
16337 DAG.getNode(IsUnsigned ? ARMISD::MVEZEXT : ARMISD::MVESEXT, dl,
16338 DAG.getVTList(MVT::v8i16, MVT::v8i16), Ops[0]);
16339 SDValue Ext1 =
16340 DAG.getNode(IsUnsigned ? ARMISD::MVEZEXT : ARMISD::MVESEXT, dl,
16341 DAG.getVTList(MVT::v8i16, MVT::v8i16), Ops[1]);
16342
16343 SDValue MLA0 = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
16344 Ext0, Ext1);
16345 SDValue MLA1 =
16346 DAG.getNode(IsUnsigned ? ARMISD::VMLALVAu : ARMISD::VMLALVAs, dl,
16347 DAG.getVTList(MVT::i32, MVT::i32), MLA0, MLA0.getValue(1),
16348 Ext0.getValue(1), Ext1.getValue(1));
16349 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, MLA1, MLA1.getValue(1));
16350 }
16351 SDValue Node = DAG.getNode(Opcode, dl, {MVT::i32, MVT::i32}, Ops);
16352 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Node,
16353 SDValue(Node.getNode(), 1));
16354 };
16355
16356 SDValue A, B;
16357 SDValue Mask;
16358 if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
16359 return DAG.getNode(ARMISD::VMLAVs, dl, ResVT, A, B);
16360 if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
16361 return DAG.getNode(ARMISD::VMLAVu, dl, ResVT, A, B);
16362 if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v16i8, MVT::v8i16, MVT::v4i32},
16363 A, B))
16364 return Create64bitNode(ARMISD::VMLALVs, {A, B});
16365 if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v16i8, MVT::v8i16, MVT::v4i32},
16366 A, B))
16367 return Create64bitNode(ARMISD::VMLALVu, {A, B});
16368 if (IsVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B))
16369 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
16370 DAG.getNode(ARMISD::VMLAVs, dl, MVT::i32, A, B));
16371 if (IsVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B))
16372 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
16373 DAG.getNode(ARMISD::VMLAVu, dl, MVT::i32, A, B));
16374
16375 if (IsPredVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B,
16376 Mask))
16377 return DAG.getNode(ARMISD::VMLAVps, dl, ResVT, A, B, Mask);
16378 if (IsPredVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B,
16379 Mask))
16380 return DAG.getNode(ARMISD::VMLAVpu, dl, ResVT, A, B, Mask);
16381 if (IsPredVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B,
16382 Mask))
16383 return Create64bitNode(ARMISD::VMLALVps, {A, B, Mask});
16384 if (IsPredVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B,
16385 Mask))
16386 return Create64bitNode(ARMISD::VMLALVpu, {A, B, Mask});
16387 if (IsPredVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B, Mask))
16388 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
16389 DAG.getNode(ARMISD::VMLAVps, dl, MVT::i32, A, B, Mask));
16390 if (IsPredVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B, Mask))
16391 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
16392 DAG.getNode(ARMISD::VMLAVpu, dl, MVT::i32, A, B, Mask));
16393
16394 if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}))
16395 return DAG.getNode(ARMISD::VADDVs, dl, ResVT, A);
16396 if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}))
16397 return DAG.getNode(ARMISD::VADDVu, dl, ResVT, A);
16398 if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}))
16399 return Create64bitNode(ARMISD::VADDLVs, {A});
16400 if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}))
16401 return Create64bitNode(ARMISD::VADDLVu, {A});
16402 if (SDValue A = IsVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}))
16403 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
16404 DAG.getNode(ARMISD::VADDVs, dl, MVT::i32, A));
16405 if (SDValue A = IsVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}))
16406 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
16407 DAG.getNode(ARMISD::VADDVu, dl, MVT::i32, A));
16408
16409 if (SDValue A = IsPredVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
16410 return DAG.getNode(ARMISD::VADDVps, dl, ResVT, A, Mask);
16411 if (SDValue A = IsPredVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
16412 return DAG.getNode(ARMISD::VADDVpu, dl, ResVT, A, Mask);
16413 if (SDValue A = IsPredVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}, Mask))
16414 return Create64bitNode(ARMISD::VADDLVps, {A, Mask});
16415 if (SDValue A = IsPredVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}, Mask))
16416 return Create64bitNode(ARMISD::VADDLVpu, {A, Mask});
16417 if (SDValue A = IsPredVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, Mask))
16418 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
16419 DAG.getNode(ARMISD::VADDVps, dl, MVT::i32, A, Mask));
16420 if (SDValue A = IsPredVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, Mask))
16421 return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
16422 DAG.getNode(ARMISD::VADDVpu, dl, MVT::i32, A, Mask));
16423
16424 // Some complications. We can get a case where the two inputs of the mul are
16425 // the same, then the output sext will have been helpfully converted to a
16426 // zext. Turn it back.
16427 SDValue Op = N0;
16428 if (Op->getOpcode() == ISD::VSELECT)
16429 Op = Op->getOperand(1);
16430 if (Op->getOpcode() == ISD::ZERO_EXTEND &&
16431 Op->getOperand(0)->getOpcode() == ISD::MUL) {
16432 SDValue Mul = Op->getOperand(0);
16433 if (Mul->getOperand(0) == Mul->getOperand(1) &&
16434 Mul->getOperand(0)->getOpcode() == ISD::SIGN_EXTEND) {
16435 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, N0->getValueType(0), Mul);
16436 if (Op != N0)
16437 Ext = DAG.getNode(ISD::VSELECT, dl, N0->getValueType(0),
16438 N0->getOperand(0), Ext, N0->getOperand(2));
16439 return DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, Ext);
16440 }
16441 }
16442
16443 return SDValue();
16444}
16445
16446static SDValue PerformVMOVNCombine(SDNode *N,
16447 TargetLowering::DAGCombinerInfo &DCI) {
16448 SDValue Op0 = N->getOperand(0);
16449 SDValue Op1 = N->getOperand(1);
16450 unsigned IsTop = N->getConstantOperandVal(2);
16451
16452 // VMOVNT a undef -> a
16453 // VMOVNB a undef -> a
16454 // VMOVNB undef a -> a
16455 if (Op1->isUndef())
16456 return Op0;
16457 if (Op0->isUndef() && !IsTop)
16458 return Op1;
16459
16460 // VMOVNt(c, VQMOVNb(a, b)) => VQMOVNt(c, b)
16461 // VMOVNb(c, VQMOVNb(a, b)) => VQMOVNb(c, b)
16462 if ((Op1->getOpcode() == ARMISD::VQMOVNs ||
16463 Op1->getOpcode() == ARMISD::VQMOVNu) &&
16464 Op1->getConstantOperandVal(2) == 0)
16465 return DCI.DAG.getNode(Op1->getOpcode(), SDLoc(Op1), N->getValueType(0),
16466 Op0, Op1->getOperand(1), N->getOperand(2));
16467
16468 // Only the bottom lanes from Qm (Op1) and either the top or bottom lanes from
16469 // Qd (Op0) are demanded from a VMOVN, depending on whether we are inserting
16470 // into the top or bottom lanes.
16471 unsigned NumElts = N->getValueType(0).getVectorNumElements();
16472 APInt Op1DemandedElts = APInt::getSplat(NumElts, APInt::getLowBitsSet(2, 1));
16473 APInt Op0DemandedElts =
16474 IsTop ? Op1DemandedElts
16475 : APInt::getSplat(NumElts, APInt::getHighBitsSet(2, 1));
16476
16477 APInt KnownUndef, KnownZero;
16478 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
16479 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef,
16480 KnownZero, DCI))
16481 return SDValue(N, 0);
16482 if (TLI.SimplifyDemandedVectorElts(Op1, Op1DemandedElts, KnownUndef,
16483 KnownZero, DCI))
16484 return SDValue(N, 0);
16485
16486 return SDValue();
16487}
16488
16489static SDValue PerformVQMOVNCombine(SDNode *N,
16490 TargetLowering::DAGCombinerInfo &DCI) {
16491 SDValue Op0 = N->getOperand(0);
16492 unsigned IsTop = N->getConstantOperandVal(2);
16493
16494 unsigned NumElts = N->getValueType(0).getVectorNumElements();
16495 APInt Op0DemandedElts =
16496 APInt::getSplat(NumElts, IsTop ? APInt::getLowBitsSet(2, 1)
16497 : APInt::getHighBitsSet(2, 1));
16498
16499 APInt KnownUndef, KnownZero;
16500 const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
16501 if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef,
16502 KnownZero, DCI))
16503 return SDValue(N, 0);
16504 return SDValue();
16505}
16506
16507static SDValue PerformLongShiftCombine(SDNode *N, SelectionDAG &DAG) {
16508 SDLoc DL(N);
16509 SDValue Op0 = N->getOperand(0);
16510 SDValue Op1 = N->getOperand(1);
16511
16512 // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from
16513 // uses of the intrinsics.
16514 if (auto C = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
16515 int ShiftAmt = C->getSExtValue();
16516 if (ShiftAmt == 0) {
16517 SDValue Merge = DAG.getMergeValues({Op0, Op1}, DL);
16518 DAG.ReplaceAllUsesWith(N, Merge.getNode());
16519 return SDValue();
16520 }
16521
16522 if (ShiftAmt >= -32 && ShiftAmt < 0) {
16523 unsigned NewOpcode =
16524 N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL;
16525 SDValue NewShift = DAG.getNode(NewOpcode, DL, N->getVTList(), Op0, Op1,
16526 DAG.getConstant(-ShiftAmt, DL, MVT::i32));
16527 DAG.ReplaceAllUsesWith(N, NewShift.getNode());
16528 return NewShift;
16529 }
16530 }
16531
16532 return SDValue();
16533}
16534
16535/// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
16536SDValue ARMTargetLowering::PerformIntrinsicCombine(SDNode *N,
16537 DAGCombinerInfo &DCI) const {
16538 SelectionDAG &DAG = DCI.DAG;
16539 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
16540 switch (IntNo) {
16541 default:
16542 // Don't do anything for most intrinsics.
16543 break;
16544
16545 // Vector shifts: check for immediate versions and lower them.
16546 // Note: This is done during DAG combining instead of DAG legalizing because
16547 // the build_vectors for 64-bit vector element shift counts are generally
16548 // not legal, and it is hard to see their values after they get legalized to
16549 // loads from a constant pool.
16550 case Intrinsic::arm_neon_vshifts:
16551 case Intrinsic::arm_neon_vshiftu:
16552 case Intrinsic::arm_neon_vrshifts:
16553 case Intrinsic::arm_neon_vrshiftu:
16554 case Intrinsic::arm_neon_vrshiftn:
16555 case Intrinsic::arm_neon_vqshifts:
16556 case Intrinsic::arm_neon_vqshiftu:
16557 case Intrinsic::arm_neon_vqshiftsu:
16558 case Intrinsic::arm_neon_vqshiftns:
16559 case Intrinsic::arm_neon_vqshiftnu:
16560 case Intrinsic::arm_neon_vqshiftnsu:
16561 case Intrinsic::arm_neon_vqrshiftns:
16562 case Intrinsic::arm_neon_vqrshiftnu:
16563 case Intrinsic::arm_neon_vqrshiftnsu: {
16564 EVT VT = N->getOperand(1).getValueType();
16565 int64_t Cnt;
16566 unsigned VShiftOpc = 0;
16567
16568 switch (IntNo) {
16569 case Intrinsic::arm_neon_vshifts:
16570 case Intrinsic::arm_neon_vshiftu:
16571 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
16572 VShiftOpc = ARMISD::VSHLIMM;
16573 break;
16574 }
16575 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
16576 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
16577 : ARMISD::VSHRuIMM);
16578 break;
16579 }
16580 return SDValue();
16581
16582 case Intrinsic::arm_neon_vrshifts:
16583 case Intrinsic::arm_neon_vrshiftu:
16584 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
16585 break;
16586 return SDValue();
16587
16588 case Intrinsic::arm_neon_vqshifts:
16589 case Intrinsic::arm_neon_vqshiftu:
16590 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
16591 break;
16592 return SDValue();
16593
16594 case Intrinsic::arm_neon_vqshiftsu:
16595 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
16596 break;
16597 llvm_unreachable("invalid shift count for vqshlu intrinsic")::llvm::llvm_unreachable_internal("invalid shift count for vqshlu intrinsic"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16597)
;
16598
16599 case Intrinsic::arm_neon_vrshiftn:
16600 case Intrinsic::arm_neon_vqshiftns:
16601 case Intrinsic::arm_neon_vqshiftnu:
16602 case Intrinsic::arm_neon_vqshiftnsu:
16603 case Intrinsic::arm_neon_vqrshiftns:
16604 case Intrinsic::arm_neon_vqrshiftnu:
16605 case Intrinsic::arm_neon_vqrshiftnsu:
16606 // Narrowing shifts require an immediate right shift.
16607 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
16608 break;
16609 llvm_unreachable("invalid shift count for narrowing vector shift "::llvm::llvm_unreachable_internal("invalid shift count for narrowing vector shift "
"intrinsic", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16610)
16610 "intrinsic")::llvm::llvm_unreachable_internal("invalid shift count for narrowing vector shift "
"intrinsic", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16610)
;
16611
16612 default:
16613 llvm_unreachable("unhandled vector shift")::llvm::llvm_unreachable_internal("unhandled vector shift", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16613)
;
16614 }
16615
16616 switch (IntNo) {
16617 case Intrinsic::arm_neon_vshifts:
16618 case Intrinsic::arm_neon_vshiftu:
16619 // Opcode already set above.
16620 break;
16621 case Intrinsic::arm_neon_vrshifts:
16622 VShiftOpc = ARMISD::VRSHRsIMM;
16623 break;
16624 case Intrinsic::arm_neon_vrshiftu:
16625 VShiftOpc = ARMISD::VRSHRuIMM;
16626 break;
16627 case Intrinsic::arm_neon_vrshiftn:
16628 VShiftOpc = ARMISD::VRSHRNIMM;
16629 break;
16630 case Intrinsic::arm_neon_vqshifts:
16631 VShiftOpc = ARMISD::VQSHLsIMM;
16632 break;
16633 case Intrinsic::arm_neon_vqshiftu:
16634 VShiftOpc = ARMISD::VQSHLuIMM;
16635 break;
16636 case Intrinsic::arm_neon_vqshiftsu:
16637 VShiftOpc = ARMISD::VQSHLsuIMM;
16638 break;
16639 case Intrinsic::arm_neon_vqshiftns:
16640 VShiftOpc = ARMISD::VQSHRNsIMM;
16641 break;
16642 case Intrinsic::arm_neon_vqshiftnu:
16643 VShiftOpc = ARMISD::VQSHRNuIMM;
16644 break;
16645 case Intrinsic::arm_neon_vqshiftnsu:
16646 VShiftOpc = ARMISD::VQSHRNsuIMM;
16647 break;
16648 case Intrinsic::arm_neon_vqrshiftns:
16649 VShiftOpc = ARMISD::VQRSHRNsIMM;
16650 break;
16651 case Intrinsic::arm_neon_vqrshiftnu:
16652 VShiftOpc = ARMISD::VQRSHRNuIMM;
16653 break;
16654 case Intrinsic::arm_neon_vqrshiftnsu:
16655 VShiftOpc = ARMISD::VQRSHRNsuIMM;
16656 break;
16657 }
16658
16659 SDLoc dl(N);
16660 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
16661 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
16662 }
16663
16664 case Intrinsic::arm_neon_vshiftins: {
16665 EVT VT = N->getOperand(1).getValueType();
16666 int64_t Cnt;
16667 unsigned VShiftOpc = 0;
16668
16669 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
16670 VShiftOpc = ARMISD::VSLIIMM;
16671 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
16672 VShiftOpc = ARMISD::VSRIIMM;
16673 else {
16674 llvm_unreachable("invalid shift count for vsli/vsri intrinsic")::llvm::llvm_unreachable_internal("invalid shift count for vsli/vsri intrinsic"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16674)
;
16675 }
16676
16677 SDLoc dl(N);
16678 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
16679 N->getOperand(1), N->getOperand(2),
16680 DAG.getConstant(Cnt, dl, MVT::i32));
16681 }
16682
16683 case Intrinsic::arm_neon_vqrshifts:
16684 case Intrinsic::arm_neon_vqrshiftu:
16685 // No immediate versions of these to check for.
16686 break;
16687
16688 case Intrinsic::arm_mve_vqdmlah:
16689 case Intrinsic::arm_mve_vqdmlash:
16690 case Intrinsic::arm_mve_vqrdmlah:
16691 case Intrinsic::arm_mve_vqrdmlash:
16692 case Intrinsic::arm_mve_vmla_n_predicated:
16693 case Intrinsic::arm_mve_vmlas_n_predicated:
16694 case Intrinsic::arm_mve_vqdmlah_predicated:
16695 case Intrinsic::arm_mve_vqdmlash_predicated:
16696 case Intrinsic::arm_mve_vqrdmlah_predicated:
16697 case Intrinsic::arm_mve_vqrdmlash_predicated: {
16698 // These intrinsics all take an i32 scalar operand which is narrowed to the
16699 // size of a single lane of the vector type they return. So we don't need
16700 // any bits of that operand above that point, which allows us to eliminate
16701 // uxth/sxth.
16702 unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
16703 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
16704 if (SimplifyDemandedBits(N->getOperand(3), DemandedMask, DCI))
16705 return SDValue();
16706 break;
16707 }
16708
16709 case Intrinsic::arm_mve_minv:
16710 case Intrinsic::arm_mve_maxv:
16711 case Intrinsic::arm_mve_minav:
16712 case Intrinsic::arm_mve_maxav:
16713 case Intrinsic::arm_mve_minv_predicated:
16714 case Intrinsic::arm_mve_maxv_predicated:
16715 case Intrinsic::arm_mve_minav_predicated:
16716 case Intrinsic::arm_mve_maxav_predicated: {
16717 // These intrinsics all take an i32 scalar operand which is narrowed to the
16718 // size of a single lane of the vector type they take as the other input.
16719 unsigned BitWidth = N->getOperand(2)->getValueType(0).getScalarSizeInBits();
16720 APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
16721 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
16722 return SDValue();
16723 break;
16724 }
16725
16726 case Intrinsic::arm_mve_addv: {
16727 // Turn this intrinsic straight into the appropriate ARMISD::VADDV node,
16728 // which allow PerformADDVecReduce to turn it into VADDLV when possible.
16729 bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
16730 unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs;
16731 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), N->getOperand(1));
16732 }
16733
16734 case Intrinsic::arm_mve_addlv:
16735 case Intrinsic::arm_mve_addlv_predicated: {
16736 // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR
16737 // which recombines the two outputs into an i64
16738 bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
16739 unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ?
16740 (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) :
16741 (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps);
16742
16743 SmallVector<SDValue, 4> Ops;
16744 for (unsigned i = 1, e = N->getNumOperands(); i < e; i++)
16745 if (i != 2) // skip the unsigned flag
16746 Ops.push_back(N->getOperand(i));
16747
16748 SDLoc dl(N);
16749 SDValue val = DAG.getNode(Opc, dl, {MVT::i32, MVT::i32}, Ops);
16750 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, val.getValue(0),
16751 val.getValue(1));
16752 }
16753 }
16754
16755 return SDValue();
16756}
16757
16758/// PerformShiftCombine - Checks for immediate versions of vector shifts and
16759/// lowers them. As with the vector shift intrinsics, this is done during DAG
16760/// combining instead of DAG legalizing because the build_vectors for 64-bit
16761/// vector element shift counts are generally not legal, and it is hard to see
16762/// their values after they get legalized to loads from a constant pool.
16763static SDValue PerformShiftCombine(SDNode *N,
16764 TargetLowering::DAGCombinerInfo &DCI,
16765 const ARMSubtarget *ST) {
16766 SelectionDAG &DAG = DCI.DAG;
16767 EVT VT = N->getValueType(0);
16768 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
16769 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
16770 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
16771 SDValue N1 = N->getOperand(1);
16772 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
16773 SDValue N0 = N->getOperand(0);
16774 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
16775 DAG.MaskedValueIsZero(N0.getOperand(0),
16776 APInt::getHighBitsSet(32, 16)))
16777 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
16778 }
16779 }
16780
16781 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
16782 N->getOperand(0)->getOpcode() == ISD::AND &&
16783 N->getOperand(0)->hasOneUse()) {
16784 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16785 return SDValue();
16786 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
16787 // usually show up because instcombine prefers to canonicalize it to
16788 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
16789 // out of GEP lowering in some cases.
16790 SDValue N0 = N->getOperand(0);
16791 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
16792 if (!ShiftAmtNode)
16793 return SDValue();
16794 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
16795 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
16796 if (!AndMaskNode)
16797 return SDValue();
16798 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
16799 // Don't transform uxtb/uxth.
16800 if (AndMask == 255 || AndMask == 65535)
16801 return SDValue();
16802 if (isMask_32(AndMask)) {
16803 uint32_t MaskedBits = countLeadingZeros(AndMask);
16804 if (MaskedBits > ShiftAmt) {
16805 SDLoc DL(N);
16806 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
16807 DAG.getConstant(MaskedBits, DL, MVT::i32));
16808 return DAG.getNode(
16809 ISD::SRL, DL, MVT::i32, SHL,
16810 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
16811 }
16812 }
16813 }
16814
16815 // Nothing to be done for scalar shifts.
16816 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16817 if (!VT.isVector() || !TLI.isTypeLegal(VT))
16818 return SDValue();
16819 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64)
16820 return SDValue();
16821
16822 int64_t Cnt;
16823
16824 switch (N->getOpcode()) {
16825 default: llvm_unreachable("unexpected shift opcode")::llvm::llvm_unreachable_internal("unexpected shift opcode", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16825)
;
16826
16827 case ISD::SHL:
16828 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
16829 SDLoc dl(N);
16830 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
16831 DAG.getConstant(Cnt, dl, MVT::i32));
16832 }
16833 break;
16834
16835 case ISD::SRA:
16836 case ISD::SRL:
16837 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
16838 unsigned VShiftOpc =
16839 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
16840 SDLoc dl(N);
16841 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
16842 DAG.getConstant(Cnt, dl, MVT::i32));
16843 }
16844 }
16845 return SDValue();
16846}
16847
16848// Look for a sign/zero/fpextend extend of a larger than legal load. This can be
16849// split into multiple extending loads, which are simpler to deal with than an
16850// arbitrary extend. For fp extends we use an integer extending load and a VCVTL
16851// to convert the type to an f32.
16852static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) {
16853 SDValue N0 = N->getOperand(0);
16854 if (N0.getOpcode() != ISD::LOAD)
16855 return SDValue();
16856 LoadSDNode *LD = cast<LoadSDNode>(N0.getNode());
16857 if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() ||
16858 LD->getExtensionType() != ISD::NON_EXTLOAD)
16859 return SDValue();
16860 EVT FromVT = LD->getValueType(0);
16861 EVT ToVT = N->getValueType(0);
16862 if (!ToVT.isVector())
16863 return SDValue();
16864 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements())(static_cast <bool> (FromVT.getVectorNumElements() == ToVT
.getVectorNumElements()) ? void (0) : __assert_fail ("FromVT.getVectorNumElements() == ToVT.getVectorNumElements()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16864, __extension__ __PRETTY_FUNCTION__))
;
16865 EVT ToEltVT = ToVT.getVectorElementType();
16866 EVT FromEltVT = FromVT.getVectorElementType();
16867
16868 unsigned NumElements = 0;
16869 if (ToEltVT == MVT::i32 && FromEltVT == MVT::i8)
16870 NumElements = 4;
16871 if (ToEltVT == MVT::f32 && FromEltVT == MVT::f16)
16872 NumElements = 4;
16873 if (NumElements == 0 ||
16874 (FromEltVT != MVT::f16 && FromVT.getVectorNumElements() == NumElements) ||
16875 FromVT.getVectorNumElements() % NumElements != 0 ||
16876 !isPowerOf2_32(NumElements))
16877 return SDValue();
16878
16879 LLVMContext &C = *DAG.getContext();
16880 SDLoc DL(LD);
16881 // Details about the old load
16882 SDValue Ch = LD->getChain();
16883 SDValue BasePtr = LD->getBasePtr();
16884 Align Alignment = LD->getOriginalAlign();
16885 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
16886 AAMDNodes AAInfo = LD->getAAInfo();
16887
16888 ISD::LoadExtType NewExtType =
16889 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
16890 SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
16891 EVT NewFromVT = EVT::getVectorVT(
16892 C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements);
16893 EVT NewToVT = EVT::getVectorVT(
16894 C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements);
16895
16896 SmallVector<SDValue, 4> Loads;
16897 SmallVector<SDValue, 4> Chains;
16898 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
16899 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
16900 SDValue NewPtr =
16901 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset));
16902
16903 SDValue NewLoad =
16904 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
16905 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
16906 Alignment, MMOFlags, AAInfo);
16907 Loads.push_back(NewLoad);
16908 Chains.push_back(SDValue(NewLoad.getNode(), 1));
16909 }
16910
16911 // Float truncs need to extended with VCVTB's into their floating point types.
16912 if (FromEltVT == MVT::f16) {
16913 SmallVector<SDValue, 4> Extends;
16914
16915 for (unsigned i = 0; i < Loads.size(); i++) {
16916 SDValue LoadBC =
16917 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v8f16, Loads[i]);
16918 SDValue FPExt = DAG.getNode(ARMISD::VCVTL, DL, MVT::v4f32, LoadBC,
16919 DAG.getConstant(0, DL, MVT::i32));
16920 Extends.push_back(FPExt);
16921 }
16922
16923 Loads = Extends;
16924 }
16925
16926 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
16927 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
16928 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Loads);
16929}
16930
16931/// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
16932/// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
16933static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
16934 const ARMSubtarget *ST) {
16935 SDValue N0 = N->getOperand(0);
16936
16937 // Check for sign- and zero-extensions of vector extract operations of 8- and
16938 // 16-bit vector elements. NEON and MVE support these directly. They are
16939 // handled during DAG combining because type legalization will promote them
16940 // to 32-bit types and it is messy to recognize the operations after that.
16941 if ((ST->hasNEON() || ST->hasMVEIntegerOps()) &&
16942 N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
16943 SDValue Vec = N0.getOperand(0);
16944 SDValue Lane = N0.getOperand(1);
16945 EVT VT = N->getValueType(0);
16946 EVT EltVT = N0.getValueType();
16947 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16948
16949 if (VT == MVT::i32 &&
16950 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
16951 TLI.isTypeLegal(Vec.getValueType()) &&
16952 isa<ConstantSDNode>(Lane)) {
16953
16954 unsigned Opc = 0;
16955 switch (N->getOpcode()) {
16956 default: llvm_unreachable("unexpected opcode")::llvm::llvm_unreachable_internal("unexpected opcode", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 16956)
;
16957 case ISD::SIGN_EXTEND:
16958 Opc = ARMISD::VGETLANEs;
16959 break;
16960 case ISD::ZERO_EXTEND:
16961 case ISD::ANY_EXTEND:
16962 Opc = ARMISD::VGETLANEu;
16963 break;
16964 }
16965 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
16966 }
16967 }
16968
16969 if (ST->hasMVEIntegerOps())
16970 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
16971 return NewLoad;
16972
16973 return SDValue();
16974}
16975
16976static SDValue PerformFPExtendCombine(SDNode *N, SelectionDAG &DAG,
16977 const ARMSubtarget *ST) {
16978 if (ST->hasMVEFloatOps())
16979 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
16980 return NewLoad;
16981
16982 return SDValue();
16983}
16984
16985/// PerformMinMaxCombine - Target-specific DAG combining for creating truncating
16986/// saturates.
16987static SDValue PerformMinMaxCombine(SDNode *N, SelectionDAG &DAG,
16988 const ARMSubtarget *ST) {
16989 EVT VT = N->getValueType(0);
16990 SDValue N0 = N->getOperand(0);
16991 if (!ST->hasMVEIntegerOps())
16992 return SDValue();
16993
16994 if (SDValue V = PerformVQDMULHCombine(N, DAG))
16995 return V;
16996
16997 if (VT != MVT::v4i32 && VT != MVT::v8i16)
16998 return SDValue();
16999
17000 auto IsSignedSaturate = [&](SDNode *Min, SDNode *Max) {
17001 // Check one is a smin and the other is a smax
17002 if (Min->getOpcode() != ISD::SMIN)
17003 std::swap(Min, Max);
17004 if (Min->getOpcode() != ISD::SMIN || Max->getOpcode() != ISD::SMAX)
17005 return false;
17006
17007 APInt SaturateC;
17008 if (VT == MVT::v4i32)
17009 SaturateC = APInt(32, (1 << 15) - 1, true);
17010 else //if (VT == MVT::v8i16)
17011 SaturateC = APInt(16, (1 << 7) - 1, true);
17012
17013 APInt MinC, MaxC;
17014 if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
17015 MinC != SaturateC)
17016 return false;
17017 if (!ISD::isConstantSplatVector(Max->getOperand(1).getNode(), MaxC) ||
17018 MaxC != ~SaturateC)
17019 return false;
17020 return true;
17021 };
17022
17023 if (IsSignedSaturate(N, N0.getNode())) {
17024 SDLoc DL(N);
17025 MVT ExtVT, HalfVT;
17026 if (VT == MVT::v4i32) {
17027 HalfVT = MVT::v8i16;
17028 ExtVT = MVT::v4i16;
17029 } else { // if (VT == MVT::v8i16)
17030 HalfVT = MVT::v16i8;
17031 ExtVT = MVT::v8i8;
17032 }
17033
17034 // Create a VQMOVNB with undef top lanes, then signed extended into the top
17035 // half. That extend will hopefully be removed if only the bottom bits are
17036 // demanded (though a truncating store, for example).
17037 SDValue VQMOVN =
17038 DAG.getNode(ARMISD::VQMOVNs, DL, HalfVT, DAG.getUNDEF(HalfVT),
17039 N0->getOperand(0), DAG.getConstant(0, DL, MVT::i32));
17040 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
17041 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Bitcast,
17042 DAG.getValueType(ExtVT));
17043 }
17044
17045 auto IsUnsignedSaturate = [&](SDNode *Min) {
17046 // For unsigned, we just need to check for <= 0xffff
17047 if (Min->getOpcode() != ISD::UMIN)
17048 return false;
17049
17050 APInt SaturateC;
17051 if (VT == MVT::v4i32)
17052 SaturateC = APInt(32, (1 << 16) - 1, true);
17053 else //if (VT == MVT::v8i16)
17054 SaturateC = APInt(16, (1 << 8) - 1, true);
17055
17056 APInt MinC;
17057 if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
17058 MinC != SaturateC)
17059 return false;
17060 return true;
17061 };
17062
17063 if (IsUnsignedSaturate(N)) {
17064 SDLoc DL(N);
17065 MVT HalfVT;
17066 unsigned ExtConst;
17067 if (VT == MVT::v4i32) {
17068 HalfVT = MVT::v8i16;
17069 ExtConst = 0x0000FFFF;
17070 } else { //if (VT == MVT::v8i16)
17071 HalfVT = MVT::v16i8;
17072 ExtConst = 0x00FF;
17073 }
17074
17075 // Create a VQMOVNB with undef top lanes, then ZExt into the top half with
17076 // an AND. That extend will hopefully be removed if only the bottom bits are
17077 // demanded (though a truncating store, for example).
17078 SDValue VQMOVN =
17079 DAG.getNode(ARMISD::VQMOVNu, DL, HalfVT, DAG.getUNDEF(HalfVT), N0,
17080 DAG.getConstant(0, DL, MVT::i32));
17081 SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
17082 return DAG.getNode(ISD::AND, DL, VT, Bitcast,
17083 DAG.getConstant(ExtConst, DL, VT));
17084 }
17085
17086 return SDValue();
17087}
17088
17089static const APInt *isPowerOf2Constant(SDValue V) {
17090 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
17091 if (!C)
17092 return nullptr;
17093 const APInt *CV = &C->getAPIntValue();
17094 return CV->isPowerOf2() ? CV : nullptr;
17095}
17096
17097SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
17098 // If we have a CMOV, OR and AND combination such as:
17099 // if (x & CN)
17100 // y |= CM;
17101 //
17102 // And:
17103 // * CN is a single bit;
17104 // * All bits covered by CM are known zero in y
17105 //
17106 // Then we can convert this into a sequence of BFI instructions. This will
17107 // always be a win if CM is a single bit, will always be no worse than the
17108 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
17109 // three bits (due to the extra IT instruction).
17110
17111 SDValue Op0 = CMOV->getOperand(0);
17112 SDValue Op1 = CMOV->getOperand(1);
17113 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
17114 auto CC = CCNode->getAPIntValue().getLimitedValue();
17115 SDValue CmpZ = CMOV->getOperand(4);
17116
17117 // The compare must be against zero.
17118 if (!isNullConstant(CmpZ->getOperand(1)))
17119 return SDValue();
17120
17121 assert(CmpZ->getOpcode() == ARMISD::CMPZ)(static_cast <bool> (CmpZ->getOpcode() == ARMISD::CMPZ
) ? void (0) : __assert_fail ("CmpZ->getOpcode() == ARMISD::CMPZ"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17121, __extension__ __PRETTY_FUNCTION__))
;
17122 SDValue And = CmpZ->getOperand(0);
17123 if (And->getOpcode() != ISD::AND)
17124 return SDValue();
17125 const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
17126 if (!AndC)
17127 return SDValue();
17128 SDValue X = And->getOperand(0);
17129
17130 if (CC == ARMCC::EQ) {
17131 // We're performing an "equal to zero" compare. Swap the operands so we
17132 // canonicalize on a "not equal to zero" compare.
17133 std::swap(Op0, Op1);
17134 } else {
17135 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?")(static_cast <bool> (CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"
) ? void (0) : __assert_fail ("CC == ARMCC::NE && \"How can a CMPZ node not be EQ or NE?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17135, __extension__ __PRETTY_FUNCTION__))
;
17136 }
17137
17138 if (Op1->getOpcode() != ISD::OR)
17139 return SDValue();
17140
17141 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
17142 if (!OrC)
17143 return SDValue();
17144 SDValue Y = Op1->getOperand(0);
17145
17146 if (Op0 != Y)
17147 return SDValue();
17148
17149 // Now, is it profitable to continue?
17150 APInt OrCI = OrC->getAPIntValue();
17151 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
17152 if (OrCI.countPopulation() > Heuristic)
17153 return SDValue();
17154
17155 // Lastly, can we determine that the bits defined by OrCI
17156 // are zero in Y?
17157 KnownBits Known = DAG.computeKnownBits(Y);
17158 if ((OrCI & Known.Zero) != OrCI)
17159 return SDValue();
17160
17161 // OK, we can do the combine.
17162 SDValue V = Y;
17163 SDLoc dl(X);
17164 EVT VT = X.getValueType();
17165 unsigned BitInX = AndC->logBase2();
17166
17167 if (BitInX != 0) {
17168 // We must shift X first.
17169 X = DAG.getNode(ISD::SRL, dl, VT, X,
17170 DAG.getConstant(BitInX, dl, VT));
17171 }
17172
17173 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
17174 BitInY < NumActiveBits; ++BitInY) {
17175 if (OrCI[BitInY] == 0)
17176 continue;
17177 APInt Mask(VT.getSizeInBits(), 0);
17178 Mask.setBit(BitInY);
17179 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
17180 // Confusingly, the operand is an *inverted* mask.
17181 DAG.getConstant(~Mask, dl, VT));
17182 }
17183
17184 return V;
17185}
17186
17187// Given N, the value controlling the conditional branch, search for the loop
17188// intrinsic, returning it, along with how the value is used. We need to handle
17189// patterns such as the following:
17190// (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
17191// (brcond (setcc (loop.decrement), 0, eq), exit)
17192// (brcond (setcc (loop.decrement), 0, ne), header)
17193static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
17194 bool &Negate) {
17195 switch (N->getOpcode()) {
17196 default:
17197 break;
17198 case ISD::XOR: {
17199 if (!isa<ConstantSDNode>(N.getOperand(1)))
17200 return SDValue();
17201 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
17202 return SDValue();
17203 Negate = !Negate;
17204 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
17205 }
17206 case ISD::SETCC: {
17207 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
17208 if (!Const)
17209 return SDValue();
17210 if (Const->isNullValue())
17211 Imm = 0;
17212 else if (Const->isOne())
17213 Imm = 1;
17214 else
17215 return SDValue();
17216 CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
17217 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
17218 }
17219 case ISD::INTRINSIC_W_CHAIN: {
17220 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
17221 if (IntOp != Intrinsic::test_start_loop_iterations &&
17222 IntOp != Intrinsic::loop_decrement_reg)
17223 return SDValue();
17224 return N;
17225 }
17226 }
17227 return SDValue();
17228}
17229
17230static SDValue PerformHWLoopCombine(SDNode *N,
17231 TargetLowering::DAGCombinerInfo &DCI,
17232 const ARMSubtarget *ST) {
17233
17234 // The hwloop intrinsics that we're interested are used for control-flow,
17235 // either for entering or exiting the loop:
17236 // - test.start.loop.iterations will test whether its operand is zero. If it
17237 // is zero, the proceeding branch should not enter the loop.
17238 // - loop.decrement.reg also tests whether its operand is zero. If it is
17239 // zero, the proceeding branch should not branch back to the beginning of
17240 // the loop.
17241 // So here, we need to check that how the brcond is using the result of each
17242 // of the intrinsics to ensure that we're branching to the right place at the
17243 // right time.
17244
17245 ISD::CondCode CC;
17246 SDValue Cond;
17247 int Imm = 1;
17248 bool Negate = false;
17249 SDValue Chain = N->getOperand(0);
17250 SDValue Dest;
17251
17252 if (N->getOpcode() == ISD::BRCOND) {
17253 CC = ISD::SETEQ;
17254 Cond = N->getOperand(1);
17255 Dest = N->getOperand(2);
17256 } else {
17257 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!")(static_cast <bool> (N->getOpcode() == ISD::BR_CC &&
"Expected BRCOND or BR_CC!") ? void (0) : __assert_fail ("N->getOpcode() == ISD::BR_CC && \"Expected BRCOND or BR_CC!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17257, __extension__ __PRETTY_FUNCTION__))
;
17258 CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
17259 Cond = N->getOperand(2);
17260 Dest = N->getOperand(4);
17261 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
17262 if (!Const->isOne() && !Const->isNullValue())
17263 return SDValue();
17264 Imm = Const->getZExtValue();
17265 } else
17266 return SDValue();
17267 }
17268
17269 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
17270 if (!Int)
17271 return SDValue();
17272
17273 if (Negate)
17274 CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32);
17275
17276 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
17277 return (CC == ISD::SETEQ && Imm == 0) ||
17278 (CC == ISD::SETNE && Imm == 1) ||
17279 (CC == ISD::SETLT && Imm == 1) ||
17280 (CC == ISD::SETULT && Imm == 1);
17281 };
17282
17283 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
17284 return (CC == ISD::SETEQ && Imm == 1) ||
17285 (CC == ISD::SETNE && Imm == 0) ||
17286 (CC == ISD::SETGT && Imm == 0) ||
17287 (CC == ISD::SETUGT && Imm == 0) ||
17288 (CC == ISD::SETGE && Imm == 1) ||
17289 (CC == ISD::SETUGE && Imm == 1);
17290 };
17291
17292 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&(static_cast <bool> ((IsTrueIfZero(CC, Imm) || IsFalseIfZero
(CC, Imm)) && "unsupported condition") ? void (0) : __assert_fail
("(IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) && \"unsupported condition\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17293, __extension__ __PRETTY_FUNCTION__))
17293 "unsupported condition")(static_cast <bool> ((IsTrueIfZero(CC, Imm) || IsFalseIfZero
(CC, Imm)) && "unsupported condition") ? void (0) : __assert_fail
("(IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) && \"unsupported condition\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17293, __extension__ __PRETTY_FUNCTION__))
;
17294
17295 SDLoc dl(Int);
17296 SelectionDAG &DAG = DCI.DAG;
17297 SDValue Elements = Int.getOperand(2);
17298 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
17299 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR)(static_cast <bool> ((N->hasOneUse() && N->
use_begin()->getOpcode() == ISD::BR) && "expected single br user"
) ? void (0) : __assert_fail ("(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR) && \"expected single br user\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17300, __extension__ __PRETTY_FUNCTION__))
17300 && "expected single br user")(static_cast <bool> ((N->hasOneUse() && N->
use_begin()->getOpcode() == ISD::BR) && "expected single br user"
) ? void (0) : __assert_fail ("(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR) && \"expected single br user\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17300, __extension__ __PRETTY_FUNCTION__))
;
17301 SDNode *Br = *N->use_begin();
17302 SDValue OtherTarget = Br->getOperand(1);
17303
17304 // Update the unconditional branch to branch to the given Dest.
17305 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
17306 SDValue NewBrOps[] = { Br->getOperand(0), Dest };
17307 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
17308 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
17309 };
17310
17311 if (IntOp == Intrinsic::test_start_loop_iterations) {
17312 SDValue Res;
17313 SDValue Setup = DAG.getNode(ARMISD::WLSSETUP, dl, MVT::i32, Elements);
17314 // We expect this 'instruction' to branch when the counter is zero.
17315 if (IsTrueIfZero(CC, Imm)) {
17316 SDValue Ops[] = {Chain, Setup, Dest};
17317 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
17318 } else {
17319 // The logic is the reverse of what we need for WLS, so find the other
17320 // basic block target: the target of the proceeding br.
17321 UpdateUncondBr(Br, Dest, DAG);
17322
17323 SDValue Ops[] = {Chain, Setup, OtherTarget};
17324 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
17325 }
17326 // Update LR count to the new value
17327 DAG.ReplaceAllUsesOfValueWith(Int.getValue(0), Setup);
17328 // Update chain
17329 DAG.ReplaceAllUsesOfValueWith(Int.getValue(2), Int.getOperand(0));
17330 return Res;
17331 } else {
17332 SDValue Size = DAG.getTargetConstant(
17333 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32);
17334 SDValue Args[] = { Int.getOperand(0), Elements, Size, };
17335 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
17336 DAG.getVTList(MVT::i32, MVT::Other), Args);
17337 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
17338
17339 // We expect this instruction to branch when the count is not zero.
17340 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
17341
17342 // Update the unconditional branch to target the loop preheader if we've
17343 // found the condition has been reversed.
17344 if (Target == OtherTarget)
17345 UpdateUncondBr(Br, Dest, DAG);
17346
17347 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17348 SDValue(LoopDec.getNode(), 1), Chain);
17349
17350 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
17351 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
17352 }
17353 return SDValue();
17354}
17355
17356/// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
17357SDValue
17358ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
17359 SDValue Cmp = N->getOperand(4);
17360 if (Cmp.getOpcode() != ARMISD::CMPZ)
17361 // Only looking at NE cases.
17362 return SDValue();
17363
17364 EVT VT = N->getValueType(0);
17365 SDLoc dl(N);
17366 SDValue LHS = Cmp.getOperand(0);
17367 SDValue RHS = Cmp.getOperand(1);
17368 SDValue Chain = N->getOperand(0);
17369 SDValue BB = N->getOperand(1);
17370 SDValue ARMcc = N->getOperand(2);
17371 ARMCC::CondCodes CC =
17372 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
17373
17374 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
17375 // -> (brcond Chain BB CC CPSR Cmp)
17376 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
17377 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
17378 LHS->getOperand(0)->hasOneUse()) {
17379 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
17380 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
17381 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
17382 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
17383 if ((LHS00C && LHS00C->getZExtValue() == 0) &&
17384 (LHS01C && LHS01C->getZExtValue() == 1) &&
17385 (LHS1C && LHS1C->getZExtValue() == 1) &&
17386 (RHSC && RHSC->getZExtValue() == 0)) {
17387 return DAG.getNode(
17388 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
17389 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
17390 }
17391 }
17392
17393 return SDValue();
17394}
17395
17396/// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
17397SDValue
17398ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
17399 SDValue Cmp = N->getOperand(4);
17400 if (Cmp.getOpcode() != ARMISD::CMPZ)
17401 // Only looking at EQ and NE cases.
17402 return SDValue();
17403
17404 EVT VT = N->getValueType(0);
17405 SDLoc dl(N);
17406 SDValue LHS = Cmp.getOperand(0);
17407 SDValue RHS = Cmp.getOperand(1);
17408 SDValue FalseVal = N->getOperand(0);
17409 SDValue TrueVal = N->getOperand(1);
17410 SDValue ARMcc = N->getOperand(2);
17411 ARMCC::CondCodes CC =
17412 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
17413
17414 // BFI is only available on V6T2+.
17415 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
17416 SDValue R = PerformCMOVToBFICombine(N, DAG);
17417 if (R)
17418 return R;
17419 }
17420
17421 // Simplify
17422 // mov r1, r0
17423 // cmp r1, x
17424 // mov r0, y
17425 // moveq r0, x
17426 // to
17427 // cmp r0, x
17428 // movne r0, y
17429 //
17430 // mov r1, r0
17431 // cmp r1, x
17432 // mov r0, x
17433 // movne r0, y
17434 // to
17435 // cmp r0, x
17436 // movne r0, y
17437 /// FIXME: Turn this into a target neutral optimization?
17438 SDValue Res;
17439 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
17440 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
17441 N->getOperand(3), Cmp);
17442 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
17443 SDValue ARMcc;
17444 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
17445 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
17446 N->getOperand(3), NewCmp);
17447 }
17448
17449 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
17450 // -> (cmov F T CC CPSR Cmp)
17451 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
17452 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
17453 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
17454 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
17455 if ((LHS0C && LHS0C->getZExtValue() == 0) &&
17456 (LHS1C && LHS1C->getZExtValue() == 1) &&
17457 (RHSC && RHSC->getZExtValue() == 0)) {
17458 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
17459 LHS->getOperand(2), LHS->getOperand(3),
17460 LHS->getOperand(4));
17461 }
17462 }
17463
17464 if (!VT.isInteger())
17465 return SDValue();
17466
17467 // Materialize a boolean comparison for integers so we can avoid branching.
17468 if (isNullConstant(FalseVal)) {
17469 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
17470 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
17471 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
17472 // right 5 bits will make that 32 be 1, otherwise it will be 0.
17473 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
17474 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
17475 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
17476 DAG.getConstant(5, dl, MVT::i32));
17477 } else {
17478 // CMOV 0, 1, ==, (CMPZ x, y) ->
17479 // (ADDCARRY (SUB x, y), t:0, t:1)
17480 // where t = (SUBCARRY 0, (SUB x, y), 0)
17481 //
17482 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
17483 // x != y. In other words, a carry C == 1 when x == y, C == 0
17484 // otherwise.
17485 // The final ADDCARRY computes
17486 // x - y + (0 - (x - y)) + C == C
17487 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
17488 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17489 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
17490 // ISD::SUBCARRY returns a borrow but we want the carry here
17491 // actually.
17492 SDValue Carry =
17493 DAG.getNode(ISD::SUB, dl, MVT::i32,
17494 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
17495 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
17496 }
17497 } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
17498 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
17499 // This seems pointless but will allow us to combine it further below.
17500 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
17501 SDValue Sub =
17502 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
17503 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
17504 Sub.getValue(1), SDValue());
17505 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
17506 N->getOperand(3), CPSRGlue.getValue(1));
17507 FalseVal = Sub;
17508 }
17509 } else if (isNullConstant(TrueVal)) {
17510 if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
17511 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
17512 // This seems pointless but will allow us to combine it further below
17513 // Note that we change == for != as this is the dual for the case above.
17514 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
17515 SDValue Sub =
17516 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
17517 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
17518 Sub.getValue(1), SDValue());
17519 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
17520 DAG.getConstant(ARMCC::NE, dl, MVT::i32),
17521 N->getOperand(3), CPSRGlue.getValue(1));
17522 FalseVal = Sub;
17523 }
17524 }
17525
17526 // On Thumb1, the DAG above may be further combined if z is a power of 2
17527 // (z == 2 ^ K).
17528 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
17529 // t1 = (USUBO (SUB x, y), 1)
17530 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
17531 // Result = if K != 0 then (SHL t2:0, K) else t2:0
17532 //
17533 // This also handles the special case of comparing against zero; it's
17534 // essentially, the same pattern, except there's no SUBS:
17535 // CMOV x, z, !=, (CMPZ x, 0) ->
17536 // t1 = (USUBO x, 1)
17537 // t2 = (SUBCARRY x, t1:0, t1:1)
17538 // Result = if K != 0 then (SHL t2:0, K) else t2:0
17539 const APInt *TrueConst;
17540 if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
17541 ((FalseVal.getOpcode() == ARMISD::SUBS &&
17542 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
17543 (FalseVal == LHS && isNullConstant(RHS))) &&
17544 (TrueConst = isPowerOf2Constant(TrueVal))) {
17545 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17546 unsigned ShiftAmount = TrueConst->logBase2();
17547 if (ShiftAmount)
17548 TrueVal = DAG.getConstant(1, dl, VT);
17549 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
17550 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
17551
17552 if (ShiftAmount)
17553 Res = DAG.getNode(ISD::SHL, dl, VT, Res,
17554 DAG.getConstant(ShiftAmount, dl, MVT::i32));
17555 }
17556
17557 if (Res.getNode()) {
17558 KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
17559 // Capture demanded bits information that would be otherwise lost.
17560 if (Known.Zero == 0xfffffffe)
17561 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
17562 DAG.getValueType(MVT::i1));
17563 else if (Known.Zero == 0xffffff00)
17564 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
17565 DAG.getValueType(MVT::i8));
17566 else if (Known.Zero == 0xffff0000)
17567 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
17568 DAG.getValueType(MVT::i16));
17569 }
17570
17571 return Res;
17572}
17573
17574static SDValue PerformBITCASTCombine(SDNode *N,
17575 TargetLowering::DAGCombinerInfo &DCI,
17576 const ARMSubtarget *ST) {
17577 SelectionDAG &DAG = DCI.DAG;
17578 SDValue Src = N->getOperand(0);
17579 EVT DstVT = N->getValueType(0);
17580
17581 // Convert v4f32 bitcast (v4i32 vdup (i32)) -> v4f32 vdup (i32) under MVE.
17582 if (ST->hasMVEIntegerOps() && Src.getOpcode() == ARMISD::VDUP) {
17583 EVT SrcVT = Src.getValueType();
17584 if (SrcVT.getScalarSizeInBits() == DstVT.getScalarSizeInBits())
17585 return DAG.getNode(ARMISD::VDUP, SDLoc(N), DstVT, Src.getOperand(0));
17586 }
17587
17588 // We may have a bitcast of something that has already had this bitcast
17589 // combine performed on it, so skip past any VECTOR_REG_CASTs.
17590 while (Src.getOpcode() == ARMISD::VECTOR_REG_CAST)
17591 Src = Src.getOperand(0);
17592
17593 // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that
17594 // would be generated is at least the width of the element type.
17595 EVT SrcVT = Src.getValueType();
17596 if ((Src.getOpcode() == ARMISD::VMOVIMM ||
17597 Src.getOpcode() == ARMISD::VMVNIMM ||
17598 Src.getOpcode() == ARMISD::VMOVFPIMM) &&
17599 SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() &&
17600 DAG.getDataLayout().isBigEndian())
17601 return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(N), DstVT, Src);
17602
17603 // bitcast(extract(x, n)); bitcast(extract(x, n+1)) -> VMOVRRD x
17604 if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI))
17605 return R;
17606
17607 return SDValue();
17608}
17609
17610// Some combines for the MVETrunc truncations legalizer helper. Also lowers the
17611// node into stack operations after legalizeOps.
17612SDValue ARMTargetLowering::PerformMVETruncCombine(
17613 SDNode *N, TargetLowering::DAGCombinerInfo &DCI) const {
17614 SelectionDAG &DAG = DCI.DAG;
17615 EVT VT = N->getValueType(0);
17616 SDLoc DL(N);
17617
17618 // MVETrunc(Undef, Undef) -> Undef
17619 if (all_of(N->ops(), [](SDValue Op) { return Op.isUndef(); }))
17620 return DAG.getUNDEF(VT);
17621
17622 // MVETrunc(MVETrunc a b, MVETrunc c, d) -> MVETrunc
17623 if (N->getNumOperands() == 2 &&
17624 N->getOperand(0).getOpcode() == ARMISD::MVETRUNC &&
17625 N->getOperand(1).getOpcode() == ARMISD::MVETRUNC)
17626 return DAG.getNode(ARMISD::MVETRUNC, DL, VT, N->getOperand(0).getOperand(0),
17627 N->getOperand(0).getOperand(1),
17628 N->getOperand(1).getOperand(0),
17629 N->getOperand(1).getOperand(1));
17630
17631 // MVETrunc(shuffle, shuffle) -> VMOVN
17632 if (N->getNumOperands() == 2 &&
17633 N->getOperand(0).getOpcode() == ISD::VECTOR_SHUFFLE &&
17634 N->getOperand(1).getOpcode() == ISD::VECTOR_SHUFFLE) {
17635 auto *S0 = cast<ShuffleVectorSDNode>(N->getOperand(0).getNode());
17636 auto *S1 = cast<ShuffleVectorSDNode>(N->getOperand(1).getNode());
17637
17638 if (S0->getOperand(0) == S1->getOperand(0) &&
17639 S0->getOperand(1) == S1->getOperand(1)) {
17640 // Construct complete shuffle mask
17641 SmallVector<int, 8> Mask(S0->getMask().begin(), S0->getMask().end());
17642 Mask.append(S1->getMask().begin(), S1->getMask().end());
17643
17644 if (isVMOVNTruncMask(Mask, VT, 0))
17645 return DAG.getNode(
17646 ARMISD::VMOVN, DL, VT,
17647 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(0)),
17648 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(1)),
17649 DAG.getConstant(1, DL, MVT::i32));
17650 if (isVMOVNTruncMask(Mask, VT, 1))
17651 return DAG.getNode(
17652 ARMISD::VMOVN, DL, VT,
17653 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(1)),
17654 DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(0)),
17655 DAG.getConstant(1, DL, MVT::i32));
17656 }
17657 }
17658
17659 // For MVETrunc of a buildvector or shuffle, it can be beneficial to lower the
17660 // truncate to a buildvector to allow the generic optimisations to kick in.
17661 if (all_of(N->ops(), [](SDValue Op) {
17662 return Op.getOpcode() == ISD::BUILD_VECTOR ||
17663 Op.getOpcode() == ISD::VECTOR_SHUFFLE ||
17664 (Op.getOpcode() == ISD::BITCAST &&
17665 Op.getOperand(0).getOpcode() == ISD::BUILD_VECTOR);
17666 })) {
17667 SmallVector<SDValue, 8> Extracts;
17668 for (unsigned Op = 0; Op < N->getNumOperands(); Op++) {
17669 SDValue O = N->getOperand(Op);
17670 for (unsigned i = 0; i < O.getValueType().getVectorNumElements(); i++) {
17671 SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, O,
17672 DAG.getConstant(i, DL, MVT::i32));
17673 Extracts.push_back(Ext);
17674 }
17675 }
17676 return DAG.getBuildVector(VT, DL, Extracts);
17677 }
17678
17679 // If we are late in the legalization process and nothing has optimised
17680 // the trunc to anything better, lower it to a stack store and reload,
17681 // performing the truncation whilst keeping the lanes in the correct order:
17682 // VSTRH.32 a, stack; VSTRH.32 b, stack+8; VLDRW.32 stack;
17683 if (!DCI.isAfterLegalizeDAG())
17684 return SDValue();
17685
17686 SDValue StackPtr = DAG.CreateStackTemporary(TypeSize::Fixed(16), Align(4));
17687 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
17688 int NumIns = N->getNumOperands();
17689 assert((NumIns == 2 || NumIns == 4) &&(static_cast <bool> ((NumIns == 2 || NumIns == 4) &&
"Expected 2 or 4 inputs to an MVETrunc") ? void (0) : __assert_fail
("(NumIns == 2 || NumIns == 4) && \"Expected 2 or 4 inputs to an MVETrunc\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17690, __extension__ __PRETTY_FUNCTION__))
17690 "Expected 2 or 4 inputs to an MVETrunc")(static_cast <bool> ((NumIns == 2 || NumIns == 4) &&
"Expected 2 or 4 inputs to an MVETrunc") ? void (0) : __assert_fail
("(NumIns == 2 || NumIns == 4) && \"Expected 2 or 4 inputs to an MVETrunc\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17690, __extension__ __PRETTY_FUNCTION__))
;
17691 EVT StoreVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
17692 if (N->getNumOperands() == 4)
17693 StoreVT = StoreVT.getHalfNumVectorElementsVT(*DAG.getContext());
17694
17695 SmallVector<SDValue> Chains;
17696 for (int I = 0; I < NumIns; I++) {
17697 SDValue Ptr = DAG.getNode(
17698 ISD::ADD, DL, StackPtr.getValueType(), StackPtr,
17699 DAG.getConstant(I * 16 / NumIns, DL, StackPtr.getValueType()));
17700 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(
17701 DAG.getMachineFunction(), SPFI, I * 16 / NumIns);
17702 SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), DL, N->getOperand(I),
17703 Ptr, MPI, StoreVT, Align(4));
17704 Chains.push_back(Ch);
17705 }
17706
17707 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
17708 MachinePointerInfo MPI =
17709 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI, 0);
17710 return DAG.getLoad(VT, DL, Chain, StackPtr, MPI, Align(4));
17711}
17712
17713// Take a MVEEXT(load x) and split that into (extload x, extload x+8)
17714static SDValue PerformSplittingMVEEXTToWideningLoad(SDNode *N,
17715 SelectionDAG &DAG) {
17716 SDValue N0 = N->getOperand(0);
17717 LoadSDNode *LD = dyn_cast<LoadSDNode>(N0.getNode());
17718 if (!LD || !LD->isSimple() || !N0.hasOneUse() || LD->isIndexed())
17719 return SDValue();
17720
17721 EVT FromVT = LD->getMemoryVT();
17722 EVT ToVT = N->getValueType(0);
17723 if (!ToVT.isVector())
17724 return SDValue();
17725 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements() * 2)(static_cast <bool> (FromVT.getVectorNumElements() == ToVT
.getVectorNumElements() * 2) ? void (0) : __assert_fail ("FromVT.getVectorNumElements() == ToVT.getVectorNumElements() * 2"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17725, __extension__ __PRETTY_FUNCTION__))
;
17726 EVT ToEltVT = ToVT.getVectorElementType();
17727 EVT FromEltVT = FromVT.getVectorElementType();
17728
17729 unsigned NumElements = 0;
17730 if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8))
17731 NumElements = 4;
17732 if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8)
17733 NumElements = 8;
17734 assert(NumElements != 0)(static_cast <bool> (NumElements != 0) ? void (0) : __assert_fail
("NumElements != 0", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17734, __extension__ __PRETTY_FUNCTION__))
;
17735
17736 ISD::LoadExtType NewExtType =
17737 N->getOpcode() == ARMISD::MVESEXT ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
17738 if (LD->getExtensionType() != ISD::NON_EXTLOAD &&
17739 LD->getExtensionType() != ISD::EXTLOAD &&
17740 LD->getExtensionType() != NewExtType)
17741 return SDValue();
17742
17743 LLVMContext &C = *DAG.getContext();
17744 SDLoc DL(LD);
17745 // Details about the old load
17746 SDValue Ch = LD->getChain();
17747 SDValue BasePtr = LD->getBasePtr();
17748 Align Alignment = LD->getOriginalAlign();
17749 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
17750 AAMDNodes AAInfo = LD->getAAInfo();
17751
17752 SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
17753 EVT NewFromVT = EVT::getVectorVT(
17754 C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements);
17755 EVT NewToVT = EVT::getVectorVT(
17756 C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements);
17757
17758 SmallVector<SDValue, 4> Loads;
17759 SmallVector<SDValue, 4> Chains;
17760 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
17761 unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
17762 SDValue NewPtr =
17763 DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset));
17764
17765 SDValue NewLoad =
17766 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
17767 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
17768 Alignment, MMOFlags, AAInfo);
17769 Loads.push_back(NewLoad);
17770 Chains.push_back(SDValue(NewLoad.getNode(), 1));
17771 }
17772
17773 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
17774 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
17775 return DAG.getMergeValues(Loads, DL);
17776}
17777
17778// Perform combines for MVEEXT. If it has not be optimized to anything better
17779// before lowering, it gets converted to stack store and extloads performing the
17780// extend whilst still keeping the same lane ordering.
17781SDValue ARMTargetLowering::PerformMVEExtCombine(
17782 SDNode *N, TargetLowering::DAGCombinerInfo &DCI) const {
17783 SelectionDAG &DAG = DCI.DAG;
17784 EVT VT = N->getValueType(0);
17785 SDLoc DL(N);
17786 assert(N->getNumValues() == 2 && "Expected MVEEXT with 2 elements")(static_cast <bool> (N->getNumValues() == 2 &&
"Expected MVEEXT with 2 elements") ? void (0) : __assert_fail
("N->getNumValues() == 2 && \"Expected MVEEXT with 2 elements\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17786, __extension__ __PRETTY_FUNCTION__))
;
17787 assert((VT == MVT::v4i32 || VT == MVT::v8i16) && "Unexpected MVEEXT type")(static_cast <bool> ((VT == MVT::v4i32 || VT == MVT::v8i16
) && "Unexpected MVEEXT type") ? void (0) : __assert_fail
("(VT == MVT::v4i32 || VT == MVT::v8i16) && \"Unexpected MVEEXT type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17787, __extension__ __PRETTY_FUNCTION__))
;
17788
17789 EVT ExtVT = N->getOperand(0).getValueType().getHalfNumVectorElementsVT(
17790 *DAG.getContext());
17791 auto Extend = [&](SDValue V) {
17792 SDValue VVT = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, V);
17793 return N->getOpcode() == ARMISD::MVESEXT
17794 ? DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, VVT,
17795 DAG.getValueType(ExtVT))
17796 : DAG.getZeroExtendInReg(VVT, DL, ExtVT);
17797 };
17798
17799 // MVEEXT(VDUP) -> SIGN_EXTEND_INREG(VDUP)
17800 if (N->getOperand(0).getOpcode() == ARMISD::VDUP) {
17801 SDValue Ext = Extend(N->getOperand(0));
17802 return DAG.getMergeValues({Ext, Ext}, DL);
17803 }
17804
17805 // MVEEXT(shuffle) -> SIGN_EXTEND_INREG/ZERO_EXTEND_INREG
17806 if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(N->getOperand(0))) {
17807 ArrayRef<int> Mask = SVN->getMask();
17808 assert(Mask.size() == 2 * VT.getVectorNumElements())(static_cast <bool> (Mask.size() == 2 * VT.getVectorNumElements
()) ? void (0) : __assert_fail ("Mask.size() == 2 * VT.getVectorNumElements()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17808, __extension__ __PRETTY_FUNCTION__))
;
17809 assert(Mask.size() == SVN->getValueType(0).getVectorNumElements())(static_cast <bool> (Mask.size() == SVN->getValueType
(0).getVectorNumElements()) ? void (0) : __assert_fail ("Mask.size() == SVN->getValueType(0).getVectorNumElements()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17809, __extension__ __PRETTY_FUNCTION__))
;
17810 unsigned Rev = VT == MVT::v4i32 ? ARMISD::VREV32 : ARMISD::VREV16;
17811 SDValue Op0 = SVN->getOperand(0);
17812 SDValue Op1 = SVN->getOperand(1);
17813
17814 auto CheckInregMask = [&](int Start, int Offset) {
17815 for (int Idx = 0, E = VT.getVectorNumElements(); Idx < E; ++Idx)
17816 if (Mask[Start + Idx] >= 0 && Mask[Start + Idx] != Idx * 2 + Offset)
17817 return false;
17818 return true;
17819 };
17820 SDValue V0 = SDValue(N, 0);
17821 SDValue V1 = SDValue(N, 1);
17822 if (CheckInregMask(0, 0))
17823 V0 = Extend(Op0);
17824 else if (CheckInregMask(0, 1))
17825 V0 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op0));
17826 else if (CheckInregMask(0, Mask.size()))
17827 V0 = Extend(Op1);
17828 else if (CheckInregMask(0, Mask.size() + 1))
17829 V0 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op1));
17830
17831 if (CheckInregMask(VT.getVectorNumElements(), Mask.size()))
17832 V1 = Extend(Op1);
17833 else if (CheckInregMask(VT.getVectorNumElements(), Mask.size() + 1))
17834 V1 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op1));
17835 else if (CheckInregMask(VT.getVectorNumElements(), 0))
17836 V1 = Extend(Op0);
17837 else if (CheckInregMask(VT.getVectorNumElements(), 1))
17838 V1 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op0));
17839
17840 if (V0.getNode() != N || V1.getNode() != N)
17841 return DAG.getMergeValues({V0, V1}, DL);
17842 }
17843
17844 // MVEEXT(load) -> extload, extload
17845 if (N->getOperand(0)->getOpcode() == ISD::LOAD)
17846 if (SDValue L = PerformSplittingMVEEXTToWideningLoad(N, DAG))
17847 return L;
17848
17849 if (!DCI.isAfterLegalizeDAG())
17850 return SDValue();
17851
17852 // Lower to a stack store and reload:
17853 // VSTRW.32 a, stack; VLDRH.32 stack; VLDRH.32 stack+8;
17854 SDValue StackPtr = DAG.CreateStackTemporary(TypeSize::Fixed(16), Align(4));
17855 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
17856 int NumOuts = N->getNumValues();
17857 assert((NumOuts == 2 || NumOuts == 4) &&(static_cast <bool> ((NumOuts == 2 || NumOuts == 4) &&
"Expected 2 or 4 outputs to an MVEEXT") ? void (0) : __assert_fail
("(NumOuts == 2 || NumOuts == 4) && \"Expected 2 or 4 outputs to an MVEEXT\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17858, __extension__ __PRETTY_FUNCTION__))
17858 "Expected 2 or 4 outputs to an MVEEXT")(static_cast <bool> ((NumOuts == 2 || NumOuts == 4) &&
"Expected 2 or 4 outputs to an MVEEXT") ? void (0) : __assert_fail
("(NumOuts == 2 || NumOuts == 4) && \"Expected 2 or 4 outputs to an MVEEXT\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 17858, __extension__ __PRETTY_FUNCTION__))
;
17859 EVT LoadVT = N->getOperand(0).getValueType().getHalfNumVectorElementsVT(
17860 *DAG.getContext());
17861 if (N->getNumOperands() == 4)
17862 LoadVT = LoadVT.getHalfNumVectorElementsVT(*DAG.getContext());
17863
17864 MachinePointerInfo MPI =
17865 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI, 0);
17866 SDValue Chain = DAG.getStore(DAG.getEntryNode(), DL, N->getOperand(0),
17867 StackPtr, MPI, Align(4));
17868
17869 SmallVector<SDValue> Loads;
17870 for (int I = 0; I < NumOuts; I++) {
17871 SDValue Ptr = DAG.getNode(
17872 ISD::ADD, DL, StackPtr.getValueType(), StackPtr,
17873 DAG.getConstant(I * 16 / NumOuts, DL, StackPtr.getValueType()));
17874 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(
17875 DAG.getMachineFunction(), SPFI, I * 16 / NumOuts);
17876 SDValue Load = DAG.getExtLoad(
17877 N->getOpcode() == ARMISD::MVESEXT ? ISD::SEXTLOAD : ISD::ZEXTLOAD, DL,
17878 VT, Chain, Ptr, MPI, LoadVT, Align(4));
17879 Loads.push_back(Load);
17880 }
17881
17882 return DAG.getMergeValues(Loads, DL);
17883}
17884
17885SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
17886 DAGCombinerInfo &DCI) const {
17887 switch (N->getOpcode()) {
17888 default: break;
17889 case ISD::SELECT_CC:
17890 case ISD::SELECT: return PerformSELECTCombine(N, DCI, Subtarget);
17891 case ISD::VSELECT: return PerformVSELECTCombine(N, DCI, Subtarget);
17892 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget);
17893 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
17894 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget);
17895 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
17896 case ISD::SUB: return PerformSUBCombine(N, DCI, Subtarget);
17897 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
17898 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
17899 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
17900 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
17901 case ISD::BRCOND:
17902 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget);
17903 case ARMISD::ADDC:
17904 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget);
17905 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget);
17906 case ARMISD::BFI: return PerformBFICombine(N, DCI.DAG);
17907 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
17908 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
17909 case ARMISD::VMOVhr: return PerformVMOVhrCombine(N, DCI);
17910 case ARMISD::VMOVrh: return PerformVMOVrhCombine(N, DCI.DAG);
17911 case ISD::STORE: return PerformSTORECombine(N, DCI, Subtarget);
17912 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
17913 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
17914 case ISD::EXTRACT_VECTOR_ELT:
17915 return PerformExtractEltCombine(N, DCI, Subtarget);
17916 case ISD::SIGN_EXTEND_INREG: return PerformSignExtendInregCombine(N, DCI.DAG);
17917 case ISD::INSERT_SUBVECTOR: return PerformInsertSubvectorCombine(N, DCI);
17918 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
17919 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI, Subtarget);
17920 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI.DAG, Subtarget);
17921 case ISD::FP_TO_SINT:
17922 case ISD::FP_TO_UINT:
17923 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
17924 case ISD::FDIV:
17925 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
17926 case ISD::INTRINSIC_WO_CHAIN:
17927 return PerformIntrinsicCombine(N, DCI);
17928 case ISD::SHL:
17929 case ISD::SRA:
17930 case ISD::SRL:
17931 return PerformShiftCombine(N, DCI, Subtarget);
17932 case ISD::SIGN_EXTEND:
17933 case ISD::ZERO_EXTEND:
17934 case ISD::ANY_EXTEND:
17935 return PerformExtendCombine(N, DCI.DAG, Subtarget);
17936 case ISD::FP_EXTEND:
17937 return PerformFPExtendCombine(N, DCI.DAG, Subtarget);
17938 case ISD::SMIN:
17939 case ISD::UMIN:
17940 case ISD::SMAX:
17941 case ISD::UMAX:
17942 return PerformMinMaxCombine(N, DCI.DAG, Subtarget);
17943 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
17944 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
17945 case ISD::LOAD: return PerformLOADCombine(N, DCI);
17946 case ARMISD::VLD1DUP:
17947 case ARMISD::VLD2DUP:
17948 case ARMISD::VLD3DUP:
17949 case ARMISD::VLD4DUP:
17950 return PerformVLDCombine(N, DCI);
17951 case ARMISD::BUILD_VECTOR:
17952 return PerformARMBUILD_VECTORCombine(N, DCI);
17953 case ISD::BITCAST:
17954 return PerformBITCASTCombine(N, DCI, Subtarget);
17955 case ARMISD::PREDICATE_CAST:
17956 return PerformPREDICATE_CASTCombine(N, DCI);
17957 case ARMISD::VECTOR_REG_CAST:
17958 return PerformVECTOR_REG_CASTCombine(N, DCI.DAG, Subtarget);
17959 case ARMISD::MVETRUNC:
17960 return PerformMVETruncCombine(N, DCI);
17961 case ARMISD::MVESEXT:
17962 case ARMISD::MVEZEXT:
17963 return PerformMVEExtCombine(N, DCI);
17964 case ARMISD::VCMP:
17965 return PerformVCMPCombine(N, DCI.DAG, Subtarget);
17966 case ISD::VECREDUCE_ADD:
17967 return PerformVECREDUCE_ADDCombine(N, DCI.DAG, Subtarget);
17968 case ARMISD::VMOVN:
17969 return PerformVMOVNCombine(N, DCI);
17970 case ARMISD::VQMOVNs:
17971 case ARMISD::VQMOVNu:
17972 return PerformVQMOVNCombine(N, DCI);
17973 case ARMISD::ASRL:
17974 case ARMISD::LSRL:
17975 case ARMISD::LSLL:
17976 return PerformLongShiftCombine(N, DCI.DAG);
17977 case ARMISD::SMULWB: {
17978 unsigned BitWidth = N->getValueType(0).getSizeInBits();
17979 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
17980 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
17981 return SDValue();
17982 break;
17983 }
17984 case ARMISD::SMULWT: {
17985 unsigned BitWidth = N->getValueType(0).getSizeInBits();
17986 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
17987 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
17988 return SDValue();
17989 break;
17990 }
17991 case ARMISD::SMLALBB:
17992 case ARMISD::QADD16b:
17993 case ARMISD::QSUB16b:
17994 case ARMISD::UQADD16b:
17995 case ARMISD::UQSUB16b: {
17996 unsigned BitWidth = N->getValueType(0).getSizeInBits();
17997 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
17998 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
17999 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
18000 return SDValue();
18001 break;
18002 }
18003 case ARMISD::SMLALBT: {
18004 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
18005 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
18006 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
18007 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
18008 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
18009 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
18010 return SDValue();
18011 break;
18012 }
18013 case ARMISD::SMLALTB: {
18014 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
18015 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
18016 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
18017 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
18018 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
18019 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
18020 return SDValue();
18021 break;
18022 }
18023 case ARMISD::SMLALTT: {
18024 unsigned BitWidth = N->getValueType(0).getSizeInBits();
18025 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
18026 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
18027 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
18028 return SDValue();
18029 break;
18030 }
18031 case ARMISD::QADD8b:
18032 case ARMISD::QSUB8b:
18033 case ARMISD::UQADD8b:
18034 case ARMISD::UQSUB8b: {
18035 unsigned BitWidth = N->getValueType(0).getSizeInBits();
18036 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
18037 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
18038 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
18039 return SDValue();
18040 break;
18041 }
18042 case ISD::INTRINSIC_VOID:
18043 case ISD::INTRINSIC_W_CHAIN:
18044 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
18045 case Intrinsic::arm_neon_vld1:
18046 case Intrinsic::arm_neon_vld1x2:
18047 case Intrinsic::arm_neon_vld1x3:
18048 case Intrinsic::arm_neon_vld1x4:
18049 case Intrinsic::arm_neon_vld2:
18050 case Intrinsic::arm_neon_vld3:
18051 case Intrinsic::arm_neon_vld4:
18052 case Intrinsic::arm_neon_vld2lane:
18053 case Intrinsic::arm_neon_vld3lane:
18054 case Intrinsic::arm_neon_vld4lane:
18055 case Intrinsic::arm_neon_vld2dup:
18056 case Intrinsic::arm_neon_vld3dup:
18057 case Intrinsic::arm_neon_vld4dup:
18058 case Intrinsic::arm_neon_vst1:
18059 case Intrinsic::arm_neon_vst1x2:
18060 case Intrinsic::arm_neon_vst1x3:
18061 case Intrinsic::arm_neon_vst1x4:
18062 case Intrinsic::arm_neon_vst2:
18063 case Intrinsic::arm_neon_vst3:
18064 case Intrinsic::arm_neon_vst4:
18065 case Intrinsic::arm_neon_vst2lane:
18066 case Intrinsic::arm_neon_vst3lane:
18067 case Intrinsic::arm_neon_vst4lane:
18068 return PerformVLDCombine(N, DCI);
18069 case Intrinsic::arm_mve_vld2q:
18070 case Intrinsic::arm_mve_vld4q:
18071 case Intrinsic::arm_mve_vst2q:
18072 case Intrinsic::arm_mve_vst4q:
18073 return PerformMVEVLDCombine(N, DCI);
18074 default: break;
18075 }
18076 break;
18077 }
18078 return SDValue();
18079}
18080
18081bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
18082 EVT VT) const {
18083 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
18084}
18085
18086bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
18087 Align Alignment,
18088 MachineMemOperand::Flags,
18089 bool *Fast) const {
18090 // Depends what it gets converted into if the type is weird.
18091 if (!VT.isSimple())
18092 return false;
18093
18094 // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus
18095 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
18096 auto Ty = VT.getSimpleVT().SimpleTy;
18097
18098 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
18099 // Unaligned access can use (for example) LRDB, LRDH, LDR
18100 if (AllowsUnaligned) {
18101 if (Fast)
18102 *Fast = Subtarget->hasV7Ops();
18103 return true;
18104 }
18105 }
18106
18107 if (Ty == MVT::f64 || Ty == MVT::v2f64) {
18108 // For any little-endian targets with neon, we can support unaligned ld/st
18109 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
18110 // A big-endian target may also explicitly support unaligned accesses
18111 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
18112 if (Fast)
18113 *Fast = true;
18114 return true;
18115 }
18116 }
18117
18118 if (!Subtarget->hasMVEIntegerOps())
18119 return false;
18120
18121 // These are for predicates
18122 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) {
18123 if (Fast)
18124 *Fast = true;
18125 return true;
18126 }
18127
18128 // These are for truncated stores/narrowing loads. They are fine so long as
18129 // the alignment is at least the size of the item being loaded
18130 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
18131 Alignment >= VT.getScalarSizeInBits() / 8) {
18132 if (Fast)
18133 *Fast = true;
18134 return true;
18135 }
18136
18137 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
18138 // VSTRW.U32 all store the vector register in exactly the same format, and
18139 // differ only in the range of their immediate offset field and the required
18140 // alignment. So there is always a store that can be used, regardless of
18141 // actual type.
18142 //
18143 // For big endian, that is not the case. But can still emit a (VSTRB.U8;
18144 // VREV64.8) pair and get the same effect. This will likely be better than
18145 // aligning the vector through the stack.
18146 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
18147 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
18148 Ty == MVT::v2f64) {
18149 if (Fast)
18150 *Fast = true;
18151 return true;
18152 }
18153
18154 return false;
18155}
18156
18157
18158EVT ARMTargetLowering::getOptimalMemOpType(
18159 const MemOp &Op, const AttributeList &FuncAttributes) const {
18160 // See if we can use NEON instructions for this...
18161 if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() &&
18162 !FuncAttributes.hasFnAttr(Attribute::NoImplicitFloat)) {
18163 bool Fast;
18164 if (Op.size() >= 16 &&
18165 (Op.isAligned(Align(16)) ||
18166 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, Align(1),
18167 MachineMemOperand::MONone, &Fast) &&
18168 Fast))) {
18169 return MVT::v2f64;
18170 } else if (Op.size() >= 8 &&
18171 (Op.isAligned(Align(8)) ||
18172 (allowsMisalignedMemoryAccesses(
18173 MVT::f64, 0, Align(1), MachineMemOperand::MONone, &Fast) &&
18174 Fast))) {
18175 return MVT::f64;
18176 }
18177 }
18178
18179 // Let the target-independent logic figure it out.
18180 return MVT::Other;
18181}
18182
18183// 64-bit integers are split into their high and low parts and held in two
18184// different registers, so the trunc is free since the low register can just
18185// be used.
18186bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
18187 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
18188 return false;
18189 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
18190 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
18191 return (SrcBits == 64 && DestBits == 32);
18192}
18193
18194bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
18195 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
18196 !DstVT.isInteger())
18197 return false;
18198 unsigned SrcBits = SrcVT.getSizeInBits();
18199 unsigned DestBits = DstVT.getSizeInBits();
18200 return (SrcBits == 64 && DestBits == 32);
18201}
18202
18203bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18204 if (Val.getOpcode() != ISD::LOAD)
18205 return false;
18206
18207 EVT VT1 = Val.getValueType();
18208 if (!VT1.isSimple() || !VT1.isInteger() ||
18209 !VT2.isSimple() || !VT2.isInteger())
18210 return false;
18211
18212 switch (VT1.getSimpleVT().SimpleTy) {
18213 default: break;
18214 case MVT::i1:
18215 case MVT::i8:
18216 case MVT::i16:
18217 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
18218 return true;
18219 }
18220
18221 return false;
18222}
18223
18224bool ARMTargetLowering::isFNegFree(EVT VT) const {
18225 if (!VT.isSimple())
18226 return false;
18227
18228 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
18229 // negate values directly (fneg is free). So, we don't want to let the DAG
18230 // combiner rewrite fneg into xors and some other instructions. For f16 and
18231 // FullFP16 argument passing, some bitcast nodes may be introduced,
18232 // triggering this DAG combine rewrite, so we are avoiding that with this.
18233 switch (VT.getSimpleVT().SimpleTy) {
18234 default: break;
18235 case MVT::f16:
18236 return Subtarget->hasFullFP16();
18237 }
18238
18239 return false;
18240}
18241
18242/// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
18243/// of the vector elements.
18244static bool areExtractExts(Value *Ext1, Value *Ext2) {
18245 auto areExtDoubled = [](Instruction *Ext) {
18246 return Ext->getType()->getScalarSizeInBits() ==
18247 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
18248 };
18249
18250 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
18251 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
18252 !areExtDoubled(cast<Instruction>(Ext1)) ||
18253 !areExtDoubled(cast<Instruction>(Ext2)))
18254 return false;
18255
18256 return true;
18257}
18258
18259/// Check if sinking \p I's operands to I's basic block is profitable, because
18260/// the operands can be folded into a target instruction, e.g.
18261/// sext/zext can be folded into vsubl.
18262bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
18263 SmallVectorImpl<Use *> &Ops) const {
18264 if (!I->getType()->isVectorTy())
18265 return false;
18266
18267 if (Subtarget->hasNEON()) {
18268 switch (I->getOpcode()) {
18269 case Instruction::Sub:
18270 case Instruction::Add: {
18271 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
18272 return false;
18273 Ops.push_back(&I->getOperandUse(0));
18274 Ops.push_back(&I->getOperandUse(1));
18275 return true;
18276 }
18277 default:
18278 return false;
18279 }
18280 }
18281
18282 if (!Subtarget->hasMVEIntegerOps())
18283 return false;
18284
18285 auto IsFMSMul = [&](Instruction *I) {
18286 if (!I->hasOneUse())
18287 return false;
18288 auto *Sub = cast<Instruction>(*I->users().begin());
18289 return Sub->getOpcode() == Instruction::FSub && Sub->getOperand(1) == I;
18290 };
18291 auto IsFMS = [&](Instruction *I) {
18292 if (match(I->getOperand(0), m_FNeg(m_Value())) ||
18293 match(I->getOperand(1), m_FNeg(m_Value())))
18294 return true;
18295 return false;
18296 };
18297
18298 auto IsSinker = [&](Instruction *I, int Operand) {
18299 switch (I->getOpcode()) {
18300 case Instruction::Add:
18301 case Instruction::Mul:
18302 case Instruction::FAdd:
18303 case Instruction::ICmp:
18304 case Instruction::FCmp:
18305 return true;
18306 case Instruction::FMul:
18307 return !IsFMSMul(I);
18308 case Instruction::Sub:
18309 case Instruction::FSub:
18310 case Instruction::Shl:
18311 case Instruction::LShr:
18312 case Instruction::AShr:
18313 return Operand == 1;
18314 case Instruction::Call:
18315 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
18316 switch (II->getIntrinsicID()) {
18317 case Intrinsic::fma:
18318 return !IsFMS(I);
18319 case Intrinsic::arm_mve_add_predicated:
18320 case Intrinsic::arm_mve_mul_predicated:
18321 case Intrinsic::arm_mve_qadd_predicated:
18322 case Intrinsic::arm_mve_hadd_predicated:
18323 case Intrinsic::arm_mve_vqdmull_predicated:
18324 case Intrinsic::arm_mve_qdmulh_predicated:
18325 case Intrinsic::arm_mve_qrdmulh_predicated:
18326 case Intrinsic::arm_mve_fma_predicated:
18327 return true;
18328 case Intrinsic::arm_mve_sub_predicated:
18329 case Intrinsic::arm_mve_qsub_predicated:
18330 case Intrinsic::arm_mve_hsub_predicated:
18331 return Operand == 1;
18332 default:
18333 return false;
18334 }
18335 }
18336 return false;
18337 default:
18338 return false;
18339 }
18340 };
18341
18342 for (auto OpIdx : enumerate(I->operands())) {
18343 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
18344 // Make sure we are not already sinking this operand
18345 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
18346 continue;
18347
18348 Instruction *Shuffle = Op;
18349 if (Shuffle->getOpcode() == Instruction::BitCast)
18350 Shuffle = dyn_cast<Instruction>(Shuffle->getOperand(0));
18351 // We are looking for a splat that can be sunk.
18352 if (!Shuffle ||
18353 !match(Shuffle, m_Shuffle(
18354 m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
18355 m_Undef(), m_ZeroMask())))
18356 continue;
18357 if (!IsSinker(I, OpIdx.index()))
18358 continue;
18359
18360 // All uses of the shuffle should be sunk to avoid duplicating it across gpr
18361 // and vector registers
18362 for (Use &U : Op->uses()) {
18363 Instruction *Insn = cast<Instruction>(U.getUser());
18364 if (!IsSinker(Insn, U.getOperandNo()))
18365 return false;
18366 }
18367
18368 Ops.push_back(&Shuffle->getOperandUse(0));
18369 if (Shuffle != Op)
18370 Ops.push_back(&Op->getOperandUse(0));
18371 Ops.push_back(&OpIdx.value());
18372 }
18373 return true;
18374}
18375
18376Type *ARMTargetLowering::shouldConvertSplatType(ShuffleVectorInst *SVI) const {
18377 if (!Subtarget->hasMVEIntegerOps())
18378 return nullptr;
18379 Type *SVIType = SVI->getType();
18380 Type *ScalarType = SVIType->getScalarType();
18381
18382 if (ScalarType->isFloatTy())
18383 return Type::getInt32Ty(SVIType->getContext());
18384 if (ScalarType->isHalfTy())
18385 return Type::getInt16Ty(SVIType->getContext());
18386 return nullptr;
18387}
18388
18389bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
18390 EVT VT = ExtVal.getValueType();
18391
18392 if (!isTypeLegal(VT))
18393 return false;
18394
18395 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) {
18396 if (Ld->isExpandingLoad())
18397 return false;
18398 }
18399
18400 if (Subtarget->hasMVEIntegerOps())
18401 return true;
18402
18403 // Don't create a loadext if we can fold the extension into a wide/long
18404 // instruction.
18405 // If there's more than one user instruction, the loadext is desirable no
18406 // matter what. There can be two uses by the same instruction.
18407 if (ExtVal->use_empty() ||
18408 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
18409 return true;
18410
18411 SDNode *U = *ExtVal->use_begin();
18412 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
18413 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
18414 return false;
18415
18416 return true;
18417}
18418
18419bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18420 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18421 return false;
18422
18423 if (!isTypeLegal(EVT::getEVT(Ty1)))
18424 return false;
18425
18426 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop")(static_cast <bool> (Ty1->getPrimitiveSizeInBits() <=
64 && "i128 is probably not a noop") ? void (0) : __assert_fail
("Ty1->getPrimitiveSizeInBits() <= 64 && \"i128 is probably not a noop\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 18426, __extension__ __PRETTY_FUNCTION__))
;
18427
18428 // Assuming the caller doesn't have a zeroext or signext return parameter,
18429 // truncation all the way down to i1 is valid.
18430 return true;
18431}
18432
18433InstructionCost ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
18434 const AddrMode &AM,
18435 Type *Ty,
18436 unsigned AS) const {
18437 if (isLegalAddressingMode(DL, AM, Ty, AS)) {
18438 if (Subtarget->hasFPAO())
18439 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
18440 return 0;
18441 }
18442 return -1;
18443}
18444
18445/// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster
18446/// than a pair of fmul and fadd instructions. fmuladd intrinsics will be
18447/// expanded to FMAs when this method returns true, otherwise fmuladd is
18448/// expanded to fmul + fadd.
18449///
18450/// ARM supports both fused and unfused multiply-add operations; we already
18451/// lower a pair of fmul and fadd to the latter so it's not clear that there
18452/// would be a gain or that the gain would be worthwhile enough to risk
18453/// correctness bugs.
18454///
18455/// For MVE, we set this to true as it helps simplify the need for some
18456/// patterns (and we don't have the non-fused floating point instruction).
18457bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
18458 EVT VT) const {
18459 if (!VT.isSimple())
18460 return false;
18461
18462 switch (VT.getSimpleVT().SimpleTy) {
18463 case MVT::v4f32:
18464 case MVT::v8f16:
18465 return Subtarget->hasMVEFloatOps();
18466 case MVT::f16:
18467 return Subtarget->useFPVFMx16();
18468 case MVT::f32:
18469 return Subtarget->useFPVFMx();
18470 case MVT::f64:
18471 return Subtarget->useFPVFMx64();
18472 default:
18473 break;
18474 }
18475
18476 return false;
18477}
18478
18479static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
18480 if (V < 0)
18481 return false;
18482
18483 unsigned Scale = 1;
18484 switch (VT.getSimpleVT().SimpleTy) {
18485 case MVT::i1:
18486 case MVT::i8:
18487 // Scale == 1;
18488 break;
18489 case MVT::i16:
18490 // Scale == 2;
18491 Scale = 2;
18492 break;
18493 default:
18494 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
18495 // Scale == 4;
18496 Scale = 4;
18497 break;
18498 }
18499
18500 if ((V & (Scale - 1)) != 0)
18501 return false;
18502 return isUInt<5>(V / Scale);
18503}
18504
18505static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
18506 const ARMSubtarget *Subtarget) {
18507 if (!VT.isInteger() && !VT.isFloatingPoint())
18508 return false;
18509 if (VT.isVector() && Subtarget->hasNEON())
18510 return false;
18511 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
18512 !Subtarget->hasMVEFloatOps())
18513 return false;
18514
18515 bool IsNeg = false;
18516 if (V < 0) {
18517 IsNeg = true;
18518 V = -V;
18519 }
18520
18521 unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U);
18522
18523 // MVE: size * imm7
18524 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
18525 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
18526 case MVT::i32:
18527 case MVT::f32:
18528 return isShiftedUInt<7,2>(V);
18529 case MVT::i16:
18530 case MVT::f16:
18531 return isShiftedUInt<7,1>(V);
18532 case MVT::i8:
18533 return isUInt<7>(V);
18534 default:
18535 return false;
18536 }
18537 }
18538
18539 // half VLDR: 2 * imm8
18540 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
18541 return isShiftedUInt<8, 1>(V);
18542 // VLDR and LDRD: 4 * imm8
18543 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
18544 return isShiftedUInt<8, 2>(V);
18545
18546 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
18547 // + imm12 or - imm8
18548 if (IsNeg)
18549 return isUInt<8>(V);
18550 return isUInt<12>(V);
18551 }
18552
18553 return false;
18554}
18555
18556/// isLegalAddressImmediate - Return true if the integer value can be used
18557/// as the offset of the target addressing mode for load / store of the
18558/// given type.
18559static bool isLegalAddressImmediate(int64_t V, EVT VT,
18560 const ARMSubtarget *Subtarget) {
18561 if (V == 0)
18562 return true;
18563
18564 if (!VT.isSimple())
18565 return false;
18566
18567 if (Subtarget->isThumb1Only())
18568 return isLegalT1AddressImmediate(V, VT);
18569 else if (Subtarget->isThumb2())
18570 return isLegalT2AddressImmediate(V, VT, Subtarget);
18571
18572 // ARM mode.
18573 if (V < 0)
18574 V = - V;
18575 switch (VT.getSimpleVT().SimpleTy) {
18576 default: return false;
18577 case MVT::i1:
18578 case MVT::i8:
18579 case MVT::i32:
18580 // +- imm12
18581 return isUInt<12>(V);
18582 case MVT::i16:
18583 // +- imm8
18584 return isUInt<8>(V);
18585 case MVT::f32:
18586 case MVT::f64:
18587 if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
18588 return false;
18589 return isShiftedUInt<8, 2>(V);
18590 }
18591}
18592
18593bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
18594 EVT VT) const {
18595 int Scale = AM.Scale;
18596 if (Scale < 0)
18597 return false;
18598
18599 switch (VT.getSimpleVT().SimpleTy) {
18600 default: return false;
18601 case MVT::i1:
18602 case MVT::i8:
18603 case MVT::i16:
18604 case MVT::i32:
18605 if (Scale == 1)
18606 return true;
18607 // r + r << imm
18608 Scale = Scale & ~1;
18609 return Scale == 2 || Scale == 4 || Scale == 8;
18610 case MVT::i64:
18611 // FIXME: What are we trying to model here? ldrd doesn't have an r + r
18612 // version in Thumb mode.
18613 // r + r
18614 if (Scale == 1)
18615 return true;
18616 // r * 2 (this can be lowered to r + r).
18617 if (!AM.HasBaseReg && Scale == 2)
18618 return true;
18619 return false;
18620 case MVT::isVoid:
18621 // Note, we allow "void" uses (basically, uses that aren't loads or
18622 // stores), because arm allows folding a scale into many arithmetic
18623 // operations. This should be made more precise and revisited later.
18624
18625 // Allow r << imm, but the imm has to be a multiple of two.
18626 if (Scale & 1) return false;
18627 return isPowerOf2_32(Scale);
18628 }
18629}
18630
18631bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
18632 EVT VT) const {
18633 const int Scale = AM.Scale;
18634
18635 // Negative scales are not supported in Thumb1.
18636 if (Scale < 0)
18637 return false;
18638
18639 // Thumb1 addressing modes do not support register scaling excepting the
18640 // following cases:
18641 // 1. Scale == 1 means no scaling.
18642 // 2. Scale == 2 this can be lowered to r + r if there is no base register.
18643 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
18644}
18645
18646/// isLegalAddressingMode - Return true if the addressing mode represented
18647/// by AM is legal for this target, for a load/store of the specified type.
18648bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
18649 const AddrMode &AM, Type *Ty,
18650 unsigned AS, Instruction *I) const {
18651 EVT VT = getValueType(DL, Ty, true);
18652 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
18653 return false;
18654
18655 // Can never fold addr of global into load/store.
18656 if (AM.BaseGV)
18657 return false;
18658
18659 switch (AM.Scale) {
18660 case 0: // no scale reg, must be "r+i" or "r", or "i".
18661 break;
18662 default:
18663 // ARM doesn't support any R+R*scale+imm addr modes.
18664 if (AM.BaseOffs)
18665 return false;
18666
18667 if (!VT.isSimple())
18668 return false;
18669
18670 if (Subtarget->isThumb1Only())
18671 return isLegalT1ScaledAddressingMode(AM, VT);
18672
18673 if (Subtarget->isThumb2())
18674 return isLegalT2ScaledAddressingMode(AM, VT);
18675
18676 int Scale = AM.Scale;
18677 switch (VT.getSimpleVT().SimpleTy) {
18678 default: return false;
18679 case MVT::i1:
18680 case MVT::i8:
18681 case MVT::i32:
18682 if (Scale < 0) Scale = -Scale;
18683 if (Scale == 1)
18684 return true;
18685 // r + r << imm
18686 return isPowerOf2_32(Scale & ~1);
18687 case MVT::i16:
18688 case MVT::i64:
18689 // r +/- r
18690 if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
18691 return true;
18692 // r * 2 (this can be lowered to r + r).
18693 if (!AM.HasBaseReg && Scale == 2)
18694 return true;
18695 return false;
18696
18697 case MVT::isVoid:
18698 // Note, we allow "void" uses (basically, uses that aren't loads or
18699 // stores), because arm allows folding a scale into many arithmetic
18700 // operations. This should be made more precise and revisited later.
18701
18702 // Allow r << imm, but the imm has to be a multiple of two.
18703 if (Scale & 1) return false;
18704 return isPowerOf2_32(Scale);
18705 }
18706 }
18707 return true;
18708}
18709
18710/// isLegalICmpImmediate - Return true if the specified immediate is legal
18711/// icmp immediate, that is the target has icmp instructions which can compare
18712/// a register against the immediate without having to materialize the
18713/// immediate into a register.
18714bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18715 // Thumb2 and ARM modes can use cmn for negative immediates.
18716 if (!Subtarget->isThumb())
18717 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
18718 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
18719 if (Subtarget->isThumb2())
18720 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
18721 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
18722 // Thumb1 doesn't have cmn, and only 8-bit immediates.
18723 return Imm >= 0 && Imm <= 255;
18724}
18725
18726/// isLegalAddImmediate - Return true if the specified immediate is a legal add
18727/// *or sub* immediate, that is the target has add or sub instructions which can
18728/// add a register with the immediate without having to materialize the
18729/// immediate into a register.
18730bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
18731 // Same encoding for add/sub, just flip the sign.
18732 int64_t AbsImm = std::abs(Imm);
18733 if (!Subtarget->isThumb())
18734 return ARM_AM::getSOImmVal(AbsImm) != -1;
18735 if (Subtarget->isThumb2())
18736 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
18737 // Thumb1 only has 8-bit unsigned immediate.
18738 return AbsImm >= 0 && AbsImm <= 255;
18739}
18740
18741static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
18742 bool isSEXTLoad, SDValue &Base,
18743 SDValue &Offset, bool &isInc,
18744 SelectionDAG &DAG) {
18745 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
18746 return false;
18747
18748 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
18749 // AddressingMode 3
18750 Base = Ptr->getOperand(0);
18751 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
18752 int RHSC = (int)RHS->getZExtValue();
18753 if (RHSC < 0 && RHSC > -256) {
18754 assert(Ptr->getOpcode() == ISD::ADD)(static_cast <bool> (Ptr->getOpcode() == ISD::ADD) ?
void (0) : __assert_fail ("Ptr->getOpcode() == ISD::ADD",
"/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 18754, __extension__ __PRETTY_FUNCTION__))
;
18755 isInc = false;
18756 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
18757 return true;
18758 }
18759 }
18760 isInc = (Ptr->getOpcode() == ISD::ADD);
18761 Offset = Ptr->getOperand(1);
18762 return true;
18763 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
18764 // AddressingMode 2
18765 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
18766 int RHSC = (int)RHS->getZExtValue();
18767 if (RHSC < 0 && RHSC > -0x1000) {
18768 assert(Ptr->getOpcode() == ISD::ADD)(static_cast <bool> (Ptr->getOpcode() == ISD::ADD) ?
void (0) : __assert_fail ("Ptr->getOpcode() == ISD::ADD",
"/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 18768, __extension__ __PRETTY_FUNCTION__))
;
18769 isInc = false;
18770 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
18771 Base = Ptr->getOperand(0);
18772 return true;
18773 }
18774 }
18775
18776 if (Ptr->getOpcode() == ISD::ADD) {
18777 isInc = true;
18778 ARM_AM::ShiftOpc ShOpcVal=
18779 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
18780 if (ShOpcVal != ARM_AM::no_shift) {
18781 Base = Ptr->getOperand(1);
18782 Offset = Ptr->getOperand(0);
18783 } else {
18784 Base = Ptr->getOperand(0);
18785 Offset = Ptr->getOperand(1);
18786 }
18787 return true;
18788 }
18789
18790 isInc = (Ptr->getOpcode() == ISD::ADD);
18791 Base = Ptr->getOperand(0);
18792 Offset = Ptr->getOperand(1);
18793 return true;
18794 }
18795
18796 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
18797 return false;
18798}
18799
18800static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
18801 bool isSEXTLoad, SDValue &Base,
18802 SDValue &Offset, bool &isInc,
18803 SelectionDAG &DAG) {
18804 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
18805 return false;
18806
18807 Base = Ptr->getOperand(0);
18808 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
18809 int RHSC = (int)RHS->getZExtValue();
18810 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
18811 assert(Ptr->getOpcode() == ISD::ADD)(static_cast <bool> (Ptr->getOpcode() == ISD::ADD) ?
void (0) : __assert_fail ("Ptr->getOpcode() == ISD::ADD",
"/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 18811, __extension__ __PRETTY_FUNCTION__))
;
18812 isInc = false;
18813 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
18814 return true;
18815 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
18816 isInc = Ptr->getOpcode() == ISD::ADD;
18817 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
18818 return true;
18819 }
18820 }
18821
18822 return false;
18823}
18824
18825static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, Align Alignment,
18826 bool isSEXTLoad, bool IsMasked, bool isLE,
18827 SDValue &Base, SDValue &Offset,
18828 bool &isInc, SelectionDAG &DAG) {
18829 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
18830 return false;
18831 if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
18832 return false;
18833
18834 // We allow LE non-masked loads to change the type (for example use a vldrb.8
18835 // as opposed to a vldrw.32). This can allow extra addressing modes or
18836 // alignments for what is otherwise an equivalent instruction.
18837 bool CanChangeType = isLE && !IsMasked;
18838
18839 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1));
18840 int RHSC = (int)RHS->getZExtValue();
18841
18842 auto IsInRange = [&](int RHSC, int Limit, int Scale) {
18843 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
18844 assert(Ptr->getOpcode() == ISD::ADD)(static_cast <bool> (Ptr->getOpcode() == ISD::ADD) ?
void (0) : __assert_fail ("Ptr->getOpcode() == ISD::ADD",
"/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 18844, __extension__ __PRETTY_FUNCTION__))
;
18845 isInc = false;
18846 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
18847 return true;
18848 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
18849 isInc = Ptr->getOpcode() == ISD::ADD;
18850 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
18851 return true;
18852 }
18853 return false;
18854 };
18855
18856 // Try to find a matching instruction based on s/zext, Alignment, Offset and
18857 // (in BE/masked) type.
18858 Base = Ptr->getOperand(0);
18859 if (VT == MVT::v4i16) {
18860 if (Alignment >= 2 && IsInRange(RHSC, 0x80, 2))
18861 return true;
18862 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
18863 if (IsInRange(RHSC, 0x80, 1))
18864 return true;
18865 } else if (Alignment >= 4 &&
18866 (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) &&
18867 IsInRange(RHSC, 0x80, 4))
18868 return true;
18869 else if (Alignment >= 2 &&
18870 (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) &&
18871 IsInRange(RHSC, 0x80, 2))
18872 return true;
18873 else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
18874 return true;
18875 return false;
18876}
18877
18878/// getPreIndexedAddressParts - returns true by value, base pointer and
18879/// offset pointer and addressing mode by reference if the node's address
18880/// can be legally represented as pre-indexed load / store address.
18881bool
18882ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
18883 SDValue &Offset,
18884 ISD::MemIndexedMode &AM,
18885 SelectionDAG &DAG) const {
18886 if (Subtarget->isThumb1Only())
18887 return false;
18888
18889 EVT VT;
18890 SDValue Ptr;
18891 Align Alignment;
18892 bool isSEXTLoad = false;
18893 bool IsMasked = false;
18894 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
18895 Ptr = LD->getBasePtr();
18896 VT = LD->getMemoryVT();
18897 Alignment = LD->getAlign();
18898 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
18899 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
18900 Ptr = ST->getBasePtr();
18901 VT = ST->getMemoryVT();
18902 Alignment = ST->getAlign();
18903 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
18904 Ptr = LD->getBasePtr();
18905 VT = LD->getMemoryVT();
18906 Alignment = LD->getAlign();
18907 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
18908 IsMasked = true;
18909 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
18910 Ptr = ST->getBasePtr();
18911 VT = ST->getMemoryVT();
18912 Alignment = ST->getAlign();
18913 IsMasked = true;
18914 } else
18915 return false;
18916
18917 bool isInc;
18918 bool isLegal = false;
18919 if (VT.isVector())
18920 isLegal = Subtarget->hasMVEIntegerOps() &&
18921 getMVEIndexedAddressParts(
18922 Ptr.getNode(), VT, Alignment, isSEXTLoad, IsMasked,
18923 Subtarget->isLittle(), Base, Offset, isInc, DAG);
18924 else {
18925 if (Subtarget->isThumb2())
18926 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
18927 Offset, isInc, DAG);
18928 else
18929 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
18930 Offset, isInc, DAG);
18931 }
18932 if (!isLegal)
18933 return false;
18934
18935 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
18936 return true;
18937}
18938
18939/// getPostIndexedAddressParts - returns true by value, base pointer and
18940/// offset pointer and addressing mode by reference if this node can be
18941/// combined with a load / store to form a post-indexed load / store.
18942bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
18943 SDValue &Base,
18944 SDValue &Offset,
18945 ISD::MemIndexedMode &AM,
18946 SelectionDAG &DAG) const {
18947 EVT VT;
18948 SDValue Ptr;
18949 Align Alignment;
18950 bool isSEXTLoad = false, isNonExt;
18951 bool IsMasked = false;
18952 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
18953 VT = LD->getMemoryVT();
18954 Ptr = LD->getBasePtr();
18955 Alignment = LD->getAlign();
18956 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
18957 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
18958 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
18959 VT = ST->getMemoryVT();
18960 Ptr = ST->getBasePtr();
18961 Alignment = ST->getAlign();
18962 isNonExt = !ST->isTruncatingStore();
18963 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
18964 VT = LD->getMemoryVT();
18965 Ptr = LD->getBasePtr();
18966 Alignment = LD->getAlign();
18967 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
18968 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
18969 IsMasked = true;
18970 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
18971 VT = ST->getMemoryVT();
18972 Ptr = ST->getBasePtr();
18973 Alignment = ST->getAlign();
18974 isNonExt = !ST->isTruncatingStore();
18975 IsMasked = true;
18976 } else
18977 return false;
18978
18979 if (Subtarget->isThumb1Only()) {
18980 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
18981 // must be non-extending/truncating, i32, with an offset of 4.
18982 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!")(static_cast <bool> (Op->getValueType(0) == MVT::i32
&& "Non-i32 post-inc op?!") ? void (0) : __assert_fail
("Op->getValueType(0) == MVT::i32 && \"Non-i32 post-inc op?!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 18982, __extension__ __PRETTY_FUNCTION__))
;
18983 if (Op->getOpcode() != ISD::ADD || !isNonExt)
18984 return false;
18985 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
18986 if (!RHS || RHS->getZExtValue() != 4)
18987 return false;
18988 if (Alignment < Align(4))
18989 return false;
18990
18991 Offset = Op->getOperand(1);
18992 Base = Op->getOperand(0);
18993 AM = ISD::POST_INC;
18994 return true;
18995 }
18996
18997 bool isInc;
18998 bool isLegal = false;
18999 if (VT.isVector())
19000 isLegal = Subtarget->hasMVEIntegerOps() &&
19001 getMVEIndexedAddressParts(Op, VT, Alignment, isSEXTLoad, IsMasked,
19002 Subtarget->isLittle(), Base, Offset,
19003 isInc, DAG);
19004 else {
19005 if (Subtarget->isThumb2())
19006 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
19007 isInc, DAG);
19008 else
19009 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
19010 isInc, DAG);
19011 }
19012 if (!isLegal)
19013 return false;
19014
19015 if (Ptr != Base) {
19016 // Swap base ptr and offset to catch more post-index load / store when
19017 // it's legal. In Thumb2 mode, offset must be an immediate.
19018 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
19019 !Subtarget->isThumb2())
19020 std::swap(Base, Offset);
19021
19022 // Post-indexed load / store update the base pointer.
19023 if (Ptr != Base)
19024 return false;
19025 }
19026
19027 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
19028 return true;
19029}
19030
19031void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19032 KnownBits &Known,
19033 const APInt &DemandedElts,
19034 const SelectionDAG &DAG,
19035 unsigned Depth) const {
19036 unsigned BitWidth = Known.getBitWidth();
19037 Known.resetAll();
19038 switch (Op.getOpcode()) {
19039 default: break;
19040 case ARMISD::ADDC:
19041 case ARMISD::ADDE:
19042 case ARMISD::SUBC:
19043 case ARMISD::SUBE:
19044 // Special cases when we convert a carry to a boolean.
19045 if (Op.getResNo() == 0) {
19046 SDValue LHS = Op.getOperand(0);
19047 SDValue RHS = Op.getOperand(1);
19048 // (ADDE 0, 0, C) will give us a single bit.
19049 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
19050 isNullConstant(RHS)) {
19051 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19052 return;
19053 }
19054 }
19055 break;
19056 case ARMISD::CMOV: {
19057 // Bits are known zero/one if known on the LHS and RHS.
19058 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
19059 if (Known.isUnknown())
19060 return;
19061
19062 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
19063 Known = KnownBits::commonBits(Known, KnownRHS);
19064 return;
19065 }
19066 case ISD::INTRINSIC_W_CHAIN: {
19067 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
19068 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
19069 switch (IntID) {
19070 default: return;
19071 case Intrinsic::arm_ldaex:
19072 case Intrinsic::arm_ldrex: {
19073 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
19074 unsigned MemBits = VT.getScalarSizeInBits();
19075 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
19076 return;
19077 }
19078 }
19079 }
19080 case ARMISD::BFI: {
19081 // Conservatively, we can recurse down the first operand
19082 // and just mask out all affected bits.
19083 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
19084
19085 // The operand to BFI is already a mask suitable for removing the bits it
19086 // sets.
19087 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
19088 const APInt &Mask = CI->getAPIntValue();
19089 Known.Zero &= Mask;
19090 Known.One &= Mask;
19091 return;
19092 }
19093 case ARMISD::VGETLANEs:
19094 case ARMISD::VGETLANEu: {
19095 const SDValue &SrcSV = Op.getOperand(0);
19096 EVT VecVT = SrcSV.getValueType();
19097 assert(VecVT.isVector() && "VGETLANE expected a vector type")(static_cast <bool> (VecVT.isVector() && "VGETLANE expected a vector type"
) ? void (0) : __assert_fail ("VecVT.isVector() && \"VGETLANE expected a vector type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19097, __extension__ __PRETTY_FUNCTION__))
;
19098 const unsigned NumSrcElts = VecVT.getVectorNumElements();
19099 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
19100 assert(Pos->getAPIntValue().ult(NumSrcElts) &&(static_cast <bool> (Pos->getAPIntValue().ult(NumSrcElts
) && "VGETLANE index out of bounds") ? void (0) : __assert_fail
("Pos->getAPIntValue().ult(NumSrcElts) && \"VGETLANE index out of bounds\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19101, __extension__ __PRETTY_FUNCTION__))
19101 "VGETLANE index out of bounds")(static_cast <bool> (Pos->getAPIntValue().ult(NumSrcElts
) && "VGETLANE index out of bounds") ? void (0) : __assert_fail
("Pos->getAPIntValue().ult(NumSrcElts) && \"VGETLANE index out of bounds\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19101, __extension__ __PRETTY_FUNCTION__))
;
19102 unsigned Idx = Pos->getZExtValue();
19103 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
19104 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
19105
19106 EVT VT = Op.getValueType();
19107 const unsigned DstSz = VT.getScalarSizeInBits();
19108 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
19109 (void)SrcSz;
19110 assert(SrcSz == Known.getBitWidth())(static_cast <bool> (SrcSz == Known.getBitWidth()) ? void
(0) : __assert_fail ("SrcSz == Known.getBitWidth()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19110, __extension__ __PRETTY_FUNCTION__))
;
19111 assert(DstSz > SrcSz)(static_cast <bool> (DstSz > SrcSz) ? void (0) : __assert_fail
("DstSz > SrcSz", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19111, __extension__ __PRETTY_FUNCTION__))
;
19112 if (Op.getOpcode() == ARMISD::VGETLANEs)
19113 Known = Known.sext(DstSz);
19114 else {
19115 Known = Known.zext(DstSz);
19116 }
19117 assert(DstSz == Known.getBitWidth())(static_cast <bool> (DstSz == Known.getBitWidth()) ? void
(0) : __assert_fail ("DstSz == Known.getBitWidth()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19117, __extension__ __PRETTY_FUNCTION__))
;
19118 break;
19119 }
19120 case ARMISD::VMOVrh: {
19121 KnownBits KnownOp = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
19122 assert(KnownOp.getBitWidth() == 16)(static_cast <bool> (KnownOp.getBitWidth() == 16) ? void
(0) : __assert_fail ("KnownOp.getBitWidth() == 16", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19122, __extension__ __PRETTY_FUNCTION__))
;
19123 Known = KnownOp.zext(32);
19124 break;
19125 }
19126 case ARMISD::CSINC:
19127 case ARMISD::CSINV:
19128 case ARMISD::CSNEG: {
19129 KnownBits KnownOp0 = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
19130 KnownBits KnownOp1 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
19131
19132 // The result is either:
19133 // CSINC: KnownOp0 or KnownOp1 + 1
19134 // CSINV: KnownOp0 or ~KnownOp1
19135 // CSNEG: KnownOp0 or KnownOp1 * -1
19136 if (Op.getOpcode() == ARMISD::CSINC)
19137 KnownOp1 = KnownBits::computeForAddSub(
19138 true, false, KnownOp1, KnownBits::makeConstant(APInt(32, 1)));
19139 else if (Op.getOpcode() == ARMISD::CSINV)
19140 std::swap(KnownOp1.Zero, KnownOp1.One);
19141 else if (Op.getOpcode() == ARMISD::CSNEG)
19142 KnownOp1 = KnownBits::mul(
19143 KnownOp1, KnownBits::makeConstant(APInt(32, -1)));
19144
19145 Known = KnownBits::commonBits(KnownOp0, KnownOp1);
19146 break;
19147 }
19148 }
19149}
19150
19151bool ARMTargetLowering::targetShrinkDemandedConstant(
19152 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
19153 TargetLoweringOpt &TLO) const {
19154 // Delay optimization, so we don't have to deal with illegal types, or block
19155 // optimizations.
19156 if (!TLO.LegalOps)
19157 return false;
19158
19159 // Only optimize AND for now.
19160 if (Op.getOpcode() != ISD::AND)
19161 return false;
19162
19163 EVT VT = Op.getValueType();
19164
19165 // Ignore vectors.
19166 if (VT.isVector())
19167 return false;
19168
19169 assert(VT == MVT::i32 && "Unexpected integer type")(static_cast <bool> (VT == MVT::i32 && "Unexpected integer type"
) ? void (0) : __assert_fail ("VT == MVT::i32 && \"Unexpected integer type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19169, __extension__ __PRETTY_FUNCTION__))
;
19170
19171 // Make sure the RHS really is a constant.
19172 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
19173 if (!C)
19174 return false;
19175
19176 unsigned Mask = C->getZExtValue();
19177
19178 unsigned Demanded = DemandedBits.getZExtValue();
19179 unsigned ShrunkMask = Mask & Demanded;
19180 unsigned ExpandedMask = Mask | ~Demanded;
19181
19182 // If the mask is all zeros, let the target-independent code replace the
19183 // result with zero.
19184 if (ShrunkMask == 0)
19185 return false;
19186
19187 // If the mask is all ones, erase the AND. (Currently, the target-independent
19188 // code won't do this, so we have to do it explicitly to avoid an infinite
19189 // loop in obscure cases.)
19190 if (ExpandedMask == ~0U)
19191 return TLO.CombineTo(Op, Op.getOperand(0));
19192
19193 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
19194 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
19195 };
19196 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
19197 if (NewMask == Mask)
19198 return true;
19199 SDLoc DL(Op);
19200 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
19201 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
19202 return TLO.CombineTo(Op, NewOp);
19203 };
19204
19205 // Prefer uxtb mask.
19206 if (IsLegalMask(0xFF))
19207 return UseMask(0xFF);
19208
19209 // Prefer uxth mask.
19210 if (IsLegalMask(0xFFFF))
19211 return UseMask(0xFFFF);
19212
19213 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
19214 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
19215 if (ShrunkMask < 256)
19216 return UseMask(ShrunkMask);
19217
19218 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
19219 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
19220 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
19221 return UseMask(ExpandedMask);
19222
19223 // Potential improvements:
19224 //
19225 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
19226 // We could try to prefer Thumb1 immediates which can be lowered to a
19227 // two-instruction sequence.
19228 // We could try to recognize more legal ARM/Thumb2 immediates here.
19229
19230 return false;
19231}
19232
19233bool ARMTargetLowering::SimplifyDemandedBitsForTargetNode(
19234 SDValue Op, const APInt &OriginalDemandedBits,
19235 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
19236 unsigned Depth) const {
19237 unsigned Opc = Op.getOpcode();
19238
19239 switch (Opc) {
19240 case ARMISD::ASRL:
19241 case ARMISD::LSRL: {
19242 // If this is result 0 and the other result is unused, see if the demand
19243 // bits allow us to shrink this long shift into a standard small shift in
19244 // the opposite direction.
19245 if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(1) &&
19246 isa<ConstantSDNode>(Op->getOperand(2))) {
19247 unsigned ShAmt = Op->getConstantOperandVal(2);
19248 if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf(
19249 APInt::getAllOnesValue(32) << (32 - ShAmt)))
19250 return TLO.CombineTo(
19251 Op, TLO.DAG.getNode(
19252 ISD::SHL, SDLoc(Op), MVT::i32, Op.getOperand(1),
19253 TLO.DAG.getConstant(32 - ShAmt, SDLoc(Op), MVT::i32)));
19254 }
19255 break;
19256 }
19257 }
19258
19259 return TargetLowering::SimplifyDemandedBitsForTargetNode(
19260 Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
19261}
19262
19263//===----------------------------------------------------------------------===//
19264// ARM Inline Assembly Support
19265//===----------------------------------------------------------------------===//
19266
19267bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
19268 // Looking for "rev" which is V6+.
19269 if (!Subtarget->hasV6Ops())
19270 return false;
19271
19272 InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand());
19273 std::string AsmStr = IA->getAsmString();
19274 SmallVector<StringRef, 4> AsmPieces;
19275 SplitString(AsmStr, AsmPieces, ";\n");
19276
19277 switch (AsmPieces.size()) {
19278 default: return false;
19279 case 1:
19280 AsmStr = std::string(AsmPieces[0]);
19281 AsmPieces.clear();
19282 SplitString(AsmStr, AsmPieces, " \t,");
19283
19284 // rev $0, $1
19285 if (AsmPieces.size() == 3 &&
19286 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
19287 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
19288 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
19289 if (Ty && Ty->getBitWidth() == 32)
19290 return IntrinsicLowering::LowerToByteSwap(CI);
19291 }
19292 break;
19293 }
19294
19295 return false;
19296}
19297
19298const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
19299 // At this point, we have to lower this constraint to something else, so we
19300 // lower it to an "r" or "w". However, by doing this we will force the result
19301 // to be in register, while the X constraint is much more permissive.
19302 //
19303 // Although we are correct (we are free to emit anything, without
19304 // constraints), we might break use cases that would expect us to be more
19305 // efficient and emit something else.
19306 if (!Subtarget->hasVFP2Base())
19307 return "r";
19308 if (ConstraintVT.isFloatingPoint())
19309 return "w";
19310 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
19311 (ConstraintVT.getSizeInBits() == 64 ||
19312 ConstraintVT.getSizeInBits() == 128))
19313 return "w";
19314
19315 return "r";
19316}
19317
19318/// getConstraintType - Given a constraint letter, return the type of
19319/// constraint it is for this target.
19320ARMTargetLowering::ConstraintType
19321ARMTargetLowering::getConstraintType(StringRef Constraint) const {
19322 unsigned S = Constraint.size();
19323 if (S == 1) {
19324 switch (Constraint[0]) {
19325 default: break;
19326 case 'l': return C_RegisterClass;
19327 case 'w': return C_RegisterClass;
19328 case 'h': return C_RegisterClass;
19329 case 'x': return C_RegisterClass;
19330 case 't': return C_RegisterClass;
19331 case 'j': return C_Immediate; // Constant for movw.
19332 // An address with a single base register. Due to the way we
19333 // currently handle addresses it is the same as an 'r' memory constraint.
19334 case 'Q': return C_Memory;
19335 }
19336 } else if (S == 2) {
19337 switch (Constraint[0]) {
19338 default: break;
19339 case 'T': return C_RegisterClass;
19340 // All 'U+' constraints are addresses.
19341 case 'U': return C_Memory;
19342 }
19343 }
19344 return TargetLowering::getConstraintType(Constraint);
19345}
19346
19347/// Examine constraint type and operand type and determine a weight value.
19348/// This object must already have been set up with the operand type
19349/// and the current alternative constraint selected.
19350TargetLowering::ConstraintWeight
19351ARMTargetLowering::getSingleConstraintMatchWeight(
19352 AsmOperandInfo &info, const char *constraint) const {
19353 ConstraintWeight weight = CW_Invalid;
19354 Value *CallOperandVal = info.CallOperandVal;
19355 // If we don't have a value, we can't do a match,
19356 // but allow it at the lowest weight.
19357 if (!CallOperandVal)
19358 return CW_Default;
19359 Type *type = CallOperandVal->getType();
19360 // Look at the constraint type.
19361 switch (*constraint) {
19362 default:
19363 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
19364 break;
19365 case 'l':
19366 if (type->isIntegerTy()) {
19367 if (Subtarget->isThumb())
19368 weight = CW_SpecificReg;
19369 else
19370 weight = CW_Register;
19371 }
19372 break;
19373 case 'w':
19374 if (type->isFloatingPointTy())
19375 weight = CW_Register;
19376 break;
19377 }
19378 return weight;
19379}
19380
19381using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
19382
19383RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
19384 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
19385 switch (Constraint.size()) {
19386 case 1:
19387 // GCC ARM Constraint Letters
19388 switch (Constraint[0]) {
19389 case 'l': // Low regs or general regs.
19390 if (Subtarget->isThumb())
19391 return RCPair(0U, &ARM::tGPRRegClass);
19392 return RCPair(0U, &ARM::GPRRegClass);
19393 case 'h': // High regs or no regs.
19394 if (Subtarget->isThumb())
19395 return RCPair(0U, &ARM::hGPRRegClass);
19396 break;
19397 case 'r':
19398 if (Subtarget->isThumb1Only())
19399 return RCPair(0U, &ARM::tGPRRegClass);
19400 return RCPair(0U, &ARM::GPRRegClass);
19401 case 'w':
19402 if (VT == MVT::Other)
19403 break;
19404 if (VT == MVT::f32)
19405 return RCPair(0U, &ARM::SPRRegClass);
19406 if (VT.getSizeInBits() == 64)
19407 return RCPair(0U, &ARM::DPRRegClass);
19408 if (VT.getSizeInBits() == 128)
19409 return RCPair(0U, &ARM::QPRRegClass);
19410 break;
19411 case 'x':
19412 if (VT == MVT::Other)
19413 break;
19414 if (VT == MVT::f32)
19415 return RCPair(0U, &ARM::SPR_8RegClass);
19416 if (VT.getSizeInBits() == 64)
19417 return RCPair(0U, &ARM::DPR_8RegClass);
19418 if (VT.getSizeInBits() == 128)
19419 return RCPair(0U, &ARM::QPR_8RegClass);
19420 break;
19421 case 't':
19422 if (VT == MVT::Other)
19423 break;
19424 if (VT == MVT::f32 || VT == MVT::i32)
19425 return RCPair(0U, &ARM::SPRRegClass);
19426 if (VT.getSizeInBits() == 64)
19427 return RCPair(0U, &ARM::DPR_VFP2RegClass);
19428 if (VT.getSizeInBits() == 128)
19429 return RCPair(0U, &ARM::QPR_VFP2RegClass);
19430 break;
19431 }
19432 break;
19433
19434 case 2:
19435 if (Constraint[0] == 'T') {
19436 switch (Constraint[1]) {
19437 default:
19438 break;
19439 case 'e':
19440 return RCPair(0U, &ARM::tGPREvenRegClass);
19441 case 'o':
19442 return RCPair(0U, &ARM::tGPROddRegClass);
19443 }
19444 }
19445 break;
19446
19447 default:
19448 break;
19449 }
19450
19451 if (StringRef("{cc}").equals_insensitive(Constraint))
19452 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
19453
19454 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
19455}
19456
19457/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
19458/// vector. If it is invalid, don't add anything to Ops.
19459void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
19460 std::string &Constraint,
19461 std::vector<SDValue>&Ops,
19462 SelectionDAG &DAG) const {
19463 SDValue Result;
19464
19465 // Currently only support length 1 constraints.
19466 if (Constraint.length() != 1) return;
19467
19468 char ConstraintLetter = Constraint[0];
19469 switch (ConstraintLetter) {
19470 default: break;
19471 case 'j':
19472 case 'I': case 'J': case 'K': case 'L':
19473 case 'M': case 'N': case 'O':
19474 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
19475 if (!C)
19476 return;
19477
19478 int64_t CVal64 = C->getSExtValue();
19479 int CVal = (int) CVal64;
19480 // None of these constraints allow values larger than 32 bits. Check
19481 // that the value fits in an int.
19482 if (CVal != CVal64)
19483 return;
19484
19485 switch (ConstraintLetter) {
19486 case 'j':
19487 // Constant suitable for movw, must be between 0 and
19488 // 65535.
19489 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
19490 if (CVal >= 0 && CVal <= 65535)
19491 break;
19492 return;
19493 case 'I':
19494 if (Subtarget->isThumb1Only()) {
19495 // This must be a constant between 0 and 255, for ADD
19496 // immediates.
19497 if (CVal >= 0 && CVal <= 255)
19498 break;
19499 } else if (Subtarget->isThumb2()) {
19500 // A constant that can be used as an immediate value in a
19501 // data-processing instruction.
19502 if (ARM_AM::getT2SOImmVal(CVal) != -1)
19503 break;
19504 } else {
19505 // A constant that can be used as an immediate value in a
19506 // data-processing instruction.
19507 if (ARM_AM::getSOImmVal(CVal) != -1)
19508 break;
19509 }
19510 return;
19511
19512 case 'J':
19513 if (Subtarget->isThumb1Only()) {
19514 // This must be a constant between -255 and -1, for negated ADD
19515 // immediates. This can be used in GCC with an "n" modifier that
19516 // prints the negated value, for use with SUB instructions. It is
19517 // not useful otherwise but is implemented for compatibility.
19518 if (CVal >= -255 && CVal <= -1)
19519 break;
19520 } else {
19521 // This must be a constant between -4095 and 4095. It is not clear
19522 // what this constraint is intended for. Implemented for
19523 // compatibility with GCC.
19524 if (CVal >= -4095 && CVal <= 4095)
19525 break;
19526 }
19527 return;
19528
19529 case 'K':
19530 if (Subtarget->isThumb1Only()) {
19531 // A 32-bit value where only one byte has a nonzero value. Exclude
19532 // zero to match GCC. This constraint is used by GCC internally for
19533 // constants that can be loaded with a move/shift combination.
19534 // It is not useful otherwise but is implemented for compatibility.
19535 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
19536 break;
19537 } else if (Subtarget->isThumb2()) {
19538 // A constant whose bitwise inverse can be used as an immediate
19539 // value in a data-processing instruction. This can be used in GCC
19540 // with a "B" modifier that prints the inverted value, for use with
19541 // BIC and MVN instructions. It is not useful otherwise but is
19542 // implemented for compatibility.
19543 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
19544 break;
19545 } else {
19546 // A constant whose bitwise inverse can be used as an immediate
19547 // value in a data-processing instruction. This can be used in GCC
19548 // with a "B" modifier that prints the inverted value, for use with
19549 // BIC and MVN instructions. It is not useful otherwise but is
19550 // implemented for compatibility.
19551 if (ARM_AM::getSOImmVal(~CVal) != -1)
19552 break;
19553 }
19554 return;
19555
19556 case 'L':
19557 if (Subtarget->isThumb1Only()) {
19558 // This must be a constant between -7 and 7,
19559 // for 3-operand ADD/SUB immediate instructions.
19560 if (CVal >= -7 && CVal < 7)
19561 break;
19562 } else if (Subtarget->isThumb2()) {
19563 // A constant whose negation can be used as an immediate value in a
19564 // data-processing instruction. This can be used in GCC with an "n"
19565 // modifier that prints the negated value, for use with SUB
19566 // instructions. It is not useful otherwise but is implemented for
19567 // compatibility.
19568 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
19569 break;
19570 } else {
19571 // A constant whose negation can be used as an immediate value in a
19572 // data-processing instruction. This can be used in GCC with an "n"
19573 // modifier that prints the negated value, for use with SUB
19574 // instructions. It is not useful otherwise but is implemented for
19575 // compatibility.
19576 if (ARM_AM::getSOImmVal(-CVal) != -1)
19577 break;
19578 }
19579 return;
19580
19581 case 'M':
19582 if (Subtarget->isThumb1Only()) {
19583 // This must be a multiple of 4 between 0 and 1020, for
19584 // ADD sp + immediate.
19585 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
19586 break;
19587 } else {
19588 // A power of two or a constant between 0 and 32. This is used in
19589 // GCC for the shift amount on shifted register operands, but it is
19590 // useful in general for any shift amounts.
19591 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
19592 break;
19593 }
19594 return;
19595
19596 case 'N':
19597 if (Subtarget->isThumb1Only()) {
19598 // This must be a constant between 0 and 31, for shift amounts.
19599 if (CVal >= 0 && CVal <= 31)
19600 break;
19601 }
19602 return;
19603
19604 case 'O':
19605 if (Subtarget->isThumb1Only()) {
19606 // This must be a multiple of 4 between -508 and 508, for
19607 // ADD/SUB sp = sp + immediate.
19608 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
19609 break;
19610 }
19611 return;
19612 }
19613 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
19614 break;
19615 }
19616
19617 if (Result.getNode()) {
19618 Ops.push_back(Result);
19619 return;
19620 }
19621 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
19622}
19623
19624static RTLIB::Libcall getDivRemLibcall(
19625 const SDNode *N, MVT::SimpleValueType SVT) {
19626 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||(static_cast <bool> ((N->getOpcode() == ISD::SDIVREM
|| N->getOpcode() == ISD::UDIVREM || N->getOpcode() ==
ISD::SREM || N->getOpcode() == ISD::UREM) && "Unhandled Opcode in getDivRemLibcall"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && \"Unhandled Opcode in getDivRemLibcall\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19628, __extension__ __PRETTY_FUNCTION__))
19627 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&(static_cast <bool> ((N->getOpcode() == ISD::SDIVREM
|| N->getOpcode() == ISD::UDIVREM || N->getOpcode() ==
ISD::SREM || N->getOpcode() == ISD::UREM) && "Unhandled Opcode in getDivRemLibcall"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && \"Unhandled Opcode in getDivRemLibcall\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19628, __extension__ __PRETTY_FUNCTION__))
19628 "Unhandled Opcode in getDivRemLibcall")(static_cast <bool> ((N->getOpcode() == ISD::SDIVREM
|| N->getOpcode() == ISD::UDIVREM || N->getOpcode() ==
ISD::SREM || N->getOpcode() == ISD::UREM) && "Unhandled Opcode in getDivRemLibcall"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && \"Unhandled Opcode in getDivRemLibcall\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19628, __extension__ __PRETTY_FUNCTION__))
;
19629 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
19630 N->getOpcode() == ISD::SREM;
19631 RTLIB::Libcall LC;
19632 switch (SVT) {
19633 default: llvm_unreachable("Unexpected request for libcall!")::llvm::llvm_unreachable_internal("Unexpected request for libcall!"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19633)
;
19634 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
19635 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
19636 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
19637 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
19638 }
19639 return LC;
19640}
19641
19642static TargetLowering::ArgListTy getDivRemArgList(
19643 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
19644 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||(static_cast <bool> ((N->getOpcode() == ISD::SDIVREM
|| N->getOpcode() == ISD::UDIVREM || N->getOpcode() ==
ISD::SREM || N->getOpcode() == ISD::UREM) && "Unhandled Opcode in getDivRemArgList"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && \"Unhandled Opcode in getDivRemArgList\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19646, __extension__ __PRETTY_FUNCTION__))
19645 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&(static_cast <bool> ((N->getOpcode() == ISD::SDIVREM
|| N->getOpcode() == ISD::UDIVREM || N->getOpcode() ==
ISD::SREM || N->getOpcode() == ISD::UREM) && "Unhandled Opcode in getDivRemArgList"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && \"Unhandled Opcode in getDivRemArgList\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19646, __extension__ __PRETTY_FUNCTION__))
19646 "Unhandled Opcode in getDivRemArgList")(static_cast <bool> ((N->getOpcode() == ISD::SDIVREM
|| N->getOpcode() == ISD::UDIVREM || N->getOpcode() ==
ISD::SREM || N->getOpcode() == ISD::UREM) && "Unhandled Opcode in getDivRemArgList"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && \"Unhandled Opcode in getDivRemArgList\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19646, __extension__ __PRETTY_FUNCTION__))
;
19647 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
19648 N->getOpcode() == ISD::SREM;
19649 TargetLowering::ArgListTy Args;
19650 TargetLowering::ArgListEntry Entry;
19651 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
19652 EVT ArgVT = N->getOperand(i).getValueType();
19653 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
19654 Entry.Node = N->getOperand(i);
19655 Entry.Ty = ArgTy;
19656 Entry.IsSExt = isSigned;
19657 Entry.IsZExt = !isSigned;
19658 Args.push_back(Entry);
19659 }
19660 if (Subtarget->isTargetWindows() && Args.size() >= 2)
19661 std::swap(Args[0], Args[1]);
19662 return Args;
19663}
19664
19665SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
19666 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||(static_cast <bool> ((Subtarget->isTargetAEABI() || Subtarget
->isTargetAndroid() || Subtarget->isTargetGNUAEABI() ||
Subtarget->isTargetMuslAEABI() || Subtarget->isTargetWindows
()) && "Register-based DivRem lowering only") ? void (
0) : __assert_fail ("(Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || Subtarget->isTargetWindows()) && \"Register-based DivRem lowering only\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19669, __extension__ __PRETTY_FUNCTION__))
19667 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||(static_cast <bool> ((Subtarget->isTargetAEABI() || Subtarget
->isTargetAndroid() || Subtarget->isTargetGNUAEABI() ||
Subtarget->isTargetMuslAEABI() || Subtarget->isTargetWindows
()) && "Register-based DivRem lowering only") ? void (
0) : __assert_fail ("(Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || Subtarget->isTargetWindows()) && \"Register-based DivRem lowering only\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19669, __extension__ __PRETTY_FUNCTION__))
19668 Subtarget->isTargetWindows()) &&(static_cast <bool> ((Subtarget->isTargetAEABI() || Subtarget
->isTargetAndroid() || Subtarget->isTargetGNUAEABI() ||
Subtarget->isTargetMuslAEABI() || Subtarget->isTargetWindows
()) && "Register-based DivRem lowering only") ? void (
0) : __assert_fail ("(Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || Subtarget->isTargetWindows()) && \"Register-based DivRem lowering only\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19669, __extension__ __PRETTY_FUNCTION__))
19669 "Register-based DivRem lowering only")(static_cast <bool> ((Subtarget->isTargetAEABI() || Subtarget
->isTargetAndroid() || Subtarget->isTargetGNUAEABI() ||
Subtarget->isTargetMuslAEABI() || Subtarget->isTargetWindows
()) && "Register-based DivRem lowering only") ? void (
0) : __assert_fail ("(Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || Subtarget->isTargetWindows()) && \"Register-based DivRem lowering only\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19669, __extension__ __PRETTY_FUNCTION__))
;
19670 unsigned Opcode = Op->getOpcode();
19671 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&(static_cast <bool> ((Opcode == ISD::SDIVREM || Opcode ==
ISD::UDIVREM) && "Invalid opcode for Div/Rem lowering"
) ? void (0) : __assert_fail ("(Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && \"Invalid opcode for Div/Rem lowering\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19672, __extension__ __PRETTY_FUNCTION__))
19672 "Invalid opcode for Div/Rem lowering")(static_cast <bool> ((Opcode == ISD::SDIVREM || Opcode ==
ISD::UDIVREM) && "Invalid opcode for Div/Rem lowering"
) ? void (0) : __assert_fail ("(Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && \"Invalid opcode for Div/Rem lowering\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19672, __extension__ __PRETTY_FUNCTION__))
;
19673 bool isSigned = (Opcode == ISD::SDIVREM);
19674 EVT VT = Op->getValueType(0);
19675 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
19676 SDLoc dl(Op);
19677
19678 // If the target has hardware divide, use divide + multiply + subtract:
19679 // div = a / b
19680 // rem = a - b * div
19681 // return {div, rem}
19682 // This should be lowered into UDIV/SDIV + MLS later on.
19683 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
19684 : Subtarget->hasDivideInARMMode();
19685 if (hasDivide && Op->getValueType(0).isSimple() &&
19686 Op->getSimpleValueType(0) == MVT::i32) {
19687 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
19688 const SDValue Dividend = Op->getOperand(0);
19689 const SDValue Divisor = Op->getOperand(1);
19690 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
19691 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
19692 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
19693
19694 SDValue Values[2] = {Div, Rem};
19695 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
19696 }
19697
19698 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
19699 VT.getSimpleVT().SimpleTy);
19700 SDValue InChain = DAG.getEntryNode();
19701
19702 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
19703 DAG.getContext(),
19704 Subtarget);
19705
19706 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
19707 getPointerTy(DAG.getDataLayout()));
19708
19709 Type *RetTy = StructType::get(Ty, Ty);
19710
19711 if (Subtarget->isTargetWindows())
19712 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
19713
19714 TargetLowering::CallLoweringInfo CLI(DAG);
19715 CLI.setDebugLoc(dl).setChain(InChain)
19716 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
19717 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
19718
19719 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
19720 return CallInfo.first;
19721}
19722
19723// Lowers REM using divmod helpers
19724// see RTABI section 4.2/4.3
19725SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
19726 // Build return types (div and rem)
19727 std::vector<Type*> RetTyParams;
19728 Type *RetTyElement;
19729
19730 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
19731 default: llvm_unreachable("Unexpected request for libcall!")::llvm::llvm_unreachable_internal("Unexpected request for libcall!"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19731)
;
19732 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
19733 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
19734 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
19735 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
19736 }
19737
19738 RetTyParams.push_back(RetTyElement);
19739 RetTyParams.push_back(RetTyElement);
19740 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
19741 Type *RetTy = StructType::get(*DAG.getContext(), ret);
19742
19743 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
19744 SimpleTy);
19745 SDValue InChain = DAG.getEntryNode();
19746 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
19747 Subtarget);
19748 bool isSigned = N->getOpcode() == ISD::SREM;
19749 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
19750 getPointerTy(DAG.getDataLayout()));
19751
19752 if (Subtarget->isTargetWindows())
19753 InChain = WinDBZCheckDenominator(DAG, N, InChain);
19754
19755 // Lower call
19756 CallLoweringInfo CLI(DAG);
19757 CLI.setChain(InChain)
19758 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
19759 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
19760 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
19761
19762 // Return second (rem) result operand (first contains div)
19763 SDNode *ResNode = CallResult.first.getNode();
19764 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands")(static_cast <bool> (ResNode->getNumOperands() == 2 &&
"divmod should return two operands") ? void (0) : __assert_fail
("ResNode->getNumOperands() == 2 && \"divmod should return two operands\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19764, __extension__ __PRETTY_FUNCTION__))
;
19765 return ResNode->getOperand(1);
19766}
19767
19768SDValue
19769ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
19770 assert(Subtarget->isTargetWindows() && "unsupported target platform")(static_cast <bool> (Subtarget->isTargetWindows() &&
"unsupported target platform") ? void (0) : __assert_fail ("Subtarget->isTargetWindows() && \"unsupported target platform\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19770, __extension__ __PRETTY_FUNCTION__))
;
19771 SDLoc DL(Op);
19772
19773 // Get the inputs.
19774 SDValue Chain = Op.getOperand(0);
19775 SDValue Size = Op.getOperand(1);
19776
19777 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
19778 "no-stack-arg-probe")) {
19779 MaybeAlign Align =
19780 cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
19781 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
19782 Chain = SP.getValue(1);
19783 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
19784 if (Align)
19785 SP =
19786 DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
19787 DAG.getConstant(-(uint64_t)Align->value(), DL, MVT::i32));
19788 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
19789 SDValue Ops[2] = { SP, Chain };
19790 return DAG.getMergeValues(Ops, DL);
19791 }
19792
19793 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
19794 DAG.getConstant(2, DL, MVT::i32));
19795
19796 SDValue Flag;
19797 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
19798 Flag = Chain.getValue(1);
19799
19800 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
19801 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
19802
19803 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
19804 Chain = NewSP.getValue(1);
19805
19806 SDValue Ops[2] = { NewSP, Chain };
19807 return DAG.getMergeValues(Ops, DL);
19808}
19809
19810SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
19811 bool IsStrict = Op->isStrictFPOpcode();
19812 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
19813 const unsigned DstSz = Op.getValueType().getSizeInBits();
19814 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
19815 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&(static_cast <bool> (DstSz > SrcSz && DstSz <=
64 && SrcSz >= 16 && "Unexpected type for custom-lowering FP_EXTEND"
) ? void (0) : __assert_fail ("DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 && \"Unexpected type for custom-lowering FP_EXTEND\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19816, __extension__ __PRETTY_FUNCTION__))
19816 "Unexpected type for custom-lowering FP_EXTEND")(static_cast <bool> (DstSz > SrcSz && DstSz <=
64 && SrcSz >= 16 && "Unexpected type for custom-lowering FP_EXTEND"
) ? void (0) : __assert_fail ("DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 && \"Unexpected type for custom-lowering FP_EXTEND\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19816, __extension__ __PRETTY_FUNCTION__))
;
19817
19818 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&(static_cast <bool> ((!Subtarget->hasFP64() || !Subtarget
->hasFPARMv8Base()) && "With both FP DP and 16, any FP conversion is legal!"
) ? void (0) : __assert_fail ("(!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && \"With both FP DP and 16, any FP conversion is legal!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19819, __extension__ __PRETTY_FUNCTION__))
19819 "With both FP DP and 16, any FP conversion is legal!")(static_cast <bool> ((!Subtarget->hasFP64() || !Subtarget
->hasFPARMv8Base()) && "With both FP DP and 16, any FP conversion is legal!"
) ? void (0) : __assert_fail ("(!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && \"With both FP DP and 16, any FP conversion is legal!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19819, __extension__ __PRETTY_FUNCTION__))
;
19820
19821 assert(!(DstSz == 32 && Subtarget->hasFP16()) &&(static_cast <bool> (!(DstSz == 32 && Subtarget
->hasFP16()) && "With FP16, 16 to 32 conversion is legal!"
) ? void (0) : __assert_fail ("!(DstSz == 32 && Subtarget->hasFP16()) && \"With FP16, 16 to 32 conversion is legal!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19822, __extension__ __PRETTY_FUNCTION__))
19822 "With FP16, 16 to 32 conversion is legal!")(static_cast <bool> (!(DstSz == 32 && Subtarget
->hasFP16()) && "With FP16, 16 to 32 conversion is legal!"
) ? void (0) : __assert_fail ("!(DstSz == 32 && Subtarget->hasFP16()) && \"With FP16, 16 to 32 conversion is legal!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19822, __extension__ __PRETTY_FUNCTION__))
;
19823
19824 // Converting from 32 -> 64 is valid if we have FP64.
19825 if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) {
19826 // FIXME: Remove this when we have strict fp instruction selection patterns
19827 if (IsStrict) {
19828 SDLoc Loc(Op);
19829 SDValue Result = DAG.getNode(ISD::FP_EXTEND,
19830 Loc, Op.getValueType(), SrcVal);
19831 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
19832 }
19833 return Op;
19834 }
19835
19836 // Either we are converting from 16 -> 64, without FP16 and/or
19837 // FP.double-precision or without Armv8-fp. So we must do it in two
19838 // steps.
19839 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
19840 // without FP16. So we must do a function call.
19841 SDLoc Loc(Op);
19842 RTLIB::Libcall LC;
19843 MakeLibCallOptions CallOptions;
19844 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
19845 for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) {
19846 bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64());
19847 MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32);
19848 MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64);
19849 if (Supported) {
19850 if (IsStrict) {
19851 SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc,
19852 {DstVT, MVT::Other}, {Chain, SrcVal});
19853 Chain = SrcVal.getValue(1);
19854 } else {
19855 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal);
19856 }
19857 } else {
19858 LC = RTLIB::getFPEXT(SrcVT, DstVT);
19859 assert(LC != RTLIB::UNKNOWN_LIBCALL &&(static_cast <bool> (LC != RTLIB::UNKNOWN_LIBCALL &&
"Unexpected type for custom-lowering FP_EXTEND") ? void (0) :
__assert_fail ("LC != RTLIB::UNKNOWN_LIBCALL && \"Unexpected type for custom-lowering FP_EXTEND\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19860, __extension__ __PRETTY_FUNCTION__))
19860 "Unexpected type for custom-lowering FP_EXTEND")(static_cast <bool> (LC != RTLIB::UNKNOWN_LIBCALL &&
"Unexpected type for custom-lowering FP_EXTEND") ? void (0) :
__assert_fail ("LC != RTLIB::UNKNOWN_LIBCALL && \"Unexpected type for custom-lowering FP_EXTEND\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19860, __extension__ __PRETTY_FUNCTION__))
;
19861 std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
19862 Loc, Chain);
19863 }
19864 }
19865
19866 return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal;
19867}
19868
19869SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
19870 bool IsStrict = Op->isStrictFPOpcode();
19871
19872 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
19873 EVT SrcVT = SrcVal.getValueType();
19874 EVT DstVT = Op.getValueType();
19875 const unsigned DstSz = Op.getValueType().getSizeInBits();
19876 const unsigned SrcSz = SrcVT.getSizeInBits();
19877 (void)DstSz;
19878 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&(static_cast <bool> (DstSz < SrcSz && SrcSz <=
64 && DstSz >= 16 && "Unexpected type for custom-lowering FP_ROUND"
) ? void (0) : __assert_fail ("DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 && \"Unexpected type for custom-lowering FP_ROUND\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19879, __extension__ __PRETTY_FUNCTION__))
19879 "Unexpected type for custom-lowering FP_ROUND")(static_cast <bool> (DstSz < SrcSz && SrcSz <=
64 && DstSz >= 16 && "Unexpected type for custom-lowering FP_ROUND"
) ? void (0) : __assert_fail ("DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 && \"Unexpected type for custom-lowering FP_ROUND\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19879, __extension__ __PRETTY_FUNCTION__))
;
19880
19881 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&(static_cast <bool> ((!Subtarget->hasFP64() || !Subtarget
->hasFPARMv8Base()) && "With both FP DP and 16, any FP conversion is legal!"
) ? void (0) : __assert_fail ("(!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && \"With both FP DP and 16, any FP conversion is legal!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19882, __extension__ __PRETTY_FUNCTION__))
19882 "With both FP DP and 16, any FP conversion is legal!")(static_cast <bool> ((!Subtarget->hasFP64() || !Subtarget
->hasFPARMv8Base()) && "With both FP DP and 16, any FP conversion is legal!"
) ? void (0) : __assert_fail ("(!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) && \"With both FP DP and 16, any FP conversion is legal!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19882, __extension__ __PRETTY_FUNCTION__))
;
19883
19884 SDLoc Loc(Op);
19885
19886 // Instruction from 32 -> 16 if hasFP16 is valid
19887 if (SrcSz == 32 && Subtarget->hasFP16())
19888 return Op;
19889
19890 // Lib call from 32 -> 16 / 64 -> [32, 16]
19891 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
19892 assert(LC != RTLIB::UNKNOWN_LIBCALL &&(static_cast <bool> (LC != RTLIB::UNKNOWN_LIBCALL &&
"Unexpected type for custom-lowering FP_ROUND") ? void (0) :
__assert_fail ("LC != RTLIB::UNKNOWN_LIBCALL && \"Unexpected type for custom-lowering FP_ROUND\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19893, __extension__ __PRETTY_FUNCTION__))
19893 "Unexpected type for custom-lowering FP_ROUND")(static_cast <bool> (LC != RTLIB::UNKNOWN_LIBCALL &&
"Unexpected type for custom-lowering FP_ROUND") ? void (0) :
__assert_fail ("LC != RTLIB::UNKNOWN_LIBCALL && \"Unexpected type for custom-lowering FP_ROUND\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19893, __extension__ __PRETTY_FUNCTION__))
;
19894 MakeLibCallOptions CallOptions;
19895 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
19896 SDValue Result;
19897 std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
19898 Loc, Chain);
19899 return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
19900}
19901
19902void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
19903 SelectionDAG &DAG) const {
19904 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.")(static_cast <bool> (N->getValueType(0) == MVT::i64 &&
"Unexpected type (!= i64) on ABS.") ? void (0) : __assert_fail
("N->getValueType(0) == MVT::i64 && \"Unexpected type (!= i64) on ABS.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 19904, __extension__ __PRETTY_FUNCTION__))
;
19905 MVT HalfT = MVT::i32;
19906 SDLoc dl(N);
19907 SDValue Hi, Lo, Tmp;
19908
19909 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
19910 !isOperationLegalOrCustom(ISD::UADDO, HalfT))
19911 return ;
19912
19913 unsigned OpTypeBits = HalfT.getScalarSizeInBits();
19914 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
19915
19916 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
19917 DAG.getConstant(0, dl, HalfT));
19918 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
19919 DAG.getConstant(1, dl, HalfT));
19920
19921 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
19922 DAG.getConstant(OpTypeBits - 1, dl,
19923 getShiftAmountTy(HalfT, DAG.getDataLayout())));
19924 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
19925 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
19926 SDValue(Lo.getNode(), 1));
19927 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
19928 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
19929
19930 Results.push_back(Lo);
19931 Results.push_back(Hi);
19932}
19933
19934bool
19935ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
19936 // The ARM target isn't yet aware of offsets.
19937 return false;
19938}
19939
19940bool ARM::isBitFieldInvertedMask(unsigned v) {
19941 if (v == 0xffffffff)
19942 return false;
19943
19944 // there can be 1's on either or both "outsides", all the "inside"
19945 // bits must be 0's
19946 return isShiftedMask_32(~v);
19947}
19948
19949/// isFPImmLegal - Returns true if the target can instruction select the
19950/// specified FP immediate natively. If false, the legalizer will
19951/// materialize the FP immediate as a load from a constant pool.
19952bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
19953 bool ForCodeSize) const {
19954 if (!Subtarget->hasVFP3Base())
19955 return false;
19956 if (VT == MVT::f16 && Subtarget->hasFullFP16())
19957 return ARM_AM::getFP16Imm(Imm) != -1;
19958 if (VT == MVT::f32 && Subtarget->hasFullFP16() &&
19959 ARM_AM::getFP32FP16Imm(Imm) != -1)
19960 return true;
19961 if (VT == MVT::f32)
19962 return ARM_AM::getFP32Imm(Imm) != -1;
19963 if (VT == MVT::f64 && Subtarget->hasFP64())
19964 return ARM_AM::getFP64Imm(Imm) != -1;
19965 return false;
19966}
19967
19968/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
19969/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
19970/// specified in the intrinsic calls.
19971bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
19972 const CallInst &I,
19973 MachineFunction &MF,
19974 unsigned Intrinsic) const {
19975 switch (Intrinsic) {
19976 case Intrinsic::arm_neon_vld1:
19977 case Intrinsic::arm_neon_vld2:
19978 case Intrinsic::arm_neon_vld3:
19979 case Intrinsic::arm_neon_vld4:
19980 case Intrinsic::arm_neon_vld2lane:
19981 case Intrinsic::arm_neon_vld3lane:
19982 case Intrinsic::arm_neon_vld4lane:
19983 case Intrinsic::arm_neon_vld2dup:
19984 case Intrinsic::arm_neon_vld3dup:
19985 case Intrinsic::arm_neon_vld4dup: {
19986 Info.opc = ISD::INTRINSIC_W_CHAIN;
19987 // Conservatively set memVT to the entire set of vectors loaded.
19988 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
19989 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
19990 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
19991 Info.ptrVal = I.getArgOperand(0);
19992 Info.offset = 0;
19993 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
19994 Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue();
19995 // volatile loads with NEON intrinsics not supported
19996 Info.flags = MachineMemOperand::MOLoad;
19997 return true;
19998 }
19999 case Intrinsic::arm_neon_vld1x2:
20000 case Intrinsic::arm_neon_vld1x3:
20001 case Intrinsic::arm_neon_vld1x4: {
20002 Info.opc = ISD::INTRINSIC_W_CHAIN;
20003 // Conservatively set memVT to the entire set of vectors loaded.
20004 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
20005 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
20006 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
20007 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
20008 Info.offset = 0;
20009 Info.align.reset();
20010 // volatile loads with NEON intrinsics not supported
20011 Info.flags = MachineMemOperand::MOLoad;
20012 return true;
20013 }
20014 case Intrinsic::arm_neon_vst1:
20015 case Intrinsic::arm_neon_vst2:
20016 case Intrinsic::arm_neon_vst3:
20017 case Intrinsic::arm_neon_vst4:
20018 case Intrinsic::arm_neon_vst2lane:
20019 case Intrinsic::arm_neon_vst3lane:
20020 case Intrinsic::arm_neon_vst4lane: {
20021 Info.opc = ISD::INTRINSIC_VOID;
20022 // Conservatively set memVT to the entire set of vectors stored.
20023 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
20024 unsigned NumElts = 0;
20025 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
20026 Type *ArgTy = I.getArgOperand(ArgI)->getType();
20027 if (!ArgTy->isVectorTy())
20028 break;
20029 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
20030 }
20031 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
20032 Info.ptrVal = I.getArgOperand(0);
20033 Info.offset = 0;
20034 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
20035 Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue();
20036 // volatile stores with NEON intrinsics not supported
20037 Info.flags = MachineMemOperand::MOStore;
20038 return true;
20039 }
20040 case Intrinsic::arm_neon_vst1x2:
20041 case Intrinsic::arm_neon_vst1x3:
20042 case Intrinsic::arm_neon_vst1x4: {
20043 Info.opc = ISD::INTRINSIC_VOID;
20044 // Conservatively set memVT to the entire set of vectors stored.
20045 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
20046 unsigned NumElts = 0;
20047 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
20048 Type *ArgTy = I.getArgOperand(ArgI)->getType();
20049 if (!ArgTy->isVectorTy())
20050 break;
20051 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
20052 }
20053 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
20054 Info.ptrVal = I.getArgOperand(0);
20055 Info.offset = 0;
20056 Info.align.reset();
20057 // volatile stores with NEON intrinsics not supported
20058 Info.flags = MachineMemOperand::MOStore;
20059 return true;
20060 }
20061 case Intrinsic::arm_mve_vld2q:
20062 case Intrinsic::arm_mve_vld4q: {
20063 Info.opc = ISD::INTRINSIC_W_CHAIN;
20064 // Conservatively set memVT to the entire set of vectors loaded.
20065 Type *VecTy = cast<StructType>(I.getType())->getElementType(1);
20066 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4;
20067 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
20068 Info.ptrVal = I.getArgOperand(0);
20069 Info.offset = 0;
20070 Info.align = Align(VecTy->getScalarSizeInBits() / 8);
20071 // volatile loads with MVE intrinsics not supported
20072 Info.flags = MachineMemOperand::MOLoad;
20073 return true;
20074 }
20075 case Intrinsic::arm_mve_vst2q:
20076 case Intrinsic::arm_mve_vst4q: {
20077 Info.opc = ISD::INTRINSIC_VOID;
20078 // Conservatively set memVT to the entire set of vectors stored.
20079 Type *VecTy = I.getArgOperand(1)->getType();
20080 unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4;
20081 Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
20082 Info.ptrVal = I.getArgOperand(0);
20083 Info.offset = 0;
20084 Info.align = Align(VecTy->getScalarSizeInBits() / 8);
20085 // volatile stores with MVE intrinsics not supported
20086 Info.flags = MachineMemOperand::MOStore;
20087 return true;
20088 }
20089 case Intrinsic::arm_mve_vldr_gather_base:
20090 case Intrinsic::arm_mve_vldr_gather_base_predicated: {
20091 Info.opc = ISD::INTRINSIC_W_CHAIN;
20092 Info.ptrVal = nullptr;
20093 Info.memVT = MVT::getVT(I.getType());
20094 Info.align = Align(1);
20095 Info.flags |= MachineMemOperand::MOLoad;
20096 return true;
20097 }
20098 case Intrinsic::arm_mve_vldr_gather_base_wb:
20099 case Intrinsic::arm_mve_vldr_gather_base_wb_predicated: {
20100 Info.opc = ISD::INTRINSIC_W_CHAIN;
20101 Info.ptrVal = nullptr;
20102 Info.memVT = MVT::getVT(I.getType()->getContainedType(0));
20103 Info.align = Align(1);
20104 Info.flags |= MachineMemOperand::MOLoad;
20105 return true;
20106 }
20107 case Intrinsic::arm_mve_vldr_gather_offset:
20108 case Intrinsic::arm_mve_vldr_gather_offset_predicated: {
20109 Info.opc = ISD::INTRINSIC_W_CHAIN;
20110 Info.ptrVal = nullptr;
20111 MVT DataVT = MVT::getVT(I.getType());
20112 unsigned MemSize = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
20113 Info.memVT = MVT::getVectorVT(MVT::getIntegerVT(MemSize),
20114 DataVT.getVectorNumElements());
20115 Info.align = Align(1);
20116 Info.flags |= MachineMemOperand::MOLoad;
20117 return true;
20118 }
20119 case Intrinsic::arm_mve_vstr_scatter_base:
20120 case Intrinsic::arm_mve_vstr_scatter_base_predicated: {
20121 Info.opc = ISD::INTRINSIC_VOID;
20122 Info.ptrVal = nullptr;
20123 Info.memVT = MVT::getVT(I.getArgOperand(2)->getType());
20124 Info.align = Align(1);
20125 Info.flags |= MachineMemOperand::MOStore;
20126 return true;
20127 }
20128 case Intrinsic::arm_mve_vstr_scatter_base_wb:
20129 case Intrinsic::arm_mve_vstr_scatter_base_wb_predicated: {
20130 Info.opc = ISD::INTRINSIC_W_CHAIN;
20131 Info.ptrVal = nullptr;
20132 Info.memVT = MVT::getVT(I.getArgOperand(2)->getType());
20133 Info.align = Align(1);
20134 Info.flags |= MachineMemOperand::MOStore;
20135 return true;
20136 }
20137 case Intrinsic::arm_mve_vstr_scatter_offset:
20138 case Intrinsic::arm_mve_vstr_scatter_offset_predicated: {
20139 Info.opc = ISD::INTRINSIC_VOID;
20140 Info.ptrVal = nullptr;
20141 MVT DataVT = MVT::getVT(I.getArgOperand(2)->getType());
20142 unsigned MemSize = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
20143 Info.memVT = MVT::getVectorVT(MVT::getIntegerVT(MemSize),
20144 DataVT.getVectorNumElements());
20145 Info.align = Align(1);
20146 Info.flags |= MachineMemOperand::MOStore;
20147 return true;
20148 }
20149 case Intrinsic::arm_ldaex:
20150 case Intrinsic::arm_ldrex: {
20151 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
20152 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
20153 Info.opc = ISD::INTRINSIC_W_CHAIN;
20154 Info.memVT = MVT::getVT(PtrTy->getElementType());
20155 Info.ptrVal = I.getArgOperand(0);
20156 Info.offset = 0;
20157 Info.align = DL.getABITypeAlign(PtrTy->getElementType());
20158 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
20159 return true;
20160 }
20161 case Intrinsic::arm_stlex:
20162 case Intrinsic::arm_strex: {
20163 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
20164 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
20165 Info.opc = ISD::INTRINSIC_W_CHAIN;
20166 Info.memVT = MVT::getVT(PtrTy->getElementType());
20167 Info.ptrVal = I.getArgOperand(1);
20168 Info.offset = 0;
20169 Info.align = DL.getABITypeAlign(PtrTy->getElementType());
20170 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
20171 return true;
20172 }
20173 case Intrinsic::arm_stlexd:
20174 case Intrinsic::arm_strexd:
20175 Info.opc = ISD::INTRINSIC_W_CHAIN;
20176 Info.memVT = MVT::i64;
20177 Info.ptrVal = I.getArgOperand(2);
20178 Info.offset = 0;
20179 Info.align = Align(8);
20180 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
20181 return true;
20182
20183 case Intrinsic::arm_ldaexd:
20184 case Intrinsic::arm_ldrexd:
20185 Info.opc = ISD::INTRINSIC_W_CHAIN;
20186 Info.memVT = MVT::i64;
20187 Info.ptrVal = I.getArgOperand(0);
20188 Info.offset = 0;
20189 Info.align = Align(8);
20190 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
20191 return true;
20192
20193 default:
20194 break;
20195 }
20196
20197 return false;
20198}
20199
20200/// Returns true if it is beneficial to convert a load of a constant
20201/// to just the constant itself.
20202bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
20203 Type *Ty) const {
20204 assert(Ty->isIntegerTy())(static_cast <bool> (Ty->isIntegerTy()) ? void (0) :
__assert_fail ("Ty->isIntegerTy()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20204, __extension__ __PRETTY_FUNCTION__))
;
20205
20206 unsigned Bits = Ty->getPrimitiveSizeInBits();
20207 if (Bits == 0 || Bits > 32)
20208 return false;
20209 return true;
20210}
20211
20212bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
20213 unsigned Index) const {
20214 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
20215 return false;
20216
20217 return (Index == 0 || Index == ResVT.getVectorNumElements());
20218}
20219
20220Instruction *ARMTargetLowering::makeDMB(IRBuilderBase &Builder,
20221 ARM_MB::MemBOpt Domain) const {
20222 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
20223
20224 // First, if the target has no DMB, see what fallback we can use.
20225 if (!Subtarget->hasDataBarrier()) {
20226 // Some ARMv6 cpus can support data barriers with an mcr instruction.
20227 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
20228 // here.
20229 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
20230 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
20231 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
20232 Builder.getInt32(0), Builder.getInt32(7),
20233 Builder.getInt32(10), Builder.getInt32(5)};
20234 return Builder.CreateCall(MCR, args);
20235 } else {
20236 // Instead of using barriers, atomic accesses on these subtargets use
20237 // libcalls.
20238 llvm_unreachable("makeDMB on a target so old that it has no barriers")::llvm::llvm_unreachable_internal("makeDMB on a target so old that it has no barriers"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20238)
;
20239 }
20240 } else {
20241 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
20242 // Only a full system barrier exists in the M-class architectures.
20243 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
20244 Constant *CDomain = Builder.getInt32(Domain);
20245 return Builder.CreateCall(DMB, CDomain);
20246 }
20247}
20248
20249// Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
20250Instruction *ARMTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
20251 Instruction *Inst,
20252 AtomicOrdering Ord) const {
20253 switch (Ord) {
20254 case AtomicOrdering::NotAtomic:
20255 case AtomicOrdering::Unordered:
20256 llvm_unreachable("Invalid fence: unordered/non-atomic")::llvm::llvm_unreachable_internal("Invalid fence: unordered/non-atomic"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20256)
;
20257 case AtomicOrdering::Monotonic:
20258 case AtomicOrdering::Acquire:
20259 return nullptr; // Nothing to do
20260 case AtomicOrdering::SequentiallyConsistent:
20261 if (!Inst->hasAtomicStore())
20262 return nullptr; // Nothing to do
20263 LLVM_FALLTHROUGH[[gnu::fallthrough]];
20264 case AtomicOrdering::Release:
20265 case AtomicOrdering::AcquireRelease:
20266 if (Subtarget->preferISHSTBarriers())
20267 return makeDMB(Builder, ARM_MB::ISHST);
20268 // FIXME: add a comment with a link to documentation justifying this.
20269 else
20270 return makeDMB(Builder, ARM_MB::ISH);
20271 }
20272 llvm_unreachable("Unknown fence ordering in emitLeadingFence")::llvm::llvm_unreachable_internal("Unknown fence ordering in emitLeadingFence"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20272)
;
20273}
20274
20275Instruction *ARMTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
20276 Instruction *Inst,
20277 AtomicOrdering Ord) const {
20278 switch (Ord) {
20279 case AtomicOrdering::NotAtomic:
20280 case AtomicOrdering::Unordered:
20281 llvm_unreachable("Invalid fence: unordered/not-atomic")::llvm::llvm_unreachable_internal("Invalid fence: unordered/not-atomic"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20281)
;
20282 case AtomicOrdering::Monotonic:
20283 case AtomicOrdering::Release:
20284 return nullptr; // Nothing to do
20285 case AtomicOrdering::Acquire:
20286 case AtomicOrdering::AcquireRelease:
20287 case AtomicOrdering::SequentiallyConsistent:
20288 return makeDMB(Builder, ARM_MB::ISH);
20289 }
20290 llvm_unreachable("Unknown fence ordering in emitTrailingFence")::llvm::llvm_unreachable_internal("Unknown fence ordering in emitTrailingFence"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20290)
;
20291}
20292
20293// Loads and stores less than 64-bits are already atomic; ones above that
20294// are doomed anyway, so defer to the default libcall and blame the OS when
20295// things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
20296// anything for those.
20297bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
20298 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
20299 return (Size == 64) && !Subtarget->isMClass();
20300}
20301
20302// Loads and stores less than 64-bits are already atomic; ones above that
20303// are doomed anyway, so defer to the default libcall and blame the OS when
20304// things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
20305// anything for those.
20306// FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
20307// guarantee, see DDI0406C ARM architecture reference manual,
20308// sections A8.8.72-74 LDRD)
20309TargetLowering::AtomicExpansionKind
20310ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
20311 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
20312 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
20313 : AtomicExpansionKind::None;
20314}
20315
20316// For the real atomic operations, we have ldrex/strex up to 32 bits,
20317// and up to 64 bits on the non-M profiles
20318TargetLowering::AtomicExpansionKind
20319ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
20320 if (AI->isFloatingPointOperation())
20321 return AtomicExpansionKind::CmpXChg;
20322
20323 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
20324 // implement atomicrmw without spilling. If the target address is also on the
20325 // stack and close enough to the spill slot, this can lead to a situation
20326 // where the monitor always gets cleared and the atomic operation can never
20327 // succeed. So at -O0 lower this operation to a CAS loop.
20328 if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
20329 return AtomicExpansionKind::CmpXChg;
20330
20331 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
20332 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
20333 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
20334 ? AtomicExpansionKind::LLSC
20335 : AtomicExpansionKind::None;
20336}
20337
20338// Similar to shouldExpandAtomicRMWInIR, ldrex/strex can be used up to 32
20339// bits, and up to 64 bits on the non-M profiles.
20340TargetLowering::AtomicExpansionKind
20341ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
20342 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
20343 // implement cmpxchg without spilling. If the address being exchanged is also
20344 // on the stack and close enough to the spill slot, this can lead to a
20345 // situation where the monitor always gets cleared and the atomic operation
20346 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
20347 unsigned Size = AI->getOperand(1)->getType()->getPrimitiveSizeInBits();
20348 bool HasAtomicCmpXchg =
20349 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
20350 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg &&
20351 Size <= (Subtarget->isMClass() ? 32U : 64U))
20352 return AtomicExpansionKind::LLSC;
20353 return AtomicExpansionKind::None;
20354}
20355
20356bool ARMTargetLowering::shouldInsertFencesForAtomic(
20357 const Instruction *I) const {
20358 return InsertFencesForAtomic;
20359}
20360
20361// This has so far only been implemented for MachO.
20362bool ARMTargetLowering::useLoadStackGuardNode() const {
20363 return Subtarget->isTargetMachO();
20364}
20365
20366void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
20367 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
20368 return TargetLowering::insertSSPDeclarations(M);
20369
20370 // MSVC CRT has a global variable holding security cookie.
20371 M.getOrInsertGlobal("__security_cookie",
20372 Type::getInt8PtrTy(M.getContext()));
20373
20374 // MSVC CRT has a function to validate security cookie.
20375 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
20376 "__security_check_cookie", Type::getVoidTy(M.getContext()),
20377 Type::getInt8PtrTy(M.getContext()));
20378 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
20379 F->addParamAttr(0, Attribute::AttrKind::InReg);
20380}
20381
20382Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
20383 // MSVC CRT has a global variable holding security cookie.
20384 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
20385 return M.getGlobalVariable("__security_cookie");
20386 return TargetLowering::getSDagStackGuard(M);
20387}
20388
20389Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
20390 // MSVC CRT has a function to validate security cookie.
20391 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
20392 return M.getFunction("__security_check_cookie");
20393 return TargetLowering::getSSPStackGuardCheck(M);
20394}
20395
20396bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
20397 unsigned &Cost) const {
20398 // If we do not have NEON, vector types are not natively supported.
20399 if (!Subtarget->hasNEON())
20400 return false;
20401
20402 // Floating point values and vector values map to the same register file.
20403 // Therefore, although we could do a store extract of a vector type, this is
20404 // better to leave at float as we have more freedom in the addressing mode for
20405 // those.
20406 if (VectorTy->isFPOrFPVectorTy())
20407 return false;
20408
20409 // If the index is unknown at compile time, this is very expensive to lower
20410 // and it is not possible to combine the store with the extract.
20411 if (!isa<ConstantInt>(Idx))
20412 return false;
20413
20414 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type")(static_cast <bool> (VectorTy->isVectorTy() &&
"VectorTy is not a vector type") ? void (0) : __assert_fail (
"VectorTy->isVectorTy() && \"VectorTy is not a vector type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20414, __extension__ __PRETTY_FUNCTION__))
;
20415 unsigned BitWidth = VectorTy->getPrimitiveSizeInBits().getFixedSize();
20416 // We can do a store + vector extract on any vector that fits perfectly in a D
20417 // or Q register.
20418 if (BitWidth == 64 || BitWidth == 128) {
20419 Cost = 0;
20420 return true;
20421 }
20422 return false;
20423}
20424
20425bool ARMTargetLowering::isCheapToSpeculateCttz() const {
20426 return Subtarget->hasV6T2Ops();
20427}
20428
20429bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
20430 return Subtarget->hasV6T2Ops();
20431}
20432
20433bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
20434 return !Subtarget->hasMinSize() || Subtarget->isTargetWindows();
20435}
20436
20437Value *ARMTargetLowering::emitLoadLinked(IRBuilderBase &Builder, Type *ValueTy,
20438 Value *Addr,
20439 AtomicOrdering Ord) const {
20440 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
20441 bool IsAcquire = isAcquireOrStronger(Ord);
20442
20443 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
20444 // intrinsic must return {i32, i32} and we have to recombine them into a
20445 // single i64 here.
20446 if (ValueTy->getPrimitiveSizeInBits() == 64) {
20447 Intrinsic::ID Int =
20448 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
20449 Function *Ldrex = Intrinsic::getDeclaration(M, Int);
20450
20451 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
20452 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
20453
20454 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
20455 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
20456 if (!Subtarget->isLittle())
20457 std::swap (Lo, Hi);
20458 Lo = Builder.CreateZExt(Lo, ValueTy, "lo64");
20459 Hi = Builder.CreateZExt(Hi, ValueTy, "hi64");
20460 return Builder.CreateOr(
20461 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValueTy, 32)), "val64");
20462 }
20463
20464 Type *Tys[] = { Addr->getType() };
20465 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
20466 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
20467
20468 return Builder.CreateTruncOrBitCast(Builder.CreateCall(Ldrex, Addr), ValueTy);
20469}
20470
20471void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
20472 IRBuilderBase &Builder) const {
20473 if (!Subtarget->hasV7Ops())
20474 return;
20475 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
20476 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
20477}
20478
20479Value *ARMTargetLowering::emitStoreConditional(IRBuilderBase &Builder,
20480 Value *Val, Value *Addr,
20481 AtomicOrdering Ord) const {
20482 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
20483 bool IsRelease = isReleaseOrStronger(Ord);
20484
20485 // Since the intrinsics must have legal type, the i64 intrinsics take two
20486 // parameters: "i32, i32". We must marshal Val into the appropriate form
20487 // before the call.
20488 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
20489 Intrinsic::ID Int =
20490 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
20491 Function *Strex = Intrinsic::getDeclaration(M, Int);
20492 Type *Int32Ty = Type::getInt32Ty(M->getContext());
20493
20494 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
20495 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
20496 if (!Subtarget->isLittle())
20497 std::swap(Lo, Hi);
20498 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
20499 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
20500 }
20501
20502 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
20503 Type *Tys[] = { Addr->getType() };
20504 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
20505
20506 return Builder.CreateCall(
20507 Strex, {Builder.CreateZExtOrBitCast(
20508 Val, Strex->getFunctionType()->getParamType(0)),
20509 Addr});
20510}
20511
20512
20513bool ARMTargetLowering::alignLoopsWithOptSize() const {
20514 return Subtarget->isMClass();
20515}
20516
20517/// A helper function for determining the number of interleaved accesses we
20518/// will generate when lowering accesses of the given type.
20519unsigned
20520ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
20521 const DataLayout &DL) const {
20522 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
20523}
20524
20525bool ARMTargetLowering::isLegalInterleavedAccessType(
20526 unsigned Factor, FixedVectorType *VecTy, Align Alignment,
20527 const DataLayout &DL) const {
20528
20529 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
20530 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
20531
20532 if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps())
20533 return false;
20534
20535 // Ensure the vector doesn't have f16 elements. Even though we could do an
20536 // i16 vldN, we can't hold the f16 vectors and will end up converting via
20537 // f32.
20538 if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy())
20539 return false;
20540 if (Subtarget->hasMVEIntegerOps() && Factor == 3)
20541 return false;
20542
20543 // Ensure the number of vector elements is greater than 1.
20544 if (VecTy->getNumElements() < 2)
20545 return false;
20546
20547 // Ensure the element type is legal.
20548 if (ElSize != 8 && ElSize != 16 && ElSize != 32)
20549 return false;
20550 // And the alignment if high enough under MVE.
20551 if (Subtarget->hasMVEIntegerOps() && Alignment < ElSize / 8)
20552 return false;
20553
20554 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
20555 // 128 will be split into multiple interleaved accesses.
20556 if (Subtarget->hasNEON() && VecSize == 64)
20557 return true;
20558 return VecSize % 128 == 0;
20559}
20560
20561unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
20562 if (Subtarget->hasNEON())
20563 return 4;
20564 if (Subtarget->hasMVEIntegerOps())
20565 return MVEMaxSupportedInterleaveFactor;
20566 return TargetLoweringBase::getMaxSupportedInterleaveFactor();
20567}
20568
20569/// Lower an interleaved load into a vldN intrinsic.
20570///
20571/// E.g. Lower an interleaved load (Factor = 2):
20572/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
20573/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
20574/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
20575///
20576/// Into:
20577/// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
20578/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
20579/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
20580bool ARMTargetLowering::lowerInterleavedLoad(
20581 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
20582 ArrayRef<unsigned> Indices, unsigned Factor) const {
20583 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&(static_cast <bool> (Factor >= 2 && Factor <=
getMaxSupportedInterleaveFactor() && "Invalid interleave factor"
) ? void (0) : __assert_fail ("Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && \"Invalid interleave factor\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20584, __extension__ __PRETTY_FUNCTION__))
20584 "Invalid interleave factor")(static_cast <bool> (Factor >= 2 && Factor <=
getMaxSupportedInterleaveFactor() && "Invalid interleave factor"
) ? void (0) : __assert_fail ("Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && \"Invalid interleave factor\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20584, __extension__ __PRETTY_FUNCTION__))
;
20585 assert(!Shuffles.empty() && "Empty shufflevector input")(static_cast <bool> (!Shuffles.empty() && "Empty shufflevector input"
) ? void (0) : __assert_fail ("!Shuffles.empty() && \"Empty shufflevector input\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20585, __extension__ __PRETTY_FUNCTION__))
;
20586 assert(Shuffles.size() == Indices.size() &&(static_cast <bool> (Shuffles.size() == Indices.size() &&
"Unmatched number of shufflevectors and indices") ? void (0)
: __assert_fail ("Shuffles.size() == Indices.size() && \"Unmatched number of shufflevectors and indices\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20587, __extension__ __PRETTY_FUNCTION__))
20587 "Unmatched number of shufflevectors and indices")(static_cast <bool> (Shuffles.size() == Indices.size() &&
"Unmatched number of shufflevectors and indices") ? void (0)
: __assert_fail ("Shuffles.size() == Indices.size() && \"Unmatched number of shufflevectors and indices\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20587, __extension__ __PRETTY_FUNCTION__))
;
20588
20589 auto *VecTy = cast<FixedVectorType>(Shuffles[0]->getType());
20590 Type *EltTy = VecTy->getElementType();
20591
20592 const DataLayout &DL = LI->getModule()->getDataLayout();
20593 Align Alignment = LI->getAlign();
20594
20595 // Skip if we do not have NEON and skip illegal vector types. We can
20596 // "legalize" wide vector types into multiple interleaved accesses as long as
20597 // the vector types are divisible by 128.
20598 if (!isLegalInterleavedAccessType(Factor, VecTy, Alignment, DL))
20599 return false;
20600
20601 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
20602
20603 // A pointer vector can not be the return type of the ldN intrinsics. Need to
20604 // load integer vectors first and then convert to pointer vectors.
20605 if (EltTy->isPointerTy())
20606 VecTy = FixedVectorType::get(DL.getIntPtrType(EltTy), VecTy);
20607
20608 IRBuilder<> Builder(LI);
20609
20610 // The base address of the load.
20611 Value *BaseAddr = LI->getPointerOperand();
20612
20613 if (NumLoads > 1) {
20614 // If we're going to generate more than one load, reset the sub-vector type
20615 // to something legal.
20616 VecTy = FixedVectorType::get(VecTy->getElementType(),
20617 VecTy->getNumElements() / NumLoads);
20618
20619 // We will compute the pointer operand of each load from the original base
20620 // address using GEPs. Cast the base address to a pointer to the scalar
20621 // element type.
20622 BaseAddr = Builder.CreateBitCast(
20623 BaseAddr,
20624 VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
20625 }
20626
20627 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!")(static_cast <bool> (isTypeLegal(EVT::getEVT(VecTy)) &&
"Illegal vldN vector type!") ? void (0) : __assert_fail ("isTypeLegal(EVT::getEVT(VecTy)) && \"Illegal vldN vector type!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20627, __extension__ __PRETTY_FUNCTION__))
;
20628
20629 auto createLoadIntrinsic = [&](Value *BaseAddr) {
20630 if (Subtarget->hasNEON()) {
20631 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
20632 Type *Tys[] = {VecTy, Int8Ptr};
20633 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
20634 Intrinsic::arm_neon_vld3,
20635 Intrinsic::arm_neon_vld4};
20636 Function *VldnFunc =
20637 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
20638
20639 SmallVector<Value *, 2> Ops;
20640 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
20641 Ops.push_back(Builder.getInt32(LI->getAlignment()));
20642
20643 return Builder.CreateCall(VldnFunc, Ops, "vldN");
20644 } else {
20645 assert((Factor == 2 || Factor == 4) &&(static_cast <bool> ((Factor == 2 || Factor == 4) &&
"expected interleave factor of 2 or 4 for MVE") ? void (0) :
__assert_fail ("(Factor == 2 || Factor == 4) && \"expected interleave factor of 2 or 4 for MVE\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20646, __extension__ __PRETTY_FUNCTION__))
20646 "expected interleave factor of 2 or 4 for MVE")(static_cast <bool> ((Factor == 2 || Factor == 4) &&
"expected interleave factor of 2 or 4 for MVE") ? void (0) :
__assert_fail ("(Factor == 2 || Factor == 4) && \"expected interleave factor of 2 or 4 for MVE\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20646, __extension__ __PRETTY_FUNCTION__))
;
20647 Intrinsic::ID LoadInts =
20648 Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q;
20649 Type *VecEltTy =
20650 VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace());
20651 Type *Tys[] = {VecTy, VecEltTy};
20652 Function *VldnFunc =
20653 Intrinsic::getDeclaration(LI->getModule(), LoadInts, Tys);
20654
20655 SmallVector<Value *, 2> Ops;
20656 Ops.push_back(Builder.CreateBitCast(BaseAddr, VecEltTy));
20657 return Builder.CreateCall(VldnFunc, Ops, "vldN");
20658 }
20659 };
20660
20661 // Holds sub-vectors extracted from the load intrinsic return values. The
20662 // sub-vectors are associated with the shufflevector instructions they will
20663 // replace.
20664 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
20665
20666 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
20667 // If we're generating more than one load, compute the base address of
20668 // subsequent loads as an offset from the previous.
20669 if (LoadCount > 0)
20670 BaseAddr = Builder.CreateConstGEP1_32(VecTy->getElementType(), BaseAddr,
20671 VecTy->getNumElements() * Factor);
20672
20673 CallInst *VldN = createLoadIntrinsic(BaseAddr);
20674
20675 // Replace uses of each shufflevector with the corresponding vector loaded
20676 // by ldN.
20677 for (unsigned i = 0; i < Shuffles.size(); i++) {
20678 ShuffleVectorInst *SV = Shuffles[i];
20679 unsigned Index = Indices[i];
20680
20681 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
20682
20683 // Convert the integer vector to pointer vector if the element is pointer.
20684 if (EltTy->isPointerTy())
20685 SubVec = Builder.CreateIntToPtr(
20686 SubVec,
20687 FixedVectorType::get(SV->getType()->getElementType(), VecTy));
20688
20689 SubVecs[SV].push_back(SubVec);
20690 }
20691 }
20692
20693 // Replace uses of the shufflevector instructions with the sub-vectors
20694 // returned by the load intrinsic. If a shufflevector instruction is
20695 // associated with more than one sub-vector, those sub-vectors will be
20696 // concatenated into a single wide vector.
20697 for (ShuffleVectorInst *SVI : Shuffles) {
20698 auto &SubVec = SubVecs[SVI];
20699 auto *WideVec =
20700 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
20701 SVI->replaceAllUsesWith(WideVec);
20702 }
20703
20704 return true;
20705}
20706
20707/// Lower an interleaved store into a vstN intrinsic.
20708///
20709/// E.g. Lower an interleaved store (Factor = 3):
20710/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
20711/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
20712/// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
20713///
20714/// Into:
20715/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
20716/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
20717/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
20718/// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
20719///
20720/// Note that the new shufflevectors will be removed and we'll only generate one
20721/// vst3 instruction in CodeGen.
20722///
20723/// Example for a more general valid mask (Factor 3). Lower:
20724/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
20725/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
20726/// store <12 x i32> %i.vec, <12 x i32>* %ptr
20727///
20728/// Into:
20729/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
20730/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
20731/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
20732/// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
20733bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
20734 ShuffleVectorInst *SVI,
20735 unsigned Factor) const {
20736 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&(static_cast <bool> (Factor >= 2 && Factor <=
getMaxSupportedInterleaveFactor() && "Invalid interleave factor"
) ? void (0) : __assert_fail ("Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && \"Invalid interleave factor\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20737, __extension__ __PRETTY_FUNCTION__))
20737 "Invalid interleave factor")(static_cast <bool> (Factor >= 2 && Factor <=
getMaxSupportedInterleaveFactor() && "Invalid interleave factor"
) ? void (0) : __assert_fail ("Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && \"Invalid interleave factor\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20737, __extension__ __PRETTY_FUNCTION__))
;
20738
20739 auto *VecTy = cast<FixedVectorType>(SVI->getType());
20740 assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store")(static_cast <bool> (VecTy->getNumElements() % Factor
== 0 && "Invalid interleaved store") ? void (0) : __assert_fail
("VecTy->getNumElements() % Factor == 0 && \"Invalid interleaved store\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20740, __extension__ __PRETTY_FUNCTION__))
;
20741
20742 unsigned LaneLen = VecTy->getNumElements() / Factor;
20743 Type *EltTy = VecTy->getElementType();
20744 auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
20745
20746 const DataLayout &DL = SI->getModule()->getDataLayout();
20747 Align Alignment = SI->getAlign();
20748
20749 // Skip if we do not have NEON and skip illegal vector types. We can
20750 // "legalize" wide vector types into multiple interleaved accesses as long as
20751 // the vector types are divisible by 128.
20752 if (!isLegalInterleavedAccessType(Factor, SubVecTy, Alignment, DL))
20753 return false;
20754
20755 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
20756
20757 Value *Op0 = SVI->getOperand(0);
20758 Value *Op1 = SVI->getOperand(1);
20759 IRBuilder<> Builder(SI);
20760
20761 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
20762 // vectors to integer vectors.
20763 if (EltTy->isPointerTy()) {
20764 Type *IntTy = DL.getIntPtrType(EltTy);
20765
20766 // Convert to the corresponding integer vector.
20767 auto *IntVecTy =
20768 FixedVectorType::get(IntTy, cast<FixedVectorType>(Op0->getType()));
20769 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
20770 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
20771
20772 SubVecTy = FixedVectorType::get(IntTy, LaneLen);
20773 }
20774
20775 // The base address of the store.
20776 Value *BaseAddr = SI->getPointerOperand();
20777
20778 if (NumStores > 1) {
20779 // If we're going to generate more than one store, reset the lane length
20780 // and sub-vector type to something legal.
20781 LaneLen /= NumStores;
20782 SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
20783
20784 // We will compute the pointer operand of each store from the original base
20785 // address using GEPs. Cast the base address to a pointer to the scalar
20786 // element type.
20787 BaseAddr = Builder.CreateBitCast(
20788 BaseAddr,
20789 SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
20790 }
20791
20792 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!")(static_cast <bool> (isTypeLegal(EVT::getEVT(SubVecTy))
&& "Illegal vstN vector type!") ? void (0) : __assert_fail
("isTypeLegal(EVT::getEVT(SubVecTy)) && \"Illegal vstN vector type!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20792, __extension__ __PRETTY_FUNCTION__))
;
20793
20794 auto Mask = SVI->getShuffleMask();
20795
20796 auto createStoreIntrinsic = [&](Value *BaseAddr,
20797 SmallVectorImpl<Value *> &Shuffles) {
20798 if (Subtarget->hasNEON()) {
20799 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
20800 Intrinsic::arm_neon_vst3,
20801 Intrinsic::arm_neon_vst4};
20802 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
20803 Type *Tys[] = {Int8Ptr, SubVecTy};
20804
20805 Function *VstNFunc = Intrinsic::getDeclaration(
20806 SI->getModule(), StoreInts[Factor - 2], Tys);
20807
20808 SmallVector<Value *, 6> Ops;
20809 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
20810 append_range(Ops, Shuffles);
20811 Ops.push_back(Builder.getInt32(SI->getAlignment()));
20812 Builder.CreateCall(VstNFunc, Ops);
20813 } else {
20814 assert((Factor == 2 || Factor == 4) &&(static_cast <bool> ((Factor == 2 || Factor == 4) &&
"expected interleave factor of 2 or 4 for MVE") ? void (0) :
__assert_fail ("(Factor == 2 || Factor == 4) && \"expected interleave factor of 2 or 4 for MVE\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20815, __extension__ __PRETTY_FUNCTION__))
20815 "expected interleave factor of 2 or 4 for MVE")(static_cast <bool> ((Factor == 2 || Factor == 4) &&
"expected interleave factor of 2 or 4 for MVE") ? void (0) :
__assert_fail ("(Factor == 2 || Factor == 4) && \"expected interleave factor of 2 or 4 for MVE\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 20815, __extension__ __PRETTY_FUNCTION__))
;
20816 Intrinsic::ID StoreInts =
20817 Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q;
20818 Type *EltPtrTy = SubVecTy->getElementType()->getPointerTo(
20819 SI->getPointerAddressSpace());
20820 Type *Tys[] = {EltPtrTy, SubVecTy};
20821 Function *VstNFunc =
20822 Intrinsic::getDeclaration(SI->getModule(), StoreInts, Tys);
20823
20824 SmallVector<Value *, 6> Ops;
20825 Ops.push_back(Builder.CreateBitCast(BaseAddr, EltPtrTy));
20826 append_range(Ops, Shuffles);
20827 for (unsigned F = 0; F < Factor; F++) {
20828 Ops.push_back(Builder.getInt32(F));
20829 Builder.CreateCall(VstNFunc, Ops);
20830 Ops.pop_back();
20831 }
20832 }
20833 };
20834
20835 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
20836 // If we generating more than one store, we compute the base address of
20837 // subsequent stores as an offset from the previous.
20838 if (StoreCount > 0)
20839 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
20840 BaseAddr, LaneLen * Factor);
20841
20842 SmallVector<Value *, 4> Shuffles;
20843
20844 // Split the shufflevector operands into sub vectors for the new vstN call.
20845 for (unsigned i = 0; i < Factor; i++) {
20846 unsigned IdxI = StoreCount * LaneLen * Factor + i;
20847 if (Mask[IdxI] >= 0) {
20848 Shuffles.push_back(Builder.CreateShuffleVector(
20849 Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
20850 } else {
20851 unsigned StartMask = 0;
20852 for (unsigned j = 1; j < LaneLen; j++) {
20853 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
20854 if (Mask[IdxJ * Factor + IdxI] >= 0) {
20855 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
20856 break;
20857 }
20858 }
20859 // Note: If all elements in a chunk are undefs, StartMask=0!
20860 // Note: Filling undef gaps with random elements is ok, since
20861 // those elements were being written anyway (with undefs).
20862 // In the case of all undefs we're defaulting to using elems from 0
20863 // Note: StartMask cannot be negative, it's checked in
20864 // isReInterleaveMask
20865 Shuffles.push_back(Builder.CreateShuffleVector(
20866 Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
20867 }
20868 }
20869
20870 createStoreIntrinsic(BaseAddr, Shuffles);
20871 }
20872 return true;
20873}
20874
20875enum HABaseType {
20876 HA_UNKNOWN = 0,
20877 HA_FLOAT,
20878 HA_DOUBLE,
20879 HA_VECT64,
20880 HA_VECT128
20881};
20882
20883static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
20884 uint64_t &Members) {
20885 if (auto *ST = dyn_cast<StructType>(Ty)) {
20886 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
20887 uint64_t SubMembers = 0;
20888 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
20889 return false;
20890 Members += SubMembers;
20891 }
20892 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
20893 uint64_t SubMembers = 0;
20894 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
20895 return false;
20896 Members += SubMembers * AT->getNumElements();
20897 } else if (Ty->isFloatTy()) {
20898 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
20899 return false;
20900 Members = 1;
20901 Base = HA_FLOAT;
20902 } else if (Ty->isDoubleTy()) {
20903 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
20904 return false;
20905 Members = 1;
20906 Base = HA_DOUBLE;
20907 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
20908 Members = 1;
20909 switch (Base) {
20910 case HA_FLOAT:
20911 case HA_DOUBLE:
20912 return false;
20913 case HA_VECT64:
20914 return VT->getPrimitiveSizeInBits().getFixedSize() == 64;
20915 case HA_VECT128:
20916 return VT->getPrimitiveSizeInBits().getFixedSize() == 128;
20917 case HA_UNKNOWN:
20918 switch (VT->getPrimitiveSizeInBits().getFixedSize()) {
20919 case 64:
20920 Base = HA_VECT64;
20921 return true;
20922 case 128:
20923 Base = HA_VECT128;
20924 return true;
20925 default:
20926 return false;
20927 }
20928 }
20929 }
20930
20931 return (Members > 0 && Members <= 4);
20932}
20933
20934/// Return the correct alignment for the current calling convention.
20935Align ARMTargetLowering::getABIAlignmentForCallingConv(
20936 Type *ArgTy, const DataLayout &DL) const {
20937 const Align ABITypeAlign = DL.getABITypeAlign(ArgTy);
20938 if (!ArgTy->isVectorTy())
20939 return ABITypeAlign;
20940
20941 // Avoid over-aligning vector parameters. It would require realigning the
20942 // stack and waste space for no real benefit.
20943 return std::min(ABITypeAlign, DL.getStackAlignment());
20944}
20945
20946/// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
20947/// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
20948/// passing according to AAPCS rules.
20949bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
20950 Type *Ty, CallingConv::ID CallConv, bool isVarArg,
20951 const DataLayout &DL) const {
20952 if (getEffectiveCallingConv(CallConv, isVarArg) !=
20953 CallingConv::ARM_AAPCS_VFP)
20954 return false;
20955
20956 HABaseType Base = HA_UNKNOWN;
20957 uint64_t Members = 0;
20958 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
20959 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("arm-isel")) { dbgs() << "isHA: " << IsHA <<
" "; Ty->dump(); } } while (false)
;
20960
20961 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
20962 return IsHA || IsIntArray;
20963}
20964
20965Register ARMTargetLowering::getExceptionPointerRegister(
20966 const Constant *PersonalityFn) const {
20967 // Platforms which do not use SjLj EH may return values in these registers
20968 // via the personality function.
20969 return Subtarget->useSjLjEH() ? Register() : ARM::R0;
20970}
20971
20972Register ARMTargetLowering::getExceptionSelectorRegister(
20973 const Constant *PersonalityFn) const {
20974 // Platforms which do not use SjLj EH may return values in these registers
20975 // via the personality function.
20976 return Subtarget->useSjLjEH() ? Register() : ARM::R1;
20977}
20978
20979void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
20980 // Update IsSplitCSR in ARMFunctionInfo.
20981 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
20982 AFI->setIsSplitCSR(true);
20983}
20984
20985void ARMTargetLowering::insertCopiesSplitCSR(
20986 MachineBasicBlock *Entry,
20987 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
20988 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
20989 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
20990 if (!IStart)
20991 return;
20992
20993 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20994 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
20995 MachineBasicBlock::iterator MBBI = Entry->begin();
20996 for (const MCPhysReg *I = IStart; *I; ++I) {
20997 const TargetRegisterClass *RC = nullptr;
20998 if (ARM::GPRRegClass.contains(*I))
20999 RC = &ARM::GPRRegClass;
21000 else if (ARM::DPRRegClass.contains(*I))
21001 RC = &ARM::DPRRegClass;
21002 else
21003 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 21003)
;
21004
21005 Register NewVR = MRI->createVirtualRegister(RC);
21006 // Create copy from CSR to a virtual register.
21007 // FIXME: this currently does not emit CFI pseudo-instructions, it works
21008 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
21009 // nounwind. If we want to generalize this later, we may need to emit
21010 // CFI pseudo-instructions.
21011 assert(Entry->getParent()->getFunction().hasFnAttribute((static_cast <bool> (Entry->getParent()->getFunction
().hasFnAttribute( Attribute::NoUnwind) && "Function should be nounwind in insertCopiesSplitCSR!"
) ? void (0) : __assert_fail ("Entry->getParent()->getFunction().hasFnAttribute( Attribute::NoUnwind) && \"Function should be nounwind in insertCopiesSplitCSR!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 21013, __extension__ __PRETTY_FUNCTION__))
21012 Attribute::NoUnwind) &&(static_cast <bool> (Entry->getParent()->getFunction
().hasFnAttribute( Attribute::NoUnwind) && "Function should be nounwind in insertCopiesSplitCSR!"
) ? void (0) : __assert_fail ("Entry->getParent()->getFunction().hasFnAttribute( Attribute::NoUnwind) && \"Function should be nounwind in insertCopiesSplitCSR!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 21013, __extension__ __PRETTY_FUNCTION__))
21013 "Function should be nounwind in insertCopiesSplitCSR!")(static_cast <bool> (Entry->getParent()->getFunction
().hasFnAttribute( Attribute::NoUnwind) && "Function should be nounwind in insertCopiesSplitCSR!"
) ? void (0) : __assert_fail ("Entry->getParent()->getFunction().hasFnAttribute( Attribute::NoUnwind) && \"Function should be nounwind in insertCopiesSplitCSR!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Target/ARM/ARMISelLowering.cpp"
, 21013, __extension__ __PRETTY_FUNCTION__))
;
21014 Entry->addLiveIn(*I);
21015 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
21016 .addReg(*I);
21017
21018 // Insert the copy-back instructions right before the terminator.
21019 for (auto *Exit : Exits)
21020 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
21021 TII->get(TargetOpcode::COPY), *I)
21022 .addReg(NewVR);
21023 }
21024}
21025
21026void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
21027 MF.getFrameInfo().computeMaxCallFrameSize(MF);
21028 TargetLoweringBase::finalizeLowering(MF);
21029}

/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/CodeGen/ValueTypes.h

1//===- CodeGen/ValueTypes.h - Low-Level Target independ. types --*- C++ -*-===//
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 set of low-level target independent types which various
10// values in the code generator are. This allows the target specific behavior
11// of instructions to be described to target independent passes.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CODEGEN_VALUETYPES_H
16#define LLVM_CODEGEN_VALUETYPES_H
17
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/MachineValueType.h"
20#include "llvm/Support/MathExtras.h"
21#include "llvm/Support/TypeSize.h"
22#include "llvm/Support/WithColor.h"
23#include <cassert>
24#include <cstdint>
25#include <string>
26
27namespace llvm {
28
29 class LLVMContext;
30 class Type;
31
32 /// Extended Value Type. Capable of holding value types which are not native
33 /// for any processor (such as the i12345 type), as well as the types an MVT
34 /// can represent.
35 struct EVT {
36 private:
37 MVT V = MVT::INVALID_SIMPLE_VALUE_TYPE;
38 Type *LLVMTy = nullptr;
39
40 public:
41 constexpr EVT() = default;
42 constexpr EVT(MVT::SimpleValueType SVT) : V(SVT) {}
43 constexpr EVT(MVT S) : V(S) {}
44
45 bool operator==(EVT VT) const {
46 return !(*this != VT);
47 }
48 bool operator!=(EVT VT) const {
49 if (V.SimpleTy != VT.V.SimpleTy)
50 return true;
51 if (V.SimpleTy == MVT::INVALID_SIMPLE_VALUE_TYPE)
52 return LLVMTy != VT.LLVMTy;
53 return false;
54 }
55
56 /// Returns the EVT that represents a floating-point type with the given
57 /// number of bits. There are two floating-point types with 128 bits - this
58 /// returns f128 rather than ppcf128.
59 static EVT getFloatingPointVT(unsigned BitWidth) {
60 return MVT::getFloatingPointVT(BitWidth);
61 }
62
63 /// Returns the EVT that represents an integer with the given number of
64 /// bits.
65 static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth) {
66 MVT M = MVT::getIntegerVT(BitWidth);
67 if (M.SimpleTy != MVT::INVALID_SIMPLE_VALUE_TYPE)
68 return M;
69 return getExtendedIntegerVT(Context, BitWidth);
70 }
71
72 /// Returns the EVT that represents a vector NumElements in length, where
73 /// each element is of type VT.
74 static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements,
75 bool IsScalable = false) {
76 MVT M = MVT::getVectorVT(VT.V, NumElements, IsScalable);
77 if (M.SimpleTy != MVT::INVALID_SIMPLE_VALUE_TYPE)
78 return M;
79 return getExtendedVectorVT(Context, VT, NumElements, IsScalable);
80 }
81
82 /// Returns the EVT that represents a vector EC.Min elements in length,
83 /// where each element is of type VT.
84 static EVT getVectorVT(LLVMContext &Context, EVT VT, ElementCount EC) {
85 MVT M = MVT::getVectorVT(VT.V, EC);
86 if (M.SimpleTy != MVT::INVALID_SIMPLE_VALUE_TYPE)
87 return M;
88 return getExtendedVectorVT(Context, VT, EC);
89 }
90
91 /// Return a vector with the same number of elements as this vector, but
92 /// with the element type converted to an integer type with the same
93 /// bitwidth.
94 EVT changeVectorElementTypeToInteger() const {
95 if (isSimple())
96 return getSimpleVT().changeVectorElementTypeToInteger();
97 return changeExtendedVectorElementTypeToInteger();
98 }
99
100 /// Return a VT for a vector type whose attributes match ourselves
101 /// with the exception of the element type that is chosen by the caller.
102 EVT changeVectorElementType(EVT EltVT) const {
103 if (isSimple()) {
104 assert(EltVT.isSimple() &&(static_cast <bool> (EltVT.isSimple() && "Can't change simple vector VT to have extended element VT"
) ? void (0) : __assert_fail ("EltVT.isSimple() && \"Can't change simple vector VT to have extended element VT\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/CodeGen/ValueTypes.h"
, 105, __extension__ __PRETTY_FUNCTION__))
105 "Can't change simple vector VT to have extended element VT")(static_cast <bool> (EltVT.isSimple() && "Can't change simple vector VT to have extended element VT"
) ? void (0) : __assert_fail ("EltVT.isSimple() && \"Can't change simple vector VT to have extended element VT\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/CodeGen/ValueTypes.h"
, 105, __extension__ __PRETTY_FUNCTION__))
;
106 return getSimpleVT().changeVectorElementType(EltVT.getSimpleVT());
107 }
108 return changeExtendedVectorElementType(EltVT);
109 }
110
111 /// Return the type converted to an equivalently sized integer or vector
112 /// with integer element type. Similar to changeVectorElementTypeToInteger,
113 /// but also handles scalars.
114 EVT changeTypeToInteger() {
115 if (isVector())
116 return changeVectorElementTypeToInteger();
117
118 if (isSimple())
119 return getSimpleVT().changeTypeToInteger();
120 return changeExtendedTypeToInteger();
121 }
122
123 /// Test if the given EVT has zero size, this will fail if called on a
124 /// scalable type
125 bool isZeroSized() const {
126 return !isScalableVector() && getSizeInBits() == 0;
127 }
128
129 /// Test if the given EVT is simple (as opposed to being extended).
130 bool isSimple() const {
131 return V.SimpleTy != MVT::INVALID_SIMPLE_VALUE_TYPE;
132 }
133
134 /// Test if the given EVT is extended (as opposed to being simple).
135 bool isExtended() const {
136 return !isSimple();
137 }
138
139 /// Return true if this is a FP or a vector FP type.
140 bool isFloatingPoint() const {
141 return isSimple() ? V.isFloatingPoint() : isExtendedFloatingPoint();
142 }
143
144 /// Return true if this is an integer or a vector integer type.
145 bool isInteger() const {
146 return isSimple() ? V.isInteger() : isExtendedInteger();
147 }
148
149 /// Return true if this is an integer, but not a vector.
150 bool isScalarInteger() const {
151 return isSimple() ? V.isScalarInteger() : isExtendedScalarInteger();
152 }
153
154 /// Return true if this is a vector value type.
155 bool isVector() const {
156 return isSimple() ? V.isVector() : isExtendedVector();
157 }
158
159 /// Return true if this is a vector type where the runtime
160 /// length is machine dependent
161 bool isScalableVector() const {
162 return isSimple() ? V.isScalableVector() : isExtendedScalableVector();
163 }
164
165 bool isFixedLengthVector() const {
166 return isSimple() ? V.isFixedLengthVector()
167 : isExtendedFixedLengthVector();
168 }
169
170 /// Return true if this is a 16-bit vector type.
171 bool is16BitVector() const {
172 return isSimple() ? V.is16BitVector() : isExtended16BitVector();
173 }
174
175 /// Return true if this is a 32-bit vector type.
176 bool is32BitVector() const {
177 return isSimple() ? V.is32BitVector() : isExtended32BitVector();
178 }
179
180 /// Return true if this is a 64-bit vector type.
181 bool is64BitVector() const {
182 return isSimple() ? V.is64BitVector() : isExtended64BitVector();
183 }
184
185 /// Return true if this is a 128-bit vector type.
186 bool is128BitVector() const {
187 return isSimple() ? V.is128BitVector() : isExtended128BitVector();
188 }
189
190 /// Return true if this is a 256-bit vector type.
191 bool is256BitVector() const {
192 return isSimple() ? V.is256BitVector() : isExtended256BitVector();
193 }
194
195 /// Return true if this is a 512-bit vector type.
196 bool is512BitVector() const {
197 return isSimple() ? V.is512BitVector() : isExtended512BitVector();
198 }
199
200 /// Return true if this is a 1024-bit vector type.
201 bool is1024BitVector() const {
202 return isSimple() ? V.is1024BitVector() : isExtended1024BitVector();
203 }
204
205 /// Return true if this is a 2048-bit vector type.
206 bool is2048BitVector() const {
207 return isSimple() ? V.is2048BitVector() : isExtended2048BitVector();
208 }
209
210 /// Return true if this is an overloaded type for TableGen.
211 bool isOverloaded() const {
212 return (V==MVT::iAny || V==MVT::fAny || V==MVT::vAny || V==MVT::iPTRAny);
213 }
214
215 /// Return true if the bit size is a multiple of 8.
216 bool isByteSized() const {
217 return !isZeroSized() && getSizeInBits().isKnownMultipleOf(8);
218 }
219
220 /// Return true if the size is a power-of-two number of bytes.
221 bool isRound() const {
222 if (isScalableVector())
223 return false;
224 unsigned BitSize = getSizeInBits();
225 return BitSize >= 8 && !(BitSize & (BitSize - 1));
226 }
227
228 /// Return true if this has the same number of bits as VT.
229 bool bitsEq(EVT VT) const {
230 if (EVT::operator==(VT)) return true;
231 return getSizeInBits() == VT.getSizeInBits();
232 }
233
234 /// Return true if we know at compile time this has more bits than VT.
235 bool knownBitsGT(EVT VT) const {
236 return TypeSize::isKnownGT(getSizeInBits(), VT.getSizeInBits());
237 }
238
239 /// Return true if we know at compile time this has more than or the same
240 /// bits as VT.
241 bool knownBitsGE(EVT VT) const {
242 return TypeSize::isKnownGE(getSizeInBits(), VT.getSizeInBits());
243 }
244
245 /// Return true if we know at compile time this has fewer bits than VT.
246 bool knownBitsLT(EVT VT) const {
247 return TypeSize::isKnownLT(getSizeInBits(), VT.getSizeInBits());
248 }
249
250 /// Return true if we know at compile time this has fewer than or the same
251 /// bits as VT.
252 bool knownBitsLE(EVT VT) const {
253 return TypeSize::isKnownLE(getSizeInBits(), VT.getSizeInBits());
254 }
255
256 /// Return true if this has more bits than VT.
257 bool bitsGT(EVT VT) const {
258 if (EVT::operator==(VT)) return false;
259 assert(isScalableVector() == VT.isScalableVector() &&(static_cast <bool> (isScalableVector() == VT.isScalableVector
() && "Comparison between scalable and fixed types") ?
void (0) : __assert_fail ("isScalableVector() == VT.isScalableVector() && \"Comparison between scalable and fixed types\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/CodeGen/ValueTypes.h"
, 260, __extension__ __PRETTY_FUNCTION__))
260 "Comparison between scalable and fixed types")(static_cast <bool> (isScalableVector() == VT.isScalableVector
() && "Comparison between scalable and fixed types") ?
void (0) : __assert_fail ("isScalableVector() == VT.isScalableVector() && \"Comparison between scalable and fixed types\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/CodeGen/ValueTypes.h"
, 260, __extension__ __PRETTY_FUNCTION__))
;
261 return knownBitsGT(VT);
262 }
263
264 /// Return true if this has no less bits than VT.
265 bool bitsGE(EVT VT) const {
266 if (EVT::operator==(VT)) return true;
267 assert(isScalableVector() == VT.isScalableVector() &&(static_cast <bool> (isScalableVector() == VT.isScalableVector
() && "Comparison between scalable and fixed types") ?
void (0) : __assert_fail ("isScalableVector() == VT.isScalableVector() && \"Comparison between scalable and fixed types\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/CodeGen/ValueTypes.h"
, 268, __extension__ __PRETTY_FUNCTION__))
268 "Comparison between scalable and fixed types")(static_cast <bool> (isScalableVector() == VT.isScalableVector
() && "Comparison between scalable and fixed types") ?
void (0) : __assert_fail ("isScalableVector() == VT.isScalableVector() && \"Comparison between scalable and fixed types\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/CodeGen/ValueTypes.h"
, 268, __extension__ __PRETTY_FUNCTION__))
;
269 return knownBitsGE(VT);
270 }
271
272 /// Return true if this has less bits than VT.
273 bool bitsLT(EVT VT) const {
274 if (EVT::operator==(VT)) return false;
275 assert(isScalableVector() == VT.isScalableVector() &&(static_cast <bool> (isScalableVector() == VT.isScalableVector
() && "Comparison between scalable and fixed types") ?
void (0) : __assert_fail ("isScalableVector() == VT.isScalableVector() && \"Comparison between scalable and fixed types\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/CodeGen/ValueTypes.h"
, 276, __extension__ __PRETTY_FUNCTION__))
276 "Comparison between scalable and fixed types")(static_cast <bool> (isScalableVector() == VT.isScalableVector
() && "Comparison between scalable and fixed types") ?
void (0) : __assert_fail ("isScalableVector() == VT.isScalableVector() && \"Comparison between scalable and fixed types\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/CodeGen/ValueTypes.h"
, 276, __extension__ __PRETTY_FUNCTION__))
;
277 return knownBitsLT(VT);
278 }
279
280 /// Return true if this has no more bits than VT.
281 bool bitsLE(EVT VT) const {
282 if (EVT::operator==(VT)) return true;
283 assert(isScalableVector() == VT.isScalableVector() &&(static_cast <bool> (isScalableVector() == VT.isScalableVector
() && "Comparison between scalable and fixed types") ?
void (0) : __assert_fail ("isScalableVector() == VT.isScalableVector() && \"Comparison between scalable and fixed types\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/CodeGen/ValueTypes.h"
, 284, __extension__ __PRETTY_FUNCTION__))
284 "Comparison between scalable and fixed types")(static_cast <bool> (isScalableVector() == VT.isScalableVector
() && "Comparison between scalable and fixed types") ?
void (0) : __assert_fail ("isScalableVector() == VT.isScalableVector() && \"Comparison between scalable and fixed types\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/CodeGen/ValueTypes.h"
, 284, __extension__ __PRETTY_FUNCTION__))
;
285 return knownBitsLE(VT);
286 }
287
288 /// Return the SimpleValueType held in the specified simple EVT.
289 MVT getSimpleVT() const {
290 assert(isSimple() && "Expected a SimpleValueType!")(static_cast <bool> (isSimple() && "Expected a SimpleValueType!"
) ? void (0) : __assert_fail ("isSimple() && \"Expected a SimpleValueType!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/CodeGen/ValueTypes.h"
, 290, __extension__ __PRETTY_FUNCTION__))
;
291 return V;
292 }
293
294 /// If this is a vector type, return the element type, otherwise return
295 /// this.
296 EVT getScalarType() const {
297 return isVector() ? getVectorElementType() : *this;
298 }
299
300 /// Given a vector type, return the type of each element.
301 EVT getVectorElementType() const {
302 assert(isVector() && "Invalid vector type!")(static_cast <bool> (isVector() && "Invalid vector type!"
) ? void (0) : __assert_fail ("isVector() && \"Invalid vector type!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/CodeGen/ValueTypes.h"
, 302, __extension__ __PRETTY_FUNCTION__))
;
303 if (isSimple())
304 return V.getVectorElementType();
305 return getExtendedVectorElementType();
306 }
307
308 /// Given a vector type, return the number of elements it contains.
309 unsigned getVectorNumElements() const {
310 assert(isVector() && "Invalid vector type!")(static_cast <bool> (isVector() && "Invalid vector type!"
) ? void (0) : __assert_fail ("isVector() && \"Invalid vector type!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/CodeGen/ValueTypes.h"
, 310, __extension__ __PRETTY_FUNCTION__))
;
14
Assuming the condition is true
15
'?' condition is true
311
312 if (isScalableVector())
16
Assuming the condition is false
313 llvm::reportInvalidSizeRequest(
314 "Possible incorrect use of EVT::getVectorNumElements() for "
315 "scalable vector. Scalable flag may be dropped, use "
316 "EVT::getVectorElementCount() instead");
317
318 return isSimple() ? V.getVectorNumElements()
17
Taking false branch
18
'?' condition is false
19
Returning value
319 : getExtendedVectorNumElements();
320 }
321
322 // Given a (possibly scalable) vector type, return the ElementCount
323 ElementCount getVectorElementCount() const {
324 assert((isVector()) && "Invalid vector type!")(static_cast <bool> ((isVector()) && "Invalid vector type!"
) ? void (0) : __assert_fail ("(isVector()) && \"Invalid vector type!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/CodeGen/ValueTypes.h"
, 324, __extension__ __PRETTY_FUNCTION__))
;
325 if (isSimple())
326 return V.getVectorElementCount();
327
328 return getExtendedVectorElementCount();
329 }
330
331 /// Given a vector type, return the minimum number of elements it contains.
332 unsigned getVectorMinNumElements() const {
333 return getVectorElementCount().getKnownMinValue();
334 }
335
336 /// Return the size of the specified value type in bits.
337 ///
338 /// If the value type is a scalable vector type, the scalable property will
339 /// be set and the runtime size will be a positive integer multiple of the
340 /// base size.
341 TypeSize getSizeInBits() const {
342 if (isSimple())
343 return V.getSizeInBits();
344 return getExtendedSizeInBits();
345 }
346
347 /// Return the size of the specified fixed width value type in bits. The
348 /// function will assert if the type is scalable.
349 uint64_t getFixedSizeInBits() const {
350 return getSizeInBits().getFixedSize();
351 }
352
353 uint64_t getScalarSizeInBits() const {
354 return getScalarType().getSizeInBits().getFixedSize();
355 }
356
357 /// Return the number of bytes overwritten by a store of the specified value
358 /// type.
359 ///
360 /// If the value type is a scalable vector type, the scalable property will
361 /// be set and the runtime size will be a positive integer multiple of the
362 /// base size.
363 TypeSize getStoreSize() const {
364 TypeSize BaseSize = getSizeInBits();
365 return {(BaseSize.getKnownMinSize() + 7) / 8, BaseSize.isScalable()};
366 }
367
368 /// Return the number of bits overwritten by a store of the specified value
369 /// type.
370 ///
371 /// If the value type is a scalable vector type, the scalable property will
372 /// be set and the runtime size will be a positive integer multiple of the
373 /// base size.
374 TypeSize getStoreSizeInBits() const {
375 return getStoreSize() * 8;
376 }
377
378 /// Rounds the bit-width of the given integer EVT up to the nearest power of
379 /// two (and at least to eight), and returns the integer EVT with that
380 /// number of bits.
381 EVT getRoundIntegerType(LLVMContext &Context) const {
382 assert(isInteger() && !isVector() && "Invalid integer type!")(static_cast <bool> (isInteger() && !isVector()
&& "Invalid integer type!") ? void (0) : __assert_fail
("isInteger() && !isVector() && \"Invalid integer type!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/CodeGen/ValueTypes.h"
, 382, __extension__ __PRETTY_FUNCTION__))
;
383 unsigned BitWidth = getSizeInBits();
384 if (BitWidth <= 8)
385 return EVT(MVT::i8);
386 return getIntegerVT(Context, 1 << Log2_32_Ceil(BitWidth));
387 }
388
389 /// Finds the smallest simple value type that is greater than or equal to
390 /// half the width of this EVT. If no simple value type can be found, an
391 /// extended integer value type of half the size (rounded up) is returned.
392 EVT getHalfSizedIntegerVT(LLVMContext &Context) const {
393 assert(isInteger() && !isVector() && "Invalid integer type!")(static_cast <bool> (isInteger() && !isVector()
&& "Invalid integer type!") ? void (0) : __assert_fail
("isInteger() && !isVector() && \"Invalid integer type!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/CodeGen/ValueTypes.h"
, 393, __extension__ __PRETTY_FUNCTION__))
;
394 unsigned EVTSize = getSizeInBits();
395 for (unsigned IntVT = MVT::FIRST_INTEGER_VALUETYPE;
396 IntVT <= MVT::LAST_INTEGER_VALUETYPE; ++IntVT) {
397 EVT HalfVT = EVT((MVT::SimpleValueType)IntVT);
398 if (HalfVT.getSizeInBits() * 2 >= EVTSize)
399 return HalfVT;
400 }
401 return getIntegerVT(Context, (EVTSize + 1) / 2);
402 }
403
404 /// Return a VT for an integer vector type with the size of the
405 /// elements doubled. The typed returned may be an extended type.
406 EVT widenIntegerVectorElementType(LLVMContext &Context) const {
407 EVT EltVT = getVectorElementType();
408 EltVT = EVT::getIntegerVT(Context, 2 * EltVT.getSizeInBits());
409 return EVT::getVectorVT(Context, EltVT, getVectorElementCount());
410 }
411
412 // Return a VT for a vector type with the same element type but
413 // half the number of elements. The type returned may be an
414 // extended type.
415 EVT getHalfNumVectorElementsVT(LLVMContext &Context) const {
416 EVT EltVT = getVectorElementType();
417 auto EltCnt = getVectorElementCount();
418 assert(EltCnt.isKnownEven() && "Splitting vector, but not in half!")(static_cast <bool> (EltCnt.isKnownEven() && "Splitting vector, but not in half!"
) ? void (0) : __assert_fail ("EltCnt.isKnownEven() && \"Splitting vector, but not in half!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include/llvm/CodeGen/ValueTypes.h"
, 418, __extension__ __PRETTY_FUNCTION__))
;
419 return EVT::getVectorVT(Context, EltVT, EltCnt.divideCoefficientBy(2));
420 }
421
422 // Return a VT for a vector type with the same element type but
423 // double the number of elements. The type returned may be an
424 // extended type.
425 EVT getDoubleNumVectorElementsVT(LLVMContext &Context) const {
426 EVT EltVT = getVectorElementType();
427 auto EltCnt = getVectorElementCount();
428 return EVT::getVectorVT(Context, EltVT, EltCnt * 2);
429 }
430
431 /// Returns true if the given vector is a power of 2.
432 bool isPow2VectorType() const {
433 unsigned NElts = getVectorMinNumElements();
434 return !(NElts & (NElts - 1));
435 }
436
437 /// Widens the length of the given vector EVT up to the nearest power of 2
438 /// and returns that type.
439 EVT getPow2VectorType(LLVMContext &Context) const {
440 if (!isPow2VectorType()) {
441 ElementCount NElts = getVectorElementCount();
442 unsigned NewMinCount = 1 << Log2_32_Ceil(NElts.getKnownMinValue());
443 NElts = ElementCount::get(NewMinCount, NElts.isScalable());
444 return EVT::getVectorVT(Context, getVectorElementType(), NElts);
445 }
446 else {
447 return *this;
448 }
449 }
450
451 /// This function returns value type as a string, e.g. "i32".
452 std::string getEVTString() const;
453
454 /// This method returns an LLVM type corresponding to the specified EVT.
455 /// For integer types, this returns an unsigned type. Note that this will
456 /// abort for types that cannot be represented.
457 Type *getTypeForEVT(LLVMContext &Context) const;
458
459 /// Return the value type corresponding to the specified type.
460 /// This returns all pointers as iPTR. If HandleUnknown is true, unknown
461 /// types are returned as Other, otherwise they are invalid.
462 static EVT getEVT(Type *Ty, bool HandleUnknown = false);
463
464 intptr_t getRawBits() const {
465 if (isSimple())
466 return V.SimpleTy;
467 else
468 return (intptr_t)(LLVMTy);
469 }
470
471 /// A meaningless but well-behaved order, useful for constructing
472 /// containers.
473 struct compareRawBits {
474 bool operator()(EVT L, EVT R) const {
475 if (L.V.SimpleTy == R.V.SimpleTy)
476 return L.LLVMTy < R.LLVMTy;
477 else
478 return L.V.SimpleTy < R.V.SimpleTy;
479 }
480 };
481
482 private:
483 // Methods for handling the Extended-type case in functions above.
484 // These are all out-of-line to prevent users of this header file
485 // from having a dependency on Type.h.
486 EVT changeExtendedTypeToInteger() const;
487 EVT changeExtendedVectorElementType(EVT EltVT) const;
488 EVT changeExtendedVectorElementTypeToInteger() const;
489 static EVT getExtendedIntegerVT(LLVMContext &C, unsigned BitWidth);
490 static EVT getExtendedVectorVT(LLVMContext &C, EVT VT, unsigned NumElements,
491 bool IsScalable);
492 static EVT getExtendedVectorVT(LLVMContext &Context, EVT VT,
493 ElementCount EC);
494 bool isExtendedFloatingPoint() const LLVM_READONLY__attribute__((__pure__));
495 bool isExtendedInteger() const LLVM_READONLY__attribute__((__pure__));
496 bool isExtendedScalarInteger() const LLVM_READONLY__attribute__((__pure__));
497 bool isExtendedVector() const LLVM_READONLY__attribute__((__pure__));
498 bool isExtended16BitVector() const LLVM_READONLY__attribute__((__pure__));
499 bool isExtended32BitVector() const LLVM_READONLY__attribute__((__pure__));
500 bool isExtended64BitVector() const LLVM_READONLY__attribute__((__pure__));
501 bool isExtended128BitVector() const LLVM_READONLY__attribute__((__pure__));
502 bool isExtended256BitVector() const LLVM_READONLY__attribute__((__pure__));
503 bool isExtended512BitVector() const LLVM_READONLY__attribute__((__pure__));
504 bool isExtended1024BitVector() const LLVM_READONLY__attribute__((__pure__));
505 bool isExtended2048BitVector() const LLVM_READONLY__attribute__((__pure__));
506 bool isExtendedFixedLengthVector() const LLVM_READONLY__attribute__((__pure__));
507 bool isExtendedScalableVector() const LLVM_READONLY__attribute__((__pure__));
508 EVT getExtendedVectorElementType() const;
509 unsigned getExtendedVectorNumElements() const LLVM_READONLY__attribute__((__pure__));
510 ElementCount getExtendedVectorElementCount() const LLVM_READONLY__attribute__((__pure__));
511 TypeSize getExtendedSizeInBits() const LLVM_READONLY__attribute__((__pure__));
512 };
513
514} // end namespace llvm
515
516#endif // LLVM_CODEGEN_VALUETYPES_H