Bug Summary

File:llvm/include/llvm/CodeGen/SelectionDAGNodes.h
Warning:line 1122, column 10
Called C++ object pointer is null

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 X86ISelLowering.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-13~++20210726100616+dead50d4427c/build-llvm/lib/Target/X86 -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/lib/Target/X86 -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86 -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/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-13/lib/clang/13.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-13~++20210726100616+dead50d4427c/build-llvm/lib/Target/X86 -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c=. -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-07-26-235520-9401-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp

/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp

1//===-- X86ISelLowering.cpp - X86 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 X86 uses to lower LLVM code into a
10// selection DAG.
11//
12//===----------------------------------------------------------------------===//
13
14#include "X86ISelLowering.h"
15#include "MCTargetDesc/X86ShuffleDecode.h"
16#include "X86.h"
17#include "X86CallingConv.h"
18#include "X86FrameLowering.h"
19#include "X86InstrBuilder.h"
20#include "X86IntrinsicsInfo.h"
21#include "X86MachineFunctionInfo.h"
22#include "X86TargetMachine.h"
23#include "X86TargetObjectFile.h"
24#include "llvm/ADT/SmallBitVector.h"
25#include "llvm/ADT/SmallSet.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/ADT/StringExtras.h"
28#include "llvm/ADT/StringSwitch.h"
29#include "llvm/Analysis/BlockFrequencyInfo.h"
30#include "llvm/Analysis/EHPersonalities.h"
31#include "llvm/Analysis/ObjCARCUtil.h"
32#include "llvm/Analysis/ProfileSummaryInfo.h"
33#include "llvm/Analysis/VectorUtils.h"
34#include "llvm/CodeGen/IntrinsicLowering.h"
35#include "llvm/CodeGen/MachineFrameInfo.h"
36#include "llvm/CodeGen/MachineFunction.h"
37#include "llvm/CodeGen/MachineInstrBuilder.h"
38#include "llvm/CodeGen/MachineJumpTableInfo.h"
39#include "llvm/CodeGen/MachineLoopInfo.h"
40#include "llvm/CodeGen/MachineModuleInfo.h"
41#include "llvm/CodeGen/MachineRegisterInfo.h"
42#include "llvm/CodeGen/TargetLowering.h"
43#include "llvm/CodeGen/WinEHFuncInfo.h"
44#include "llvm/IR/CallingConv.h"
45#include "llvm/IR/Constants.h"
46#include "llvm/IR/DerivedTypes.h"
47#include "llvm/IR/DiagnosticInfo.h"
48#include "llvm/IR/Function.h"
49#include "llvm/IR/GlobalAlias.h"
50#include "llvm/IR/GlobalVariable.h"
51#include "llvm/IR/Instructions.h"
52#include "llvm/IR/Intrinsics.h"
53#include "llvm/IR/IRBuilder.h"
54#include "llvm/MC/MCAsmInfo.h"
55#include "llvm/MC/MCContext.h"
56#include "llvm/MC/MCExpr.h"
57#include "llvm/MC/MCSymbol.h"
58#include "llvm/Support/CommandLine.h"
59#include "llvm/Support/Debug.h"
60#include "llvm/Support/ErrorHandling.h"
61#include "llvm/Support/KnownBits.h"
62#include "llvm/Support/MathExtras.h"
63#include "llvm/Target/TargetOptions.h"
64#include <algorithm>
65#include <bitset>
66#include <cctype>
67#include <numeric>
68using namespace llvm;
69
70#define DEBUG_TYPE"x86-isel" "x86-isel"
71
72STATISTIC(NumTailCalls, "Number of tail calls")static llvm::Statistic NumTailCalls = {"x86-isel", "NumTailCalls"
, "Number of tail calls"}
;
73
74static cl::opt<int> ExperimentalPrefLoopAlignment(
75 "x86-experimental-pref-loop-alignment", cl::init(4),
76 cl::desc(
77 "Sets the preferable loop alignment for experiments (as log2 bytes)"
78 "(the last x86-experimental-pref-loop-alignment bits"
79 " of the loop header PC will be 0)."),
80 cl::Hidden);
81
82static cl::opt<int> ExperimentalPrefInnermostLoopAlignment(
83 "x86-experimental-pref-innermost-loop-alignment", cl::init(4),
84 cl::desc(
85 "Sets the preferable loop alignment for experiments (as log2 bytes) "
86 "for innermost loops only. If specified, this option overrides "
87 "alignment set by x86-experimental-pref-loop-alignment."),
88 cl::Hidden);
89
90static cl::opt<bool> MulConstantOptimization(
91 "mul-constant-optimization", cl::init(true),
92 cl::desc("Replace 'mul x, Const' with more effective instructions like "
93 "SHIFT, LEA, etc."),
94 cl::Hidden);
95
96static cl::opt<bool> ExperimentalUnorderedISEL(
97 "x86-experimental-unordered-atomic-isel", cl::init(false),
98 cl::desc("Use LoadSDNode and StoreSDNode instead of "
99 "AtomicSDNode for unordered atomic loads and "
100 "stores respectively."),
101 cl::Hidden);
102
103/// Call this when the user attempts to do something unsupported, like
104/// returning a double without SSE2 enabled on x86_64. This is not fatal, unlike
105/// report_fatal_error, so calling code should attempt to recover without
106/// crashing.
107static void errorUnsupported(SelectionDAG &DAG, const SDLoc &dl,
108 const char *Msg) {
109 MachineFunction &MF = DAG.getMachineFunction();
110 DAG.getContext()->diagnose(
111 DiagnosticInfoUnsupported(MF.getFunction(), Msg, dl.getDebugLoc()));
112}
113
114X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
115 const X86Subtarget &STI)
116 : TargetLowering(TM), Subtarget(STI) {
117 bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
118 X86ScalarSSEf64 = Subtarget.hasSSE2();
119 X86ScalarSSEf32 = Subtarget.hasSSE1();
120 MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0));
121
122 // Set up the TargetLowering object.
123
124 // X86 is weird. It always uses i8 for shift amounts and setcc results.
125 setBooleanContents(ZeroOrOneBooleanContent);
126 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
127 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
128
129 // For 64-bit, since we have so many registers, use the ILP scheduler.
130 // For 32-bit, use the register pressure specific scheduling.
131 // For Atom, always use ILP scheduling.
132 if (Subtarget.isAtom())
133 setSchedulingPreference(Sched::ILP);
134 else if (Subtarget.is64Bit())
135 setSchedulingPreference(Sched::ILP);
136 else
137 setSchedulingPreference(Sched::RegPressure);
138 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
139 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
140
141 // Bypass expensive divides and use cheaper ones.
142 if (TM.getOptLevel() >= CodeGenOpt::Default) {
143 if (Subtarget.hasSlowDivide32())
144 addBypassSlowDiv(32, 8);
145 if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
146 addBypassSlowDiv(64, 32);
147 }
148
149 // Setup Windows compiler runtime calls.
150 if (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()) {
151 static const struct {
152 const RTLIB::Libcall Op;
153 const char * const Name;
154 const CallingConv::ID CC;
155 } LibraryCalls[] = {
156 { RTLIB::SDIV_I64, "_alldiv", CallingConv::X86_StdCall },
157 { RTLIB::UDIV_I64, "_aulldiv", CallingConv::X86_StdCall },
158 { RTLIB::SREM_I64, "_allrem", CallingConv::X86_StdCall },
159 { RTLIB::UREM_I64, "_aullrem", CallingConv::X86_StdCall },
160 { RTLIB::MUL_I64, "_allmul", CallingConv::X86_StdCall },
161 };
162
163 for (const auto &LC : LibraryCalls) {
164 setLibcallName(LC.Op, LC.Name);
165 setLibcallCallingConv(LC.Op, LC.CC);
166 }
167 }
168
169 if (Subtarget.getTargetTriple().isOSMSVCRT()) {
170 // MSVCRT doesn't have powi; fall back to pow
171 setLibcallName(RTLIB::POWI_F32, nullptr);
172 setLibcallName(RTLIB::POWI_F64, nullptr);
173 }
174
175 // If we don't have cmpxchg8b(meaing this is a 386/486), limit atomic size to
176 // 32 bits so the AtomicExpandPass will expand it so we don't need cmpxchg8b.
177 // FIXME: Should we be limiting the atomic size on other configs? Default is
178 // 1024.
179 if (!Subtarget.hasCmpxchg8b())
180 setMaxAtomicSizeInBitsSupported(32);
181
182 // Set up the register classes.
183 addRegisterClass(MVT::i8, &X86::GR8RegClass);
184 addRegisterClass(MVT::i16, &X86::GR16RegClass);
185 addRegisterClass(MVT::i32, &X86::GR32RegClass);
186 if (Subtarget.is64Bit())
187 addRegisterClass(MVT::i64, &X86::GR64RegClass);
188
189 for (MVT VT : MVT::integer_valuetypes())
190 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
191
192 // We don't accept any truncstore of integer registers.
193 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
194 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
195 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
196 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
197 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
198 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
199
200 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
201
202 // SETOEQ and SETUNE require checking two conditions.
203 for (auto VT : {MVT::f32, MVT::f64, MVT::f80}) {
204 setCondCodeAction(ISD::SETOEQ, VT, Expand);
205 setCondCodeAction(ISD::SETUNE, VT, Expand);
206 }
207
208 // Integer absolute.
209 if (Subtarget.hasCMov()) {
210 setOperationAction(ISD::ABS , MVT::i16 , Custom);
211 setOperationAction(ISD::ABS , MVT::i32 , Custom);
212 if (Subtarget.is64Bit())
213 setOperationAction(ISD::ABS , MVT::i64 , Custom);
214 }
215
216 // Funnel shifts.
217 for (auto ShiftOp : {ISD::FSHL, ISD::FSHR}) {
218 // For slow shld targets we only lower for code size.
219 LegalizeAction ShiftDoubleAction = Subtarget.isSHLDSlow() ? Custom : Legal;
220
221 setOperationAction(ShiftOp , MVT::i8 , Custom);
222 setOperationAction(ShiftOp , MVT::i16 , Custom);
223 setOperationAction(ShiftOp , MVT::i32 , ShiftDoubleAction);
224 if (Subtarget.is64Bit())
225 setOperationAction(ShiftOp , MVT::i64 , ShiftDoubleAction);
226 }
227
228 if (!Subtarget.useSoftFloat()) {
229 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
230 // operation.
231 setOperationAction(ISD::UINT_TO_FP, MVT::i8, Promote);
232 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i8, Promote);
233 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
234 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i16, Promote);
235 // We have an algorithm for SSE2, and we turn this into a 64-bit
236 // FILD or VCVTUSI2SS/SD for other targets.
237 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
238 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
239 // We have an algorithm for SSE2->double, and we turn this into a
240 // 64-bit FILD followed by conditional FADD for other targets.
241 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
242 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
243
244 // Promote i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
245 // this operation.
246 setOperationAction(ISD::SINT_TO_FP, MVT::i8, Promote);
247 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i8, Promote);
248 // SSE has no i16 to fp conversion, only i32. We promote in the handler
249 // to allow f80 to use i16 and f64 to use i16 with sse1 only
250 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
251 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i16, Custom);
252 // f32 and f64 cases are Legal with SSE1/SSE2, f80 case is not
253 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
254 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
255 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
256 // are Legal, f80 is custom lowered.
257 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
258 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
259
260 // Promote i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
261 // this operation.
262 setOperationAction(ISD::FP_TO_SINT, MVT::i8, Promote);
263 // FIXME: This doesn't generate invalid exception when it should. PR44019.
264 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i8, Promote);
265 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom);
266 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i16, Custom);
267 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
268 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
269 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
270 // are Legal, f80 is custom lowered.
271 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
272 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
273
274 // Handle FP_TO_UINT by promoting the destination to a larger signed
275 // conversion.
276 setOperationAction(ISD::FP_TO_UINT, MVT::i8, Promote);
277 // FIXME: This doesn't generate invalid exception when it should. PR44019.
278 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i8, Promote);
279 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
280 // FIXME: This doesn't generate invalid exception when it should. PR44019.
281 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i16, Promote);
282 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
283 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
284 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
285 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
286
287 setOperationAction(ISD::LRINT, MVT::f32, Custom);
288 setOperationAction(ISD::LRINT, MVT::f64, Custom);
289 setOperationAction(ISD::LLRINT, MVT::f32, Custom);
290 setOperationAction(ISD::LLRINT, MVT::f64, Custom);
291
292 if (!Subtarget.is64Bit()) {
293 setOperationAction(ISD::LRINT, MVT::i64, Custom);
294 setOperationAction(ISD::LLRINT, MVT::i64, Custom);
295 }
296 }
297
298 if (Subtarget.hasSSE2()) {
299 // Custom lowering for saturating float to int conversions.
300 // We handle promotion to larger result types manually.
301 for (MVT VT : { MVT::i8, MVT::i16, MVT::i32 }) {
302 setOperationAction(ISD::FP_TO_UINT_SAT, VT, Custom);
303 setOperationAction(ISD::FP_TO_SINT_SAT, VT, Custom);
304 }
305 if (Subtarget.is64Bit()) {
306 setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i64, Custom);
307 setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i64, Custom);
308 }
309 }
310
311 // Handle address space casts between mixed sized pointers.
312 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
313 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
314
315 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
316 if (!X86ScalarSSEf64) {
317 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
318 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
319 if (Subtarget.is64Bit()) {
320 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
321 // Without SSE, i64->f64 goes through memory.
322 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
323 }
324 } else if (!Subtarget.is64Bit())
325 setOperationAction(ISD::BITCAST , MVT::i64 , Custom);
326
327 // Scalar integer divide and remainder are lowered to use operations that
328 // produce two results, to match the available instructions. This exposes
329 // the two-result form to trivial CSE, which is able to combine x/y and x%y
330 // into a single instruction.
331 //
332 // Scalar integer multiply-high is also lowered to use two-result
333 // operations, to match the available instructions. However, plain multiply
334 // (low) operations are left as Legal, as there are single-result
335 // instructions for this in x86. Using the two-result multiply instructions
336 // when both high and low results are needed must be arranged by dagcombine.
337 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
338 setOperationAction(ISD::MULHS, VT, Expand);
339 setOperationAction(ISD::MULHU, VT, Expand);
340 setOperationAction(ISD::SDIV, VT, Expand);
341 setOperationAction(ISD::UDIV, VT, Expand);
342 setOperationAction(ISD::SREM, VT, Expand);
343 setOperationAction(ISD::UREM, VT, Expand);
344 }
345
346 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
347 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
348 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
349 MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
350 setOperationAction(ISD::BR_CC, VT, Expand);
351 setOperationAction(ISD::SELECT_CC, VT, Expand);
352 }
353 if (Subtarget.is64Bit())
354 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
355 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
356 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
357 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
358
359 setOperationAction(ISD::FREM , MVT::f32 , Expand);
360 setOperationAction(ISD::FREM , MVT::f64 , Expand);
361 setOperationAction(ISD::FREM , MVT::f80 , Expand);
362 setOperationAction(ISD::FREM , MVT::f128 , Expand);
363
364 if (!Subtarget.useSoftFloat() && Subtarget.hasX87()) {
365 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
366 setOperationAction(ISD::SET_ROUNDING , MVT::Other, Custom);
367 }
368
369 // Promote the i8 variants and force them on up to i32 which has a shorter
370 // encoding.
371 setOperationPromotedToType(ISD::CTTZ , MVT::i8 , MVT::i32);
372 setOperationPromotedToType(ISD::CTTZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
373
374 if (Subtarget.hasBMI()) {
375 // Promote the i16 zero undef variant and force it on up to i32 when tzcnt
376 // is enabled.
377 setOperationPromotedToType(ISD::CTTZ_ZERO_UNDEF, MVT::i16, MVT::i32);
378 } else {
379 setOperationAction(ISD::CTTZ, MVT::i16, Custom);
380 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
381 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Legal);
382 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Legal);
383 if (Subtarget.is64Bit()) {
384 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
385 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Legal);
386 }
387 }
388
389 if (Subtarget.hasLZCNT()) {
390 // When promoting the i8 variants, force them to i32 for a shorter
391 // encoding.
392 setOperationPromotedToType(ISD::CTLZ , MVT::i8 , MVT::i32);
393 setOperationPromotedToType(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
394 } else {
395 for (auto VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64}) {
396 if (VT == MVT::i64 && !Subtarget.is64Bit())
397 continue;
398 setOperationAction(ISD::CTLZ , VT, Custom);
399 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
400 }
401 }
402
403 for (auto Op : {ISD::FP16_TO_FP, ISD::STRICT_FP16_TO_FP, ISD::FP_TO_FP16,
404 ISD::STRICT_FP_TO_FP16}) {
405 // Special handling for half-precision floating point conversions.
406 // If we don't have F16C support, then lower half float conversions
407 // into library calls.
408 setOperationAction(
409 Op, MVT::f32,
410 (!Subtarget.useSoftFloat() && Subtarget.hasF16C()) ? Custom : Expand);
411 // There's never any support for operations beyond MVT::f32.
412 setOperationAction(Op, MVT::f64, Expand);
413 setOperationAction(Op, MVT::f80, Expand);
414 setOperationAction(Op, MVT::f128, Expand);
415 }
416
417 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
418 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
419 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
420 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f16, Expand);
421 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
422 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
423 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
424 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
425
426 setOperationAction(ISD::PARITY, MVT::i8, Custom);
427 if (Subtarget.hasPOPCNT()) {
428 setOperationPromotedToType(ISD::CTPOP, MVT::i8, MVT::i32);
429 } else {
430 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
431 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
432 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
433 if (Subtarget.is64Bit())
434 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
435 else
436 setOperationAction(ISD::CTPOP , MVT::i64 , Custom);
437
438 setOperationAction(ISD::PARITY, MVT::i16, Custom);
439 setOperationAction(ISD::PARITY, MVT::i32, Custom);
440 if (Subtarget.is64Bit())
441 setOperationAction(ISD::PARITY, MVT::i64, Custom);
442 }
443
444 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
445
446 if (!Subtarget.hasMOVBE())
447 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
448
449 // X86 wants to expand cmov itself.
450 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
451 setOperationAction(ISD::SELECT, VT, Custom);
452 setOperationAction(ISD::SETCC, VT, Custom);
453 setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
454 setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
455 }
456 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
457 if (VT == MVT::i64 && !Subtarget.is64Bit())
458 continue;
459 setOperationAction(ISD::SELECT, VT, Custom);
460 setOperationAction(ISD::SETCC, VT, Custom);
461 }
462
463 // Custom action for SELECT MMX and expand action for SELECT_CC MMX
464 setOperationAction(ISD::SELECT, MVT::x86mmx, Custom);
465 setOperationAction(ISD::SELECT_CC, MVT::x86mmx, Expand);
466
467 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
468 // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
469 // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
470 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
471 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
472 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
473 if (TM.Options.ExceptionModel == ExceptionHandling::SjLj)
474 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
475
476 // Darwin ABI issue.
477 for (auto VT : { MVT::i32, MVT::i64 }) {
478 if (VT == MVT::i64 && !Subtarget.is64Bit())
479 continue;
480 setOperationAction(ISD::ConstantPool , VT, Custom);
481 setOperationAction(ISD::JumpTable , VT, Custom);
482 setOperationAction(ISD::GlobalAddress , VT, Custom);
483 setOperationAction(ISD::GlobalTLSAddress, VT, Custom);
484 setOperationAction(ISD::ExternalSymbol , VT, Custom);
485 setOperationAction(ISD::BlockAddress , VT, Custom);
486 }
487
488 // 64-bit shl, sra, srl (iff 32-bit x86)
489 for (auto VT : { MVT::i32, MVT::i64 }) {
490 if (VT == MVT::i64 && !Subtarget.is64Bit())
491 continue;
492 setOperationAction(ISD::SHL_PARTS, VT, Custom);
493 setOperationAction(ISD::SRA_PARTS, VT, Custom);
494 setOperationAction(ISD::SRL_PARTS, VT, Custom);
495 }
496
497 if (Subtarget.hasSSEPrefetch() || Subtarget.has3DNow())
498 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
499
500 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
501
502 // Expand certain atomics
503 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
504 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
505 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
506 setOperationAction(ISD::ATOMIC_LOAD_ADD, VT, Custom);
507 setOperationAction(ISD::ATOMIC_LOAD_OR, VT, Custom);
508 setOperationAction(ISD::ATOMIC_LOAD_XOR, VT, Custom);
509 setOperationAction(ISD::ATOMIC_LOAD_AND, VT, Custom);
510 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
511 }
512
513 if (!Subtarget.is64Bit())
514 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
515
516 if (Subtarget.hasCmpxchg16b()) {
517 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
518 }
519
520 // FIXME - use subtarget debug flags
521 if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
522 !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
523 TM.Options.ExceptionModel != ExceptionHandling::SjLj) {
524 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
525 }
526
527 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
528 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
529
530 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
531 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
532
533 setOperationAction(ISD::TRAP, MVT::Other, Legal);
534 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
535 setOperationAction(ISD::UBSANTRAP, MVT::Other, Legal);
536
537 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
538 setOperationAction(ISD::VASTART , MVT::Other, Custom);
539 setOperationAction(ISD::VAEND , MVT::Other, Expand);
540 bool Is64Bit = Subtarget.is64Bit();
541 setOperationAction(ISD::VAARG, MVT::Other, Is64Bit ? Custom : Expand);
542 setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
543
544 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
545 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
546
547 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
548
549 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
550 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
551 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
552
553 if (!Subtarget.useSoftFloat() && X86ScalarSSEf64) {
554 // f32 and f64 use SSE.
555 // Set up the FP register classes.
556 addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
557 : &X86::FR32RegClass);
558 addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
559 : &X86::FR64RegClass);
560
561 // Disable f32->f64 extload as we can only generate this in one instruction
562 // under optsize. So its easier to pattern match (fpext (load)) for that
563 // case instead of needing to emit 2 instructions for extload in the
564 // non-optsize case.
565 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
566
567 for (auto VT : { MVT::f32, MVT::f64 }) {
568 // Use ANDPD to simulate FABS.
569 setOperationAction(ISD::FABS, VT, Custom);
570
571 // Use XORP to simulate FNEG.
572 setOperationAction(ISD::FNEG, VT, Custom);
573
574 // Use ANDPD and ORPD to simulate FCOPYSIGN.
575 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
576
577 // These might be better off as horizontal vector ops.
578 setOperationAction(ISD::FADD, VT, Custom);
579 setOperationAction(ISD::FSUB, VT, Custom);
580
581 // We don't support sin/cos/fmod
582 setOperationAction(ISD::FSIN , VT, Expand);
583 setOperationAction(ISD::FCOS , VT, Expand);
584 setOperationAction(ISD::FSINCOS, VT, Expand);
585 }
586
587 // Lower this to MOVMSK plus an AND.
588 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
589 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
590
591 } else if (!Subtarget.useSoftFloat() && X86ScalarSSEf32 &&
592 (UseX87 || Is64Bit)) {
593 // Use SSE for f32, x87 for f64.
594 // Set up the FP register classes.
595 addRegisterClass(MVT::f32, &X86::FR32RegClass);
596 if (UseX87)
597 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
598
599 // Use ANDPS to simulate FABS.
600 setOperationAction(ISD::FABS , MVT::f32, Custom);
601
602 // Use XORP to simulate FNEG.
603 setOperationAction(ISD::FNEG , MVT::f32, Custom);
604
605 if (UseX87)
606 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
607
608 // Use ANDPS and ORPS to simulate FCOPYSIGN.
609 if (UseX87)
610 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
611 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
612
613 // We don't support sin/cos/fmod
614 setOperationAction(ISD::FSIN , MVT::f32, Expand);
615 setOperationAction(ISD::FCOS , MVT::f32, Expand);
616 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
617
618 if (UseX87) {
619 // Always expand sin/cos functions even though x87 has an instruction.
620 setOperationAction(ISD::FSIN, MVT::f64, Expand);
621 setOperationAction(ISD::FCOS, MVT::f64, Expand);
622 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
623 }
624 } else if (UseX87) {
625 // f32 and f64 in x87.
626 // Set up the FP register classes.
627 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
628 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
629
630 for (auto VT : { MVT::f32, MVT::f64 }) {
631 setOperationAction(ISD::UNDEF, VT, Expand);
632 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
633
634 // Always expand sin/cos functions even though x87 has an instruction.
635 setOperationAction(ISD::FSIN , VT, Expand);
636 setOperationAction(ISD::FCOS , VT, Expand);
637 setOperationAction(ISD::FSINCOS, VT, Expand);
638 }
639 }
640
641 // Expand FP32 immediates into loads from the stack, save special cases.
642 if (isTypeLegal(MVT::f32)) {
643 if (UseX87 && (getRegClassFor(MVT::f32) == &X86::RFP32RegClass)) {
644 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
645 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
646 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
647 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
648 } else // SSE immediates.
649 addLegalFPImmediate(APFloat(+0.0f)); // xorps
650 }
651 // Expand FP64 immediates into loads from the stack, save special cases.
652 if (isTypeLegal(MVT::f64)) {
653 if (UseX87 && getRegClassFor(MVT::f64) == &X86::RFP64RegClass) {
654 addLegalFPImmediate(APFloat(+0.0)); // FLD0
655 addLegalFPImmediate(APFloat(+1.0)); // FLD1
656 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
657 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
658 } else // SSE immediates.
659 addLegalFPImmediate(APFloat(+0.0)); // xorpd
660 }
661 // Handle constrained floating-point operations of scalar.
662 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
663 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
664 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
665 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
666 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
667 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
668 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
669 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
670 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
671 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
672 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
673 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
674 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
675
676 // We don't support FMA.
677 setOperationAction(ISD::FMA, MVT::f64, Expand);
678 setOperationAction(ISD::FMA, MVT::f32, Expand);
679
680 // f80 always uses X87.
681 if (UseX87) {
682 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
683 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
684 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
685 {
686 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended());
687 addLegalFPImmediate(TmpFlt); // FLD0
688 TmpFlt.changeSign();
689 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
690
691 bool ignored;
692 APFloat TmpFlt2(+1.0);
693 TmpFlt2.convert(APFloat::x87DoubleExtended(), APFloat::rmNearestTiesToEven,
694 &ignored);
695 addLegalFPImmediate(TmpFlt2); // FLD1
696 TmpFlt2.changeSign();
697 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
698 }
699
700 // Always expand sin/cos functions even though x87 has an instruction.
701 setOperationAction(ISD::FSIN , MVT::f80, Expand);
702 setOperationAction(ISD::FCOS , MVT::f80, Expand);
703 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
704
705 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
706 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
707 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
708 setOperationAction(ISD::FRINT, MVT::f80, Expand);
709 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
710 setOperationAction(ISD::FMA, MVT::f80, Expand);
711 setOperationAction(ISD::LROUND, MVT::f80, Expand);
712 setOperationAction(ISD::LLROUND, MVT::f80, Expand);
713 setOperationAction(ISD::LRINT, MVT::f80, Custom);
714 setOperationAction(ISD::LLRINT, MVT::f80, Custom);
715
716 // Handle constrained floating-point operations of scalar.
717 setOperationAction(ISD::STRICT_FADD , MVT::f80, Legal);
718 setOperationAction(ISD::STRICT_FSUB , MVT::f80, Legal);
719 setOperationAction(ISD::STRICT_FMUL , MVT::f80, Legal);
720 setOperationAction(ISD::STRICT_FDIV , MVT::f80, Legal);
721 setOperationAction(ISD::STRICT_FSQRT , MVT::f80, Legal);
722 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f80, Legal);
723 // FIXME: When the target is 64-bit, STRICT_FP_ROUND will be overwritten
724 // as Custom.
725 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f80, Legal);
726 }
727
728 // f128 uses xmm registers, but most operations require libcalls.
729 if (!Subtarget.useSoftFloat() && Subtarget.is64Bit() && Subtarget.hasSSE1()) {
730 addRegisterClass(MVT::f128, Subtarget.hasVLX() ? &X86::VR128XRegClass
731 : &X86::VR128RegClass);
732
733 addLegalFPImmediate(APFloat::getZero(APFloat::IEEEquad())); // xorps
734
735 setOperationAction(ISD::FADD, MVT::f128, LibCall);
736 setOperationAction(ISD::STRICT_FADD, MVT::f128, LibCall);
737 setOperationAction(ISD::FSUB, MVT::f128, LibCall);
738 setOperationAction(ISD::STRICT_FSUB, MVT::f128, LibCall);
739 setOperationAction(ISD::FDIV, MVT::f128, LibCall);
740 setOperationAction(ISD::STRICT_FDIV, MVT::f128, LibCall);
741 setOperationAction(ISD::FMUL, MVT::f128, LibCall);
742 setOperationAction(ISD::STRICT_FMUL, MVT::f128, LibCall);
743 setOperationAction(ISD::FMA, MVT::f128, LibCall);
744 setOperationAction(ISD::STRICT_FMA, MVT::f128, LibCall);
745
746 setOperationAction(ISD::FABS, MVT::f128, Custom);
747 setOperationAction(ISD::FNEG, MVT::f128, Custom);
748 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
749
750 setOperationAction(ISD::FSIN, MVT::f128, LibCall);
751 setOperationAction(ISD::STRICT_FSIN, MVT::f128, LibCall);
752 setOperationAction(ISD::FCOS, MVT::f128, LibCall);
753 setOperationAction(ISD::STRICT_FCOS, MVT::f128, LibCall);
754 setOperationAction(ISD::FSINCOS, MVT::f128, LibCall);
755 // No STRICT_FSINCOS
756 setOperationAction(ISD::FSQRT, MVT::f128, LibCall);
757 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, LibCall);
758
759 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
760 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Custom);
761 // We need to custom handle any FP_ROUND with an f128 input, but
762 // LegalizeDAG uses the result type to know when to run a custom handler.
763 // So we have to list all legal floating point result types here.
764 if (isTypeLegal(MVT::f32)) {
765 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
766 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
767 }
768 if (isTypeLegal(MVT::f64)) {
769 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
770 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
771 }
772 if (isTypeLegal(MVT::f80)) {
773 setOperationAction(ISD::FP_ROUND, MVT::f80, Custom);
774 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f80, Custom);
775 }
776
777 setOperationAction(ISD::SETCC, MVT::f128, Custom);
778
779 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
780 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
781 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f80, Expand);
782 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
783 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
784 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
785 }
786
787 // Always use a library call for pow.
788 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
789 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
790 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
791 setOperationAction(ISD::FPOW , MVT::f128 , Expand);
792
793 setOperationAction(ISD::FLOG, MVT::f80, Expand);
794 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
795 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
796 setOperationAction(ISD::FEXP, MVT::f80, Expand);
797 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
798 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
799 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
800
801 // Some FP actions are always expanded for vector types.
802 for (auto VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32,
803 MVT::v2f64, MVT::v4f64, MVT::v8f64 }) {
804 setOperationAction(ISD::FSIN, VT, Expand);
805 setOperationAction(ISD::FSINCOS, VT, Expand);
806 setOperationAction(ISD::FCOS, VT, Expand);
807 setOperationAction(ISD::FREM, VT, Expand);
808 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
809 setOperationAction(ISD::FPOW, VT, Expand);
810 setOperationAction(ISD::FLOG, VT, Expand);
811 setOperationAction(ISD::FLOG2, VT, Expand);
812 setOperationAction(ISD::FLOG10, VT, Expand);
813 setOperationAction(ISD::FEXP, VT, Expand);
814 setOperationAction(ISD::FEXP2, VT, Expand);
815 }
816
817 // First set operation action for all vector types to either promote
818 // (for widening) or expand (for scalarization). Then we will selectively
819 // turn on ones that can be effectively codegen'd.
820 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
821 setOperationAction(ISD::SDIV, VT, Expand);
822 setOperationAction(ISD::UDIV, VT, Expand);
823 setOperationAction(ISD::SREM, VT, Expand);
824 setOperationAction(ISD::UREM, VT, Expand);
825 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
826 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
827 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
828 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
829 setOperationAction(ISD::FMA, VT, Expand);
830 setOperationAction(ISD::FFLOOR, VT, Expand);
831 setOperationAction(ISD::FCEIL, VT, Expand);
832 setOperationAction(ISD::FTRUNC, VT, Expand);
833 setOperationAction(ISD::FRINT, VT, Expand);
834 setOperationAction(ISD::FNEARBYINT, VT, Expand);
835 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
836 setOperationAction(ISD::MULHS, VT, Expand);
837 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
838 setOperationAction(ISD::MULHU, VT, Expand);
839 setOperationAction(ISD::SDIVREM, VT, Expand);
840 setOperationAction(ISD::UDIVREM, VT, Expand);
841 setOperationAction(ISD::CTPOP, VT, Expand);
842 setOperationAction(ISD::CTTZ, VT, Expand);
843 setOperationAction(ISD::CTLZ, VT, Expand);
844 setOperationAction(ISD::ROTL, VT, Expand);
845 setOperationAction(ISD::ROTR, VT, Expand);
846 setOperationAction(ISD::BSWAP, VT, Expand);
847 setOperationAction(ISD::SETCC, VT, Expand);
848 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
849 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
850 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
851 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
852 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
853 setOperationAction(ISD::TRUNCATE, VT, Expand);
854 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
855 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
856 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
857 setOperationAction(ISD::SELECT_CC, VT, Expand);
858 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
859 setTruncStoreAction(InnerVT, VT, Expand);
860
861 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
862 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
863
864 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
865 // types, we have to deal with them whether we ask for Expansion or not.
866 // Setting Expand causes its own optimisation problems though, so leave
867 // them legal.
868 if (VT.getVectorElementType() == MVT::i1)
869 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
870
871 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
872 // split/scalarized right now.
873 if (VT.getVectorElementType() == MVT::f16)
874 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
875 }
876 }
877
878 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
879 // with -msoft-float, disable use of MMX as well.
880 if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
881 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
882 // No operations on x86mmx supported, everything uses intrinsics.
883 }
884
885 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
886 addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
887 : &X86::VR128RegClass);
888
889 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
890 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
891 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Custom);
892 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
893 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
894 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
895 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
896 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
897
898 setOperationAction(ISD::LOAD, MVT::v2f32, Custom);
899 setOperationAction(ISD::STORE, MVT::v2f32, Custom);
900
901 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
902 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
903 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
904 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
905 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
906 }
907
908 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
909 addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
910 : &X86::VR128RegClass);
911
912 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
913 // registers cannot be used even for integer operations.
914 addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
915 : &X86::VR128RegClass);
916 addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
917 : &X86::VR128RegClass);
918 addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
919 : &X86::VR128RegClass);
920 addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
921 : &X86::VR128RegClass);
922
923 for (auto VT : { MVT::v2i8, MVT::v4i8, MVT::v8i8,
924 MVT::v2i16, MVT::v4i16, MVT::v2i32 }) {
925 setOperationAction(ISD::SDIV, VT, Custom);
926 setOperationAction(ISD::SREM, VT, Custom);
927 setOperationAction(ISD::UDIV, VT, Custom);
928 setOperationAction(ISD::UREM, VT, Custom);
929 }
930
931 setOperationAction(ISD::MUL, MVT::v2i8, Custom);
932 setOperationAction(ISD::MUL, MVT::v4i8, Custom);
933 setOperationAction(ISD::MUL, MVT::v8i8, Custom);
934
935 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
936 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
937 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
938 setOperationAction(ISD::MULHU, MVT::v4i32, Custom);
939 setOperationAction(ISD::MULHS, MVT::v4i32, Custom);
940 setOperationAction(ISD::MULHU, MVT::v16i8, Custom);
941 setOperationAction(ISD::MULHS, MVT::v16i8, Custom);
942 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
943 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
944 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
945
946 setOperationAction(ISD::SMULO, MVT::v16i8, Custom);
947 setOperationAction(ISD::UMULO, MVT::v16i8, Custom);
948
949 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
950 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
951 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Custom);
952
953 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
954 setOperationAction(ISD::SMAX, VT, VT == MVT::v8i16 ? Legal : Custom);
955 setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
956 setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
957 setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
958 }
959
960 setOperationAction(ISD::UADDSAT, MVT::v16i8, Legal);
961 setOperationAction(ISD::SADDSAT, MVT::v16i8, Legal);
962 setOperationAction(ISD::USUBSAT, MVT::v16i8, Legal);
963 setOperationAction(ISD::SSUBSAT, MVT::v16i8, Legal);
964 setOperationAction(ISD::UADDSAT, MVT::v8i16, Legal);
965 setOperationAction(ISD::SADDSAT, MVT::v8i16, Legal);
966 setOperationAction(ISD::USUBSAT, MVT::v8i16, Legal);
967 setOperationAction(ISD::SSUBSAT, MVT::v8i16, Legal);
968 setOperationAction(ISD::USUBSAT, MVT::v4i32, Custom);
969 setOperationAction(ISD::USUBSAT, MVT::v2i64, Custom);
970
971 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
972 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
973 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
974
975 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
976 setOperationAction(ISD::SETCC, VT, Custom);
977 setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
978 setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
979 setOperationAction(ISD::CTPOP, VT, Custom);
980 setOperationAction(ISD::ABS, VT, Custom);
981
982 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
983 // setcc all the way to isel and prefer SETGT in some isel patterns.
984 setCondCodeAction(ISD::SETLT, VT, Custom);
985 setCondCodeAction(ISD::SETLE, VT, Custom);
986 }
987
988 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
989 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
990 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
991 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
992 setOperationAction(ISD::VSELECT, VT, Custom);
993 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
994 }
995
996 for (auto VT : { MVT::v2f64, MVT::v2i64 }) {
997 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
998 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
999 setOperationAction(ISD::VSELECT, VT, Custom);
1000
1001 if (VT == MVT::v2i64 && !Subtarget.is64Bit())
1002 continue;
1003
1004 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1005 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1006 }
1007
1008 // Custom lower v2i64 and v2f64 selects.
1009 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1010 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1011 setOperationAction(ISD::SELECT, MVT::v4i32, Custom);
1012 setOperationAction(ISD::SELECT, MVT::v8i16, Custom);
1013 setOperationAction(ISD::SELECT, MVT::v16i8, Custom);
1014
1015 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1016 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Custom);
1017 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
1018 setOperationAction(ISD::FP_TO_UINT, MVT::v2i32, Custom);
1019 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
1020 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i32, Custom);
1021
1022 // Custom legalize these to avoid over promotion or custom promotion.
1023 for (auto VT : {MVT::v2i8, MVT::v4i8, MVT::v8i8, MVT::v2i16, MVT::v4i16}) {
1024 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1025 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1026 setOperationAction(ISD::STRICT_FP_TO_SINT, VT, Custom);
1027 setOperationAction(ISD::STRICT_FP_TO_UINT, VT, Custom);
1028 }
1029
1030 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1031 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
1032 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
1033 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i32, Custom);
1034
1035 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
1036 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i32, Custom);
1037
1038 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
1039 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Custom);
1040
1041 // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
1042 setOperationAction(ISD::SINT_TO_FP, MVT::v2f32, Custom);
1043 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2f32, Custom);
1044 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1045 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2f32, Custom);
1046
1047 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1048 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::v2f32, Custom);
1049 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1050 setOperationAction(ISD::STRICT_FP_ROUND, MVT::v2f32, Custom);
1051
1052 // We want to legalize this to an f64 load rather than an i64 load on
1053 // 64-bit targets and two 32-bit loads on a 32-bit target. Similar for
1054 // store.
1055 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
1056 setOperationAction(ISD::LOAD, MVT::v4i16, Custom);
1057 setOperationAction(ISD::LOAD, MVT::v8i8, Custom);
1058 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
1059 setOperationAction(ISD::STORE, MVT::v4i16, Custom);
1060 setOperationAction(ISD::STORE, MVT::v8i8, Custom);
1061
1062 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1063 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1064 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1065 if (!Subtarget.hasAVX512())
1066 setOperationAction(ISD::BITCAST, MVT::v16i1, Custom);
1067
1068 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1069 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1070 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1071
1072 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1073
1074 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
1075 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
1076 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Custom);
1077 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
1078 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
1079 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
1080
1081 // In the customized shift lowering, the legal v4i32/v2i64 cases
1082 // in AVX2 will be recognized.
1083 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1084 setOperationAction(ISD::SRL, VT, Custom);
1085 setOperationAction(ISD::SHL, VT, Custom);
1086 setOperationAction(ISD::SRA, VT, Custom);
1087 }
1088
1089 setOperationAction(ISD::ROTL, MVT::v4i32, Custom);
1090 setOperationAction(ISD::ROTL, MVT::v8i16, Custom);
1091
1092 // With 512-bit registers or AVX512VL+BW, expanding (and promoting the
1093 // shifts) is better.
1094 if (!Subtarget.useAVX512Regs() &&
1095 !(Subtarget.hasBWI() && Subtarget.hasVLX()))
1096 setOperationAction(ISD::ROTL, MVT::v16i8, Custom);
1097
1098 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1099 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1100 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1101 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1102 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1103 }
1104
1105 if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
1106 setOperationAction(ISD::ABS, MVT::v16i8, Legal);
1107 setOperationAction(ISD::ABS, MVT::v8i16, Legal);
1108 setOperationAction(ISD::ABS, MVT::v4i32, Legal);
1109 setOperationAction(ISD::BITREVERSE, MVT::v16i8, Custom);
1110 setOperationAction(ISD::CTLZ, MVT::v16i8, Custom);
1111 setOperationAction(ISD::CTLZ, MVT::v8i16, Custom);
1112 setOperationAction(ISD::CTLZ, MVT::v4i32, Custom);
1113 setOperationAction(ISD::CTLZ, MVT::v2i64, Custom);
1114
1115 // These might be better off as horizontal vector ops.
1116 setOperationAction(ISD::ADD, MVT::i16, Custom);
1117 setOperationAction(ISD::ADD, MVT::i32, Custom);
1118 setOperationAction(ISD::SUB, MVT::i16, Custom);
1119 setOperationAction(ISD::SUB, MVT::i32, Custom);
1120 }
1121
1122 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
1123 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1124 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
1125 setOperationAction(ISD::STRICT_FFLOOR, RoundedTy, Legal);
1126 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
1127 setOperationAction(ISD::STRICT_FCEIL, RoundedTy, Legal);
1128 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
1129 setOperationAction(ISD::STRICT_FTRUNC, RoundedTy, Legal);
1130 setOperationAction(ISD::FRINT, RoundedTy, Legal);
1131 setOperationAction(ISD::STRICT_FRINT, RoundedTy, Legal);
1132 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
1133 setOperationAction(ISD::STRICT_FNEARBYINT, RoundedTy, Legal);
1134 setOperationAction(ISD::FROUNDEVEN, RoundedTy, Legal);
1135 setOperationAction(ISD::STRICT_FROUNDEVEN, RoundedTy, Legal);
1136
1137 setOperationAction(ISD::FROUND, RoundedTy, Custom);
1138 }
1139
1140 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
1141 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
1142 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
1143 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
1144 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
1145 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
1146 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
1147 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
1148
1149 setOperationAction(ISD::UADDSAT, MVT::v4i32, Custom);
1150
1151 // FIXME: Do we need to handle scalar-to-vector here?
1152 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1153
1154 // We directly match byte blends in the backend as they match the VSELECT
1155 // condition form.
1156 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1157
1158 // SSE41 brings specific instructions for doing vector sign extend even in
1159 // cases where we don't have SRA.
1160 for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1161 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Legal);
1162 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Legal);
1163 }
1164
1165 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1166 for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1167 setLoadExtAction(LoadExtOp, MVT::v8i16, MVT::v8i8, Legal);
1168 setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i8, Legal);
1169 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i8, Legal);
1170 setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i16, Legal);
1171 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i16, Legal);
1172 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i32, Legal);
1173 }
1174
1175 // i8 vectors are custom because the source register and source
1176 // source memory operand types are not the same width.
1177 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1178
1179 if (Subtarget.is64Bit() && !Subtarget.hasAVX512()) {
1180 // We need to scalarize v4i64->v432 uint_to_fp using cvtsi2ss, but we can
1181 // do the pre and post work in the vector domain.
1182 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Custom);
1183 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i64, Custom);
1184 // We need to mark SINT_TO_FP as Custom even though we want to expand it
1185 // so that DAG combine doesn't try to turn it into uint_to_fp.
1186 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Custom);
1187 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i64, Custom);
1188 }
1189 }
1190
1191 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE42()) {
1192 setOperationAction(ISD::UADDSAT, MVT::v2i64, Custom);
1193 }
1194
1195 if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
1196 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1197 MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
1198 setOperationAction(ISD::ROTL, VT, Custom);
1199
1200 // XOP can efficiently perform BITREVERSE with VPPERM.
1201 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
1202 setOperationAction(ISD::BITREVERSE, VT, Custom);
1203
1204 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1205 MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
1206 setOperationAction(ISD::BITREVERSE, VT, Custom);
1207 }
1208
1209 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
1210 bool HasInt256 = Subtarget.hasInt256();
1211
1212 addRegisterClass(MVT::v32i8, Subtarget.hasVLX() ? &X86::VR256XRegClass
1213 : &X86::VR256RegClass);
1214 addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1215 : &X86::VR256RegClass);
1216 addRegisterClass(MVT::v8i32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1217 : &X86::VR256RegClass);
1218 addRegisterClass(MVT::v8f32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1219 : &X86::VR256RegClass);
1220 addRegisterClass(MVT::v4i64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1221 : &X86::VR256RegClass);
1222 addRegisterClass(MVT::v4f64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1223 : &X86::VR256RegClass);
1224
1225 for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1226 setOperationAction(ISD::FFLOOR, VT, Legal);
1227 setOperationAction(ISD::STRICT_FFLOOR, VT, Legal);
1228 setOperationAction(ISD::FCEIL, VT, Legal);
1229 setOperationAction(ISD::STRICT_FCEIL, VT, Legal);
1230 setOperationAction(ISD::FTRUNC, VT, Legal);
1231 setOperationAction(ISD::STRICT_FTRUNC, VT, Legal);
1232 setOperationAction(ISD::FRINT, VT, Legal);
1233 setOperationAction(ISD::STRICT_FRINT, VT, Legal);
1234 setOperationAction(ISD::FNEARBYINT, VT, Legal);
1235 setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
1236 setOperationAction(ISD::FROUNDEVEN, VT, Legal);
1237 setOperationAction(ISD::STRICT_FROUNDEVEN, VT, Legal);
1238
1239 setOperationAction(ISD::FROUND, VT, Custom);
1240
1241 setOperationAction(ISD::FNEG, VT, Custom);
1242 setOperationAction(ISD::FABS, VT, Custom);
1243 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1244 }
1245
1246 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1247 // even though v8i16 is a legal type.
1248 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1249 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1250 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1251 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1252 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1253 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Custom);
1254 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v8i32, Legal);
1255
1256 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1257 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v8i32, Legal);
1258
1259 setOperationAction(ISD::STRICT_FP_ROUND, MVT::v4f32, Legal);
1260 setOperationAction(ISD::STRICT_FADD, MVT::v8f32, Legal);
1261 setOperationAction(ISD::STRICT_FADD, MVT::v4f64, Legal);
1262 setOperationAction(ISD::STRICT_FSUB, MVT::v8f32, Legal);
1263 setOperationAction(ISD::STRICT_FSUB, MVT::v4f64, Legal);
1264 setOperationAction(ISD::STRICT_FMUL, MVT::v8f32, Legal);
1265 setOperationAction(ISD::STRICT_FMUL, MVT::v4f64, Legal);
1266 setOperationAction(ISD::STRICT_FDIV, MVT::v8f32, Legal);
1267 setOperationAction(ISD::STRICT_FDIV, MVT::v4f64, Legal);
1268 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::v4f64, Legal);
1269 setOperationAction(ISD::STRICT_FSQRT, MVT::v8f32, Legal);
1270 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f64, Legal);
1271
1272 if (!Subtarget.hasAVX512())
1273 setOperationAction(ISD::BITCAST, MVT::v32i1, Custom);
1274
1275 // In the customized shift lowering, the legal v8i32/v4i64 cases
1276 // in AVX2 will be recognized.
1277 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1278 setOperationAction(ISD::SRL, VT, Custom);
1279 setOperationAction(ISD::SHL, VT, Custom);
1280 setOperationAction(ISD::SRA, VT, Custom);
1281 }
1282
1283 // These types need custom splitting if their input is a 128-bit vector.
1284 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1285 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1286 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1287 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1288
1289 setOperationAction(ISD::ROTL, MVT::v8i32, Custom);
1290 setOperationAction(ISD::ROTL, MVT::v16i16, Custom);
1291
1292 // With BWI, expanding (and promoting the shifts) is the better.
1293 if (!Subtarget.useBWIRegs())
1294 setOperationAction(ISD::ROTL, MVT::v32i8, Custom);
1295
1296 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1297 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1298 setOperationAction(ISD::SELECT, MVT::v8i32, Custom);
1299 setOperationAction(ISD::SELECT, MVT::v16i16, Custom);
1300 setOperationAction(ISD::SELECT, MVT::v32i8, Custom);
1301 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1302
1303 for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1304 setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1305 setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1306 setOperationAction(ISD::ANY_EXTEND, VT, Custom);
1307 }
1308
1309 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1310 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1311 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1312 setOperationAction(ISD::BITREVERSE, MVT::v32i8, Custom);
1313
1314 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1315 setOperationAction(ISD::SETCC, VT, Custom);
1316 setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
1317 setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
1318 setOperationAction(ISD::CTPOP, VT, Custom);
1319 setOperationAction(ISD::CTLZ, VT, Custom);
1320
1321 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1322 // setcc all the way to isel and prefer SETGT in some isel patterns.
1323 setCondCodeAction(ISD::SETLT, VT, Custom);
1324 setCondCodeAction(ISD::SETLE, VT, Custom);
1325 }
1326
1327 if (Subtarget.hasAnyFMA()) {
1328 for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1329 MVT::v2f64, MVT::v4f64 }) {
1330 setOperationAction(ISD::FMA, VT, Legal);
1331 setOperationAction(ISD::STRICT_FMA, VT, Legal);
1332 }
1333 }
1334
1335 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1336 setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1337 setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1338 }
1339
1340 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1341 setOperationAction(ISD::MUL, MVT::v8i32, HasInt256 ? Legal : Custom);
1342 setOperationAction(ISD::MUL, MVT::v16i16, HasInt256 ? Legal : Custom);
1343 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1344
1345 setOperationAction(ISD::MULHU, MVT::v8i32, Custom);
1346 setOperationAction(ISD::MULHS, MVT::v8i32, Custom);
1347 setOperationAction(ISD::MULHU, MVT::v16i16, HasInt256 ? Legal : Custom);
1348 setOperationAction(ISD::MULHS, MVT::v16i16, HasInt256 ? Legal : Custom);
1349 setOperationAction(ISD::MULHU, MVT::v32i8, Custom);
1350 setOperationAction(ISD::MULHS, MVT::v32i8, Custom);
1351
1352 setOperationAction(ISD::SMULO, MVT::v32i8, Custom);
1353 setOperationAction(ISD::UMULO, MVT::v32i8, Custom);
1354
1355 setOperationAction(ISD::ABS, MVT::v4i64, Custom);
1356 setOperationAction(ISD::SMAX, MVT::v4i64, Custom);
1357 setOperationAction(ISD::UMAX, MVT::v4i64, Custom);
1358 setOperationAction(ISD::SMIN, MVT::v4i64, Custom);
1359 setOperationAction(ISD::UMIN, MVT::v4i64, Custom);
1360
1361 setOperationAction(ISD::UADDSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1362 setOperationAction(ISD::SADDSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1363 setOperationAction(ISD::USUBSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1364 setOperationAction(ISD::SSUBSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1365 setOperationAction(ISD::UADDSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1366 setOperationAction(ISD::SADDSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1367 setOperationAction(ISD::USUBSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1368 setOperationAction(ISD::SSUBSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1369 setOperationAction(ISD::UADDSAT, MVT::v8i32, Custom);
1370 setOperationAction(ISD::USUBSAT, MVT::v8i32, Custom);
1371 setOperationAction(ISD::UADDSAT, MVT::v4i64, Custom);
1372 setOperationAction(ISD::USUBSAT, MVT::v4i64, Custom);
1373
1374 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1375 setOperationAction(ISD::ABS, VT, HasInt256 ? Legal : Custom);
1376 setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1377 setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1378 setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1379 setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1380 }
1381
1382 for (auto VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64}) {
1383 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1384 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1385 }
1386
1387 if (HasInt256) {
1388 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1389 // when we have a 256bit-wide blend with immediate.
1390 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1391 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v8i32, Custom);
1392
1393 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1394 for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1395 setLoadExtAction(LoadExtOp, MVT::v16i16, MVT::v16i8, Legal);
1396 setLoadExtAction(LoadExtOp, MVT::v8i32, MVT::v8i8, Legal);
1397 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i8, Legal);
1398 setLoadExtAction(LoadExtOp, MVT::v8i32, MVT::v8i16, Legal);
1399 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i16, Legal);
1400 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i32, Legal);
1401 }
1402 }
1403
1404 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1405 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 }) {
1406 setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
1407 setOperationAction(ISD::MSTORE, VT, Legal);
1408 }
1409
1410 // Extract subvector is special because the value type
1411 // (result) is 128-bit but the source is 256-bit wide.
1412 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1413 MVT::v4f32, MVT::v2f64 }) {
1414 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1415 }
1416
1417 // Custom lower several nodes for 256-bit types.
1418 for (MVT VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1419 MVT::v8f32, MVT::v4f64 }) {
1420 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1421 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1422 setOperationAction(ISD::VSELECT, VT, Custom);
1423 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1424 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1425 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1426 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Legal);
1427 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1428 setOperationAction(ISD::STORE, VT, Custom);
1429 }
1430
1431 if (HasInt256) {
1432 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1433
1434 // Custom legalize 2x32 to get a little better code.
1435 setOperationAction(ISD::MGATHER, MVT::v2f32, Custom);
1436 setOperationAction(ISD::MGATHER, MVT::v2i32, Custom);
1437
1438 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1439 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1440 setOperationAction(ISD::MGATHER, VT, Custom);
1441 }
1442 }
1443
1444 // This block controls legalization of the mask vector sizes that are
1445 // available with AVX512. 512-bit vectors are in a separate block controlled
1446 // by useAVX512Regs.
1447 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1448 addRegisterClass(MVT::v1i1, &X86::VK1RegClass);
1449 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1450 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1451 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1452 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1453
1454 setOperationAction(ISD::SELECT, MVT::v1i1, Custom);
1455 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v1i1, Custom);
1456 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i1, Custom);
1457
1458 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v8i1, MVT::v8i32);
1459 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v8i1, MVT::v8i32);
1460 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v4i1, MVT::v4i32);
1461 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v4i1, MVT::v4i32);
1462 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i1, MVT::v8i32);
1463 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i1, MVT::v8i32);
1464 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v4i1, MVT::v4i32);
1465 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v4i1, MVT::v4i32);
1466 setOperationAction(ISD::FP_TO_SINT, MVT::v2i1, Custom);
1467 setOperationAction(ISD::FP_TO_UINT, MVT::v2i1, Custom);
1468 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i1, Custom);
1469 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i1, Custom);
1470
1471 // There is no byte sized k-register load or store without AVX512DQ.
1472 if (!Subtarget.hasDQI()) {
1473 setOperationAction(ISD::LOAD, MVT::v1i1, Custom);
1474 setOperationAction(ISD::LOAD, MVT::v2i1, Custom);
1475 setOperationAction(ISD::LOAD, MVT::v4i1, Custom);
1476 setOperationAction(ISD::LOAD, MVT::v8i1, Custom);
1477
1478 setOperationAction(ISD::STORE, MVT::v1i1, Custom);
1479 setOperationAction(ISD::STORE, MVT::v2i1, Custom);
1480 setOperationAction(ISD::STORE, MVT::v4i1, Custom);
1481 setOperationAction(ISD::STORE, MVT::v8i1, Custom);
1482 }
1483
1484 // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1485 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1486 setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1487 setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1488 setOperationAction(ISD::ANY_EXTEND, VT, Custom);
1489 }
1490
1491 for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 })
1492 setOperationAction(ISD::VSELECT, VT, Expand);
1493
1494 for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1495 setOperationAction(ISD::SETCC, VT, Custom);
1496 setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
1497 setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
1498 setOperationAction(ISD::SELECT, VT, Custom);
1499 setOperationAction(ISD::TRUNCATE, VT, Custom);
1500
1501 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1502 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1503 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1504 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1505 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1506 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1507 }
1508
1509 for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1510 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1511 }
1512
1513 // This block controls legalization for 512-bit operations with 32/64 bit
1514 // elements. 512-bits can be disabled based on prefer-vector-width and
1515 // required-vector-width function attributes.
1516 if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1517 bool HasBWI = Subtarget.hasBWI();
1518
1519 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1520 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1521 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1522 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1523 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1524 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1525
1526 for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1527 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i8, Legal);
1528 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i16, Legal);
1529 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i8, Legal);
1530 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i16, Legal);
1531 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i32, Legal);
1532 if (HasBWI)
1533 setLoadExtAction(ExtType, MVT::v32i16, MVT::v32i8, Legal);
1534 }
1535
1536 for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1537 setOperationAction(ISD::FNEG, VT, Custom);
1538 setOperationAction(ISD::FABS, VT, Custom);
1539 setOperationAction(ISD::FMA, VT, Legal);
1540 setOperationAction(ISD::STRICT_FMA, VT, Legal);
1541 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1542 }
1543
1544 for (MVT VT : { MVT::v16i1, MVT::v16i8, MVT::v16i16 }) {
1545 setOperationPromotedToType(ISD::FP_TO_SINT , VT, MVT::v16i32);
1546 setOperationPromotedToType(ISD::FP_TO_UINT , VT, MVT::v16i32);
1547 setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, VT, MVT::v16i32);
1548 setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, VT, MVT::v16i32);
1549 }
1550 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1551 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1552 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v16i32, Legal);
1553 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v16i32, Legal);
1554 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1555 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1556 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v16i32, Legal);
1557 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v16i32, Legal);
1558
1559 setOperationAction(ISD::STRICT_FADD, MVT::v16f32, Legal);
1560 setOperationAction(ISD::STRICT_FADD, MVT::v8f64, Legal);
1561 setOperationAction(ISD::STRICT_FSUB, MVT::v16f32, Legal);
1562 setOperationAction(ISD::STRICT_FSUB, MVT::v8f64, Legal);
1563 setOperationAction(ISD::STRICT_FMUL, MVT::v16f32, Legal);
1564 setOperationAction(ISD::STRICT_FMUL, MVT::v8f64, Legal);
1565 setOperationAction(ISD::STRICT_FDIV, MVT::v16f32, Legal);
1566 setOperationAction(ISD::STRICT_FDIV, MVT::v8f64, Legal);
1567 setOperationAction(ISD::STRICT_FSQRT, MVT::v16f32, Legal);
1568 setOperationAction(ISD::STRICT_FSQRT, MVT::v8f64, Legal);
1569 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::v8f64, Legal);
1570 setOperationAction(ISD::STRICT_FP_ROUND, MVT::v8f32, Legal);
1571
1572 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1573 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1574 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1575 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1576 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1577 if (HasBWI)
1578 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1579
1580 // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1581 // to 512-bit rather than use the AVX2 instructions so that we can use
1582 // k-masks.
1583 if (!Subtarget.hasVLX()) {
1584 for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1585 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1586 setOperationAction(ISD::MLOAD, VT, Custom);
1587 setOperationAction(ISD::MSTORE, VT, Custom);
1588 }
1589 }
1590
1591 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Legal);
1592 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Legal);
1593 setOperationAction(ISD::TRUNCATE, MVT::v32i8, HasBWI ? Legal : Custom);
1594 setOperationAction(ISD::TRUNCATE, MVT::v16i64, Custom);
1595 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1596 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1597 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1598 setOperationAction(ISD::ANY_EXTEND, MVT::v32i16, Custom);
1599 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1600 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1601 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1602 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1603 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1604
1605 if (HasBWI) {
1606 // Extends from v64i1 masks to 512-bit vectors.
1607 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1608 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1609 setOperationAction(ISD::ANY_EXTEND, MVT::v64i8, Custom);
1610 }
1611
1612 for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1613 setOperationAction(ISD::FFLOOR, VT, Legal);
1614 setOperationAction(ISD::STRICT_FFLOOR, VT, Legal);
1615 setOperationAction(ISD::FCEIL, VT, Legal);
1616 setOperationAction(ISD::STRICT_FCEIL, VT, Legal);
1617 setOperationAction(ISD::FTRUNC, VT, Legal);
1618 setOperationAction(ISD::STRICT_FTRUNC, VT, Legal);
1619 setOperationAction(ISD::FRINT, VT, Legal);
1620 setOperationAction(ISD::STRICT_FRINT, VT, Legal);
1621 setOperationAction(ISD::FNEARBYINT, VT, Legal);
1622 setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
1623 setOperationAction(ISD::FROUNDEVEN, VT, Legal);
1624 setOperationAction(ISD::STRICT_FROUNDEVEN, VT, Legal);
1625
1626 setOperationAction(ISD::FROUND, VT, Custom);
1627 }
1628
1629 for (auto VT : {MVT::v32i16, MVT::v16i32, MVT::v8i64}) {
1630 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1631 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1632 }
1633
1634 setOperationAction(ISD::ADD, MVT::v32i16, HasBWI ? Legal : Custom);
1635 setOperationAction(ISD::SUB, MVT::v32i16, HasBWI ? Legal : Custom);
1636 setOperationAction(ISD::ADD, MVT::v64i8, HasBWI ? Legal : Custom);
1637 setOperationAction(ISD::SUB, MVT::v64i8, HasBWI ? Legal : Custom);
1638
1639 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1640 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1641 setOperationAction(ISD::MUL, MVT::v32i16, HasBWI ? Legal : Custom);
1642 setOperationAction(ISD::MUL, MVT::v64i8, Custom);
1643
1644 setOperationAction(ISD::MULHU, MVT::v16i32, Custom);
1645 setOperationAction(ISD::MULHS, MVT::v16i32, Custom);
1646 setOperationAction(ISD::MULHS, MVT::v32i16, HasBWI ? Legal : Custom);
1647 setOperationAction(ISD::MULHU, MVT::v32i16, HasBWI ? Legal : Custom);
1648 setOperationAction(ISD::MULHS, MVT::v64i8, Custom);
1649 setOperationAction(ISD::MULHU, MVT::v64i8, Custom);
1650
1651 setOperationAction(ISD::SMULO, MVT::v64i8, Custom);
1652 setOperationAction(ISD::UMULO, MVT::v64i8, Custom);
1653
1654 setOperationAction(ISD::BITREVERSE, MVT::v64i8, Custom);
1655
1656 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64 }) {
1657 setOperationAction(ISD::SRL, VT, Custom);
1658 setOperationAction(ISD::SHL, VT, Custom);
1659 setOperationAction(ISD::SRA, VT, Custom);
1660 setOperationAction(ISD::SETCC, VT, Custom);
1661
1662 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1663 // setcc all the way to isel and prefer SETGT in some isel patterns.
1664 setCondCodeAction(ISD::SETLT, VT, Custom);
1665 setCondCodeAction(ISD::SETLE, VT, Custom);
1666 }
1667 for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1668 setOperationAction(ISD::SMAX, VT, Legal);
1669 setOperationAction(ISD::UMAX, VT, Legal);
1670 setOperationAction(ISD::SMIN, VT, Legal);
1671 setOperationAction(ISD::UMIN, VT, Legal);
1672 setOperationAction(ISD::ABS, VT, Legal);
1673 setOperationAction(ISD::CTPOP, VT, Custom);
1674 setOperationAction(ISD::ROTL, VT, Custom);
1675 setOperationAction(ISD::ROTR, VT, Custom);
1676 setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
1677 setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
1678 }
1679
1680 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1681 setOperationAction(ISD::ABS, VT, HasBWI ? Legal : Custom);
1682 setOperationAction(ISD::CTPOP, VT, Subtarget.hasBITALG() ? Legal : Custom);
1683 setOperationAction(ISD::CTLZ, VT, Custom);
1684 setOperationAction(ISD::SMAX, VT, HasBWI ? Legal : Custom);
1685 setOperationAction(ISD::UMAX, VT, HasBWI ? Legal : Custom);
1686 setOperationAction(ISD::SMIN, VT, HasBWI ? Legal : Custom);
1687 setOperationAction(ISD::UMIN, VT, HasBWI ? Legal : Custom);
1688 setOperationAction(ISD::UADDSAT, VT, HasBWI ? Legal : Custom);
1689 setOperationAction(ISD::SADDSAT, VT, HasBWI ? Legal : Custom);
1690 setOperationAction(ISD::USUBSAT, VT, HasBWI ? Legal : Custom);
1691 setOperationAction(ISD::SSUBSAT, VT, HasBWI ? Legal : Custom);
1692 }
1693
1694 if (Subtarget.hasDQI()) {
1695 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1696 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1697 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v8i64, Legal);
1698 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v8i64, Legal);
1699 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1700 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1701 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v8i64, Legal);
1702 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v8i64, Legal);
1703
1704 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1705 }
1706
1707 if (Subtarget.hasCDI()) {
1708 // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1709 for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
1710 setOperationAction(ISD::CTLZ, VT, Legal);
1711 }
1712 } // Subtarget.hasCDI()
1713
1714 if (Subtarget.hasVPOPCNTDQ()) {
1715 for (auto VT : { MVT::v16i32, MVT::v8i64 })
1716 setOperationAction(ISD::CTPOP, VT, Legal);
1717 }
1718
1719 // Extract subvector is special because the value type
1720 // (result) is 256-bit but the source is 512-bit wide.
1721 // 128-bit was made Legal under AVX1.
1722 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1723 MVT::v8f32, MVT::v4f64 })
1724 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1725
1726 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64,
1727 MVT::v16f32, MVT::v8f64 }) {
1728 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1729 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Legal);
1730 setOperationAction(ISD::SELECT, VT, Custom);
1731 setOperationAction(ISD::VSELECT, VT, Custom);
1732 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1733 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1734 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1735 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1736 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1737 }
1738
1739 for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
1740 setOperationAction(ISD::MLOAD, VT, Legal);
1741 setOperationAction(ISD::MSTORE, VT, Legal);
1742 setOperationAction(ISD::MGATHER, VT, Custom);
1743 setOperationAction(ISD::MSCATTER, VT, Custom);
1744 }
1745 if (HasBWI) {
1746 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1747 setOperationAction(ISD::MLOAD, VT, Legal);
1748 setOperationAction(ISD::MSTORE, VT, Legal);
1749 }
1750 } else {
1751 setOperationAction(ISD::STORE, MVT::v32i16, Custom);
1752 setOperationAction(ISD::STORE, MVT::v64i8, Custom);
1753 }
1754
1755 if (Subtarget.hasVBMI2()) {
1756 for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64,
1757 MVT::v16i16, MVT::v8i32, MVT::v4i64,
1758 MVT::v32i16, MVT::v16i32, MVT::v8i64 }) {
1759 setOperationAction(ISD::FSHL, VT, Custom);
1760 setOperationAction(ISD::FSHR, VT, Custom);
1761 }
1762
1763 setOperationAction(ISD::ROTL, MVT::v32i16, Custom);
1764 setOperationAction(ISD::ROTR, MVT::v8i16, Custom);
1765 setOperationAction(ISD::ROTR, MVT::v16i16, Custom);
1766 setOperationAction(ISD::ROTR, MVT::v32i16, Custom);
1767 }
1768 }// useAVX512Regs
1769
1770 // This block controls legalization for operations that don't have
1771 // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
1772 // narrower widths.
1773 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1774 // These operations are handled on non-VLX by artificially widening in
1775 // isel patterns.
1776
1777 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32,
1778 Subtarget.hasVLX() ? Legal : Custom);
1779 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32,
1780 Subtarget.hasVLX() ? Legal : Custom);
1781 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v8i32,
1782 Subtarget.hasVLX() ? Legal : Custom);
1783 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32,
1784 Subtarget.hasVLX() ? Legal : Custom);
1785 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i32, Custom);
1786 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32,
1787 Subtarget.hasVLX() ? Legal : Custom);
1788 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32,
1789 Subtarget.hasVLX() ? Legal : Custom);
1790 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v8i32,
1791 Subtarget.hasVLX() ? Legal : Custom);
1792 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32,
1793 Subtarget.hasVLX() ? Legal : Custom);
1794
1795 if (Subtarget.hasDQI()) {
1796 // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
1797 // v2f32 UINT_TO_FP is already custom under SSE2.
1798 assert(isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) &&(static_cast <bool> (isOperationCustom(ISD::UINT_TO_FP,
MVT::v2f32) && isOperationCustom(ISD::STRICT_UINT_TO_FP
, MVT::v2f32) && "Unexpected operation action!") ? void
(0) : __assert_fail ("isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) && isOperationCustom(ISD::STRICT_UINT_TO_FP, MVT::v2f32) && \"Unexpected operation action!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 1800, __extension__ __PRETTY_FUNCTION__))
1799 isOperationCustom(ISD::STRICT_UINT_TO_FP, MVT::v2f32) &&(static_cast <bool> (isOperationCustom(ISD::UINT_TO_FP,
MVT::v2f32) && isOperationCustom(ISD::STRICT_UINT_TO_FP
, MVT::v2f32) && "Unexpected operation action!") ? void
(0) : __assert_fail ("isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) && isOperationCustom(ISD::STRICT_UINT_TO_FP, MVT::v2f32) && \"Unexpected operation action!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 1800, __extension__ __PRETTY_FUNCTION__))
1800 "Unexpected operation action!")(static_cast <bool> (isOperationCustom(ISD::UINT_TO_FP,
MVT::v2f32) && isOperationCustom(ISD::STRICT_UINT_TO_FP
, MVT::v2f32) && "Unexpected operation action!") ? void
(0) : __assert_fail ("isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) && isOperationCustom(ISD::STRICT_UINT_TO_FP, MVT::v2f32) && \"Unexpected operation action!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 1800, __extension__ __PRETTY_FUNCTION__))
;
1801 // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
1802 setOperationAction(ISD::FP_TO_SINT, MVT::v2f32, Custom);
1803 setOperationAction(ISD::FP_TO_UINT, MVT::v2f32, Custom);
1804 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2f32, Custom);
1805 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2f32, Custom);
1806 }
1807
1808 for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1809 setOperationAction(ISD::SMAX, VT, Legal);
1810 setOperationAction(ISD::UMAX, VT, Legal);
1811 setOperationAction(ISD::SMIN, VT, Legal);
1812 setOperationAction(ISD::UMIN, VT, Legal);
1813 setOperationAction(ISD::ABS, VT, Legal);
1814 }
1815
1816 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1817 setOperationAction(ISD::ROTL, VT, Custom);
1818 setOperationAction(ISD::ROTR, VT, Custom);
1819 }
1820
1821 // Custom legalize 2x32 to get a little better code.
1822 setOperationAction(ISD::MSCATTER, MVT::v2f32, Custom);
1823 setOperationAction(ISD::MSCATTER, MVT::v2i32, Custom);
1824
1825 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1826 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1827 setOperationAction(ISD::MSCATTER, VT, Custom);
1828
1829 if (Subtarget.hasDQI()) {
1830 for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1831 setOperationAction(ISD::SINT_TO_FP, VT,
1832 Subtarget.hasVLX() ? Legal : Custom);
1833 setOperationAction(ISD::UINT_TO_FP, VT,
1834 Subtarget.hasVLX() ? Legal : Custom);
1835 setOperationAction(ISD::STRICT_SINT_TO_FP, VT,
1836 Subtarget.hasVLX() ? Legal : Custom);
1837 setOperationAction(ISD::STRICT_UINT_TO_FP, VT,
1838 Subtarget.hasVLX() ? Legal : Custom);
1839 setOperationAction(ISD::FP_TO_SINT, VT,
1840 Subtarget.hasVLX() ? Legal : Custom);
1841 setOperationAction(ISD::FP_TO_UINT, VT,
1842 Subtarget.hasVLX() ? Legal : Custom);
1843 setOperationAction(ISD::STRICT_FP_TO_SINT, VT,
1844 Subtarget.hasVLX() ? Legal : Custom);
1845 setOperationAction(ISD::STRICT_FP_TO_UINT, VT,
1846 Subtarget.hasVLX() ? Legal : Custom);
1847 setOperationAction(ISD::MUL, VT, Legal);
1848 }
1849 }
1850
1851 if (Subtarget.hasCDI()) {
1852 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1853 setOperationAction(ISD::CTLZ, VT, Legal);
1854 }
1855 } // Subtarget.hasCDI()
1856
1857 if (Subtarget.hasVPOPCNTDQ()) {
1858 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 })
1859 setOperationAction(ISD::CTPOP, VT, Legal);
1860 }
1861 }
1862
1863 // This block control legalization of v32i1/v64i1 which are available with
1864 // AVX512BW. 512-bit v32i16 and v64i8 vector legalization is controlled with
1865 // useBWIRegs.
1866 if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1867 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1868 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1869
1870 for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
1871 setOperationAction(ISD::VSELECT, VT, Expand);
1872 setOperationAction(ISD::TRUNCATE, VT, Custom);
1873 setOperationAction(ISD::SETCC, VT, Custom);
1874 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1875 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1876 setOperationAction(ISD::SELECT, VT, Custom);
1877 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1878 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1879 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1880 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1881 }
1882
1883 for (auto VT : { MVT::v16i1, MVT::v32i1 })
1884 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1885
1886 // Extends from v32i1 masks to 256-bit vectors.
1887 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1888 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1889 setOperationAction(ISD::ANY_EXTEND, MVT::v32i8, Custom);
1890
1891 for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
1892 setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
1893 setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
1894 }
1895
1896 // These operations are handled on non-VLX by artificially widening in
1897 // isel patterns.
1898 // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1899
1900 if (Subtarget.hasBITALG()) {
1901 for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
1902 setOperationAction(ISD::CTPOP, VT, Legal);
1903 }
1904 }
1905
1906 if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
1907 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1908 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1909 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1910 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1911 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1912
1913 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1914 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1915 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1916 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1917 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1918
1919 if (Subtarget.hasBWI()) {
1920 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1921 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1922 }
1923
1924 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Custom);
1925 setOperationAction(ISD::TRUNCATE, MVT::v8i64, Custom);
1926 setOperationAction(ISD::TRUNCATE, MVT::v16i64, Custom);
1927 }
1928
1929 if (Subtarget.hasAMXTILE()) {
1930 addRegisterClass(MVT::x86amx, &X86::TILERegClass);
1931 }
1932
1933 // We want to custom lower some of our intrinsics.
1934 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1935 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1936 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1937 if (!Subtarget.is64Bit()) {
1938 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1939 }
1940
1941 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1942 // handle type legalization for these operations here.
1943 //
1944 // FIXME: We really should do custom legalization for addition and
1945 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1946 // than generic legalization for 64-bit multiplication-with-overflow, though.
1947 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1948 if (VT == MVT::i64 && !Subtarget.is64Bit())
1949 continue;
1950 // Add/Sub/Mul with overflow operations are custom lowered.
1951 setOperationAction(ISD::SADDO, VT, Custom);
1952 setOperationAction(ISD::UADDO, VT, Custom);
1953 setOperationAction(ISD::SSUBO, VT, Custom);
1954 setOperationAction(ISD::USUBO, VT, Custom);
1955 setOperationAction(ISD::SMULO, VT, Custom);
1956 setOperationAction(ISD::UMULO, VT, Custom);
1957
1958 // Support carry in as value rather than glue.
1959 setOperationAction(ISD::ADDCARRY, VT, Custom);
1960 setOperationAction(ISD::SUBCARRY, VT, Custom);
1961 setOperationAction(ISD::SETCCCARRY, VT, Custom);
1962 setOperationAction(ISD::SADDO_CARRY, VT, Custom);
1963 setOperationAction(ISD::SSUBO_CARRY, VT, Custom);
1964 }
1965
1966 if (!Subtarget.is64Bit()) {
1967 // These libcalls are not available in 32-bit.
1968 setLibcallName(RTLIB::SHL_I128, nullptr);
1969 setLibcallName(RTLIB::SRL_I128, nullptr);
1970 setLibcallName(RTLIB::SRA_I128, nullptr);
1971 setLibcallName(RTLIB::MUL_I128, nullptr);
1972 }
1973
1974 // Combine sin / cos into _sincos_stret if it is available.
1975 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1976 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1977 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1978 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1979 }
1980
1981 if (Subtarget.isTargetWin64()) {
1982 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1983 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1984 setOperationAction(ISD::SREM, MVT::i128, Custom);
1985 setOperationAction(ISD::UREM, MVT::i128, Custom);
1986 }
1987
1988 // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
1989 // is. We should promote the value to 64-bits to solve this.
1990 // This is what the CRT headers do - `fmodf` is an inline header
1991 // function casting to f64 and calling `fmod`.
1992 if (Subtarget.is32Bit() &&
1993 (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()))
1994 for (ISD::NodeType Op :
1995 {ISD::FCEIL, ISD::STRICT_FCEIL,
1996 ISD::FCOS, ISD::STRICT_FCOS,
1997 ISD::FEXP, ISD::STRICT_FEXP,
1998 ISD::FFLOOR, ISD::STRICT_FFLOOR,
1999 ISD::FREM, ISD::STRICT_FREM,
2000 ISD::FLOG, ISD::STRICT_FLOG,
2001 ISD::FLOG10, ISD::STRICT_FLOG10,
2002 ISD::FPOW, ISD::STRICT_FPOW,
2003 ISD::FSIN, ISD::STRICT_FSIN})
2004 if (isOperationExpand(Op, MVT::f32))
2005 setOperationAction(Op, MVT::f32, Promote);
2006
2007 // We have target-specific dag combine patterns for the following nodes:
2008 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
2009 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
2010 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
2011 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
2012 setTargetDAGCombine(ISD::CONCAT_VECTORS);
2013 setTargetDAGCombine(ISD::INSERT_SUBVECTOR);
2014 setTargetDAGCombine(ISD::EXTRACT_SUBVECTOR);
2015 setTargetDAGCombine(ISD::BITCAST);
2016 setTargetDAGCombine(ISD::VSELECT);
2017 setTargetDAGCombine(ISD::SELECT);
2018 setTargetDAGCombine(ISD::SHL);
2019 setTargetDAGCombine(ISD::SRA);
2020 setTargetDAGCombine(ISD::SRL);
2021 setTargetDAGCombine(ISD::OR);
2022 setTargetDAGCombine(ISD::AND);
2023 setTargetDAGCombine(ISD::ADD);
2024 setTargetDAGCombine(ISD::FADD);
2025 setTargetDAGCombine(ISD::FSUB);
2026 setTargetDAGCombine(ISD::FNEG);
2027 setTargetDAGCombine(ISD::FMA);
2028 setTargetDAGCombine(ISD::STRICT_FMA);
2029 setTargetDAGCombine(ISD::FMINNUM);
2030 setTargetDAGCombine(ISD::FMAXNUM);
2031 setTargetDAGCombine(ISD::SUB);
2032 setTargetDAGCombine(ISD::LOAD);
2033 setTargetDAGCombine(ISD::MLOAD);
2034 setTargetDAGCombine(ISD::STORE);
2035 setTargetDAGCombine(ISD::MSTORE);
2036 setTargetDAGCombine(ISD::TRUNCATE);
2037 setTargetDAGCombine(ISD::ZERO_EXTEND);
2038 setTargetDAGCombine(ISD::ANY_EXTEND);
2039 setTargetDAGCombine(ISD::SIGN_EXTEND);
2040 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
2041 setTargetDAGCombine(ISD::ANY_EXTEND_VECTOR_INREG);
2042 setTargetDAGCombine(ISD::SIGN_EXTEND_VECTOR_INREG);
2043 setTargetDAGCombine(ISD::ZERO_EXTEND_VECTOR_INREG);
2044 setTargetDAGCombine(ISD::SINT_TO_FP);
2045 setTargetDAGCombine(ISD::UINT_TO_FP);
2046 setTargetDAGCombine(ISD::STRICT_SINT_TO_FP);
2047 setTargetDAGCombine(ISD::STRICT_UINT_TO_FP);
2048 setTargetDAGCombine(ISD::SETCC);
2049 setTargetDAGCombine(ISD::MUL);
2050 setTargetDAGCombine(ISD::XOR);
2051 setTargetDAGCombine(ISD::MSCATTER);
2052 setTargetDAGCombine(ISD::MGATHER);
2053 setTargetDAGCombine(ISD::FP16_TO_FP);
2054 setTargetDAGCombine(ISD::FP_EXTEND);
2055 setTargetDAGCombine(ISD::STRICT_FP_EXTEND);
2056 setTargetDAGCombine(ISD::FP_ROUND);
2057
2058 computeRegisterProperties(Subtarget.getRegisterInfo());
2059
2060 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
2061 MaxStoresPerMemsetOptSize = 8;
2062 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
2063 MaxStoresPerMemcpyOptSize = 4;
2064 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
2065 MaxStoresPerMemmoveOptSize = 4;
2066
2067 // TODO: These control memcmp expansion in CGP and could be raised higher, but
2068 // that needs to benchmarked and balanced with the potential use of vector
2069 // load/store types (PR33329, PR33914).
2070 MaxLoadsPerMemcmp = 2;
2071 MaxLoadsPerMemcmpOptSize = 2;
2072
2073 // Set loop alignment to 2^ExperimentalPrefLoopAlignment bytes (default: 2^4).
2074 setPrefLoopAlignment(Align(1ULL << ExperimentalPrefLoopAlignment));
2075
2076 // An out-of-order CPU can speculatively execute past a predictable branch,
2077 // but a conditional move could be stalled by an expensive earlier operation.
2078 PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
2079 EnableExtLdPromotion = true;
2080 setPrefFunctionAlignment(Align(16));
2081
2082 verifyIntrinsicTables();
2083
2084 // Default to having -disable-strictnode-mutation on
2085 IsStrictFPEnabled = true;
2086}
2087
2088// This has so far only been implemented for 64-bit MachO.
2089bool X86TargetLowering::useLoadStackGuardNode() const {
2090 return Subtarget.isTargetMachO() && Subtarget.is64Bit();
2091}
2092
2093bool X86TargetLowering::useStackGuardXorFP() const {
2094 // Currently only MSVC CRTs XOR the frame pointer into the stack guard value.
2095 return Subtarget.getTargetTriple().isOSMSVCRT() && !Subtarget.isTargetMachO();
2096}
2097
2098SDValue X86TargetLowering::emitStackGuardXorFP(SelectionDAG &DAG, SDValue Val,
2099 const SDLoc &DL) const {
2100 EVT PtrTy = getPointerTy(DAG.getDataLayout());
2101 unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
2102 MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
2103 return SDValue(Node, 0);
2104}
2105
2106TargetLoweringBase::LegalizeTypeAction
2107X86TargetLowering::getPreferredVectorAction(MVT VT) const {
2108 if ((VT == MVT::v32i1 || VT == MVT::v64i1) && Subtarget.hasAVX512() &&
2109 !Subtarget.hasBWI())
2110 return TypeSplitVector;
2111
2112 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
2113 VT.getVectorElementType() != MVT::i1)
2114 return TypeWidenVector;
2115
2116 return TargetLoweringBase::getPreferredVectorAction(VT);
2117}
2118
2119static std::pair<MVT, unsigned>
2120handleMaskRegisterForCallingConv(unsigned NumElts, CallingConv::ID CC,
2121 const X86Subtarget &Subtarget) {
2122 // v2i1/v4i1/v8i1/v16i1 all pass in xmm registers unless the calling
2123 // convention is one that uses k registers.
2124 if (NumElts == 2)
2125 return {MVT::v2i64, 1};
2126 if (NumElts == 4)
2127 return {MVT::v4i32, 1};
2128 if (NumElts == 8 && CC != CallingConv::X86_RegCall &&
2129 CC != CallingConv::Intel_OCL_BI)
2130 return {MVT::v8i16, 1};
2131 if (NumElts == 16 && CC != CallingConv::X86_RegCall &&
2132 CC != CallingConv::Intel_OCL_BI)
2133 return {MVT::v16i8, 1};
2134 // v32i1 passes in ymm unless we have BWI and the calling convention is
2135 // regcall.
2136 if (NumElts == 32 && (!Subtarget.hasBWI() || CC != CallingConv::X86_RegCall))
2137 return {MVT::v32i8, 1};
2138 // Split v64i1 vectors if we don't have v64i8 available.
2139 if (NumElts == 64 && Subtarget.hasBWI() && CC != CallingConv::X86_RegCall) {
2140 if (Subtarget.useAVX512Regs())
2141 return {MVT::v64i8, 1};
2142 return {MVT::v32i8, 2};
2143 }
2144
2145 // Break wide or odd vXi1 vectors into scalars to match avx2 behavior.
2146 if (!isPowerOf2_32(NumElts) || (NumElts == 64 && !Subtarget.hasBWI()) ||
2147 NumElts > 64)
2148 return {MVT::i8, NumElts};
2149
2150 return {MVT::INVALID_SIMPLE_VALUE_TYPE, 0};
2151}
2152
2153MVT X86TargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
2154 CallingConv::ID CC,
2155 EVT VT) const {
2156 if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
2157 Subtarget.hasAVX512()) {
2158 unsigned NumElts = VT.getVectorNumElements();
2159
2160 MVT RegisterVT;
2161 unsigned NumRegisters;
2162 std::tie(RegisterVT, NumRegisters) =
2163 handleMaskRegisterForCallingConv(NumElts, CC, Subtarget);
2164 if (RegisterVT != MVT::INVALID_SIMPLE_VALUE_TYPE)
2165 return RegisterVT;
2166 }
2167
2168 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
2169}
2170
2171unsigned X86TargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
2172 CallingConv::ID CC,
2173 EVT VT) const {
2174 if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
2175 Subtarget.hasAVX512()) {
2176 unsigned NumElts = VT.getVectorNumElements();
2177
2178 MVT RegisterVT;
2179 unsigned NumRegisters;
2180 std::tie(RegisterVT, NumRegisters) =
2181 handleMaskRegisterForCallingConv(NumElts, CC, Subtarget);
2182 if (RegisterVT != MVT::INVALID_SIMPLE_VALUE_TYPE)
2183 return NumRegisters;
2184 }
2185
2186 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
2187}
2188
2189unsigned X86TargetLowering::getVectorTypeBreakdownForCallingConv(
2190 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
2191 unsigned &NumIntermediates, MVT &RegisterVT) const {
2192 // Break wide or odd vXi1 vectors into scalars to match avx2 behavior.
2193 if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
2194 Subtarget.hasAVX512() &&
2195 (!isPowerOf2_32(VT.getVectorNumElements()) ||
2196 (VT.getVectorNumElements() == 64 && !Subtarget.hasBWI()) ||
2197 VT.getVectorNumElements() > 64)) {
2198 RegisterVT = MVT::i8;
2199 IntermediateVT = MVT::i1;
2200 NumIntermediates = VT.getVectorNumElements();
2201 return NumIntermediates;
2202 }
2203
2204 // Split v64i1 vectors if we don't have v64i8 available.
2205 if (VT == MVT::v64i1 && Subtarget.hasBWI() && !Subtarget.useAVX512Regs() &&
2206 CC != CallingConv::X86_RegCall) {
2207 RegisterVT = MVT::v32i8;
2208 IntermediateVT = MVT::v32i1;
2209 NumIntermediates = 2;
2210 return 2;
2211 }
2212
2213 return TargetLowering::getVectorTypeBreakdownForCallingConv(Context, CC, VT, IntermediateVT,
2214 NumIntermediates, RegisterVT);
2215}
2216
2217EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL,
2218 LLVMContext& Context,
2219 EVT VT) const {
2220 if (!VT.isVector())
2221 return MVT::i8;
2222
2223 if (Subtarget.hasAVX512()) {
2224 // Figure out what this type will be legalized to.
2225 EVT LegalVT = VT;
2226 while (getTypeAction(Context, LegalVT) != TypeLegal)
2227 LegalVT = getTypeToTransformTo(Context, LegalVT);
2228
2229 // If we got a 512-bit vector then we'll definitely have a vXi1 compare.
2230 if (LegalVT.getSimpleVT().is512BitVector())
2231 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
2232
2233 if (LegalVT.getSimpleVT().isVector() && Subtarget.hasVLX()) {
2234 // If we legalized to less than a 512-bit vector, then we will use a vXi1
2235 // compare for vXi32/vXi64 for sure. If we have BWI we will also support
2236 // vXi16/vXi8.
2237 MVT EltVT = LegalVT.getSimpleVT().getVectorElementType();
2238 if (Subtarget.hasBWI() || EltVT.getSizeInBits() >= 32)
2239 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
2240 }
2241 }
2242
2243 return VT.changeVectorElementTypeToInteger();
2244}
2245
2246/// Helper for getByValTypeAlignment to determine
2247/// the desired ByVal argument alignment.
2248static void getMaxByValAlign(Type *Ty, Align &MaxAlign) {
2249 if (MaxAlign == 16)
2250 return;
2251 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
2252 if (VTy->getPrimitiveSizeInBits().getFixedSize() == 128)
2253 MaxAlign = Align(16);
2254 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2255 Align EltAlign;
2256 getMaxByValAlign(ATy->getElementType(), EltAlign);
2257 if (EltAlign > MaxAlign)
2258 MaxAlign = EltAlign;
2259 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2260 for (auto *EltTy : STy->elements()) {
2261 Align EltAlign;
2262 getMaxByValAlign(EltTy, EltAlign);
2263 if (EltAlign > MaxAlign)
2264 MaxAlign = EltAlign;
2265 if (MaxAlign == 16)
2266 break;
2267 }
2268 }
2269}
2270
2271/// Return the desired alignment for ByVal aggregate
2272/// function arguments in the caller parameter area. For X86, aggregates
2273/// that contain SSE vectors are placed at 16-byte boundaries while the rest
2274/// are at 4-byte boundaries.
2275unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
2276 const DataLayout &DL) const {
2277 if (Subtarget.is64Bit()) {
2278 // Max of 8 and alignment of type.
2279 Align TyAlign = DL.getABITypeAlign(Ty);
2280 if (TyAlign > 8)
2281 return TyAlign.value();
2282 return 8;
2283 }
2284
2285 Align Alignment(4);
2286 if (Subtarget.hasSSE1())
2287 getMaxByValAlign(Ty, Alignment);
2288 return Alignment.value();
2289}
2290
2291/// It returns EVT::Other if the type should be determined using generic
2292/// target-independent logic.
2293/// For vector ops we check that the overall size isn't larger than our
2294/// preferred vector width.
2295EVT X86TargetLowering::getOptimalMemOpType(
2296 const MemOp &Op, const AttributeList &FuncAttributes) const {
2297 if (!FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
2298 if (Op.size() >= 16 &&
2299 (!Subtarget.isUnalignedMem16Slow() || Op.isAligned(Align(16)))) {
2300 // FIXME: Check if unaligned 64-byte accesses are slow.
2301 if (Op.size() >= 64 && Subtarget.hasAVX512() &&
2302 (Subtarget.getPreferVectorWidth() >= 512)) {
2303 return Subtarget.hasBWI() ? MVT::v64i8 : MVT::v16i32;
2304 }
2305 // FIXME: Check if unaligned 32-byte accesses are slow.
2306 if (Op.size() >= 32 && Subtarget.hasAVX() &&
2307 (Subtarget.getPreferVectorWidth() >= 256)) {
2308 // Although this isn't a well-supported type for AVX1, we'll let
2309 // legalization and shuffle lowering produce the optimal codegen. If we
2310 // choose an optimal type with a vector element larger than a byte,
2311 // getMemsetStores() may create an intermediate splat (using an integer
2312 // multiply) before we splat as a vector.
2313 return MVT::v32i8;
2314 }
2315 if (Subtarget.hasSSE2() && (Subtarget.getPreferVectorWidth() >= 128))
2316 return MVT::v16i8;
2317 // TODO: Can SSE1 handle a byte vector?
2318 // If we have SSE1 registers we should be able to use them.
2319 if (Subtarget.hasSSE1() && (Subtarget.is64Bit() || Subtarget.hasX87()) &&
2320 (Subtarget.getPreferVectorWidth() >= 128))
2321 return MVT::v4f32;
2322 } else if (((Op.isMemcpy() && !Op.isMemcpyStrSrc()) || Op.isZeroMemset()) &&
2323 Op.size() >= 8 && !Subtarget.is64Bit() && Subtarget.hasSSE2()) {
2324 // Do not use f64 to lower memcpy if source is string constant. It's
2325 // better to use i32 to avoid the loads.
2326 // Also, do not use f64 to lower memset unless this is a memset of zeros.
2327 // The gymnastics of splatting a byte value into an XMM register and then
2328 // only using 8-byte stores (because this is a CPU with slow unaligned
2329 // 16-byte accesses) makes that a loser.
2330 return MVT::f64;
2331 }
2332 }
2333 // This is a compromise. If we reach here, unaligned accesses may be slow on
2334 // this target. However, creating smaller, aligned accesses could be even
2335 // slower and would certainly be a lot more code.
2336 if (Subtarget.is64Bit() && Op.size() >= 8)
2337 return MVT::i64;
2338 return MVT::i32;
2339}
2340
2341bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2342 if (VT == MVT::f32)
2343 return X86ScalarSSEf32;
2344 if (VT == MVT::f64)
2345 return X86ScalarSSEf64;
2346 return true;
2347}
2348
2349bool X86TargetLowering::allowsMisalignedMemoryAccesses(
2350 EVT VT, unsigned, Align Alignment, MachineMemOperand::Flags Flags,
2351 bool *Fast) const {
2352 if (Fast) {
2353 switch (VT.getSizeInBits()) {
2354 default:
2355 // 8-byte and under are always assumed to be fast.
2356 *Fast = true;
2357 break;
2358 case 128:
2359 *Fast = !Subtarget.isUnalignedMem16Slow();
2360 break;
2361 case 256:
2362 *Fast = !Subtarget.isUnalignedMem32Slow();
2363 break;
2364 // TODO: What about AVX-512 (512-bit) accesses?
2365 }
2366 }
2367 // NonTemporal vector memory ops must be aligned.
2368 if (!!(Flags & MachineMemOperand::MONonTemporal) && VT.isVector()) {
2369 // NT loads can only be vector aligned, so if its less aligned than the
2370 // minimum vector size (which we can split the vector down to), we might as
2371 // well use a regular unaligned vector load.
2372 // We don't have any NT loads pre-SSE41.
2373 if (!!(Flags & MachineMemOperand::MOLoad))
2374 return (Alignment < 16 || !Subtarget.hasSSE41());
2375 return false;
2376 }
2377 // Misaligned accesses of any size are always allowed.
2378 return true;
2379}
2380
2381/// Return the entry encoding for a jump table in the
2382/// current function. The returned value is a member of the
2383/// MachineJumpTableInfo::JTEntryKind enum.
2384unsigned X86TargetLowering::getJumpTableEncoding() const {
2385 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2386 // symbol.
2387 if (isPositionIndependent() && Subtarget.isPICStyleGOT())
2388 return MachineJumpTableInfo::EK_Custom32;
2389
2390 // Otherwise, use the normal jump table encoding heuristics.
2391 return TargetLowering::getJumpTableEncoding();
2392}
2393
2394bool X86TargetLowering::useSoftFloat() const {
2395 return Subtarget.useSoftFloat();
2396}
2397
2398void X86TargetLowering::markLibCallAttributes(MachineFunction *MF, unsigned CC,
2399 ArgListTy &Args) const {
2400
2401 // Only relabel X86-32 for C / Stdcall CCs.
2402 if (Subtarget.is64Bit())
2403 return;
2404 if (CC != CallingConv::C && CC != CallingConv::X86_StdCall)
2405 return;
2406 unsigned ParamRegs = 0;
2407 if (auto *M = MF->getFunction().getParent())
2408 ParamRegs = M->getNumberRegisterParameters();
2409
2410 // Mark the first N int arguments as having reg
2411 for (auto &Arg : Args) {
2412 Type *T = Arg.Ty;
2413 if (T->isIntOrPtrTy())
2414 if (MF->getDataLayout().getTypeAllocSize(T) <= 8) {
2415 unsigned numRegs = 1;
2416 if (MF->getDataLayout().getTypeAllocSize(T) > 4)
2417 numRegs = 2;
2418 if (ParamRegs < numRegs)
2419 return;
2420 ParamRegs -= numRegs;
2421 Arg.IsInReg = true;
2422 }
2423 }
2424}
2425
2426const MCExpr *
2427X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2428 const MachineBasicBlock *MBB,
2429 unsigned uid,MCContext &Ctx) const{
2430 assert(isPositionIndependent() && Subtarget.isPICStyleGOT())(static_cast <bool> (isPositionIndependent() &&
Subtarget.isPICStyleGOT()) ? void (0) : __assert_fail ("isPositionIndependent() && Subtarget.isPICStyleGOT()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 2430, __extension__ __PRETTY_FUNCTION__))
;
2431 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2432 // entries.
2433 return MCSymbolRefExpr::create(MBB->getSymbol(),
2434 MCSymbolRefExpr::VK_GOTOFF, Ctx);
2435}
2436
2437/// Returns relocation base for the given PIC jumptable.
2438SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2439 SelectionDAG &DAG) const {
2440 if (!Subtarget.is64Bit())
2441 // This doesn't have SDLoc associated with it, but is not really the
2442 // same as a Register.
2443 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2444 getPointerTy(DAG.getDataLayout()));
2445 return Table;
2446}
2447
2448/// This returns the relocation base for the given PIC jumptable,
2449/// the same as getPICJumpTableRelocBase, but as an MCExpr.
2450const MCExpr *X86TargetLowering::
2451getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2452 MCContext &Ctx) const {
2453 // X86-64 uses RIP relative addressing based on the jump table label.
2454 if (Subtarget.isPICStyleRIPRel())
2455 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2456
2457 // Otherwise, the reference is relative to the PIC base.
2458 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2459}
2460
2461std::pair<const TargetRegisterClass *, uint8_t>
2462X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2463 MVT VT) const {
2464 const TargetRegisterClass *RRC = nullptr;
2465 uint8_t Cost = 1;
2466 switch (VT.SimpleTy) {
2467 default:
2468 return TargetLowering::findRepresentativeClass(TRI, VT);
2469 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2470 RRC = Subtarget.is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2471 break;
2472 case MVT::x86mmx:
2473 RRC = &X86::VR64RegClass;
2474 break;
2475 case MVT::f32: case MVT::f64:
2476 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2477 case MVT::v4f32: case MVT::v2f64:
2478 case MVT::v32i8: case MVT::v16i16: case MVT::v8i32: case MVT::v4i64:
2479 case MVT::v8f32: case MVT::v4f64:
2480 case MVT::v64i8: case MVT::v32i16: case MVT::v16i32: case MVT::v8i64:
2481 case MVT::v16f32: case MVT::v8f64:
2482 RRC = &X86::VR128XRegClass;
2483 break;
2484 }
2485 return std::make_pair(RRC, Cost);
2486}
2487
2488unsigned X86TargetLowering::getAddressSpace() const {
2489 if (Subtarget.is64Bit())
2490 return (getTargetMachine().getCodeModel() == CodeModel::Kernel) ? 256 : 257;
2491 return 256;
2492}
2493
2494static bool hasStackGuardSlotTLS(const Triple &TargetTriple) {
2495 return TargetTriple.isOSGlibc() || TargetTriple.isOSFuchsia() ||
2496 (TargetTriple.isAndroid() && !TargetTriple.isAndroidVersionLT(17));
2497}
2498
2499static Constant* SegmentOffset(IRBuilderBase &IRB,
2500 int Offset, unsigned AddressSpace) {
2501 return ConstantExpr::getIntToPtr(
2502 ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2503 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2504}
2505
2506Value *X86TargetLowering::getIRStackGuard(IRBuilderBase &IRB) const {
2507 // glibc, bionic, and Fuchsia have a special slot for the stack guard in
2508 // tcbhead_t; use it instead of the usual global variable (see
2509 // sysdeps/{i386,x86_64}/nptl/tls.h)
2510 if (hasStackGuardSlotTLS(Subtarget.getTargetTriple())) {
2511 if (Subtarget.isTargetFuchsia()) {
2512 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
2513 return SegmentOffset(IRB, 0x10, getAddressSpace());
2514 } else {
2515 unsigned AddressSpace = getAddressSpace();
2516 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
2517 // Specially, some users may customize the base reg and offset.
2518 int Offset = M->getStackProtectorGuardOffset();
2519 // If we don't set -stack-protector-guard-offset value:
2520 // %fs:0x28, unless we're using a Kernel code model, in which case
2521 // it's %gs:0x28. gs:0x14 on i386.
2522 if (Offset == INT_MAX2147483647)
2523 Offset = (Subtarget.is64Bit()) ? 0x28 : 0x14;
2524
2525 StringRef GuardReg = M->getStackProtectorGuardReg();
2526 if (GuardReg == "fs")
2527 AddressSpace = X86AS::FS;
2528 else if (GuardReg == "gs")
2529 AddressSpace = X86AS::GS;
2530 return SegmentOffset(IRB, Offset, AddressSpace);
2531 }
2532 }
2533 return TargetLowering::getIRStackGuard(IRB);
2534}
2535
2536void X86TargetLowering::insertSSPDeclarations(Module &M) const {
2537 // MSVC CRT provides functionalities for stack protection.
2538 if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2539 Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2540 // MSVC CRT has a global variable holding security cookie.
2541 M.getOrInsertGlobal("__security_cookie",
2542 Type::getInt8PtrTy(M.getContext()));
2543
2544 // MSVC CRT has a function to validate security cookie.
2545 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
2546 "__security_check_cookie", Type::getVoidTy(M.getContext()),
2547 Type::getInt8PtrTy(M.getContext()));
2548 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
2549 F->setCallingConv(CallingConv::X86_FastCall);
2550 F->addAttribute(1, Attribute::AttrKind::InReg);
2551 }
2552 return;
2553 }
2554
2555 StringRef GuardMode = M.getStackProtectorGuard();
2556
2557 // glibc, bionic, and Fuchsia have a special slot for the stack guard.
2558 if ((GuardMode == "tls" || GuardMode.empty()) &&
2559 hasStackGuardSlotTLS(Subtarget.getTargetTriple()))
2560 return;
2561 TargetLowering::insertSSPDeclarations(M);
2562}
2563
2564Value *X86TargetLowering::getSDagStackGuard(const Module &M) const {
2565 // MSVC CRT has a global variable holding security cookie.
2566 if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2567 Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2568 return M.getGlobalVariable("__security_cookie");
2569 }
2570 return TargetLowering::getSDagStackGuard(M);
2571}
2572
2573Function *X86TargetLowering::getSSPStackGuardCheck(const Module &M) const {
2574 // MSVC CRT has a function to validate security cookie.
2575 if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2576 Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2577 return M.getFunction("__security_check_cookie");
2578 }
2579 return TargetLowering::getSSPStackGuardCheck(M);
2580}
2581
2582Value *
2583X86TargetLowering::getSafeStackPointerLocation(IRBuilderBase &IRB) const {
2584 if (Subtarget.getTargetTriple().isOSContiki())
2585 return getDefaultSafeStackPointerLocation(IRB, false);
2586
2587 // Android provides a fixed TLS slot for the SafeStack pointer. See the
2588 // definition of TLS_SLOT_SAFESTACK in
2589 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2590 if (Subtarget.isTargetAndroid()) {
2591 // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2592 // %gs:0x24 on i386
2593 int Offset = (Subtarget.is64Bit()) ? 0x48 : 0x24;
2594 return SegmentOffset(IRB, Offset, getAddressSpace());
2595 }
2596
2597 // Fuchsia is similar.
2598 if (Subtarget.isTargetFuchsia()) {
2599 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
2600 return SegmentOffset(IRB, 0x18, getAddressSpace());
2601 }
2602
2603 return TargetLowering::getSafeStackPointerLocation(IRB);
2604}
2605
2606//===----------------------------------------------------------------------===//
2607// Return Value Calling Convention Implementation
2608//===----------------------------------------------------------------------===//
2609
2610bool X86TargetLowering::CanLowerReturn(
2611 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2612 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2613 SmallVector<CCValAssign, 16> RVLocs;
2614 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2615 return CCInfo.CheckReturn(Outs, RetCC_X86);
2616}
2617
2618const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2619 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2620 return ScratchRegs;
2621}
2622
2623/// Lowers masks values (v*i1) to the local register values
2624/// \returns DAG node after lowering to register type
2625static SDValue lowerMasksToReg(const SDValue &ValArg, const EVT &ValLoc,
2626 const SDLoc &Dl, SelectionDAG &DAG) {
2627 EVT ValVT = ValArg.getValueType();
2628
2629 if (ValVT == MVT::v1i1)
2630 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Dl, ValLoc, ValArg,
2631 DAG.getIntPtrConstant(0, Dl));
2632
2633 if ((ValVT == MVT::v8i1 && (ValLoc == MVT::i8 || ValLoc == MVT::i32)) ||
2634 (ValVT == MVT::v16i1 && (ValLoc == MVT::i16 || ValLoc == MVT::i32))) {
2635 // Two stage lowering might be required
2636 // bitcast: v8i1 -> i8 / v16i1 -> i16
2637 // anyextend: i8 -> i32 / i16 -> i32
2638 EVT TempValLoc = ValVT == MVT::v8i1 ? MVT::i8 : MVT::i16;
2639 SDValue ValToCopy = DAG.getBitcast(TempValLoc, ValArg);
2640 if (ValLoc == MVT::i32)
2641 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValToCopy);
2642 return ValToCopy;
2643 }
2644
2645 if ((ValVT == MVT::v32i1 && ValLoc == MVT::i32) ||
2646 (ValVT == MVT::v64i1 && ValLoc == MVT::i64)) {
2647 // One stage lowering is required
2648 // bitcast: v32i1 -> i32 / v64i1 -> i64
2649 return DAG.getBitcast(ValLoc, ValArg);
2650 }
2651
2652 return DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValArg);
2653}
2654
2655/// Breaks v64i1 value into two registers and adds the new node to the DAG
2656static void Passv64i1ArgInRegs(
2657 const SDLoc &Dl, SelectionDAG &DAG, SDValue &Arg,
2658 SmallVectorImpl<std::pair<Register, SDValue>> &RegsToPass, CCValAssign &VA,
2659 CCValAssign &NextVA, const X86Subtarget &Subtarget) {
2660 assert(Subtarget.hasBWI() && "Expected AVX512BW target!")(static_cast <bool> (Subtarget.hasBWI() && "Expected AVX512BW target!"
) ? void (0) : __assert_fail ("Subtarget.hasBWI() && \"Expected AVX512BW target!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 2660, __extension__ __PRETTY_FUNCTION__))
;
2661 assert(Subtarget.is32Bit() && "Expecting 32 bit target")(static_cast <bool> (Subtarget.is32Bit() && "Expecting 32 bit target"
) ? void (0) : __assert_fail ("Subtarget.is32Bit() && \"Expecting 32 bit target\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 2661, __extension__ __PRETTY_FUNCTION__))
;
2662 assert(Arg.getValueType() == MVT::i64 && "Expecting 64 bit value")(static_cast <bool> (Arg.getValueType() == MVT::i64 &&
"Expecting 64 bit value") ? void (0) : __assert_fail ("Arg.getValueType() == MVT::i64 && \"Expecting 64 bit value\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 2662, __extension__ __PRETTY_FUNCTION__))
;
2663 assert(VA.isRegLoc() && NextVA.isRegLoc() &&(static_cast <bool> (VA.isRegLoc() && NextVA.isRegLoc
() && "The value should reside in two registers") ? void
(0) : __assert_fail ("VA.isRegLoc() && NextVA.isRegLoc() && \"The value should reside in two registers\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 2664, __extension__ __PRETTY_FUNCTION__))
2664 "The value should reside in two registers")(static_cast <bool> (VA.isRegLoc() && NextVA.isRegLoc
() && "The value should reside in two registers") ? void
(0) : __assert_fail ("VA.isRegLoc() && NextVA.isRegLoc() && \"The value should reside in two registers\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 2664, __extension__ __PRETTY_FUNCTION__))
;
2665
2666 // Before splitting the value we cast it to i64
2667 Arg = DAG.getBitcast(MVT::i64, Arg);
2668
2669 // Splitting the value into two i32 types
2670 SDValue Lo, Hi;
2671 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2672 DAG.getConstant(0, Dl, MVT::i32));
2673 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2674 DAG.getConstant(1, Dl, MVT::i32));
2675
2676 // Attach the two i32 types into corresponding registers
2677 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
2678 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Hi));
2679}
2680
2681SDValue
2682X86TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2683 bool isVarArg,
2684 const SmallVectorImpl<ISD::OutputArg> &Outs,
2685 const SmallVectorImpl<SDValue> &OutVals,
2686 const SDLoc &dl, SelectionDAG &DAG) const {
2687 MachineFunction &MF = DAG.getMachineFunction();
2688 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2689
2690 // In some cases we need to disable registers from the default CSR list.
2691 // For example, when they are used for argument passing.
2692 bool ShouldDisableCalleeSavedRegister =
2693 CallConv == CallingConv::X86_RegCall ||
2694 MF.getFunction().hasFnAttribute("no_caller_saved_registers");
2695
2696 if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2697 report_fatal_error("X86 interrupts may not return any value");
2698
2699 SmallVector<CCValAssign, 16> RVLocs;
2700 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2701 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2702
2703 SmallVector<std::pair<Register, SDValue>, 4> RetVals;
2704 for (unsigned I = 0, OutsIndex = 0, E = RVLocs.size(); I != E;
2705 ++I, ++OutsIndex) {
2706 CCValAssign &VA = RVLocs[I];
2707 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-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 2707, __extension__ __PRETTY_FUNCTION__))
;
2708
2709 // Add the register to the CalleeSaveDisableRegs list.
2710 if (ShouldDisableCalleeSavedRegister)
2711 MF.getRegInfo().disableCalleeSavedRegister(VA.getLocReg());
2712
2713 SDValue ValToCopy = OutVals[OutsIndex];
2714 EVT ValVT = ValToCopy.getValueType();
2715
2716 // Promote values to the appropriate types.
2717 if (VA.getLocInfo() == CCValAssign::SExt)
2718 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2719 else if (VA.getLocInfo() == CCValAssign::ZExt)
2720 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2721 else if (VA.getLocInfo() == CCValAssign::AExt) {
2722 if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2723 ValToCopy = lowerMasksToReg(ValToCopy, VA.getLocVT(), dl, DAG);
2724 else
2725 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2726 }
2727 else if (VA.getLocInfo() == CCValAssign::BCvt)
2728 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2729
2730 assert(VA.getLocInfo() != CCValAssign::FPExt &&(static_cast <bool> (VA.getLocInfo() != CCValAssign::FPExt
&& "Unexpected FP-extend for return value.") ? void (
0) : __assert_fail ("VA.getLocInfo() != CCValAssign::FPExt && \"Unexpected FP-extend for return value.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 2731, __extension__ __PRETTY_FUNCTION__))
2731 "Unexpected FP-extend for return value.")(static_cast <bool> (VA.getLocInfo() != CCValAssign::FPExt
&& "Unexpected FP-extend for return value.") ? void (
0) : __assert_fail ("VA.getLocInfo() != CCValAssign::FPExt && \"Unexpected FP-extend for return value.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 2731, __extension__ __PRETTY_FUNCTION__))
;
2732
2733 // Report an error if we have attempted to return a value via an XMM
2734 // register and SSE was disabled.
2735 if (!Subtarget.hasSSE1() && X86::FR32XRegClass.contains(VA.getLocReg())) {
2736 errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2737 VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2738 } else if (!Subtarget.hasSSE2() &&
2739 X86::FR64XRegClass.contains(VA.getLocReg()) &&
2740 ValVT == MVT::f64) {
2741 // When returning a double via an XMM register, report an error if SSE2 is
2742 // not enabled.
2743 errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
2744 VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2745 }
2746
2747 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2748 // the RET instruction and handled by the FP Stackifier.
2749 if (VA.getLocReg() == X86::FP0 ||
2750 VA.getLocReg() == X86::FP1) {
2751 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2752 // change the value to the FP stack register class.
2753 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2754 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2755 RetVals.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
2756 // Don't emit a copytoreg.
2757 continue;
2758 }
2759
2760 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2761 // which is returned in RAX / RDX.
2762 if (Subtarget.is64Bit()) {
2763 if (ValVT == MVT::x86mmx) {
2764 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2765 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2766 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2767 ValToCopy);
2768 // If we don't have SSE2 available, convert to v4f32 so the generated
2769 // register is legal.
2770 if (!Subtarget.hasSSE2())
2771 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2772 }
2773 }
2774 }
2775
2776 if (VA.needsCustom()) {
2777 assert(VA.getValVT() == MVT::v64i1 &&(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? void (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 2778, __extension__ __PRETTY_FUNCTION__))
2778 "Currently the only custom case is when we split v64i1 to 2 regs")(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? void (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 2778, __extension__ __PRETTY_FUNCTION__))
;
2779
2780 Passv64i1ArgInRegs(dl, DAG, ValToCopy, RetVals, VA, RVLocs[++I],
2781 Subtarget);
2782
2783 // Add the second register to the CalleeSaveDisableRegs list.
2784 if (ShouldDisableCalleeSavedRegister)
2785 MF.getRegInfo().disableCalleeSavedRegister(RVLocs[I].getLocReg());
2786 } else {
2787 RetVals.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
2788 }
2789 }
2790
2791 SDValue Flag;
2792 SmallVector<SDValue, 6> RetOps;
2793 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2794 // Operand #1 = Bytes To Pop
2795 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2796 MVT::i32));
2797
2798 // Copy the result values into the output registers.
2799 for (auto &RetVal : RetVals) {
2800 if (RetVal.first == X86::FP0 || RetVal.first == X86::FP1) {
2801 RetOps.push_back(RetVal.second);
2802 continue; // Don't emit a copytoreg.
2803 }
2804
2805 Chain = DAG.getCopyToReg(Chain, dl, RetVal.first, RetVal.second, Flag);
2806 Flag = Chain.getValue(1);
2807 RetOps.push_back(
2808 DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
2809 }
2810
2811 // Swift calling convention does not require we copy the sret argument
2812 // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
2813
2814 // All x86 ABIs require that for returning structs by value we copy
2815 // the sret argument into %rax/%eax (depending on ABI) for the return.
2816 // We saved the argument into a virtual register in the entry block,
2817 // so now we copy the value out and into %rax/%eax.
2818 //
2819 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2820 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2821 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2822 // either case FuncInfo->setSRetReturnReg() will have been called.
2823 if (Register SRetReg = FuncInfo->getSRetReturnReg()) {
2824 // When we have both sret and another return value, we should use the
2825 // original Chain stored in RetOps[0], instead of the current Chain updated
2826 // in the above loop. If we only have sret, RetOps[0] equals to Chain.
2827
2828 // For the case of sret and another return value, we have
2829 // Chain_0 at the function entry
2830 // Chain_1 = getCopyToReg(Chain_0) in the above loop
2831 // If we use Chain_1 in getCopyFromReg, we will have
2832 // Val = getCopyFromReg(Chain_1)
2833 // Chain_2 = getCopyToReg(Chain_1, Val) from below
2834
2835 // getCopyToReg(Chain_0) will be glued together with
2836 // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
2837 // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
2838 // Data dependency from Unit B to Unit A due to usage of Val in
2839 // getCopyToReg(Chain_1, Val)
2840 // Chain dependency from Unit A to Unit B
2841
2842 // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
2843 SDValue Val = DAG.getCopyFromReg(RetOps[0], dl, SRetReg,
2844 getPointerTy(MF.getDataLayout()));
2845
2846 Register RetValReg
2847 = (Subtarget.is64Bit() && !Subtarget.isTarget64BitILP32()) ?
2848 X86::RAX : X86::EAX;
2849 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2850 Flag = Chain.getValue(1);
2851
2852 // RAX/EAX now acts like a return value.
2853 RetOps.push_back(
2854 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2855
2856 // Add the returned register to the CalleeSaveDisableRegs list.
2857 if (ShouldDisableCalleeSavedRegister)
2858 MF.getRegInfo().disableCalleeSavedRegister(RetValReg);
2859 }
2860
2861 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
2862 const MCPhysReg *I =
2863 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2864 if (I) {
2865 for (; *I; ++I) {
2866 if (X86::GR64RegClass.contains(*I))
2867 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2868 else
2869 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 2869)
;
2870 }
2871 }
2872
2873 RetOps[0] = Chain; // Update chain.
2874
2875 // Add the flag if we have it.
2876 if (Flag.getNode())
2877 RetOps.push_back(Flag);
2878
2879 X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2880 if (CallConv == CallingConv::X86_INTR)
2881 opcode = X86ISD::IRET;
2882 return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2883}
2884
2885bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2886 if (N->getNumValues() != 1 || !N->hasNUsesOfValue(1, 0))
2887 return false;
2888
2889 SDValue TCChain = Chain;
2890 SDNode *Copy = *N->use_begin();
2891 if (Copy->getOpcode() == ISD::CopyToReg) {
2892 // If the copy has a glue operand, we conservatively assume it isn't safe to
2893 // perform a tail call.
2894 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2895 return false;
2896 TCChain = Copy->getOperand(0);
2897 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2898 return false;
2899
2900 bool HasRet = false;
2901 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2902 UI != UE; ++UI) {
2903 if (UI->getOpcode() != X86ISD::RET_FLAG)
2904 return false;
2905 // If we are returning more than one value, we can definitely
2906 // not make a tail call see PR19530
2907 if (UI->getNumOperands() > 4)
2908 return false;
2909 if (UI->getNumOperands() == 4 &&
2910 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2911 return false;
2912 HasRet = true;
2913 }
2914
2915 if (!HasRet)
2916 return false;
2917
2918 Chain = TCChain;
2919 return true;
2920}
2921
2922EVT X86TargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
2923 ISD::NodeType ExtendKind) const {
2924 MVT ReturnMVT = MVT::i32;
2925
2926 bool Darwin = Subtarget.getTargetTriple().isOSDarwin();
2927 if (VT == MVT::i1 || (!Darwin && (VT == MVT::i8 || VT == MVT::i16))) {
2928 // The ABI does not require i1, i8 or i16 to be extended.
2929 //
2930 // On Darwin, there is code in the wild relying on Clang's old behaviour of
2931 // always extending i8/i16 return values, so keep doing that for now.
2932 // (PR26665).
2933 ReturnMVT = MVT::i8;
2934 }
2935
2936 EVT MinVT = getRegisterType(Context, ReturnMVT);
2937 return VT.bitsLT(MinVT) ? MinVT : VT;
2938}
2939
2940/// Reads two 32 bit registers and creates a 64 bit mask value.
2941/// \param VA The current 32 bit value that need to be assigned.
2942/// \param NextVA The next 32 bit value that need to be assigned.
2943/// \param Root The parent DAG node.
2944/// \param [in,out] InFlag Represents SDvalue in the parent DAG node for
2945/// glue purposes. In the case the DAG is already using
2946/// physical register instead of virtual, we should glue
2947/// our new SDValue to InFlag SDvalue.
2948/// \return a new SDvalue of size 64bit.
2949static SDValue getv64i1Argument(CCValAssign &VA, CCValAssign &NextVA,
2950 SDValue &Root, SelectionDAG &DAG,
2951 const SDLoc &Dl, const X86Subtarget &Subtarget,
2952 SDValue *InFlag = nullptr) {
2953 assert((Subtarget.hasBWI()) && "Expected AVX512BW target!")(static_cast <bool> ((Subtarget.hasBWI()) && "Expected AVX512BW target!"
) ? void (0) : __assert_fail ("(Subtarget.hasBWI()) && \"Expected AVX512BW target!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 2953, __extension__ __PRETTY_FUNCTION__))
;
2954 assert(Subtarget.is32Bit() && "Expecting 32 bit target")(static_cast <bool> (Subtarget.is32Bit() && "Expecting 32 bit target"
) ? void (0) : __assert_fail ("Subtarget.is32Bit() && \"Expecting 32 bit target\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 2954, __extension__ __PRETTY_FUNCTION__))
;
2955 assert(VA.getValVT() == MVT::v64i1 &&(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Expecting first location of 64 bit width type") ? void (0) :
__assert_fail ("VA.getValVT() == MVT::v64i1 && \"Expecting first location of 64 bit width type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 2956, __extension__ __PRETTY_FUNCTION__))
2956 "Expecting first location of 64 bit width type")(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Expecting first location of 64 bit width type") ? void (0) :
__assert_fail ("VA.getValVT() == MVT::v64i1 && \"Expecting first location of 64 bit width type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 2956, __extension__ __PRETTY_FUNCTION__))
;
2957 assert(NextVA.getValVT() == VA.getValVT() &&(static_cast <bool> (NextVA.getValVT() == VA.getValVT()
&& "The locations should have the same type") ? void
(0) : __assert_fail ("NextVA.getValVT() == VA.getValVT() && \"The locations should have the same type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 2958, __extension__ __PRETTY_FUNCTION__))
2958 "The locations should have the same type")(static_cast <bool> (NextVA.getValVT() == VA.getValVT()
&& "The locations should have the same type") ? void
(0) : __assert_fail ("NextVA.getValVT() == VA.getValVT() && \"The locations should have the same type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 2958, __extension__ __PRETTY_FUNCTION__))
;
2959 assert(VA.isRegLoc() && NextVA.isRegLoc() &&(static_cast <bool> (VA.isRegLoc() && NextVA.isRegLoc
() && "The values should reside in two registers") ? void
(0) : __assert_fail ("VA.isRegLoc() && NextVA.isRegLoc() && \"The values should reside in two registers\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 2960, __extension__ __PRETTY_FUNCTION__))
2960 "The values should reside in two registers")(static_cast <bool> (VA.isRegLoc() && NextVA.isRegLoc
() && "The values should reside in two registers") ? void
(0) : __assert_fail ("VA.isRegLoc() && NextVA.isRegLoc() && \"The values should reside in two registers\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 2960, __extension__ __PRETTY_FUNCTION__))
;
2961
2962 SDValue Lo, Hi;
2963 SDValue ArgValueLo, ArgValueHi;
2964
2965 MachineFunction &MF = DAG.getMachineFunction();
2966 const TargetRegisterClass *RC = &X86::GR32RegClass;
2967
2968 // Read a 32 bit value from the registers.
2969 if (nullptr == InFlag) {
2970 // When no physical register is present,
2971 // create an intermediate virtual register.
2972 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
2973 ArgValueLo = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2974 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2975 ArgValueHi = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2976 } else {
2977 // When a physical register is available read the value from it and glue
2978 // the reads together.
2979 ArgValueLo =
2980 DAG.getCopyFromReg(Root, Dl, VA.getLocReg(), MVT::i32, *InFlag);
2981 *InFlag = ArgValueLo.getValue(2);
2982 ArgValueHi =
2983 DAG.getCopyFromReg(Root, Dl, NextVA.getLocReg(), MVT::i32, *InFlag);
2984 *InFlag = ArgValueHi.getValue(2);
2985 }
2986
2987 // Convert the i32 type into v32i1 type.
2988 Lo = DAG.getBitcast(MVT::v32i1, ArgValueLo);
2989
2990 // Convert the i32 type into v32i1 type.
2991 Hi = DAG.getBitcast(MVT::v32i1, ArgValueHi);
2992
2993 // Concatenate the two values together.
2994 return DAG.getNode(ISD::CONCAT_VECTORS, Dl, MVT::v64i1, Lo, Hi);
2995}
2996
2997/// The function will lower a register of various sizes (8/16/32/64)
2998/// to a mask value of the expected size (v8i1/v16i1/v32i1/v64i1)
2999/// \returns a DAG node contains the operand after lowering to mask type.
3000static SDValue lowerRegToMasks(const SDValue &ValArg, const EVT &ValVT,
3001 const EVT &ValLoc, const SDLoc &Dl,
3002 SelectionDAG &DAG) {
3003 SDValue ValReturned = ValArg;
3004
3005 if (ValVT == MVT::v1i1)
3006 return DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v1i1, ValReturned);
3007
3008 if (ValVT == MVT::v64i1) {
3009 // In 32 bit machine, this case is handled by getv64i1Argument
3010 assert(ValLoc == MVT::i64 && "Expecting only i64 locations")(static_cast <bool> (ValLoc == MVT::i64 && "Expecting only i64 locations"
) ? void (0) : __assert_fail ("ValLoc == MVT::i64 && \"Expecting only i64 locations\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3010, __extension__ __PRETTY_FUNCTION__))
;
3011 // In 64 bit machine, There is no need to truncate the value only bitcast
3012 } else {
3013 MVT maskLen;
3014 switch (ValVT.getSimpleVT().SimpleTy) {
3015 case MVT::v8i1:
3016 maskLen = MVT::i8;
3017 break;
3018 case MVT::v16i1:
3019 maskLen = MVT::i16;
3020 break;
3021 case MVT::v32i1:
3022 maskLen = MVT::i32;
3023 break;
3024 default:
3025 llvm_unreachable("Expecting a vector of i1 types")::llvm::llvm_unreachable_internal("Expecting a vector of i1 types"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3025)
;
3026 }
3027
3028 ValReturned = DAG.getNode(ISD::TRUNCATE, Dl, maskLen, ValReturned);
3029 }
3030 return DAG.getBitcast(ValVT, ValReturned);
3031}
3032
3033/// Lower the result values of a call into the
3034/// appropriate copies out of appropriate physical registers.
3035///
3036SDValue X86TargetLowering::LowerCallResult(
3037 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
3038 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3039 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
3040 uint32_t *RegMask) const {
3041
3042 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3043 // Assign locations to each value returned by this call.
3044 SmallVector<CCValAssign, 16> RVLocs;
3045 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3046 *DAG.getContext());
3047 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3048
3049 // Copy all of the result registers out of their specified physreg.
3050 for (unsigned I = 0, InsIndex = 0, E = RVLocs.size(); I != E;
3051 ++I, ++InsIndex) {
3052 CCValAssign &VA = RVLocs[I];
3053 EVT CopyVT = VA.getLocVT();
3054
3055 // In some calling conventions we need to remove the used registers
3056 // from the register mask.
3057 if (RegMask) {
3058 for (MCSubRegIterator SubRegs(VA.getLocReg(), TRI, /*IncludeSelf=*/true);
3059 SubRegs.isValid(); ++SubRegs)
3060 RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
3061 }
3062
3063 // Report an error if there was an attempt to return FP values via XMM
3064 // registers.
3065 if (!Subtarget.hasSSE1() && X86::FR32XRegClass.contains(VA.getLocReg())) {
3066 errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
3067 if (VA.getLocReg() == X86::XMM1)
3068 VA.convertToReg(X86::FP1); // Set reg to FP1, avoid hitting asserts.
3069 else
3070 VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
3071 } else if (!Subtarget.hasSSE2() &&
3072 X86::FR64XRegClass.contains(VA.getLocReg()) &&
3073 CopyVT == MVT::f64) {
3074 errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
3075 if (VA.getLocReg() == X86::XMM1)
3076 VA.convertToReg(X86::FP1); // Set reg to FP1, avoid hitting asserts.
3077 else
3078 VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
3079 }
3080
3081 // If we prefer to use the value in xmm registers, copy it out as f80 and
3082 // use a truncate to move it from fp stack reg to xmm reg.
3083 bool RoundAfterCopy = false;
3084 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3085 isScalarFPTypeInSSEReg(VA.getValVT())) {
3086 if (!Subtarget.hasX87())
3087 report_fatal_error("X87 register return with X87 disabled");
3088 CopyVT = MVT::f80;
3089 RoundAfterCopy = (CopyVT != VA.getLocVT());
3090 }
3091
3092 SDValue Val;
3093 if (VA.needsCustom()) {
3094 assert(VA.getValVT() == MVT::v64i1 &&(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? void (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3095, __extension__ __PRETTY_FUNCTION__))
3095 "Currently the only custom case is when we split v64i1 to 2 regs")(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? void (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3095, __extension__ __PRETTY_FUNCTION__))
;
3096 Val =
3097 getv64i1Argument(VA, RVLocs[++I], Chain, DAG, dl, Subtarget, &InFlag);
3098 } else {
3099 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), CopyVT, InFlag)
3100 .getValue(1);
3101 Val = Chain.getValue(0);
3102 InFlag = Chain.getValue(2);
3103 }
3104
3105 if (RoundAfterCopy)
3106 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
3107 // This truncation won't change the value.
3108 DAG.getIntPtrConstant(1, dl));
3109
3110 if (VA.isExtInLoc()) {
3111 if (VA.getValVT().isVector() &&
3112 VA.getValVT().getScalarType() == MVT::i1 &&
3113 ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3114 (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3115 // promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3116 Val = lowerRegToMasks(Val, VA.getValVT(), VA.getLocVT(), dl, DAG);
3117 } else
3118 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3119 }
3120
3121 if (VA.getLocInfo() == CCValAssign::BCvt)
3122 Val = DAG.getBitcast(VA.getValVT(), Val);
3123
3124 InVals.push_back(Val);
3125 }
3126
3127 return Chain;
3128}
3129
3130//===----------------------------------------------------------------------===//
3131// C & StdCall & Fast Calling Convention implementation
3132//===----------------------------------------------------------------------===//
3133// StdCall calling convention seems to be standard for many Windows' API
3134// routines and around. It differs from C calling convention just a little:
3135// callee should clean up the stack, not caller. Symbols should be also
3136// decorated in some fancy way :) It doesn't support any vector arguments.
3137// For info on fast calling convention see Fast Calling Convention (tail call)
3138// implementation LowerX86_32FastCCCallTo.
3139
3140/// CallIsStructReturn - Determines whether a call uses struct return
3141/// semantics.
3142enum StructReturnType {
3143 NotStructReturn,
3144 RegStructReturn,
3145 StackStructReturn
3146};
3147static StructReturnType
3148callIsStructReturn(ArrayRef<ISD::OutputArg> Outs, bool IsMCU) {
3149 if (Outs.empty())
3150 return NotStructReturn;
3151
3152 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
3153 if (!Flags.isSRet())
3154 return NotStructReturn;
3155 if (Flags.isInReg() || IsMCU)
3156 return RegStructReturn;
3157 return StackStructReturn;
3158}
3159
3160/// Determines whether a function uses struct return semantics.
3161static StructReturnType
3162argsAreStructReturn(ArrayRef<ISD::InputArg> Ins, bool IsMCU) {
3163 if (Ins.empty())
3164 return NotStructReturn;
3165
3166 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
3167 if (!Flags.isSRet())
3168 return NotStructReturn;
3169 if (Flags.isInReg() || IsMCU)
3170 return RegStructReturn;
3171 return StackStructReturn;
3172}
3173
3174/// Make a copy of an aggregate at address specified by "Src" to address
3175/// "Dst" with size and alignment information specified by the specific
3176/// parameter attribute. The copy will be passed as a byval function parameter.
3177static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
3178 SDValue Chain, ISD::ArgFlagsTy Flags,
3179 SelectionDAG &DAG, const SDLoc &dl) {
3180 SDValue SizeNode = DAG.getIntPtrConstant(Flags.getByValSize(), dl);
3181
3182 return DAG.getMemcpy(
3183 Chain, dl, Dst, Src, SizeNode, Flags.getNonZeroByValAlign(),
3184 /*isVolatile*/ false, /*AlwaysInline=*/true,
3185 /*isTailCall*/ false, MachinePointerInfo(), MachinePointerInfo());
3186}
3187
3188/// Return true if the calling convention is one that we can guarantee TCO for.
3189static bool canGuaranteeTCO(CallingConv::ID CC) {
3190 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
3191 CC == CallingConv::X86_RegCall || CC == CallingConv::HiPE ||
3192 CC == CallingConv::HHVM || CC == CallingConv::Tail ||
3193 CC == CallingConv::SwiftTail);
3194}
3195
3196/// Return true if we might ever do TCO for calls with this calling convention.
3197static bool mayTailCallThisCC(CallingConv::ID CC) {
3198 switch (CC) {
3199 // C calling conventions:
3200 case CallingConv::C:
3201 case CallingConv::Win64:
3202 case CallingConv::X86_64_SysV:
3203 // Callee pop conventions:
3204 case CallingConv::X86_ThisCall:
3205 case CallingConv::X86_StdCall:
3206 case CallingConv::X86_VectorCall:
3207 case CallingConv::X86_FastCall:
3208 // Swift:
3209 case CallingConv::Swift:
3210 return true;
3211 default:
3212 return canGuaranteeTCO(CC);
3213 }
3214}
3215
3216/// Return true if the function is being made into a tailcall target by
3217/// changing its ABI.
3218static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
3219 return (GuaranteedTailCallOpt && canGuaranteeTCO(CC)) ||
3220 CC == CallingConv::Tail || CC == CallingConv::SwiftTail;
3221}
3222
3223bool X86TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3224 if (!CI->isTailCall())
3225 return false;
3226
3227 CallingConv::ID CalleeCC = CI->getCallingConv();
3228 if (!mayTailCallThisCC(CalleeCC))
3229 return false;
3230
3231 return true;
3232}
3233
3234SDValue
3235X86TargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
3236 const SmallVectorImpl<ISD::InputArg> &Ins,
3237 const SDLoc &dl, SelectionDAG &DAG,
3238 const CCValAssign &VA,
3239 MachineFrameInfo &MFI, unsigned i) const {
3240 // Create the nodes corresponding to a load from this parameter slot.
3241 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3242 bool AlwaysUseMutable = shouldGuaranteeTCO(
3243 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
3244 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
3245 EVT ValVT;
3246 MVT PtrVT = getPointerTy(DAG.getDataLayout());
3247
3248 // If value is passed by pointer we have address passed instead of the value
3249 // itself. No need to extend if the mask value and location share the same
3250 // absolute size.
3251 bool ExtendedInMem =
3252 VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1 &&
3253 VA.getValVT().getSizeInBits() != VA.getLocVT().getSizeInBits();
3254
3255 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
3256 ValVT = VA.getLocVT();
3257 else
3258 ValVT = VA.getValVT();
3259
3260 // FIXME: For now, all byval parameter objects are marked mutable. This can be
3261 // changed with more analysis.
3262 // In case of tail call optimization mark all arguments mutable. Since they
3263 // could be overwritten by lowering of arguments in case of a tail call.
3264 if (Flags.isByVal()) {
3265 unsigned Bytes = Flags.getByValSize();
3266 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
3267
3268 // FIXME: For now, all byval parameter objects are marked as aliasing. This
3269 // can be improved with deeper analysis.
3270 int FI = MFI.CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable,
3271 /*isAliased=*/true);
3272 return DAG.getFrameIndex(FI, PtrVT);
3273 }
3274
3275 EVT ArgVT = Ins[i].ArgVT;
3276
3277 // If this is a vector that has been split into multiple parts, and the
3278 // scalar size of the parts don't match the vector element size, then we can't
3279 // elide the copy. The parts will have padding between them instead of being
3280 // packed like a vector.
3281 bool ScalarizedAndExtendedVector =
3282 ArgVT.isVector() && !VA.getLocVT().isVector() &&
3283 VA.getLocVT().getSizeInBits() != ArgVT.getScalarSizeInBits();
3284
3285 // This is an argument in memory. We might be able to perform copy elision.
3286 // If the argument is passed directly in memory without any extension, then we
3287 // can perform copy elision. Large vector types, for example, may be passed
3288 // indirectly by pointer.
3289 if (Flags.isCopyElisionCandidate() &&
3290 VA.getLocInfo() != CCValAssign::Indirect && !ExtendedInMem &&
3291 !ScalarizedAndExtendedVector) {
3292 SDValue PartAddr;
3293 if (Ins[i].PartOffset == 0) {
3294 // If this is a one-part value or the first part of a multi-part value,
3295 // create a stack object for the entire argument value type and return a
3296 // load from our portion of it. This assumes that if the first part of an
3297 // argument is in memory, the rest will also be in memory.
3298 int FI = MFI.CreateFixedObject(ArgVT.getStoreSize(), VA.getLocMemOffset(),
3299 /*IsImmutable=*/false);
3300 PartAddr = DAG.getFrameIndex(FI, PtrVT);
3301 return DAG.getLoad(
3302 ValVT, dl, Chain, PartAddr,
3303 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3304 } else {
3305 // This is not the first piece of an argument in memory. See if there is
3306 // already a fixed stack object including this offset. If so, assume it
3307 // was created by the PartOffset == 0 branch above and create a load from
3308 // the appropriate offset into it.
3309 int64_t PartBegin = VA.getLocMemOffset();
3310 int64_t PartEnd = PartBegin + ValVT.getSizeInBits() / 8;
3311 int FI = MFI.getObjectIndexBegin();
3312 for (; MFI.isFixedObjectIndex(FI); ++FI) {
3313 int64_t ObjBegin = MFI.getObjectOffset(FI);
3314 int64_t ObjEnd = ObjBegin + MFI.getObjectSize(FI);
3315 if (ObjBegin <= PartBegin && PartEnd <= ObjEnd)
3316 break;
3317 }
3318 if (MFI.isFixedObjectIndex(FI)) {
3319 SDValue Addr =
3320 DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getFrameIndex(FI, PtrVT),
3321 DAG.getIntPtrConstant(Ins[i].PartOffset, dl));
3322 return DAG.getLoad(
3323 ValVT, dl, Chain, Addr,
3324 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI,
3325 Ins[i].PartOffset));
3326 }
3327 }
3328 }
3329
3330 int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
3331 VA.getLocMemOffset(), isImmutable);
3332
3333 // Set SExt or ZExt flag.
3334 if (VA.getLocInfo() == CCValAssign::ZExt) {
3335 MFI.setObjectZExt(FI, true);
3336 } else if (VA.getLocInfo() == CCValAssign::SExt) {
3337 MFI.setObjectSExt(FI, true);
3338 }
3339
3340 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3341 SDValue Val = DAG.getLoad(
3342 ValVT, dl, Chain, FIN,
3343 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3344 return ExtendedInMem
3345 ? (VA.getValVT().isVector()
3346 ? DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VA.getValVT(), Val)
3347 : DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val))
3348 : Val;
3349}
3350
3351// FIXME: Get this from tablegen.
3352static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
3353 const X86Subtarget &Subtarget) {
3354 assert(Subtarget.is64Bit())(static_cast <bool> (Subtarget.is64Bit()) ? void (0) : __assert_fail
("Subtarget.is64Bit()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3354, __extension__ __PRETTY_FUNCTION__))
;
3355
3356 if (Subtarget.isCallingConvWin64(CallConv)) {
3357 static const MCPhysReg GPR64ArgRegsWin64[] = {
3358 X86::RCX, X86::RDX, X86::R8, X86::R9
3359 };
3360 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
3361 }
3362
3363 static const MCPhysReg GPR64ArgRegs64Bit[] = {
3364 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
3365 };
3366 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
3367}
3368
3369// FIXME: Get this from tablegen.
3370static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
3371 CallingConv::ID CallConv,
3372 const X86Subtarget &Subtarget) {
3373 assert(Subtarget.is64Bit())(static_cast <bool> (Subtarget.is64Bit()) ? void (0) : __assert_fail
("Subtarget.is64Bit()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3373, __extension__ __PRETTY_FUNCTION__))
;
3374 if (Subtarget.isCallingConvWin64(CallConv)) {
3375 // The XMM registers which might contain var arg parameters are shadowed
3376 // in their paired GPR. So we only need to save the GPR to their home
3377 // slots.
3378 // TODO: __vectorcall will change this.
3379 return None;
3380 }
3381
3382 bool isSoftFloat = Subtarget.useSoftFloat();
3383 if (isSoftFloat || !Subtarget.hasSSE1())
3384 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
3385 // registers.
3386 return None;
3387
3388 static const MCPhysReg XMMArgRegs64Bit[] = {
3389 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3390 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3391 };
3392 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
3393}
3394
3395#ifndef NDEBUG
3396static bool isSortedByValueNo(ArrayRef<CCValAssign> ArgLocs) {
3397 return llvm::is_sorted(
3398 ArgLocs, [](const CCValAssign &A, const CCValAssign &B) -> bool {
3399 return A.getValNo() < B.getValNo();
3400 });
3401}
3402#endif
3403
3404namespace {
3405/// This is a helper class for lowering variable arguments parameters.
3406class VarArgsLoweringHelper {
3407public:
3408 VarArgsLoweringHelper(X86MachineFunctionInfo *FuncInfo, const SDLoc &Loc,
3409 SelectionDAG &DAG, const X86Subtarget &Subtarget,
3410 CallingConv::ID CallConv, CCState &CCInfo)
3411 : FuncInfo(FuncInfo), DL(Loc), DAG(DAG), Subtarget(Subtarget),
3412 TheMachineFunction(DAG.getMachineFunction()),
3413 TheFunction(TheMachineFunction.getFunction()),
3414 FrameInfo(TheMachineFunction.getFrameInfo()),
3415 FrameLowering(*Subtarget.getFrameLowering()),
3416 TargLowering(DAG.getTargetLoweringInfo()), CallConv(CallConv),
3417 CCInfo(CCInfo) {}
3418
3419 // Lower variable arguments parameters.
3420 void lowerVarArgsParameters(SDValue &Chain, unsigned StackSize);
3421
3422private:
3423 void createVarArgAreaAndStoreRegisters(SDValue &Chain, unsigned StackSize);
3424
3425 void forwardMustTailParameters(SDValue &Chain);
3426
3427 bool is64Bit() const { return Subtarget.is64Bit(); }
3428 bool isWin64() const { return Subtarget.isCallingConvWin64(CallConv); }
3429
3430 X86MachineFunctionInfo *FuncInfo;
3431 const SDLoc &DL;
3432 SelectionDAG &DAG;
3433 const X86Subtarget &Subtarget;
3434 MachineFunction &TheMachineFunction;
3435 const Function &TheFunction;
3436 MachineFrameInfo &FrameInfo;
3437 const TargetFrameLowering &FrameLowering;
3438 const TargetLowering &TargLowering;
3439 CallingConv::ID CallConv;
3440 CCState &CCInfo;
3441};
3442} // namespace
3443
3444void VarArgsLoweringHelper::createVarArgAreaAndStoreRegisters(
3445 SDValue &Chain, unsigned StackSize) {
3446 // If the function takes variable number of arguments, make a frame index for
3447 // the start of the first vararg value... for expansion of llvm.va_start. We
3448 // can skip this if there are no va_start calls.
3449 if (is64Bit() || (CallConv != CallingConv::X86_FastCall &&
3450 CallConv != CallingConv::X86_ThisCall)) {
3451 FuncInfo->setVarArgsFrameIndex(
3452 FrameInfo.CreateFixedObject(1, StackSize, true));
3453 }
3454
3455 // 64-bit calling conventions support varargs and register parameters, so we
3456 // have to do extra work to spill them in the prologue.
3457 if (is64Bit()) {
3458 // Find the first unallocated argument registers.
3459 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
3460 ArrayRef<MCPhysReg> ArgXMMs =
3461 get64BitArgumentXMMs(TheMachineFunction, CallConv, Subtarget);
3462 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
3463 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
3464
3465 assert(!(NumXMMRegs && !Subtarget.hasSSE1()) &&(static_cast <bool> (!(NumXMMRegs && !Subtarget
.hasSSE1()) && "SSE register cannot be used when SSE is disabled!"
) ? void (0) : __assert_fail ("!(NumXMMRegs && !Subtarget.hasSSE1()) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3466, __extension__ __PRETTY_FUNCTION__))
3466 "SSE register cannot be used when SSE is disabled!")(static_cast <bool> (!(NumXMMRegs && !Subtarget
.hasSSE1()) && "SSE register cannot be used when SSE is disabled!"
) ? void (0) : __assert_fail ("!(NumXMMRegs && !Subtarget.hasSSE1()) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3466, __extension__ __PRETTY_FUNCTION__))
;
3467
3468 if (isWin64()) {
3469 // Get to the caller-allocated home save location. Add 8 to account
3470 // for the return address.
3471 int HomeOffset = FrameLowering.getOffsetOfLocalArea() + 8;
3472 FuncInfo->setRegSaveFrameIndex(
3473 FrameInfo.CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
3474 // Fixup to set vararg frame on shadow area (4 x i64).
3475 if (NumIntRegs < 4)
3476 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
3477 } else {
3478 // For X86-64, if there are vararg parameters that are passed via
3479 // registers, then we must store them to their spots on the stack so
3480 // they may be loaded by dereferencing the result of va_next.
3481 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
3482 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
3483 FuncInfo->setRegSaveFrameIndex(FrameInfo.CreateStackObject(
3484 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, Align(16), false));
3485 }
3486
3487 SmallVector<SDValue, 6>
3488 LiveGPRs; // list of SDValue for GPR registers keeping live input value
3489 SmallVector<SDValue, 8> LiveXMMRegs; // list of SDValue for XMM registers
3490 // keeping live input value
3491 SDValue ALVal; // if applicable keeps SDValue for %al register
3492
3493 // Gather all the live in physical registers.
3494 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
3495 Register GPR = TheMachineFunction.addLiveIn(Reg, &X86::GR64RegClass);
3496 LiveGPRs.push_back(DAG.getCopyFromReg(Chain, DL, GPR, MVT::i64));
3497 }
3498 const auto &AvailableXmms = ArgXMMs.slice(NumXMMRegs);
3499 if (!AvailableXmms.empty()) {
3500 Register AL = TheMachineFunction.addLiveIn(X86::AL, &X86::GR8RegClass);
3501 ALVal = DAG.getCopyFromReg(Chain, DL, AL, MVT::i8);
3502 for (MCPhysReg Reg : AvailableXmms) {
3503 // FastRegisterAllocator spills virtual registers at basic
3504 // block boundary. That leads to usages of xmm registers
3505 // outside of check for %al. Pass physical registers to
3506 // VASTART_SAVE_XMM_REGS to avoid unneccessary spilling.
3507 TheMachineFunction.getRegInfo().addLiveIn(Reg);
3508 LiveXMMRegs.push_back(DAG.getRegister(Reg, MVT::v4f32));
3509 }
3510 }
3511
3512 // Store the integer parameter registers.
3513 SmallVector<SDValue, 8> MemOps;
3514 SDValue RSFIN =
3515 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
3516 TargLowering.getPointerTy(DAG.getDataLayout()));
3517 unsigned Offset = FuncInfo->getVarArgsGPOffset();
3518 for (SDValue Val : LiveGPRs) {
3519 SDValue FIN = DAG.getNode(ISD::ADD, DL,
3520 TargLowering.getPointerTy(DAG.getDataLayout()),
3521 RSFIN, DAG.getIntPtrConstant(Offset, DL));
3522 SDValue Store =
3523 DAG.getStore(Val.getValue(1), DL, Val, FIN,
3524 MachinePointerInfo::getFixedStack(
3525 DAG.getMachineFunction(),
3526 FuncInfo->getRegSaveFrameIndex(), Offset));
3527 MemOps.push_back(Store);
3528 Offset += 8;
3529 }
3530
3531 // Now store the XMM (fp + vector) parameter registers.
3532 if (!LiveXMMRegs.empty()) {
3533 SmallVector<SDValue, 12> SaveXMMOps;
3534 SaveXMMOps.push_back(Chain);
3535 SaveXMMOps.push_back(ALVal);
3536 SaveXMMOps.push_back(
3537 DAG.getTargetConstant(FuncInfo->getRegSaveFrameIndex(), DL, MVT::i32));
3538 SaveXMMOps.push_back(
3539 DAG.getTargetConstant(FuncInfo->getVarArgsFPOffset(), DL, MVT::i32));
3540 llvm::append_range(SaveXMMOps, LiveXMMRegs);
3541 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, DL,
3542 MVT::Other, SaveXMMOps));
3543 }
3544
3545 if (!MemOps.empty())
3546 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3547 }
3548}
3549
3550void VarArgsLoweringHelper::forwardMustTailParameters(SDValue &Chain) {
3551 // Find the largest legal vector type.
3552 MVT VecVT = MVT::Other;
3553 // FIXME: Only some x86_32 calling conventions support AVX512.
3554 if (Subtarget.useAVX512Regs() &&
3555 (is64Bit() || (CallConv == CallingConv::X86_VectorCall ||
3556 CallConv == CallingConv::Intel_OCL_BI)))
3557 VecVT = MVT::v16f32;
3558 else if (Subtarget.hasAVX())
3559 VecVT = MVT::v8f32;
3560 else if (Subtarget.hasSSE2())
3561 VecVT = MVT::v4f32;
3562
3563 // We forward some GPRs and some vector types.
3564 SmallVector<MVT, 2> RegParmTypes;
3565 MVT IntVT = is64Bit() ? MVT::i64 : MVT::i32;
3566 RegParmTypes.push_back(IntVT);
3567 if (VecVT != MVT::Other)
3568 RegParmTypes.push_back(VecVT);
3569
3570 // Compute the set of forwarded registers. The rest are scratch.
3571 SmallVectorImpl<ForwardedRegister> &Forwards =
3572 FuncInfo->getForwardedMustTailRegParms();
3573 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
3574
3575 // Forward AL for SysV x86_64 targets, since it is used for varargs.
3576 if (is64Bit() && !isWin64() && !CCInfo.isAllocated(X86::AL)) {
3577 Register ALVReg = TheMachineFunction.addLiveIn(X86::AL, &X86::GR8RegClass);
3578 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
3579 }
3580
3581 // Copy all forwards from physical to virtual registers.
3582 for (ForwardedRegister &FR : Forwards) {
3583 // FIXME: Can we use a less constrained schedule?
3584 SDValue RegVal = DAG.getCopyFromReg(Chain, DL, FR.VReg, FR.VT);
3585 FR.VReg = TheMachineFunction.getRegInfo().createVirtualRegister(
3586 TargLowering.getRegClassFor(FR.VT));
3587 Chain = DAG.getCopyToReg(Chain, DL, FR.VReg, RegVal);
3588 }
3589}
3590
3591void VarArgsLoweringHelper::lowerVarArgsParameters(SDValue &Chain,
3592 unsigned StackSize) {
3593 // Set FrameIndex to the 0xAAAAAAA value to mark unset state.
3594 // If necessary, it would be set into the correct value later.
3595 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
3596 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
3597
3598 if (FrameInfo.hasVAStart())
3599 createVarArgAreaAndStoreRegisters(Chain, StackSize);
3600
3601 if (FrameInfo.hasMustTailInVarArgFunc())
3602 forwardMustTailParameters(Chain);
3603}
3604
3605SDValue X86TargetLowering::LowerFormalArguments(
3606 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
3607 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3608 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3609 MachineFunction &MF = DAG.getMachineFunction();
3610 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3611
3612 const Function &F = MF.getFunction();
3613 if (F.hasExternalLinkage() && Subtarget.isTargetCygMing() &&
3614 F.getName() == "main")
3615 FuncInfo->setForceFramePointer(true);
3616
3617 MachineFrameInfo &MFI = MF.getFrameInfo();
3618 bool Is64Bit = Subtarget.is64Bit();
3619 bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3620
3621 assert((static_cast <bool> (!(IsVarArg && canGuaranteeTCO
(CallConv)) && "Var args not supported with calling conv' regcall, fastcc, ghc or hipe"
) ? void (0) : __assert_fail ("!(IsVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling conv' regcall, fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3623, __extension__ __PRETTY_FUNCTION__))
3622 !(IsVarArg && canGuaranteeTCO(CallConv)) &&(static_cast <bool> (!(IsVarArg && canGuaranteeTCO
(CallConv)) && "Var args not supported with calling conv' regcall, fastcc, ghc or hipe"
) ? void (0) : __assert_fail ("!(IsVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling conv' regcall, fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3623, __extension__ __PRETTY_FUNCTION__))
3623 "Var args not supported with calling conv' regcall, fastcc, ghc or hipe")(static_cast <bool> (!(IsVarArg && canGuaranteeTCO
(CallConv)) && "Var args not supported with calling conv' regcall, fastcc, ghc or hipe"
) ? void (0) : __assert_fail ("!(IsVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling conv' regcall, fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3623, __extension__ __PRETTY_FUNCTION__))
;
3624
3625 // Assign locations to all of the incoming arguments.
3626 SmallVector<CCValAssign, 16> ArgLocs;
3627 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3628
3629 // Allocate shadow area for Win64.
3630 if (IsWin64)
3631 CCInfo.AllocateStack(32, Align(8));
3632
3633 CCInfo.AnalyzeArguments(Ins, CC_X86);
3634
3635 // In vectorcall calling convention a second pass is required for the HVA
3636 // types.
3637 if (CallingConv::X86_VectorCall == CallConv) {
3638 CCInfo.AnalyzeArgumentsSecondPass(Ins, CC_X86);
3639 }
3640
3641 // The next loop assumes that the locations are in the same order of the
3642 // input arguments.
3643 assert(isSortedByValueNo(ArgLocs) &&(static_cast <bool> (isSortedByValueNo(ArgLocs) &&
"Argument Location list must be sorted before lowering") ? void
(0) : __assert_fail ("isSortedByValueNo(ArgLocs) && \"Argument Location list must be sorted before lowering\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3644, __extension__ __PRETTY_FUNCTION__))
3644 "Argument Location list must be sorted before lowering")(static_cast <bool> (isSortedByValueNo(ArgLocs) &&
"Argument Location list must be sorted before lowering") ? void
(0) : __assert_fail ("isSortedByValueNo(ArgLocs) && \"Argument Location list must be sorted before lowering\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3644, __extension__ __PRETTY_FUNCTION__))
;
3645
3646 SDValue ArgValue;
3647 for (unsigned I = 0, InsIndex = 0, E = ArgLocs.size(); I != E;
3648 ++I, ++InsIndex) {
3649 assert(InsIndex < Ins.size() && "Invalid Ins index")(static_cast <bool> (InsIndex < Ins.size() &&
"Invalid Ins index") ? void (0) : __assert_fail ("InsIndex < Ins.size() && \"Invalid Ins index\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3649, __extension__ __PRETTY_FUNCTION__))
;
3650 CCValAssign &VA = ArgLocs[I];
3651
3652 if (VA.isRegLoc()) {
3653 EVT RegVT = VA.getLocVT();
3654 if (VA.needsCustom()) {
3655 assert((static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? void (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3657, __extension__ __PRETTY_FUNCTION__))
3656 VA.getValVT() == MVT::v64i1 &&(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? void (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3657, __extension__ __PRETTY_FUNCTION__))
3657 "Currently the only custom case is when we split v64i1 to 2 regs")(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? void (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3657, __extension__ __PRETTY_FUNCTION__))
;
3658
3659 // v64i1 values, in regcall calling convention, that are
3660 // compiled to 32 bit arch, are split up into two registers.
3661 ArgValue =
3662 getv64i1Argument(VA, ArgLocs[++I], Chain, DAG, dl, Subtarget);
3663 } else {
3664 const TargetRegisterClass *RC;
3665 if (RegVT == MVT::i8)
3666 RC = &X86::GR8RegClass;
3667 else if (RegVT == MVT::i16)
3668 RC = &X86::GR16RegClass;
3669 else if (RegVT == MVT::i32)
3670 RC = &X86::GR32RegClass;
3671 else if (Is64Bit && RegVT == MVT::i64)
3672 RC = &X86::GR64RegClass;
3673 else if (RegVT == MVT::f32)
3674 RC = Subtarget.hasAVX512() ? &X86::FR32XRegClass : &X86::FR32RegClass;
3675 else if (RegVT == MVT::f64)
3676 RC = Subtarget.hasAVX512() ? &X86::FR64XRegClass : &X86::FR64RegClass;
3677 else if (RegVT == MVT::f80)
3678 RC = &X86::RFP80RegClass;
3679 else if (RegVT == MVT::f128)
3680 RC = &X86::VR128RegClass;
3681 else if (RegVT.is512BitVector())
3682 RC = &X86::VR512RegClass;
3683 else if (RegVT.is256BitVector())
3684 RC = Subtarget.hasVLX() ? &X86::VR256XRegClass : &X86::VR256RegClass;
3685 else if (RegVT.is128BitVector())
3686 RC = Subtarget.hasVLX() ? &X86::VR128XRegClass : &X86::VR128RegClass;
3687 else if (RegVT == MVT::x86mmx)
3688 RC = &X86::VR64RegClass;
3689 else if (RegVT == MVT::v1i1)
3690 RC = &X86::VK1RegClass;
3691 else if (RegVT == MVT::v8i1)
3692 RC = &X86::VK8RegClass;
3693 else if (RegVT == MVT::v16i1)
3694 RC = &X86::VK16RegClass;
3695 else if (RegVT == MVT::v32i1)
3696 RC = &X86::VK32RegClass;
3697 else if (RegVT == MVT::v64i1)
3698 RC = &X86::VK64RegClass;
3699 else
3700 llvm_unreachable("Unknown argument type!")::llvm::llvm_unreachable_internal("Unknown argument type!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3700)
;
3701
3702 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
3703 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3704 }
3705
3706 // If this is an 8 or 16-bit value, it is really passed promoted to 32
3707 // bits. Insert an assert[sz]ext to capture this, then truncate to the
3708 // right size.
3709 if (VA.getLocInfo() == CCValAssign::SExt)
3710 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3711 DAG.getValueType(VA.getValVT()));
3712 else if (VA.getLocInfo() == CCValAssign::ZExt)
3713 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3714 DAG.getValueType(VA.getValVT()));
3715 else if (VA.getLocInfo() == CCValAssign::BCvt)
3716 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
3717
3718 if (VA.isExtInLoc()) {
3719 // Handle MMX values passed in XMM regs.
3720 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
3721 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
3722 else if (VA.getValVT().isVector() &&
3723 VA.getValVT().getScalarType() == MVT::i1 &&
3724 ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3725 (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3726 // Promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3727 ArgValue = lowerRegToMasks(ArgValue, VA.getValVT(), RegVT, dl, DAG);
3728 } else
3729 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3730 }
3731 } else {
3732 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3732, __extension__ __PRETTY_FUNCTION__))
;
3733 ArgValue =
3734 LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, InsIndex);
3735 }
3736
3737 // If value is passed via pointer - do a load.
3738 if (VA.getLocInfo() == CCValAssign::Indirect && !Ins[I].Flags.isByVal())
3739 ArgValue =
3740 DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, MachinePointerInfo());
3741
3742 InVals.push_back(ArgValue);
3743 }
3744
3745 for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3746 if (Ins[I].Flags.isSwiftAsync()) {
3747 auto X86FI = MF.getInfo<X86MachineFunctionInfo>();
3748 if (Subtarget.is64Bit())
3749 X86FI->setHasSwiftAsyncContext(true);
3750 else {
3751 int FI = MF.getFrameInfo().CreateStackObject(4, Align(4), false);
3752 X86FI->setSwiftAsyncContextFrameIdx(FI);
3753 SDValue St = DAG.getStore(DAG.getEntryNode(), dl, InVals[I],
3754 DAG.getFrameIndex(FI, MVT::i32),
3755 MachinePointerInfo::getFixedStack(MF, FI));
3756 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, St, Chain);
3757 }
3758 }
3759
3760 // Swift calling convention does not require we copy the sret argument
3761 // into %rax/%eax for the return. We don't set SRetReturnReg for Swift.
3762 if (CallConv == CallingConv::Swift || CallConv == CallingConv::SwiftTail)
3763 continue;
3764
3765 // All x86 ABIs require that for returning structs by value we copy the
3766 // sret argument into %rax/%eax (depending on ABI) for the return. Save
3767 // the argument into a virtual register so that we can access it from the
3768 // return points.
3769 if (Ins[I].Flags.isSRet()) {
3770 Register Reg = FuncInfo->getSRetReturnReg();
3771 if (!Reg) {
3772 MVT PtrTy = getPointerTy(DAG.getDataLayout());
3773 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3774 FuncInfo->setSRetReturnReg(Reg);
3775 }
3776 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[I]);
3777 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3778 break;
3779 }
3780 }
3781
3782 unsigned StackSize = CCInfo.getNextStackOffset();
3783 // Align stack specially for tail calls.
3784 if (shouldGuaranteeTCO(CallConv,
3785 MF.getTarget().Options.GuaranteedTailCallOpt))
3786 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
3787
3788 if (IsVarArg)
3789 VarArgsLoweringHelper(FuncInfo, dl, DAG, Subtarget, CallConv, CCInfo)
3790 .lowerVarArgsParameters(Chain, StackSize);
3791
3792 // Some CCs need callee pop.
3793 if (X86::isCalleePop(CallConv, Is64Bit, IsVarArg,
3794 MF.getTarget().Options.GuaranteedTailCallOpt)) {
3795 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
3796 } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
3797 // X86 interrupts must pop the error code (and the alignment padding) if
3798 // present.
3799 FuncInfo->setBytesToPopOnReturn(Is64Bit ? 16 : 4);
3800 } else {
3801 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
3802 // If this is an sret function, the return should pop the hidden pointer.
3803 if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3804 !Subtarget.getTargetTriple().isOSMSVCRT() &&
3805 argsAreStructReturn(Ins, Subtarget.isTargetMCU()) == StackStructReturn)
3806 FuncInfo->setBytesToPopOnReturn(4);
3807 }
3808
3809 if (!Is64Bit) {
3810 // RegSaveFrameIndex is X86-64 only.
3811 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
3812 }
3813
3814 FuncInfo->setArgumentStackSize(StackSize);
3815
3816 if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
3817 EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
3818 if (Personality == EHPersonality::CoreCLR) {
3819 assert(Is64Bit)(static_cast <bool> (Is64Bit) ? void (0) : __assert_fail
("Is64Bit", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3819, __extension__ __PRETTY_FUNCTION__))
;
3820 // TODO: Add a mechanism to frame lowering that will allow us to indicate
3821 // that we'd prefer this slot be allocated towards the bottom of the frame
3822 // (i.e. near the stack pointer after allocating the frame). Every
3823 // funclet needs a copy of this slot in its (mostly empty) frame, and the
3824 // offset from the bottom of this and each funclet's frame must be the
3825 // same, so the size of funclets' (mostly empty) frames is dictated by
3826 // how far this slot is from the bottom (since they allocate just enough
3827 // space to accommodate holding this slot at the correct offset).
3828 int PSPSymFI = MFI.CreateStackObject(8, Align(8), /*isSpillSlot=*/false);
3829 EHInfo->PSPSymFrameIdx = PSPSymFI;
3830 }
3831 }
3832
3833 if (CallConv == CallingConv::X86_RegCall ||
3834 F.hasFnAttribute("no_caller_saved_registers")) {
3835 MachineRegisterInfo &MRI = MF.getRegInfo();
3836 for (std::pair<Register, Register> Pair : MRI.liveins())
3837 MRI.disableCalleeSavedRegister(Pair.first);
3838 }
3839
3840 return Chain;
3841}
3842
3843SDValue X86TargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
3844 SDValue Arg, const SDLoc &dl,
3845 SelectionDAG &DAG,
3846 const CCValAssign &VA,
3847 ISD::ArgFlagsTy Flags,
3848 bool isByVal) const {
3849 unsigned LocMemOffset = VA.getLocMemOffset();
3850 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3851 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3852 StackPtr, PtrOff);
3853 if (isByVal)
3854 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3855
3856 return DAG.getStore(
3857 Chain, dl, Arg, PtrOff,
3858 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
3859}
3860
3861/// Emit a load of return address if tail call
3862/// optimization is performed and it is required.
3863SDValue X86TargetLowering::EmitTailCallLoadRetAddr(
3864 SelectionDAG &DAG, SDValue &OutRetAddr, SDValue Chain, bool IsTailCall,
3865 bool Is64Bit, int FPDiff, const SDLoc &dl) const {
3866 // Adjust the Return address stack slot.
3867 EVT VT = getPointerTy(DAG.getDataLayout());
3868 OutRetAddr = getReturnAddressFrameIndex(DAG);
3869
3870 // Load the "old" Return address.
3871 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo());
3872 return SDValue(OutRetAddr.getNode(), 1);
3873}
3874
3875/// Emit a store of the return address if tail call
3876/// optimization is performed and it is required (FPDiff!=0).
3877static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3878 SDValue Chain, SDValue RetAddrFrIdx,
3879 EVT PtrVT, unsigned SlotSize,
3880 int FPDiff, const SDLoc &dl) {
3881 // Store the return address to the appropriate stack slot.
3882 if (!FPDiff) return Chain;
3883 // Calculate the new stack slot for the return address.
3884 int NewReturnAddrFI =
3885 MF.getFrameInfo().CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3886 false);
3887 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3888 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3889 MachinePointerInfo::getFixedStack(
3890 DAG.getMachineFunction(), NewReturnAddrFI));
3891 return Chain;
3892}
3893
3894/// Returns a vector_shuffle mask for an movs{s|d}, movd
3895/// operation of specified width.
3896static SDValue getMOVL(SelectionDAG &DAG, const SDLoc &dl, MVT VT, SDValue V1,
3897 SDValue V2) {
3898 unsigned NumElems = VT.getVectorNumElements();
3899 SmallVector<int, 8> Mask;
3900 Mask.push_back(NumElems);
3901 for (unsigned i = 1; i != NumElems; ++i)
3902 Mask.push_back(i);
3903 return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
3904}
3905
3906SDValue
3907X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3908 SmallVectorImpl<SDValue> &InVals) const {
3909 SelectionDAG &DAG = CLI.DAG;
3910 SDLoc &dl = CLI.DL;
3911 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3912 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3913 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3914 SDValue Chain = CLI.Chain;
3915 SDValue Callee = CLI.Callee;
3916 CallingConv::ID CallConv = CLI.CallConv;
3917 bool &isTailCall = CLI.IsTailCall;
3918 bool isVarArg = CLI.IsVarArg;
3919 const auto *CB = CLI.CB;
3920
3921 MachineFunction &MF = DAG.getMachineFunction();
3922 bool Is64Bit = Subtarget.is64Bit();
3923 bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3924 StructReturnType SR = callIsStructReturn(Outs, Subtarget.isTargetMCU());
3925 bool IsSibcall = false;
3926 bool IsGuaranteeTCO = MF.getTarget().Options.GuaranteedTailCallOpt ||
3927 CallConv == CallingConv::Tail || CallConv == CallingConv::SwiftTail;
3928 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3929 bool HasNCSR = (CB && isa<CallInst>(CB) &&
3930 CB->hasFnAttr("no_caller_saved_registers"));
3931 bool HasNoCfCheck = (CB && CB->doesNoCfCheck());
3932 bool IsIndirectCall = (CB && isa<CallInst>(CB) && CB->isIndirectCall());
3933 const Module *M = MF.getMMI().getModule();
3934 Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
3935
3936 MachineFunction::CallSiteInfo CSInfo;
3937 if (CallConv == CallingConv::X86_INTR)
3938 report_fatal_error("X86 interrupts may not be called directly");
3939
3940 bool IsMustTail = CLI.CB && CLI.CB->isMustTailCall();
3941 if (Subtarget.isPICStyleGOT() && !IsGuaranteeTCO && !IsMustTail) {
3942 // If we are using a GOT, disable tail calls to external symbols with
3943 // default visibility. Tail calling such a symbol requires using a GOT
3944 // relocation, which forces early binding of the symbol. This breaks code
3945 // that require lazy function symbol resolution. Using musttail or
3946 // GuaranteedTailCallOpt will override this.
3947 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3948 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3949 G->getGlobal()->hasDefaultVisibility()))
3950 isTailCall = false;
3951 }
3952
3953
3954 if (isTailCall && !IsMustTail) {
3955 // Check if it's really possible to do a tail call.
3956 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3957 isVarArg, SR != NotStructReturn,
3958 MF.getFunction().hasStructRetAttr(), CLI.RetTy,
3959 Outs, OutVals, Ins, DAG);
3960
3961 // Sibcalls are automatically detected tailcalls which do not require
3962 // ABI changes.
3963 if (!IsGuaranteeTCO && isTailCall)
3964 IsSibcall = true;
3965
3966 if (isTailCall)
3967 ++NumTailCalls;
3968 }
3969
3970 if (IsMustTail && !isTailCall)
3971 report_fatal_error("failed to perform tail call elimination on a call "
3972 "site marked musttail");
3973
3974 assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&(static_cast <bool> (!(isVarArg && canGuaranteeTCO
(CallConv)) && "Var args not supported with calling convention fastcc, ghc or hipe"
) ? void (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling convention fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3975, __extension__ __PRETTY_FUNCTION__))
3975 "Var args not supported with calling convention fastcc, ghc or hipe")(static_cast <bool> (!(isVarArg && canGuaranteeTCO
(CallConv)) && "Var args not supported with calling convention fastcc, ghc or hipe"
) ? void (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling convention fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 3975, __extension__ __PRETTY_FUNCTION__))
;
3976
3977 // Analyze operands of the call, assigning locations to each operand.
3978 SmallVector<CCValAssign, 16> ArgLocs;
3979 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3980
3981 // Allocate shadow area for Win64.
3982 if (IsWin64)
3983 CCInfo.AllocateStack(32, Align(8));
3984
3985 CCInfo.AnalyzeArguments(Outs, CC_X86);
3986
3987 // In vectorcall calling convention a second pass is required for the HVA
3988 // types.
3989 if (CallingConv::X86_VectorCall == CallConv) {
3990 CCInfo.AnalyzeArgumentsSecondPass(Outs, CC_X86);
3991 }
3992
3993 // Get a count of how many bytes are to be pushed on the stack.
3994 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3995 if (IsSibcall)
3996 // This is a sibcall. The memory operands are available in caller's
3997 // own caller's stack.
3998 NumBytes = 0;
3999 else if (IsGuaranteeTCO && canGuaranteeTCO(CallConv))
4000 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
4001
4002 int FPDiff = 0;
4003 if (isTailCall &&
4004 shouldGuaranteeTCO(CallConv,
4005 MF.getTarget().Options.GuaranteedTailCallOpt)) {
4006 // Lower arguments at fp - stackoffset + fpdiff.
4007 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
4008
4009 FPDiff = NumBytesCallerPushed - NumBytes;
4010
4011 // Set the delta of movement of the returnaddr stackslot.
4012 // But only set if delta is greater than previous delta.
4013 if (FPDiff < X86Info->getTCReturnAddrDelta())
4014 X86Info->setTCReturnAddrDelta(FPDiff);
4015 }
4016
4017 unsigned NumBytesToPush = NumBytes;
4018 unsigned NumBytesToPop = NumBytes;
4019
4020 // If we have an inalloca argument, all stack space has already been allocated
4021 // for us and be right at the top of the stack. We don't support multiple
4022 // arguments passed in memory when using inalloca.
4023 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
4024 NumBytesToPush = 0;
4025 if (!ArgLocs.back().isMemLoc())
4026 report_fatal_error("cannot use inalloca attribute on a register "
4027 "parameter");
4028 if (ArgLocs.back().getLocMemOffset() != 0)
4029 report_fatal_error("any parameter with the inalloca attribute must be "
4030 "the only memory argument");
4031 } else if (CLI.IsPreallocated) {
4032 assert(ArgLocs.back().isMemLoc() &&(static_cast <bool> (ArgLocs.back().isMemLoc() &&
"cannot use preallocated attribute on a register " "parameter"
) ? void (0) : __assert_fail ("ArgLocs.back().isMemLoc() && \"cannot use preallocated attribute on a register \" \"parameter\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4034, __extension__ __PRETTY_FUNCTION__))
4033 "cannot use preallocated attribute on a register "(static_cast <bool> (ArgLocs.back().isMemLoc() &&
"cannot use preallocated attribute on a register " "parameter"
) ? void (0) : __assert_fail ("ArgLocs.back().isMemLoc() && \"cannot use preallocated attribute on a register \" \"parameter\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4034, __extension__ __PRETTY_FUNCTION__))
4034 "parameter")(static_cast <bool> (ArgLocs.back().isMemLoc() &&
"cannot use preallocated attribute on a register " "parameter"
) ? void (0) : __assert_fail ("ArgLocs.back().isMemLoc() && \"cannot use preallocated attribute on a register \" \"parameter\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4034, __extension__ __PRETTY_FUNCTION__))
;
4035 SmallVector<size_t, 4> PreallocatedOffsets;
4036 for (size_t i = 0; i < CLI.OutVals.size(); ++i) {
4037 if (CLI.CB->paramHasAttr(i, Attribute::Preallocated)) {
4038 PreallocatedOffsets.push_back(ArgLocs[i].getLocMemOffset());
4039 }
4040 }
4041 auto *MFI = DAG.getMachineFunction().getInfo<X86MachineFunctionInfo>();
4042 size_t PreallocatedId = MFI->getPreallocatedIdForCallSite(CLI.CB);
4043 MFI->setPreallocatedStackSize(PreallocatedId, NumBytes);
4044 MFI->setPreallocatedArgOffsets(PreallocatedId, PreallocatedOffsets);
4045 NumBytesToPush = 0;
4046 }
4047
4048 if (!IsSibcall && !IsMustTail)
4049 Chain = DAG.getCALLSEQ_START(Chain, NumBytesToPush,
4050 NumBytes - NumBytesToPush, dl);
4051
4052 SDValue RetAddrFrIdx;
4053 // Load return address for tail calls.
4054 if (isTailCall && FPDiff)
4055 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
4056 Is64Bit, FPDiff, dl);
4057
4058 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
4059 SmallVector<SDValue, 8> MemOpChains;
4060 SDValue StackPtr;
4061
4062 // The next loop assumes that the locations are in the same order of the
4063 // input arguments.
4064 assert(isSortedByValueNo(ArgLocs) &&(static_cast <bool> (isSortedByValueNo(ArgLocs) &&
"Argument Location list must be sorted before lowering") ? void
(0) : __assert_fail ("isSortedByValueNo(ArgLocs) && \"Argument Location list must be sorted before lowering\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4065, __extension__ __PRETTY_FUNCTION__))
4065 "Argument Location list must be sorted before lowering")(static_cast <bool> (isSortedByValueNo(ArgLocs) &&
"Argument Location list must be sorted before lowering") ? void
(0) : __assert_fail ("isSortedByValueNo(ArgLocs) && \"Argument Location list must be sorted before lowering\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4065, __extension__ __PRETTY_FUNCTION__))
;
4066
4067 // Walk the register/memloc assignments, inserting copies/loads. In the case
4068 // of tail call optimization arguments are handle later.
4069 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4070 for (unsigned I = 0, OutIndex = 0, E = ArgLocs.size(); I != E;
4071 ++I, ++OutIndex) {
4072 assert(OutIndex < Outs.size() && "Invalid Out index")(static_cast <bool> (OutIndex < Outs.size() &&
"Invalid Out index") ? void (0) : __assert_fail ("OutIndex < Outs.size() && \"Invalid Out index\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4072, __extension__ __PRETTY_FUNCTION__))
;
4073 // Skip inalloca/preallocated arguments, they have already been written.
4074 ISD::ArgFlagsTy Flags = Outs[OutIndex].Flags;
4075 if (Flags.isInAlloca() || Flags.isPreallocated())
4076 continue;
4077
4078 CCValAssign &VA = ArgLocs[I];
4079 EVT RegVT = VA.getLocVT();
4080 SDValue Arg = OutVals[OutIndex];
4081 bool isByVal = Flags.isByVal();
4082
4083 // Promote the value if needed.
4084 switch (VA.getLocInfo()) {
4085 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4085)
;
4086 case CCValAssign::Full: break;
4087 case CCValAssign::SExt:
4088 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
4089 break;
4090 case CCValAssign::ZExt:
4091 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
4092 break;
4093 case CCValAssign::AExt:
4094 if (Arg.getValueType().isVector() &&
4095 Arg.getValueType().getVectorElementType() == MVT::i1)
4096 Arg = lowerMasksToReg(Arg, RegVT, dl, DAG);
4097 else if (RegVT.is128BitVector()) {
4098 // Special case: passing MMX values in XMM registers.
4099 Arg = DAG.getBitcast(MVT::i64, Arg);
4100 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
4101 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
4102 } else
4103 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
4104 break;
4105 case CCValAssign::BCvt:
4106 Arg = DAG.getBitcast(RegVT, Arg);
4107 break;
4108 case CCValAssign::Indirect: {
4109 if (isByVal) {
4110 // Memcpy the argument to a temporary stack slot to prevent
4111 // the caller from seeing any modifications the callee may make
4112 // as guaranteed by the `byval` attribute.
4113 int FrameIdx = MF.getFrameInfo().CreateStackObject(
4114 Flags.getByValSize(),
4115 std::max(Align(16), Flags.getNonZeroByValAlign()), false);
4116 SDValue StackSlot =
4117 DAG.getFrameIndex(FrameIdx, getPointerTy(DAG.getDataLayout()));
4118 Chain =
4119 CreateCopyOfByValArgument(Arg, StackSlot, Chain, Flags, DAG, dl);
4120 // From now on treat this as a regular pointer
4121 Arg = StackSlot;
4122 isByVal = false;
4123 } else {
4124 // Store the argument.
4125 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
4126 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
4127 Chain = DAG.getStore(
4128 Chain, dl, Arg, SpillSlot,
4129 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4130 Arg = SpillSlot;
4131 }
4132 break;
4133 }
4134 }
4135
4136 if (VA.needsCustom()) {
4137 assert(VA.getValVT() == MVT::v64i1 &&(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? void (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4138, __extension__ __PRETTY_FUNCTION__))
4138 "Currently the only custom case is when we split v64i1 to 2 regs")(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? void (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4138, __extension__ __PRETTY_FUNCTION__))
;
4139 // Split v64i1 value into two registers
4140 Passv64i1ArgInRegs(dl, DAG, Arg, RegsToPass, VA, ArgLocs[++I], Subtarget);
4141 } else if (VA.isRegLoc()) {
4142 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4143 const TargetOptions &Options = DAG.getTarget().Options;
4144 if (Options.EmitCallSiteInfo)
4145 CSInfo.emplace_back(VA.getLocReg(), I);
4146 if (isVarArg && IsWin64) {
4147 // Win64 ABI requires argument XMM reg to be copied to the corresponding
4148 // shadow reg if callee is a varargs function.
4149 Register ShadowReg;
4150 switch (VA.getLocReg()) {
4151 case X86::XMM0: ShadowReg = X86::RCX; break;
4152 case X86::XMM1: ShadowReg = X86::RDX; break;
4153 case X86::XMM2: ShadowReg = X86::R8; break;
4154 case X86::XMM3: ShadowReg = X86::R9; break;
4155 }
4156 if (ShadowReg)
4157 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
4158 }
4159 } else if (!IsSibcall && (!isTailCall || isByVal)) {
4160 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4160, __extension__ __PRETTY_FUNCTION__))
;
4161 if (!StackPtr.getNode())
4162 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
4163 getPointerTy(DAG.getDataLayout()));
4164 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
4165 dl, DAG, VA, Flags, isByVal));
4166 }
4167 }
4168
4169 if (!MemOpChains.empty())
4170 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4171
4172 if (Subtarget.isPICStyleGOT()) {
4173 // ELF / PIC requires GOT in the EBX register before function calls via PLT
4174 // GOT pointer (except regcall).
4175 if (!isTailCall) {
4176 // Indirect call with RegCall calling convertion may use up all the
4177 // general registers, so it is not suitable to bind EBX reister for
4178 // GOT address, just let register allocator handle it.
4179 if (CallConv != CallingConv::X86_RegCall)
4180 RegsToPass.push_back(std::make_pair(
4181 Register(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
4182 getPointerTy(DAG.getDataLayout()))));
4183 } else {
4184 // If we are tail calling and generating PIC/GOT style code load the
4185 // address of the callee into ECX. The value in ecx is used as target of
4186 // the tail jump. This is done to circumvent the ebx/callee-saved problem
4187 // for tail calls on PIC/GOT architectures. Normally we would just put the
4188 // address of GOT into ebx and then call target@PLT. But for tail calls
4189 // ebx would be restored (since ebx is callee saved) before jumping to the
4190 // target@PLT.
4191
4192 // Note: The actual moving to ECX is done further down.
4193 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4194 if (G && !G->getGlobal()->hasLocalLinkage() &&
4195 G->getGlobal()->hasDefaultVisibility())
4196 Callee = LowerGlobalAddress(Callee, DAG);
4197 else if (isa<ExternalSymbolSDNode>(Callee))
4198 Callee = LowerExternalSymbol(Callee, DAG);
4199 }
4200 }
4201
4202 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
4203 // From AMD64 ABI document:
4204 // For calls that may call functions that use varargs or stdargs
4205 // (prototype-less calls or calls to functions containing ellipsis (...) in
4206 // the declaration) %al is used as hidden argument to specify the number
4207 // of SSE registers used. The contents of %al do not need to match exactly
4208 // the number of registers, but must be an ubound on the number of SSE
4209 // registers used and is in the range 0 - 8 inclusive.
4210
4211 // Count the number of XMM registers allocated.
4212 static const MCPhysReg XMMArgRegs[] = {
4213 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
4214 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
4215 };
4216 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
4217 assert((Subtarget.hasSSE1() || !NumXMMRegs)(static_cast <bool> ((Subtarget.hasSSE1() || !NumXMMRegs
) && "SSE registers cannot be used when SSE is disabled"
) ? void (0) : __assert_fail ("(Subtarget.hasSSE1() || !NumXMMRegs) && \"SSE registers cannot be used when SSE is disabled\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4218, __extension__ __PRETTY_FUNCTION__))
4218 && "SSE registers cannot be used when SSE is disabled")(static_cast <bool> ((Subtarget.hasSSE1() || !NumXMMRegs
) && "SSE registers cannot be used when SSE is disabled"
) ? void (0) : __assert_fail ("(Subtarget.hasSSE1() || !NumXMMRegs) && \"SSE registers cannot be used when SSE is disabled\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4218, __extension__ __PRETTY_FUNCTION__))
;
4219 RegsToPass.push_back(std::make_pair(Register(X86::AL),
4220 DAG.getConstant(NumXMMRegs, dl,
4221 MVT::i8)));
4222 }
4223
4224 if (isVarArg && IsMustTail) {
4225 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
4226 for (const auto &F : Forwards) {
4227 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
4228 RegsToPass.push_back(std::make_pair(F.PReg, Val));
4229 }
4230 }
4231
4232 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
4233 // don't need this because the eligibility check rejects calls that require
4234 // shuffling arguments passed in memory.
4235 if (!IsSibcall && isTailCall) {
4236 // Force all the incoming stack arguments to be loaded from the stack
4237 // before any new outgoing arguments are stored to the stack, because the
4238 // outgoing stack slots may alias the incoming argument stack slots, and
4239 // the alias isn't otherwise explicit. This is slightly more conservative
4240 // than necessary, because it means that each store effectively depends
4241 // on every argument instead of just those arguments it would clobber.
4242 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
4243
4244 SmallVector<SDValue, 8> MemOpChains2;
4245 SDValue FIN;
4246 int FI = 0;
4247 for (unsigned I = 0, OutsIndex = 0, E = ArgLocs.size(); I != E;
4248 ++I, ++OutsIndex) {
4249 CCValAssign &VA = ArgLocs[I];
4250
4251 if (VA.isRegLoc()) {
4252 if (VA.needsCustom()) {
4253 assert((CallConv == CallingConv::X86_RegCall) &&(static_cast <bool> ((CallConv == CallingConv::X86_RegCall
) && "Expecting custom case only in regcall calling convention"
) ? void (0) : __assert_fail ("(CallConv == CallingConv::X86_RegCall) && \"Expecting custom case only in regcall calling convention\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4254, __extension__ __PRETTY_FUNCTION__))
4254 "Expecting custom case only in regcall calling convention")(static_cast <bool> ((CallConv == CallingConv::X86_RegCall
) && "Expecting custom case only in regcall calling convention"
) ? void (0) : __assert_fail ("(CallConv == CallingConv::X86_RegCall) && \"Expecting custom case only in regcall calling convention\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4254, __extension__ __PRETTY_FUNCTION__))
;
4255 // This means that we are in special case where one argument was
4256 // passed through two register locations - Skip the next location
4257 ++I;
4258 }
4259
4260 continue;
4261 }
4262
4263 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4263, __extension__ __PRETTY_FUNCTION__))
;
4264 SDValue Arg = OutVals[OutsIndex];
4265 ISD::ArgFlagsTy Flags = Outs[OutsIndex].Flags;
4266 // Skip inalloca/preallocated arguments. They don't require any work.
4267 if (Flags.isInAlloca() || Flags.isPreallocated())
4268 continue;
4269 // Create frame index.
4270 int32_t Offset = VA.getLocMemOffset()+FPDiff;
4271 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
4272 FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4273 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4274
4275 if (Flags.isByVal()) {
4276 // Copy relative to framepointer.
4277 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
4278 if (!StackPtr.getNode())
4279 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
4280 getPointerTy(DAG.getDataLayout()));
4281 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
4282 StackPtr, Source);
4283
4284 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
4285 ArgChain,
4286 Flags, DAG, dl));
4287 } else {
4288 // Store relative to framepointer.
4289 MemOpChains2.push_back(DAG.getStore(
4290 ArgChain, dl, Arg, FIN,
4291 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4292 }
4293 }
4294
4295 if (!MemOpChains2.empty())
4296 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4297
4298 // Store the return address to the appropriate stack slot.
4299 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
4300 getPointerTy(DAG.getDataLayout()),
4301 RegInfo->getSlotSize(), FPDiff, dl);
4302 }
4303
4304 // Build a sequence of copy-to-reg nodes chained together with token chain
4305 // and flag operands which copy the outgoing args into registers.
4306 SDValue InFlag;
4307 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4308 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4309 RegsToPass[i].second, InFlag);
4310 InFlag = Chain.getValue(1);
4311 }
4312
4313 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
4314 assert(Is64Bit && "Large code model is only legal in 64-bit mode.")(static_cast <bool> (Is64Bit && "Large code model is only legal in 64-bit mode."
) ? void (0) : __assert_fail ("Is64Bit && \"Large code model is only legal in 64-bit mode.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4314, __extension__ __PRETTY_FUNCTION__))
;
4315 // In the 64-bit large code model, we have to make all calls
4316 // through a register, since the call instruction's 32-bit
4317 // pc-relative offset may not be large enough to hold the whole
4318 // address.
4319 } else if (Callee->getOpcode() == ISD::GlobalAddress ||
4320 Callee->getOpcode() == ISD::ExternalSymbol) {
4321 // Lower direct calls to global addresses and external symbols. Setting
4322 // ForCall to true here has the effect of removing WrapperRIP when possible
4323 // to allow direct calls to be selected without first materializing the
4324 // address into a register.
4325 Callee = LowerGlobalOrExternal(Callee, DAG, /*ForCall=*/true);
4326 } else if (Subtarget.isTarget64BitILP32() &&
4327 Callee->getValueType(0) == MVT::i32) {
4328 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
4329 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
4330 }
4331
4332 // Returns a chain & a flag for retval copy to use.
4333 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4334 SmallVector<SDValue, 8> Ops;
4335
4336 if (!IsSibcall && isTailCall && !IsMustTail) {
4337 Chain = DAG.getCALLSEQ_END(Chain,
4338 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
4339 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4340 InFlag = Chain.getValue(1);
4341 }
4342
4343 Ops.push_back(Chain);
4344 Ops.push_back(Callee);
4345
4346 if (isTailCall)
4347 Ops.push_back(DAG.getTargetConstant(FPDiff, dl, MVT::i32));
4348
4349 // Add argument registers to the end of the list so that they are known live
4350 // into the call.
4351 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4352 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4353 RegsToPass[i].second.getValueType()));
4354
4355 // Add a register mask operand representing the call-preserved registers.
4356 const uint32_t *Mask = [&]() {
4357 auto AdaptedCC = CallConv;
4358 // If HasNCSR is asserted (attribute NoCallerSavedRegisters exists),
4359 // use X86_INTR calling convention because it has the same CSR mask
4360 // (same preserved registers).
4361 if (HasNCSR)
4362 AdaptedCC = (CallingConv::ID)CallingConv::X86_INTR;
4363 // If NoCalleeSavedRegisters is requested, than use GHC since it happens
4364 // to use the CSR_NoRegs_RegMask.
4365 if (CB && CB->hasFnAttr("no_callee_saved_registers"))
4366 AdaptedCC = (CallingConv::ID)CallingConv::GHC;
4367 return RegInfo->getCallPreservedMask(MF, AdaptedCC);
4368 }();
4369 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-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4369, __extension__ __PRETTY_FUNCTION__))
;
4370
4371 // If this is an invoke in a 32-bit function using a funclet-based
4372 // personality, assume the function clobbers all registers. If an exception
4373 // is thrown, the runtime will not restore CSRs.
4374 // FIXME: Model this more precisely so that we can register allocate across
4375 // the normal edge and spill and fill across the exceptional edge.
4376 if (!Is64Bit && CLI.CB && isa<InvokeInst>(CLI.CB)) {
4377 const Function &CallerFn = MF.getFunction();
4378 EHPersonality Pers =
4379 CallerFn.hasPersonalityFn()
4380 ? classifyEHPersonality(CallerFn.getPersonalityFn())
4381 : EHPersonality::Unknown;
4382 if (isFuncletEHPersonality(Pers))
4383 Mask = RegInfo->getNoPreservedMask();
4384 }
4385
4386 // Define a new register mask from the existing mask.
4387 uint32_t *RegMask = nullptr;
4388
4389 // In some calling conventions we need to remove the used physical registers
4390 // from the reg mask.
4391 if (CallConv == CallingConv::X86_RegCall || HasNCSR) {
4392 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4393
4394 // Allocate a new Reg Mask and copy Mask.
4395 RegMask = MF.allocateRegMask();
4396 unsigned RegMaskSize = MachineOperand::getRegMaskSize(TRI->getNumRegs());
4397 memcpy(RegMask, Mask, sizeof(RegMask[0]) * RegMaskSize);
4398
4399 // Make sure all sub registers of the argument registers are reset
4400 // in the RegMask.
4401 for (auto const &RegPair : RegsToPass)
4402 for (MCSubRegIterator SubRegs(RegPair.first, TRI, /*IncludeSelf=*/true);
4403 SubRegs.isValid(); ++SubRegs)
4404 RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
4405
4406 // Create the RegMask Operand according to our updated mask.
4407 Ops.push_back(DAG.getRegisterMask(RegMask));
4408 } else {
4409 // Create the RegMask Operand according to the static mask.
4410 Ops.push_back(DAG.getRegisterMask(Mask));
4411 }
4412
4413 if (InFlag.getNode())
4414 Ops.push_back(InFlag);
4415
4416 if (isTailCall) {
4417 // We used to do:
4418 //// If this is the first return lowered for this function, add the regs
4419 //// to the liveout set for the function.
4420 // This isn't right, although it's probably harmless on x86; liveouts
4421 // should be computed from returns not tail calls. Consider a void
4422 // function making a tail call to a function returning int.
4423 MF.getFrameInfo().setHasTailCall();
4424 SDValue Ret = DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
4425 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
4426 return Ret;
4427 }
4428
4429 if (HasNoCfCheck && IsCFProtectionSupported && IsIndirectCall) {
4430 Chain = DAG.getNode(X86ISD::NT_CALL, dl, NodeTys, Ops);
4431 } else if (CLI.CB && objcarc::hasAttachedCallOpBundle(CLI.CB)) {
4432 // Calls with a "clang.arc.attachedcall" bundle are special. They should be
4433 // expanded to the call, directly followed by a special marker sequence and
4434 // a call to a ObjC library function. Use the CALL_RVMARKER to do that.
4435 assert(!isTailCall &&(static_cast <bool> (!isTailCall && "tail calls cannot be marked with clang.arc.attachedcall"
) ? void (0) : __assert_fail ("!isTailCall && \"tail calls cannot be marked with clang.arc.attachedcall\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4436, __extension__ __PRETTY_FUNCTION__))
4436 "tail calls cannot be marked with clang.arc.attachedcall")(static_cast <bool> (!isTailCall && "tail calls cannot be marked with clang.arc.attachedcall"
) ? void (0) : __assert_fail ("!isTailCall && \"tail calls cannot be marked with clang.arc.attachedcall\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4436, __extension__ __PRETTY_FUNCTION__))
;
4437 assert(Is64Bit && "clang.arc.attachedcall is only supported in 64bit mode")(static_cast <bool> (Is64Bit && "clang.arc.attachedcall is only supported in 64bit mode"
) ? void (0) : __assert_fail ("Is64Bit && \"clang.arc.attachedcall is only supported in 64bit mode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4437, __extension__ __PRETTY_FUNCTION__))
;
4438
4439 // Add target constant to select ObjC runtime call just before the call
4440 // target. RuntimeCallType == 0 selects objc_retainAutoreleasedReturnValue,
4441 // RuntimeCallType == 0 selects objc_unsafeClaimAutoreleasedReturnValue when
4442 // epxanding the pseudo.
4443 unsigned RuntimeCallType =
4444 objcarc::hasAttachedCallOpBundle(CLI.CB, true) ? 0 : 1;
4445 Ops.insert(Ops.begin() + 1,
4446 DAG.getTargetConstant(RuntimeCallType, dl, MVT::i32));
4447 Chain = DAG.getNode(X86ISD::CALL_RVMARKER, dl, NodeTys, Ops);
4448 } else {
4449 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
4450 }
4451
4452 InFlag = Chain.getValue(1);
4453 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
4454 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
4455
4456 // Save heapallocsite metadata.
4457 if (CLI.CB)
4458 if (MDNode *HeapAlloc = CLI.CB->getMetadata("heapallocsite"))
4459 DAG.addHeapAllocSite(Chain.getNode(), HeapAlloc);
4460
4461 // Create the CALLSEQ_END node.
4462 unsigned NumBytesForCalleeToPop;
4463 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
4464 DAG.getTarget().Options.GuaranteedTailCallOpt))
4465 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
4466 else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
4467 !Subtarget.getTargetTriple().isOSMSVCRT() &&
4468 SR == StackStructReturn)
4469 // If this is a call to a struct-return function, the callee
4470 // pops the hidden struct pointer, so we have to push it back.
4471 // This is common for Darwin/X86, Linux & Mingw32 targets.
4472 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
4473 NumBytesForCalleeToPop = 4;
4474 else
4475 NumBytesForCalleeToPop = 0; // Callee pops nothing.
4476
4477 // Returns a flag for retval copy to use.
4478 if (!IsSibcall) {
4479 Chain = DAG.getCALLSEQ_END(Chain,
4480 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
4481 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
4482 true),
4483 InFlag, dl);
4484 InFlag = Chain.getValue(1);
4485 }
4486
4487 // Handle result values, copying them out of physregs into vregs that we
4488 // return.
4489 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
4490 InVals, RegMask);
4491}
4492
4493//===----------------------------------------------------------------------===//
4494// Fast Calling Convention (tail call) implementation
4495//===----------------------------------------------------------------------===//
4496
4497// Like std call, callee cleans arguments, convention except that ECX is
4498// reserved for storing the tail called function address. Only 2 registers are
4499// free for argument passing (inreg). Tail call optimization is performed
4500// provided:
4501// * tailcallopt is enabled
4502// * caller/callee are fastcc
4503// On X86_64 architecture with GOT-style position independent code only local
4504// (within module) calls are supported at the moment.
4505// To keep the stack aligned according to platform abi the function
4506// GetAlignedArgumentStackSize ensures that argument delta is always multiples
4507// of stack alignment. (Dynamic linkers need this - Darwin's dyld for example)
4508// If a tail called function callee has more arguments than the caller the
4509// caller needs to make sure that there is room to move the RETADDR to. This is
4510// achieved by reserving an area the size of the argument delta right after the
4511// original RETADDR, but before the saved framepointer or the spilled registers
4512// e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
4513// stack layout:
4514// arg1
4515// arg2
4516// RETADDR
4517// [ new RETADDR
4518// move area ]
4519// (possible EBP)
4520// ESI
4521// EDI
4522// local1 ..
4523
4524/// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
4525/// requirement.
4526unsigned
4527X86TargetLowering::GetAlignedArgumentStackSize(const unsigned StackSize,
4528 SelectionDAG &DAG) const {
4529 const Align StackAlignment = Subtarget.getFrameLowering()->getStackAlign();
4530 const uint64_t SlotSize = Subtarget.getRegisterInfo()->getSlotSize();
4531 assert(StackSize % SlotSize == 0 &&(static_cast <bool> (StackSize % SlotSize == 0 &&
"StackSize must be a multiple of SlotSize") ? void (0) : __assert_fail
("StackSize % SlotSize == 0 && \"StackSize must be a multiple of SlotSize\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4532, __extension__ __PRETTY_FUNCTION__))
4532 "StackSize must be a multiple of SlotSize")(static_cast <bool> (StackSize % SlotSize == 0 &&
"StackSize must be a multiple of SlotSize") ? void (0) : __assert_fail
("StackSize % SlotSize == 0 && \"StackSize must be a multiple of SlotSize\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4532, __extension__ __PRETTY_FUNCTION__))
;
4533 return alignTo(StackSize + SlotSize, StackAlignment) - SlotSize;
4534}
4535
4536/// Return true if the given stack call argument is already available in the
4537/// same position (relatively) of the caller's incoming argument stack.
4538static
4539bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
4540 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
4541 const X86InstrInfo *TII, const CCValAssign &VA) {
4542 unsigned Bytes = Arg.getValueSizeInBits() / 8;
4543
4544 for (;;) {
4545 // Look through nodes that don't alter the bits of the incoming value.
4546 unsigned Op = Arg.getOpcode();
4547 if (Op == ISD::ZERO_EXTEND || Op == ISD::ANY_EXTEND || Op == ISD::BITCAST) {
4548 Arg = Arg.getOperand(0);
4549 continue;
4550 }
4551 if (Op == ISD::TRUNCATE) {
4552 const SDValue &TruncInput = Arg.getOperand(0);
4553 if (TruncInput.getOpcode() == ISD::AssertZext &&
4554 cast<VTSDNode>(TruncInput.getOperand(1))->getVT() ==
4555 Arg.getValueType()) {
4556 Arg = TruncInput.getOperand(0);
4557 continue;
4558 }
4559 }
4560 break;
4561 }
4562
4563 int FI = INT_MAX2147483647;
4564 if (Arg.getOpcode() == ISD::CopyFromReg) {
4565 Register VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
4566 if (!VR.isVirtual())
4567 return false;
4568 MachineInstr *Def = MRI->getVRegDef(VR);
4569 if (!Def)
4570 return false;
4571 if (!Flags.isByVal()) {
4572 if (!TII->isLoadFromStackSlot(*Def, FI))
4573 return false;
4574 } else {
4575 unsigned Opcode = Def->getOpcode();
4576 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
4577 Opcode == X86::LEA64_32r) &&
4578 Def->getOperand(1).isFI()) {
4579 FI = Def->getOperand(1).getIndex();
4580 Bytes = Flags.getByValSize();
4581 } else
4582 return false;
4583 }
4584 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
4585 if (Flags.isByVal())
4586 // ByVal argument is passed in as a pointer but it's now being
4587 // dereferenced. e.g.
4588 // define @foo(%struct.X* %A) {
4589 // tail call @bar(%struct.X* byval %A)
4590 // }
4591 return false;
4592 SDValue Ptr = Ld->getBasePtr();
4593 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
4594 if (!FINode)
4595 return false;
4596 FI = FINode->getIndex();
4597 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
4598 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
4599 FI = FINode->getIndex();
4600 Bytes = Flags.getByValSize();
4601 } else
4602 return false;
4603
4604 assert(FI != INT_MAX)(static_cast <bool> (FI != 2147483647) ? void (0) : __assert_fail
("FI != INT_MAX", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4604, __extension__ __PRETTY_FUNCTION__))
;
4605 if (!MFI.isFixedObjectIndex(FI))
4606 return false;
4607
4608 if (Offset != MFI.getObjectOffset(FI))
4609 return false;
4610
4611 // If this is not byval, check that the argument stack object is immutable.
4612 // inalloca and argument copy elision can create mutable argument stack
4613 // objects. Byval objects can be mutated, but a byval call intends to pass the
4614 // mutated memory.
4615 if (!Flags.isByVal() && !MFI.isImmutableObjectIndex(FI))
4616 return false;
4617
4618 if (VA.getLocVT().getFixedSizeInBits() >
4619 Arg.getValueSizeInBits().getFixedSize()) {
4620 // If the argument location is wider than the argument type, check that any
4621 // extension flags match.
4622 if (Flags.isZExt() != MFI.isObjectZExt(FI) ||
4623 Flags.isSExt() != MFI.isObjectSExt(FI)) {
4624 return false;
4625 }
4626 }
4627
4628 return Bytes == MFI.getObjectSize(FI);
4629}
4630
4631/// Check whether the call is eligible for tail call optimization. Targets
4632/// that want to do tail call optimization should implement this function.
4633bool X86TargetLowering::IsEligibleForTailCallOptimization(
4634 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
4635 bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
4636 const SmallVectorImpl<ISD::OutputArg> &Outs,
4637 const SmallVectorImpl<SDValue> &OutVals,
4638 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4639 if (!mayTailCallThisCC(CalleeCC))
4640 return false;
4641
4642 // If -tailcallopt is specified, make fastcc functions tail-callable.
4643 MachineFunction &MF = DAG.getMachineFunction();
4644 const Function &CallerF = MF.getFunction();
4645
4646 // If the function return type is x86_fp80 and the callee return type is not,
4647 // then the FP_EXTEND of the call result is not a nop. It's not safe to
4648 // perform a tailcall optimization here.
4649 if (CallerF.getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
4650 return false;
4651
4652 CallingConv::ID CallerCC = CallerF.getCallingConv();
4653 bool CCMatch = CallerCC == CalleeCC;
4654 bool IsCalleeWin64 = Subtarget.isCallingConvWin64(CalleeCC);
4655 bool IsCallerWin64 = Subtarget.isCallingConvWin64(CallerCC);
4656 bool IsGuaranteeTCO = DAG.getTarget().Options.GuaranteedTailCallOpt ||
4657 CalleeCC == CallingConv::Tail || CalleeCC == CallingConv::SwiftTail;
4658
4659 // Win64 functions have extra shadow space for argument homing. Don't do the
4660 // sibcall if the caller and callee have mismatched expectations for this
4661 // space.
4662 if (IsCalleeWin64 != IsCallerWin64)
4663 return false;
4664
4665 if (IsGuaranteeTCO) {
4666 if (canGuaranteeTCO(CalleeCC) && CCMatch)
4667 return true;
4668 return false;
4669 }
4670
4671 // Look for obvious safe cases to perform tail call optimization that do not
4672 // require ABI changes. This is what gcc calls sibcall.
4673
4674 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
4675 // emit a special epilogue.
4676 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4677 if (RegInfo->hasStackRealignment(MF))
4678 return false;
4679
4680 // Also avoid sibcall optimization if either caller or callee uses struct
4681 // return semantics.
4682 if (isCalleeStructRet || isCallerStructRet)
4683 return false;
4684
4685 // Do not sibcall optimize vararg calls unless all arguments are passed via
4686 // registers.
4687 LLVMContext &C = *DAG.getContext();
4688 if (isVarArg && !Outs.empty()) {
4689 // Optimizing for varargs on Win64 is unlikely to be safe without
4690 // additional testing.
4691 if (IsCalleeWin64 || IsCallerWin64)
4692 return false;
4693
4694 SmallVector<CCValAssign, 16> ArgLocs;
4695 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4696
4697 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
4698 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
4699 if (!ArgLocs[i].isRegLoc())
4700 return false;
4701 }
4702
4703 // If the call result is in ST0 / ST1, it needs to be popped off the x87
4704 // stack. Therefore, if it's not used by the call it is not safe to optimize
4705 // this into a sibcall.
4706 bool Unused = false;
4707 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4708 if (!Ins[i].Used) {
4709 Unused = true;
4710 break;
4711 }
4712 }
4713 if (Unused) {
4714 SmallVector<CCValAssign, 16> RVLocs;
4715 CCState CCInfo(CalleeCC, false, MF, RVLocs, C);
4716 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
4717 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4718 CCValAssign &VA = RVLocs[i];
4719 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
4720 return false;
4721 }
4722 }
4723
4724 // Check that the call results are passed in the same way.
4725 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
4726 RetCC_X86, RetCC_X86))
4727 return false;
4728 // The callee has to preserve all registers the caller needs to preserve.
4729 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
4730 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
4731 if (!CCMatch) {
4732 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
4733 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
4734 return false;
4735 }
4736
4737 unsigned StackArgsSize = 0;
4738
4739 // If the callee takes no arguments then go on to check the results of the
4740 // call.
4741 if (!Outs.empty()) {
4742 // Check if stack adjustment is needed. For now, do not do this if any
4743 // argument is passed on the stack.
4744 SmallVector<CCValAssign, 16> ArgLocs;
4745 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4746
4747 // Allocate shadow area for Win64
4748 if (IsCalleeWin64)
4749 CCInfo.AllocateStack(32, Align(8));
4750
4751 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
4752 StackArgsSize = CCInfo.getNextStackOffset();
4753
4754 if (CCInfo.getNextStackOffset()) {
4755 // Check if the arguments are already laid out in the right way as
4756 // the caller's fixed stack objects.
4757 MachineFrameInfo &MFI = MF.getFrameInfo();
4758 const MachineRegisterInfo *MRI = &MF.getRegInfo();
4759 const X86InstrInfo *TII = Subtarget.getInstrInfo();
4760 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4761 CCValAssign &VA = ArgLocs[i];
4762 SDValue Arg = OutVals[i];
4763 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4764 if (VA.getLocInfo() == CCValAssign::Indirect)
4765 return false;
4766 if (!VA.isRegLoc()) {
4767 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
4768 MFI, MRI, TII, VA))
4769 return false;
4770 }
4771 }
4772 }
4773
4774 bool PositionIndependent = isPositionIndependent();
4775 // If the tailcall address may be in a register, then make sure it's
4776 // possible to register allocate for it. In 32-bit, the call address can
4777 // only target EAX, EDX, or ECX since the tail call must be scheduled after
4778 // callee-saved registers are restored. These happen to be the same
4779 // registers used to pass 'inreg' arguments so watch out for those.
4780 if (!Subtarget.is64Bit() && ((!isa<GlobalAddressSDNode>(Callee) &&
4781 !isa<ExternalSymbolSDNode>(Callee)) ||
4782 PositionIndependent)) {
4783 unsigned NumInRegs = 0;
4784 // In PIC we need an extra register to formulate the address computation
4785 // for the callee.
4786 unsigned MaxInRegs = PositionIndependent ? 2 : 3;
4787
4788 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4789 CCValAssign &VA = ArgLocs[i];
4790 if (!VA.isRegLoc())
4791 continue;
4792 Register Reg = VA.getLocReg();
4793 switch (Reg) {
4794 default: break;
4795 case X86::EAX: case X86::EDX: case X86::ECX:
4796 if (++NumInRegs == MaxInRegs)
4797 return false;
4798 break;
4799 }
4800 }
4801 }
4802
4803 const MachineRegisterInfo &MRI = MF.getRegInfo();
4804 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
4805 return false;
4806 }
4807
4808 bool CalleeWillPop =
4809 X86::isCalleePop(CalleeCC, Subtarget.is64Bit(), isVarArg,
4810 MF.getTarget().Options.GuaranteedTailCallOpt);
4811
4812 if (unsigned BytesToPop =
4813 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
4814 // If we have bytes to pop, the callee must pop them.
4815 bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
4816 if (!CalleePopMatches)
4817 return false;
4818 } else if (CalleeWillPop && StackArgsSize > 0) {
4819 // If we don't have bytes to pop, make sure the callee doesn't pop any.
4820 return false;
4821 }
4822
4823 return true;
4824}
4825
4826FastISel *
4827X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
4828 const TargetLibraryInfo *libInfo) const {
4829 return X86::createFastISel(funcInfo, libInfo);
4830}
4831
4832//===----------------------------------------------------------------------===//
4833// Other Lowering Hooks
4834//===----------------------------------------------------------------------===//
4835
4836static bool MayFoldLoad(SDValue Op) {
4837 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
4838}
4839
4840static bool MayFoldIntoStore(SDValue Op) {
4841 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
4842}
4843
4844static bool MayFoldIntoZeroExtend(SDValue Op) {
4845 if (Op.hasOneUse()) {
4846 unsigned Opcode = Op.getNode()->use_begin()->getOpcode();
4847 return (ISD::ZERO_EXTEND == Opcode);
4848 }
4849 return false;
4850}
4851
4852static bool isTargetShuffle(unsigned Opcode) {
4853 switch(Opcode) {
4854 default: return false;
4855 case X86ISD::BLENDI:
4856 case X86ISD::PSHUFB:
4857 case X86ISD::PSHUFD:
4858 case X86ISD::PSHUFHW:
4859 case X86ISD::PSHUFLW:
4860 case X86ISD::SHUFP:
4861 case X86ISD::INSERTPS:
4862 case X86ISD::EXTRQI:
4863 case X86ISD::INSERTQI:
4864 case X86ISD::VALIGN:
4865 case X86ISD::PALIGNR:
4866 case X86ISD::VSHLDQ:
4867 case X86ISD::VSRLDQ:
4868 case X86ISD::MOVLHPS:
4869 case X86ISD::MOVHLPS:
4870 case X86ISD::MOVSHDUP:
4871 case X86ISD::MOVSLDUP:
4872 case X86ISD::MOVDDUP:
4873 case X86ISD::MOVSS:
4874 case X86ISD::MOVSD:
4875 case X86ISD::UNPCKL:
4876 case X86ISD::UNPCKH:
4877 case X86ISD::VBROADCAST:
4878 case X86ISD::VPERMILPI:
4879 case X86ISD::VPERMILPV:
4880 case X86ISD::VPERM2X128:
4881 case X86ISD::SHUF128:
4882 case X86ISD::VPERMIL2:
4883 case X86ISD::VPERMI:
4884 case X86ISD::VPPERM:
4885 case X86ISD::VPERMV:
4886 case X86ISD::VPERMV3:
4887 case X86ISD::VZEXT_MOVL:
4888 return true;
4889 }
4890}
4891
4892static bool isTargetShuffleVariableMask(unsigned Opcode) {
4893 switch (Opcode) {
4894 default: return false;
4895 // Target Shuffles.
4896 case X86ISD::PSHUFB:
4897 case X86ISD::VPERMILPV:
4898 case X86ISD::VPERMIL2:
4899 case X86ISD::VPPERM:
4900 case X86ISD::VPERMV:
4901 case X86ISD::VPERMV3:
4902 return true;
4903 // 'Faux' Target Shuffles.
4904 case ISD::OR:
4905 case ISD::AND:
4906 case X86ISD::ANDNP:
4907 return true;
4908 }
4909}
4910
4911static bool isTargetShuffleSplat(SDValue Op) {
4912 unsigned Opcode = Op.getOpcode();
4913 if (Opcode == ISD::EXTRACT_SUBVECTOR)
4914 return isTargetShuffleSplat(Op.getOperand(0));
4915 return Opcode == X86ISD::VBROADCAST || Opcode == X86ISD::VBROADCAST_LOAD;
4916}
4917
4918SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
4919 MachineFunction &MF = DAG.getMachineFunction();
4920 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4921 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
4922 int ReturnAddrIndex = FuncInfo->getRAIndex();
4923
4924 if (ReturnAddrIndex == 0) {
4925 // Set up a frame object for the return address.
4926 unsigned SlotSize = RegInfo->getSlotSize();
4927 ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize,
4928 -(int64_t)SlotSize,
4929 false);
4930 FuncInfo->setRAIndex(ReturnAddrIndex);
4931 }
4932
4933 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
4934}
4935
4936bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
4937 bool hasSymbolicDisplacement) {
4938 // Offset should fit into 32 bit immediate field.
4939 if (!isInt<32>(Offset))
4940 return false;
4941
4942 // If we don't have a symbolic displacement - we don't have any extra
4943 // restrictions.
4944 if (!hasSymbolicDisplacement)
4945 return true;
4946
4947 // FIXME: Some tweaks might be needed for medium code model.
4948 if (M != CodeModel::Small && M != CodeModel::Kernel)
4949 return false;
4950
4951 // For small code model we assume that latest object is 16MB before end of 31
4952 // bits boundary. We may also accept pretty large negative constants knowing
4953 // that all objects are in the positive half of address space.
4954 if (M == CodeModel::Small && Offset < 16*1024*1024)
4955 return true;
4956
4957 // For kernel code model we know that all object resist in the negative half
4958 // of 32bits address space. We may not accept negative offsets, since they may
4959 // be just off and we may accept pretty large positive ones.
4960 if (M == CodeModel::Kernel && Offset >= 0)
4961 return true;
4962
4963 return false;
4964}
4965
4966/// Determines whether the callee is required to pop its own arguments.
4967/// Callee pop is necessary to support tail calls.
4968bool X86::isCalleePop(CallingConv::ID CallingConv,
4969 bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4970 // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4971 // can guarantee TCO.
4972 if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4973 return true;
4974
4975 switch (CallingConv) {
4976 default:
4977 return false;
4978 case CallingConv::X86_StdCall:
4979 case CallingConv::X86_FastCall:
4980 case CallingConv::X86_ThisCall:
4981 case CallingConv::X86_VectorCall:
4982 return !is64Bit;
4983 }
4984}
4985
4986/// Return true if the condition is an signed comparison operation.
4987static bool isX86CCSigned(unsigned X86CC) {
4988 switch (X86CC) {
4989 default:
4990 llvm_unreachable("Invalid integer condition!")::llvm::llvm_unreachable_internal("Invalid integer condition!"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 4990)
;
4991 case X86::COND_E:
4992 case X86::COND_NE:
4993 case X86::COND_B:
4994 case X86::COND_A:
4995 case X86::COND_BE:
4996 case X86::COND_AE:
4997 return false;
4998 case X86::COND_G:
4999 case X86::COND_GE:
5000 case X86::COND_L:
5001 case X86::COND_LE:
5002 return true;
5003 }
5004}
5005
5006static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
5007 switch (SetCCOpcode) {
5008 default: llvm_unreachable("Invalid integer condition!")::llvm::llvm_unreachable_internal("Invalid integer condition!"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5008)
;
5009 case ISD::SETEQ: return X86::COND_E;
5010 case ISD::SETGT: return X86::COND_G;
5011 case ISD::SETGE: return X86::COND_GE;
5012 case ISD::SETLT: return X86::COND_L;
5013 case ISD::SETLE: return X86::COND_LE;
5014 case ISD::SETNE: return X86::COND_NE;
5015 case ISD::SETULT: return X86::COND_B;
5016 case ISD::SETUGT: return X86::COND_A;
5017 case ISD::SETULE: return X86::COND_BE;
5018 case ISD::SETUGE: return X86::COND_AE;
5019 }
5020}
5021
5022/// Do a one-to-one translation of a ISD::CondCode to the X86-specific
5023/// condition code, returning the condition code and the LHS/RHS of the
5024/// comparison to make.
5025static X86::CondCode TranslateX86CC(ISD::CondCode SetCCOpcode, const SDLoc &DL,
5026 bool isFP, SDValue &LHS, SDValue &RHS,
5027 SelectionDAG &DAG) {
5028 if (!isFP) {
5029 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5030 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
5031 // X > -1 -> X == 0, jump !sign.
5032 RHS = DAG.getConstant(0, DL, RHS.getValueType());
5033 return X86::COND_NS;
5034 }
5035 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
5036 // X < 0 -> X == 0, jump on sign.
5037 return X86::COND_S;
5038 }
5039 if (SetCCOpcode == ISD::SETGE && RHSC->isNullValue()) {
5040 // X >= 0 -> X == 0, jump on !sign.
5041 return X86::COND_NS;
5042 }
5043 if (SetCCOpcode == ISD::SETLT && RHSC->isOne()) {
5044 // X < 1 -> X <= 0
5045 RHS = DAG.getConstant(0, DL, RHS.getValueType());
5046 return X86::COND_LE;
5047 }
5048 }
5049
5050 return TranslateIntegerX86CC(SetCCOpcode);
5051 }
5052
5053 // First determine if it is required or is profitable to flip the operands.
5054
5055 // If LHS is a foldable load, but RHS is not, flip the condition.
5056 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
5057 !ISD::isNON_EXTLoad(RHS.getNode())) {
5058 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
5059 std::swap(LHS, RHS);
5060 }
5061
5062 switch (SetCCOpcode) {
5063 default: break;
5064 case ISD::SETOLT:
5065 case ISD::SETOLE:
5066 case ISD::SETUGT:
5067 case ISD::SETUGE:
5068 std::swap(LHS, RHS);
5069 break;
5070 }
5071
5072 // On a floating point condition, the flags are set as follows:
5073 // ZF PF CF op
5074 // 0 | 0 | 0 | X > Y
5075 // 0 | 0 | 1 | X < Y
5076 // 1 | 0 | 0 | X == Y
5077 // 1 | 1 | 1 | unordered
5078 switch (SetCCOpcode) {
5079 default: llvm_unreachable("Condcode should be pre-legalized away")::llvm::llvm_unreachable_internal("Condcode should be pre-legalized away"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5079)
;
5080 case ISD::SETUEQ:
5081 case ISD::SETEQ: return X86::COND_E;
5082 case ISD::SETOLT: // flipped
5083 case ISD::SETOGT:
5084 case ISD::SETGT: return X86::COND_A;
5085 case ISD::SETOLE: // flipped
5086 case ISD::SETOGE:
5087 case ISD::SETGE: return X86::COND_AE;
5088 case ISD::SETUGT: // flipped
5089 case ISD::SETULT:
5090 case ISD::SETLT: return X86::COND_B;
5091 case ISD::SETUGE: // flipped
5092 case ISD::SETULE:
5093 case ISD::SETLE: return X86::COND_BE;
5094 case ISD::SETONE:
5095 case ISD::SETNE: return X86::COND_NE;
5096 case ISD::SETUO: return X86::COND_P;
5097 case ISD::SETO: return X86::COND_NP;
5098 case ISD::SETOEQ:
5099 case ISD::SETUNE: return X86::COND_INVALID;
5100 }
5101}
5102
5103/// Is there a floating point cmov for the specific X86 condition code?
5104/// Current x86 isa includes the following FP cmov instructions:
5105/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
5106static bool hasFPCMov(unsigned X86CC) {
5107 switch (X86CC) {
5108 default:
5109 return false;
5110 case X86::COND_B:
5111 case X86::COND_BE:
5112 case X86::COND_E:
5113 case X86::COND_P:
5114 case X86::COND_A:
5115 case X86::COND_AE:
5116 case X86::COND_NE:
5117 case X86::COND_NP:
5118 return true;
5119 }
5120}
5121
5122
5123bool X86TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
5124 const CallInst &I,
5125 MachineFunction &MF,
5126 unsigned Intrinsic) const {
5127 Info.flags = MachineMemOperand::MONone;
5128 Info.offset = 0;
5129
5130 const IntrinsicData* IntrData = getIntrinsicWithChain(Intrinsic);
5131 if (!IntrData) {
5132 switch (Intrinsic) {
5133 case Intrinsic::x86_aesenc128kl:
5134 case Intrinsic::x86_aesdec128kl:
5135 Info.opc = ISD::INTRINSIC_W_CHAIN;
5136 Info.ptrVal = I.getArgOperand(1);
5137 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
5138 Info.align = Align(1);
5139 Info.flags |= MachineMemOperand::MOLoad;
5140 return true;
5141 case Intrinsic::x86_aesenc256kl:
5142 case Intrinsic::x86_aesdec256kl:
5143 Info.opc = ISD::INTRINSIC_W_CHAIN;
5144 Info.ptrVal = I.getArgOperand(1);
5145 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
5146 Info.align = Align(1);
5147 Info.flags |= MachineMemOperand::MOLoad;
5148 return true;
5149 case Intrinsic::x86_aesencwide128kl:
5150 case Intrinsic::x86_aesdecwide128kl:
5151 Info.opc = ISD::INTRINSIC_W_CHAIN;
5152 Info.ptrVal = I.getArgOperand(0);
5153 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
5154 Info.align = Align(1);
5155 Info.flags |= MachineMemOperand::MOLoad;
5156 return true;
5157 case Intrinsic::x86_aesencwide256kl:
5158 case Intrinsic::x86_aesdecwide256kl:
5159 Info.opc = ISD::INTRINSIC_W_CHAIN;
5160 Info.ptrVal = I.getArgOperand(0);
5161 Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
5162 Info.align = Align(1);
5163 Info.flags |= MachineMemOperand::MOLoad;
5164 return true;
5165 }
5166 return false;
5167 }
5168
5169 switch (IntrData->Type) {
5170 case TRUNCATE_TO_MEM_VI8:
5171 case TRUNCATE_TO_MEM_VI16:
5172 case TRUNCATE_TO_MEM_VI32: {
5173 Info.opc = ISD::INTRINSIC_VOID;
5174 Info.ptrVal = I.getArgOperand(0);
5175 MVT VT = MVT::getVT(I.getArgOperand(1)->getType());
5176 MVT ScalarVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
5177 if (IntrData->Type == TRUNCATE_TO_MEM_VI8)
5178 ScalarVT = MVT::i8;
5179 else if (IntrData->Type == TRUNCATE_TO_MEM_VI16)
5180 ScalarVT = MVT::i16;
5181 else if (IntrData->Type == TRUNCATE_TO_MEM_VI32)
5182 ScalarVT = MVT::i32;
5183
5184 Info.memVT = MVT::getVectorVT(ScalarVT, VT.getVectorNumElements());
5185 Info.align = Align(1);
5186 Info.flags |= MachineMemOperand::MOStore;
5187 break;
5188 }
5189 case GATHER:
5190 case GATHER_AVX2: {
5191 Info.opc = ISD::INTRINSIC_W_CHAIN;
5192 Info.ptrVal = nullptr;
5193 MVT DataVT = MVT::getVT(I.getType());
5194 MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
5195 unsigned NumElts = std::min(DataVT.getVectorNumElements(),
5196 IndexVT.getVectorNumElements());
5197 Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
5198 Info.align = Align(1);
5199 Info.flags |= MachineMemOperand::MOLoad;
5200 break;
5201 }
5202 case SCATTER: {
5203 Info.opc = ISD::INTRINSIC_VOID;
5204 Info.ptrVal = nullptr;
5205 MVT DataVT = MVT::getVT(I.getArgOperand(3)->getType());
5206 MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
5207 unsigned NumElts = std::min(DataVT.getVectorNumElements(),
5208 IndexVT.getVectorNumElements());
5209 Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
5210 Info.align = Align(1);
5211 Info.flags |= MachineMemOperand::MOStore;
5212 break;
5213 }
5214 default:
5215 return false;
5216 }
5217
5218 return true;
5219}
5220
5221/// Returns true if the target can instruction select the
5222/// specified FP immediate natively. If false, the legalizer will
5223/// materialize the FP immediate as a load from a constant pool.
5224bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
5225 bool ForCodeSize) const {
5226 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
5227 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
5228 return true;
5229 }
5230 return false;
5231}
5232
5233bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
5234 ISD::LoadExtType ExtTy,
5235 EVT NewVT) const {
5236 assert(cast<LoadSDNode>(Load)->isSimple() && "illegal to narrow")(static_cast <bool> (cast<LoadSDNode>(Load)->isSimple
() && "illegal to narrow") ? void (0) : __assert_fail
("cast<LoadSDNode>(Load)->isSimple() && \"illegal to narrow\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5236, __extension__ __PRETTY_FUNCTION__))
;
5237
5238 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
5239 // relocation target a movq or addq instruction: don't let the load shrink.
5240 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
5241 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
5242 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
5243 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
5244
5245 // If this is an (1) AVX vector load with (2) multiple uses and (3) all of
5246 // those uses are extracted directly into a store, then the extract + store
5247 // can be store-folded. Therefore, it's probably not worth splitting the load.
5248 EVT VT = Load->getValueType(0);
5249 if ((VT.is256BitVector() || VT.is512BitVector()) && !Load->hasOneUse()) {
5250 for (auto UI = Load->use_begin(), UE = Load->use_end(); UI != UE; ++UI) {
5251 // Skip uses of the chain value. Result 0 of the node is the load value.
5252 if (UI.getUse().getResNo() != 0)
5253 continue;
5254
5255 // If this use is not an extract + store, it's probably worth splitting.
5256 if (UI->getOpcode() != ISD::EXTRACT_SUBVECTOR || !UI->hasOneUse() ||
5257 UI->use_begin()->getOpcode() != ISD::STORE)
5258 return true;
5259 }
5260 // All non-chain uses are extract + store.
5261 return false;
5262 }
5263
5264 return true;
5265}
5266
5267/// Returns true if it is beneficial to convert a load of a constant
5268/// to just the constant itself.
5269bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
5270 Type *Ty) const {
5271 assert(Ty->isIntegerTy())(static_cast <bool> (Ty->isIntegerTy()) ? void (0) :
__assert_fail ("Ty->isIntegerTy()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5271, __extension__ __PRETTY_FUNCTION__))
;
5272
5273 unsigned BitSize = Ty->getPrimitiveSizeInBits();
5274 if (BitSize == 0 || BitSize > 64)
5275 return false;
5276 return true;
5277}
5278
5279bool X86TargetLowering::reduceSelectOfFPConstantLoads(EVT CmpOpVT) const {
5280 // If we are using XMM registers in the ABI and the condition of the select is
5281 // a floating-point compare and we have blendv or conditional move, then it is
5282 // cheaper to select instead of doing a cross-register move and creating a
5283 // load that depends on the compare result.
5284 bool IsFPSetCC = CmpOpVT.isFloatingPoint() && CmpOpVT != MVT::f128;
5285 return !IsFPSetCC || !Subtarget.isTarget64BitLP64() || !Subtarget.hasAVX();
5286}
5287
5288bool X86TargetLowering::convertSelectOfConstantsToMath(EVT VT) const {
5289 // TODO: It might be a win to ease or lift this restriction, but the generic
5290 // folds in DAGCombiner conflict with vector folds for an AVX512 target.
5291 if (VT.isVector() && Subtarget.hasAVX512())
5292 return false;
5293
5294 return true;
5295}
5296
5297bool X86TargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
5298 SDValue C) const {
5299 // TODO: We handle scalars using custom code, but generic combining could make
5300 // that unnecessary.
5301 APInt MulC;
5302 if (!ISD::isConstantSplatVector(C.getNode(), MulC))
5303 return false;
5304
5305 // Find the type this will be legalized too. Otherwise we might prematurely
5306 // convert this to shl+add/sub and then still have to type legalize those ops.
5307 // Another choice would be to defer the decision for illegal types until
5308 // after type legalization. But constant splat vectors of i64 can't make it
5309 // through type legalization on 32-bit targets so we would need to special
5310 // case vXi64.
5311 while (getTypeAction(Context, VT) != TypeLegal)
5312 VT = getTypeToTransformTo(Context, VT);
5313
5314 // If vector multiply is legal, assume that's faster than shl + add/sub.
5315 // TODO: Multiply is a complex op with higher latency and lower throughput in
5316 // most implementations, so this check could be loosened based on type
5317 // and/or a CPU attribute.
5318 if (isOperationLegal(ISD::MUL, VT))
5319 return false;
5320
5321 // shl+add, shl+sub, shl+add+neg
5322 return (MulC + 1).isPowerOf2() || (MulC - 1).isPowerOf2() ||
5323 (1 - MulC).isPowerOf2() || (-(MulC + 1)).isPowerOf2();
5324}
5325
5326bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
5327 unsigned Index) const {
5328 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
5329 return false;
5330
5331 // Mask vectors support all subregister combinations and operations that
5332 // extract half of vector.
5333 if (ResVT.getVectorElementType() == MVT::i1)
5334 return Index == 0 || ((ResVT.getSizeInBits() == SrcVT.getSizeInBits()*2) &&
5335 (Index == ResVT.getVectorNumElements()));
5336
5337 return (Index % ResVT.getVectorNumElements()) == 0;
5338}
5339
5340bool X86TargetLowering::shouldScalarizeBinop(SDValue VecOp) const {
5341 unsigned Opc = VecOp.getOpcode();
5342
5343 // Assume target opcodes can't be scalarized.
5344 // TODO - do we have any exceptions?
5345 if (Opc >= ISD::BUILTIN_OP_END)
5346 return false;
5347
5348 // If the vector op is not supported, try to convert to scalar.
5349 EVT VecVT = VecOp.getValueType();
5350 if (!isOperationLegalOrCustomOrPromote(Opc, VecVT))
5351 return true;
5352
5353 // If the vector op is supported, but the scalar op is not, the transform may
5354 // not be worthwhile.
5355 EVT ScalarVT = VecVT.getScalarType();
5356 return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
5357}
5358
5359bool X86TargetLowering::shouldFormOverflowOp(unsigned Opcode, EVT VT,
5360 bool) const {
5361 // TODO: Allow vectors?
5362 if (VT.isVector())
5363 return false;
5364 return VT.isSimple() || !isOperationExpand(Opcode, VT);
5365}
5366
5367bool X86TargetLowering::isCheapToSpeculateCttz() const {
5368 // Speculate cttz only if we can directly use TZCNT.
5369 return Subtarget.hasBMI();
5370}
5371
5372bool X86TargetLowering::isCheapToSpeculateCtlz() const {
5373 // Speculate ctlz only if we can directly use LZCNT.
5374 return Subtarget.hasLZCNT();
5375}
5376
5377bool X86TargetLowering::isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT,
5378 const SelectionDAG &DAG,
5379 const MachineMemOperand &MMO) const {
5380 if (!Subtarget.hasAVX512() && !LoadVT.isVector() && BitcastVT.isVector() &&
5381 BitcastVT.getVectorElementType() == MVT::i1)
5382 return false;
5383
5384 if (!Subtarget.hasDQI() && BitcastVT == MVT::v8i1 && LoadVT == MVT::i8)
5385 return false;
5386
5387 // If both types are legal vectors, it's always ok to convert them.
5388 if (LoadVT.isVector() && BitcastVT.isVector() &&
5389 isTypeLegal(LoadVT) && isTypeLegal(BitcastVT))
5390 return true;
5391
5392 return TargetLowering::isLoadBitCastBeneficial(LoadVT, BitcastVT, DAG, MMO);
5393}
5394
5395bool X86TargetLowering::canMergeStoresTo(unsigned AddressSpace, EVT MemVT,
5396 const SelectionDAG &DAG) const {
5397 // Do not merge to float value size (128 bytes) if no implicit
5398 // float attribute is set.
5399 bool NoFloat = DAG.getMachineFunction().getFunction().hasFnAttribute(
5400 Attribute::NoImplicitFloat);
5401
5402 if (NoFloat) {
5403 unsigned MaxIntSize = Subtarget.is64Bit() ? 64 : 32;
5404 return (MemVT.getSizeInBits() <= MaxIntSize);
5405 }
5406 // Make sure we don't merge greater than our preferred vector
5407 // width.
5408 if (MemVT.getSizeInBits() > Subtarget.getPreferVectorWidth())
5409 return false;
5410
5411 return true;
5412}
5413
5414bool X86TargetLowering::isCtlzFast() const {
5415 return Subtarget.hasFastLZCNT();
5416}
5417
5418bool X86TargetLowering::isMaskAndCmp0FoldingBeneficial(
5419 const Instruction &AndI) const {
5420 return true;
5421}
5422
5423bool X86TargetLowering::hasAndNotCompare(SDValue Y) const {
5424 EVT VT = Y.getValueType();
5425
5426 if (VT.isVector())
5427 return false;
5428
5429 if (!Subtarget.hasBMI())
5430 return false;
5431
5432 // There are only 32-bit and 64-bit forms for 'andn'.
5433 if (VT != MVT::i32 && VT != MVT::i64)
5434 return false;
5435
5436 return !isa<ConstantSDNode>(Y);
5437}
5438
5439bool X86TargetLowering::hasAndNot(SDValue Y) const {
5440 EVT VT = Y.getValueType();
5441
5442 if (!VT.isVector())
5443 return hasAndNotCompare(Y);
5444
5445 // Vector.
5446
5447 if (!Subtarget.hasSSE1() || VT.getSizeInBits() < 128)
5448 return false;
5449
5450 if (VT == MVT::v4i32)
5451 return true;
5452
5453 return Subtarget.hasSSE2();
5454}
5455
5456bool X86TargetLowering::hasBitTest(SDValue X, SDValue Y) const {
5457 return X.getValueType().isScalarInteger(); // 'bt'
5458}
5459
5460bool X86TargetLowering::
5461 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
5462 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
5463 unsigned OldShiftOpcode, unsigned NewShiftOpcode,
5464 SelectionDAG &DAG) const {
5465 // Does baseline recommend not to perform the fold by default?
5466 if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
5467 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
5468 return false;
5469 // For scalars this transform is always beneficial.
5470 if (X.getValueType().isScalarInteger())
5471 return true;
5472 // If all the shift amounts are identical, then transform is beneficial even
5473 // with rudimentary SSE2 shifts.
5474 if (DAG.isSplatValue(Y, /*AllowUndefs=*/true))
5475 return true;
5476 // If we have AVX2 with it's powerful shift operations, then it's also good.
5477 if (Subtarget.hasAVX2())
5478 return true;
5479 // Pre-AVX2 vector codegen for this pattern is best for variant with 'shl'.
5480 return NewShiftOpcode == ISD::SHL;
5481}
5482
5483bool X86TargetLowering::shouldFoldConstantShiftPairToMask(
5484 const SDNode *N, CombineLevel Level) const {
5485 assert(((N->getOpcode() == ISD::SHL &&(static_cast <bool> (((N->getOpcode() == ISD::SHL &&
N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode
() == ISD::SRL && N->getOperand(0).getOpcode() == ISD
::SHL)) && "Expected shift-shift mask") ? void (0) : __assert_fail
("((N->getOpcode() == ISD::SHL && N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL && N->getOperand(0).getOpcode() == ISD::SHL)) && \"Expected shift-shift mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5489, __extension__ __PRETTY_FUNCTION__))
5486 N->getOperand(0).getOpcode() == ISD::SRL) ||(static_cast <bool> (((N->getOpcode() == ISD::SHL &&
N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode
() == ISD::SRL && N->getOperand(0).getOpcode() == ISD
::SHL)) && "Expected shift-shift mask") ? void (0) : __assert_fail
("((N->getOpcode() == ISD::SHL && N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL && N->getOperand(0).getOpcode() == ISD::SHL)) && \"Expected shift-shift mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5489, __extension__ __PRETTY_FUNCTION__))
5487 (N->getOpcode() == ISD::SRL &&(static_cast <bool> (((N->getOpcode() == ISD::SHL &&
N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode
() == ISD::SRL && N->getOperand(0).getOpcode() == ISD
::SHL)) && "Expected shift-shift mask") ? void (0) : __assert_fail
("((N->getOpcode() == ISD::SHL && N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL && N->getOperand(0).getOpcode() == ISD::SHL)) && \"Expected shift-shift mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5489, __extension__ __PRETTY_FUNCTION__))
5488 N->getOperand(0).getOpcode() == ISD::SHL)) &&(static_cast <bool> (((N->getOpcode() == ISD::SHL &&
N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode
() == ISD::SRL && N->getOperand(0).getOpcode() == ISD
::SHL)) && "Expected shift-shift mask") ? void (0) : __assert_fail
("((N->getOpcode() == ISD::SHL && N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL && N->getOperand(0).getOpcode() == ISD::SHL)) && \"Expected shift-shift mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5489, __extension__ __PRETTY_FUNCTION__))
5489 "Expected shift-shift mask")(static_cast <bool> (((N->getOpcode() == ISD::SHL &&
N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode
() == ISD::SRL && N->getOperand(0).getOpcode() == ISD
::SHL)) && "Expected shift-shift mask") ? void (0) : __assert_fail
("((N->getOpcode() == ISD::SHL && N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL && N->getOperand(0).getOpcode() == ISD::SHL)) && \"Expected shift-shift mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5489, __extension__ __PRETTY_FUNCTION__))
;
5490 EVT VT = N->getValueType(0);
5491 if ((Subtarget.hasFastVectorShiftMasks() && VT.isVector()) ||
5492 (Subtarget.hasFastScalarShiftMasks() && !VT.isVector())) {
5493 // Only fold if the shift values are equal - so it folds to AND.
5494 // TODO - we should fold if either is a non-uniform vector but we don't do
5495 // the fold for non-splats yet.
5496 return N->getOperand(1) == N->getOperand(0).getOperand(1);
5497 }
5498 return TargetLoweringBase::shouldFoldConstantShiftPairToMask(N, Level);
5499}
5500
5501bool X86TargetLowering::shouldFoldMaskToVariableShiftPair(SDValue Y) const {
5502 EVT VT = Y.getValueType();
5503
5504 // For vectors, we don't have a preference, but we probably want a mask.
5505 if (VT.isVector())
5506 return false;
5507
5508 // 64-bit shifts on 32-bit targets produce really bad bloated code.
5509 if (VT == MVT::i64 && !Subtarget.is64Bit())
5510 return false;
5511
5512 return true;
5513}
5514
5515bool X86TargetLowering::shouldExpandShift(SelectionDAG &DAG,
5516 SDNode *N) const {
5517 if (DAG.getMachineFunction().getFunction().hasMinSize() &&
5518 !Subtarget.isOSWindows())
5519 return false;
5520 return true;
5521}
5522
5523bool X86TargetLowering::shouldSplatInsEltVarIndex(EVT VT) const {
5524 // Any legal vector type can be splatted more efficiently than
5525 // loading/spilling from memory.
5526 return isTypeLegal(VT);
5527}
5528
5529MVT X86TargetLowering::hasFastEqualityCompare(unsigned NumBits) const {
5530 MVT VT = MVT::getIntegerVT(NumBits);
5531 if (isTypeLegal(VT))
5532 return VT;
5533
5534 // PMOVMSKB can handle this.
5535 if (NumBits == 128 && isTypeLegal(MVT::v16i8))
5536 return MVT::v16i8;
5537
5538 // VPMOVMSKB can handle this.
5539 if (NumBits == 256 && isTypeLegal(MVT::v32i8))
5540 return MVT::v32i8;
5541
5542 // TODO: Allow 64-bit type for 32-bit target.
5543 // TODO: 512-bit types should be allowed, but make sure that those
5544 // cases are handled in combineVectorSizedSetCCEquality().
5545
5546 return MVT::INVALID_SIMPLE_VALUE_TYPE;
5547}
5548
5549/// Val is the undef sentinel value or equal to the specified value.
5550static bool isUndefOrEqual(int Val, int CmpVal) {
5551 return ((Val == SM_SentinelUndef) || (Val == CmpVal));
5552}
5553
5554/// Return true if every element in Mask is the undef sentinel value or equal to
5555/// the specified value..
5556static bool isUndefOrEqual(ArrayRef<int> Mask, int CmpVal) {
5557 return llvm::all_of(Mask, [CmpVal](int M) {
5558 return (M == SM_SentinelUndef) || (M == CmpVal);
5559 });
5560}
5561
5562/// Val is either the undef or zero sentinel value.
5563static bool isUndefOrZero(int Val) {
5564 return ((Val == SM_SentinelUndef) || (Val == SM_SentinelZero));
5565}
5566
5567/// Return true if every element in Mask, beginning from position Pos and ending
5568/// in Pos+Size is the undef sentinel value.
5569static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
5570 return llvm::all_of(Mask.slice(Pos, Size),
5571 [](int M) { return M == SM_SentinelUndef; });
5572}
5573
5574/// Return true if the mask creates a vector whose lower half is undefined.
5575static bool isUndefLowerHalf(ArrayRef<int> Mask) {
5576 unsigned NumElts = Mask.size();
5577 return isUndefInRange(Mask, 0, NumElts / 2);
5578}
5579
5580/// Return true if the mask creates a vector whose upper half is undefined.
5581static bool isUndefUpperHalf(ArrayRef<int> Mask) {
5582 unsigned NumElts = Mask.size();
5583 return isUndefInRange(Mask, NumElts / 2, NumElts / 2);
5584}
5585
5586/// Return true if Val falls within the specified range (L, H].
5587static bool isInRange(int Val, int Low, int Hi) {
5588 return (Val >= Low && Val < Hi);
5589}
5590
5591/// Return true if the value of any element in Mask falls within the specified
5592/// range (L, H].
5593static bool isAnyInRange(ArrayRef<int> Mask, int Low, int Hi) {
5594 return llvm::any_of(Mask, [Low, Hi](int M) { return isInRange(M, Low, Hi); });
5595}
5596
5597/// Return true if the value of any element in Mask is the zero sentinel value.
5598static bool isAnyZero(ArrayRef<int> Mask) {
5599 return llvm::any_of(Mask, [](int M) { return M == SM_SentinelZero; });
5600}
5601
5602/// Return true if the value of any element in Mask is the zero or undef
5603/// sentinel values.
5604static bool isAnyZeroOrUndef(ArrayRef<int> Mask) {
5605 return llvm::any_of(Mask, [](int M) {
5606 return M == SM_SentinelZero || M == SM_SentinelUndef;
5607 });
5608}
5609
5610/// Return true if Val is undef or if its value falls within the
5611/// specified range (L, H].
5612static bool isUndefOrInRange(int Val, int Low, int Hi) {
5613 return (Val == SM_SentinelUndef) || isInRange(Val, Low, Hi);
5614}
5615
5616/// Return true if every element in Mask is undef or if its value
5617/// falls within the specified range (L, H].
5618static bool isUndefOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
5619 return llvm::all_of(
5620 Mask, [Low, Hi](int M) { return isUndefOrInRange(M, Low, Hi); });
5621}
5622
5623/// Return true if Val is undef, zero or if its value falls within the
5624/// specified range (L, H].
5625static bool isUndefOrZeroOrInRange(int Val, int Low, int Hi) {
5626 return isUndefOrZero(Val) || isInRange(Val, Low, Hi);
5627}
5628
5629/// Return true if every element in Mask is undef, zero or if its value
5630/// falls within the specified range (L, H].
5631static bool isUndefOrZeroOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
5632 return llvm::all_of(
5633 Mask, [Low, Hi](int M) { return isUndefOrZeroOrInRange(M, Low, Hi); });
5634}
5635
5636/// Return true if every element in Mask, beginning
5637/// from position Pos and ending in Pos + Size, falls within the specified
5638/// sequence (Low, Low + Step, ..., Low + (Size - 1) * Step) or is undef.
5639static bool isSequentialOrUndefInRange(ArrayRef<int> Mask, unsigned Pos,
5640 unsigned Size, int Low, int Step = 1) {
5641 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
5642 if (!isUndefOrEqual(Mask[i], Low))
5643 return false;
5644 return true;
5645}
5646
5647/// Return true if every element in Mask, beginning
5648/// from position Pos and ending in Pos+Size, falls within the specified
5649/// sequential range (Low, Low+Size], or is undef or is zero.
5650static bool isSequentialOrUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
5651 unsigned Size, int Low,
5652 int Step = 1) {
5653 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
5654 if (!isUndefOrZero(Mask[i]) && Mask[i] != Low)
5655 return false;
5656 return true;
5657}
5658
5659/// Return true if every element in Mask, beginning
5660/// from position Pos and ending in Pos+Size is undef or is zero.
5661static bool isUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
5662 unsigned Size) {
5663 return llvm::all_of(Mask.slice(Pos, Size),
5664 [](int M) { return isUndefOrZero(M); });
5665}
5666
5667/// Helper function to test whether a shuffle mask could be
5668/// simplified by widening the elements being shuffled.
5669///
5670/// Appends the mask for wider elements in WidenedMask if valid. Otherwise
5671/// leaves it in an unspecified state.
5672///
5673/// NOTE: This must handle normal vector shuffle masks and *target* vector
5674/// shuffle masks. The latter have the special property of a '-2' representing
5675/// a zero-ed lane of a vector.
5676static bool canWidenShuffleElements(ArrayRef<int> Mask,
5677 SmallVectorImpl<int> &WidenedMask) {
5678 WidenedMask.assign(Mask.size() / 2, 0);
5679 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
5680 int M0 = Mask[i];
5681 int M1 = Mask[i + 1];
5682
5683 // If both elements are undef, its trivial.
5684 if (M0 == SM_SentinelUndef && M1 == SM_SentinelUndef) {
5685 WidenedMask[i / 2] = SM_SentinelUndef;
5686 continue;
5687 }
5688
5689 // Check for an undef mask and a mask value properly aligned to fit with
5690 // a pair of values. If we find such a case, use the non-undef mask's value.
5691 if (M0 == SM_SentinelUndef && M1 >= 0 && (M1 % 2) == 1) {
5692 WidenedMask[i / 2] = M1 / 2;
5693 continue;
5694 }
5695 if (M1 == SM_SentinelUndef && M0 >= 0 && (M0 % 2) == 0) {
5696 WidenedMask[i / 2] = M0 / 2;
5697 continue;
5698 }
5699
5700 // When zeroing, we need to spread the zeroing across both lanes to widen.
5701 if (M0 == SM_SentinelZero || M1 == SM_SentinelZero) {
5702 if ((M0 == SM_SentinelZero || M0 == SM_SentinelUndef) &&
5703 (M1 == SM_SentinelZero || M1 == SM_SentinelUndef)) {
5704 WidenedMask[i / 2] = SM_SentinelZero;
5705 continue;
5706 }
5707 return false;
5708 }
5709
5710 // Finally check if the two mask values are adjacent and aligned with
5711 // a pair.
5712 if (M0 != SM_SentinelUndef && (M0 % 2) == 0 && (M0 + 1) == M1) {
5713 WidenedMask[i / 2] = M0 / 2;
5714 continue;
5715 }
5716
5717 // Otherwise we can't safely widen the elements used in this shuffle.
5718 return false;
5719 }
5720 assert(WidenedMask.size() == Mask.size() / 2 &&(static_cast <bool> (WidenedMask.size() == Mask.size() /
2 && "Incorrect size of mask after widening the elements!"
) ? void (0) : __assert_fail ("WidenedMask.size() == Mask.size() / 2 && \"Incorrect size of mask after widening the elements!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5721, __extension__ __PRETTY_FUNCTION__))
5721 "Incorrect size of mask after widening the elements!")(static_cast <bool> (WidenedMask.size() == Mask.size() /
2 && "Incorrect size of mask after widening the elements!"
) ? void (0) : __assert_fail ("WidenedMask.size() == Mask.size() / 2 && \"Incorrect size of mask after widening the elements!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5721, __extension__ __PRETTY_FUNCTION__))
;
5722
5723 return true;
5724}
5725
5726static bool canWidenShuffleElements(ArrayRef<int> Mask,
5727 const APInt &Zeroable,
5728 bool V2IsZero,
5729 SmallVectorImpl<int> &WidenedMask) {
5730 // Create an alternative mask with info about zeroable elements.
5731 // Here we do not set undef elements as zeroable.
5732 SmallVector<int, 64> ZeroableMask(Mask.begin(), Mask.end());
5733 if (V2IsZero) {
5734 assert(!Zeroable.isNullValue() && "V2's non-undef elements are used?!")(static_cast <bool> (!Zeroable.isNullValue() &&
"V2's non-undef elements are used?!") ? void (0) : __assert_fail
("!Zeroable.isNullValue() && \"V2's non-undef elements are used?!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5734, __extension__ __PRETTY_FUNCTION__))
;
5735 for (int i = 0, Size = Mask.size(); i != Size; ++i)
5736 if (Mask[i] != SM_SentinelUndef && Zeroable[i])
5737 ZeroableMask[i] = SM_SentinelZero;
5738 }
5739 return canWidenShuffleElements(ZeroableMask, WidenedMask);
5740}
5741
5742static bool canWidenShuffleElements(ArrayRef<int> Mask) {
5743 SmallVector<int, 32> WidenedMask;
5744 return canWidenShuffleElements(Mask, WidenedMask);
5745}
5746
5747// Attempt to narrow/widen shuffle mask until it matches the target number of
5748// elements.
5749static bool scaleShuffleElements(ArrayRef<int> Mask, unsigned NumDstElts,
5750 SmallVectorImpl<int> &ScaledMask) {
5751 unsigned NumSrcElts = Mask.size();
5752 assert(((NumSrcElts % NumDstElts) == 0 || (NumDstElts % NumSrcElts) == 0) &&(static_cast <bool> (((NumSrcElts % NumDstElts) == 0 ||
(NumDstElts % NumSrcElts) == 0) && "Illegal shuffle scale factor"
) ? void (0) : __assert_fail ("((NumSrcElts % NumDstElts) == 0 || (NumDstElts % NumSrcElts) == 0) && \"Illegal shuffle scale factor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5753, __extension__ __PRETTY_FUNCTION__))
5753 "Illegal shuffle scale factor")(static_cast <bool> (((NumSrcElts % NumDstElts) == 0 ||
(NumDstElts % NumSrcElts) == 0) && "Illegal shuffle scale factor"
) ? void (0) : __assert_fail ("((NumSrcElts % NumDstElts) == 0 || (NumDstElts % NumSrcElts) == 0) && \"Illegal shuffle scale factor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5753, __extension__ __PRETTY_FUNCTION__))
;
5754
5755 // Narrowing is guaranteed to work.
5756 if (NumDstElts >= NumSrcElts) {
5757 int Scale = NumDstElts / NumSrcElts;
5758 llvm::narrowShuffleMaskElts(Scale, Mask, ScaledMask);
5759 return true;
5760 }
5761
5762 // We have to repeat the widening until we reach the target size, but we can
5763 // split out the first widening as it sets up ScaledMask for us.
5764 if (canWidenShuffleElements(Mask, ScaledMask)) {
5765 while (ScaledMask.size() > NumDstElts) {
5766 SmallVector<int, 16> WidenedMask;
5767 if (!canWidenShuffleElements(ScaledMask, WidenedMask))
5768 return false;
5769 ScaledMask = std::move(WidenedMask);
5770 }
5771 return true;
5772 }
5773
5774 return false;
5775}
5776
5777/// Returns true if Elt is a constant zero or a floating point constant +0.0.
5778bool X86::isZeroNode(SDValue Elt) {
5779 return isNullConstant(Elt) || isNullFPConstant(Elt);
5780}
5781
5782// Build a vector of constants.
5783// Use an UNDEF node if MaskElt == -1.
5784// Split 64-bit constants in the 32-bit mode.
5785static SDValue getConstVector(ArrayRef<int> Values, MVT VT, SelectionDAG &DAG,
5786 const SDLoc &dl, bool IsMask = false) {
5787
5788 SmallVector<SDValue, 32> Ops;
5789 bool Split = false;
5790
5791 MVT ConstVecVT = VT;
5792 unsigned NumElts = VT.getVectorNumElements();
5793 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
5794 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
5795 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
5796 Split = true;
5797 }
5798
5799 MVT EltVT = ConstVecVT.getVectorElementType();
5800 for (unsigned i = 0; i < NumElts; ++i) {
5801 bool IsUndef = Values[i] < 0 && IsMask;
5802 SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
5803 DAG.getConstant(Values[i], dl, EltVT);
5804 Ops.push_back(OpNode);
5805 if (Split)
5806 Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
5807 DAG.getConstant(0, dl, EltVT));
5808 }
5809 SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
5810 if (Split)
5811 ConstsNode = DAG.getBitcast(VT, ConstsNode);
5812 return ConstsNode;
5813}
5814
5815static SDValue getConstVector(ArrayRef<APInt> Bits, APInt &Undefs,
5816 MVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5817 assert(Bits.size() == Undefs.getBitWidth() &&(static_cast <bool> (Bits.size() == Undefs.getBitWidth(
) && "Unequal constant and undef arrays") ? void (0) :
__assert_fail ("Bits.size() == Undefs.getBitWidth() && \"Unequal constant and undef arrays\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5818, __extension__ __PRETTY_FUNCTION__))
5818 "Unequal constant and undef arrays")(static_cast <bool> (Bits.size() == Undefs.getBitWidth(
) && "Unequal constant and undef arrays") ? void (0) :
__assert_fail ("Bits.size() == Undefs.getBitWidth() && \"Unequal constant and undef arrays\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5818, __extension__ __PRETTY_FUNCTION__))
;
5819 SmallVector<SDValue, 32> Ops;
5820 bool Split = false;
5821
5822 MVT ConstVecVT = VT;
5823 unsigned NumElts = VT.getVectorNumElements();
5824 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
5825 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
5826 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
5827 Split = true;
5828 }
5829
5830 MVT EltVT = ConstVecVT.getVectorElementType();
5831 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
5832 if (Undefs[i]) {
5833 Ops.append(Split ? 2 : 1, DAG.getUNDEF(EltVT));
5834 continue;
5835 }
5836 const APInt &V = Bits[i];
5837 assert(V.getBitWidth() == VT.getScalarSizeInBits() && "Unexpected sizes")(static_cast <bool> (V.getBitWidth() == VT.getScalarSizeInBits
() && "Unexpected sizes") ? void (0) : __assert_fail (
"V.getBitWidth() == VT.getScalarSizeInBits() && \"Unexpected sizes\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5837, __extension__ __PRETTY_FUNCTION__))
;
5838 if (Split) {
5839 Ops.push_back(DAG.getConstant(V.trunc(32), dl, EltVT));
5840 Ops.push_back(DAG.getConstant(V.lshr(32).trunc(32), dl, EltVT));
5841 } else if (EltVT == MVT::f32) {
5842 APFloat FV(APFloat::IEEEsingle(), V);
5843 Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
5844 } else if (EltVT == MVT::f64) {
5845 APFloat FV(APFloat::IEEEdouble(), V);
5846 Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
5847 } else {
5848 Ops.push_back(DAG.getConstant(V, dl, EltVT));
5849 }
5850 }
5851
5852 SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
5853 return DAG.getBitcast(VT, ConstsNode);
5854}
5855
5856/// Returns a vector of specified type with all zero elements.
5857static SDValue getZeroVector(MVT VT, const X86Subtarget &Subtarget,
5858 SelectionDAG &DAG, const SDLoc &dl) {
5859 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() ||(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector() || VT.getVectorElementType() == MVT
::i1) && "Unexpected vector type") ? void (0) : __assert_fail
("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() || VT.getVectorElementType() == MVT::i1) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5861, __extension__ __PRETTY_FUNCTION__))
5860 VT.getVectorElementType() == MVT::i1) &&(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector() || VT.getVectorElementType() == MVT
::i1) && "Unexpected vector type") ? void (0) : __assert_fail
("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() || VT.getVectorElementType() == MVT::i1) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5861, __extension__ __PRETTY_FUNCTION__))
5861 "Unexpected vector type")(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector() || VT.getVectorElementType() == MVT
::i1) && "Unexpected vector type") ? void (0) : __assert_fail
("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() || VT.getVectorElementType() == MVT::i1) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5861, __extension__ __PRETTY_FUNCTION__))
;
5862
5863 // Try to build SSE/AVX zero vectors as <N x i32> bitcasted to their dest
5864 // type. This ensures they get CSE'd. But if the integer type is not
5865 // available, use a floating-point +0.0 instead.
5866 SDValue Vec;
5867 if (!Subtarget.hasSSE2() && VT.is128BitVector()) {
5868 Vec = DAG.getConstantFP(+0.0, dl, MVT::v4f32);
5869 } else if (VT.isFloatingPoint()) {
5870 Vec = DAG.getConstantFP(+0.0, dl, VT);
5871 } else if (VT.getVectorElementType() == MVT::i1) {
5872 assert((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&(static_cast <bool> ((Subtarget.hasBWI() || VT.getVectorNumElements
() <= 16) && "Unexpected vector type") ? void (0) :
__assert_fail ("(Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5873, __extension__ __PRETTY_FUNCTION__))
5873 "Unexpected vector type")(static_cast <bool> ((Subtarget.hasBWI() || VT.getVectorNumElements
() <= 16) && "Unexpected vector type") ? void (0) :
__assert_fail ("(Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5873, __extension__ __PRETTY_FUNCTION__))
;
5874 Vec = DAG.getConstant(0, dl, VT);
5875 } else {
5876 unsigned Num32BitElts = VT.getSizeInBits() / 32;
5877 Vec = DAG.getConstant(0, dl, MVT::getVectorVT(MVT::i32, Num32BitElts));
5878 }
5879 return DAG.getBitcast(VT, Vec);
5880}
5881
5882static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG,
5883 const SDLoc &dl, unsigned vectorWidth) {
5884 EVT VT = Vec.getValueType();
5885 EVT ElVT = VT.getVectorElementType();
5886 unsigned Factor = VT.getSizeInBits() / vectorWidth;
5887 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
5888 VT.getVectorNumElements() / Factor);
5889
5890 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
5891 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
5892 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2")(static_cast <bool> (isPowerOf2_32(ElemsPerChunk) &&
"Elements per chunk not power of 2") ? void (0) : __assert_fail
("isPowerOf2_32(ElemsPerChunk) && \"Elements per chunk not power of 2\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5892, __extension__ __PRETTY_FUNCTION__))
;
5893
5894 // This is the index of the first element of the vectorWidth-bit chunk
5895 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
5896 IdxVal &= ~(ElemsPerChunk - 1);
5897
5898 // If the input is a buildvector just emit a smaller one.
5899 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
5900 return DAG.getBuildVector(ResultVT, dl,
5901 Vec->ops().slice(IdxVal, ElemsPerChunk));
5902
5903 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
5904 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
5905}
5906
5907/// Generate a DAG to grab 128-bits from a vector > 128 bits. This
5908/// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
5909/// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
5910/// instructions or a simple subregister reference. Idx is an index in the
5911/// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
5912/// lowering EXTRACT_VECTOR_ELT operations easier.
5913static SDValue extract128BitVector(SDValue Vec, unsigned IdxVal,
5914 SelectionDAG &DAG, const SDLoc &dl) {
5915 assert((Vec.getValueType().is256BitVector() ||(static_cast <bool> ((Vec.getValueType().is256BitVector
() || Vec.getValueType().is512BitVector()) && "Unexpected vector size!"
) ? void (0) : __assert_fail ("(Vec.getValueType().is256BitVector() || Vec.getValueType().is512BitVector()) && \"Unexpected vector size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5916, __extension__ __PRETTY_FUNCTION__))
5916 Vec.getValueType().is512BitVector()) && "Unexpected vector size!")(static_cast <bool> ((Vec.getValueType().is256BitVector
() || Vec.getValueType().is512BitVector()) && "Unexpected vector size!"
) ? void (0) : __assert_fail ("(Vec.getValueType().is256BitVector() || Vec.getValueType().is512BitVector()) && \"Unexpected vector size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5916, __extension__ __PRETTY_FUNCTION__))
;
5917 return extractSubVector(Vec, IdxVal, DAG, dl, 128);
5918}
5919
5920/// Generate a DAG to grab 256-bits from a 512-bit vector.
5921static SDValue extract256BitVector(SDValue Vec, unsigned IdxVal,
5922 SelectionDAG &DAG, const SDLoc &dl) {
5923 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!")(static_cast <bool> (Vec.getValueType().is512BitVector(
) && "Unexpected vector size!") ? void (0) : __assert_fail
("Vec.getValueType().is512BitVector() && \"Unexpected vector size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5923, __extension__ __PRETTY_FUNCTION__))
;
5924 return extractSubVector(Vec, IdxVal, DAG, dl, 256);
5925}
5926
5927static SDValue insertSubVector(SDValue Result, SDValue Vec, unsigned IdxVal,
5928 SelectionDAG &DAG, const SDLoc &dl,
5929 unsigned vectorWidth) {
5930 assert((vectorWidth == 128 || vectorWidth == 256) &&(static_cast <bool> ((vectorWidth == 128 || vectorWidth
== 256) && "Unsupported vector width") ? void (0) : __assert_fail
("(vectorWidth == 128 || vectorWidth == 256) && \"Unsupported vector width\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5931, __extension__ __PRETTY_FUNCTION__))
5931 "Unsupported vector width")(static_cast <bool> ((vectorWidth == 128 || vectorWidth
== 256) && "Unsupported vector width") ? void (0) : __assert_fail
("(vectorWidth == 128 || vectorWidth == 256) && \"Unsupported vector width\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5931, __extension__ __PRETTY_FUNCTION__))
;
5932 // Inserting UNDEF is Result
5933 if (Vec.isUndef())
5934 return Result;
5935 EVT VT = Vec.getValueType();
5936 EVT ElVT = VT.getVectorElementType();
5937 EVT ResultVT = Result.getValueType();
5938
5939 // Insert the relevant vectorWidth bits.
5940 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
5941 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2")(static_cast <bool> (isPowerOf2_32(ElemsPerChunk) &&
"Elements per chunk not power of 2") ? void (0) : __assert_fail
("isPowerOf2_32(ElemsPerChunk) && \"Elements per chunk not power of 2\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5941, __extension__ __PRETTY_FUNCTION__))
;
5942
5943 // This is the index of the first element of the vectorWidth-bit chunk
5944 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
5945 IdxVal &= ~(ElemsPerChunk - 1);
5946
5947 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
5948 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
5949}
5950
5951/// Generate a DAG to put 128-bits into a vector > 128 bits. This
5952/// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
5953/// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
5954/// simple superregister reference. Idx is an index in the 128 bits
5955/// we want. It need not be aligned to a 128-bit boundary. That makes
5956/// lowering INSERT_VECTOR_ELT operations easier.
5957static SDValue insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
5958 SelectionDAG &DAG, const SDLoc &dl) {
5959 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!")(static_cast <bool> (Vec.getValueType().is128BitVector(
) && "Unexpected vector size!") ? void (0) : __assert_fail
("Vec.getValueType().is128BitVector() && \"Unexpected vector size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5959, __extension__ __PRETTY_FUNCTION__))
;
5960 return insertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
5961}
5962
5963/// Widen a vector to a larger size with the same scalar type, with the new
5964/// elements either zero or undef.
5965static SDValue widenSubVector(MVT VT, SDValue Vec, bool ZeroNewElements,
5966 const X86Subtarget &Subtarget, SelectionDAG &DAG,
5967 const SDLoc &dl) {
5968 assert(Vec.getValueSizeInBits().getFixedSize() < VT.getFixedSizeInBits() &&(static_cast <bool> (Vec.getValueSizeInBits().getFixedSize
() < VT.getFixedSizeInBits() && Vec.getValueType()
.getScalarType() == VT.getScalarType() && "Unsupported vector widening type"
) ? void (0) : __assert_fail ("Vec.getValueSizeInBits().getFixedSize() < VT.getFixedSizeInBits() && Vec.getValueType().getScalarType() == VT.getScalarType() && \"Unsupported vector widening type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5970, __extension__ __PRETTY_FUNCTION__))
5969 Vec.getValueType().getScalarType() == VT.getScalarType() &&(static_cast <bool> (Vec.getValueSizeInBits().getFixedSize
() < VT.getFixedSizeInBits() && Vec.getValueType()
.getScalarType() == VT.getScalarType() && "Unsupported vector widening type"
) ? void (0) : __assert_fail ("Vec.getValueSizeInBits().getFixedSize() < VT.getFixedSizeInBits() && Vec.getValueType().getScalarType() == VT.getScalarType() && \"Unsupported vector widening type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5970, __extension__ __PRETTY_FUNCTION__))
5970 "Unsupported vector widening type")(static_cast <bool> (Vec.getValueSizeInBits().getFixedSize
() < VT.getFixedSizeInBits() && Vec.getValueType()
.getScalarType() == VT.getScalarType() && "Unsupported vector widening type"
) ? void (0) : __assert_fail ("Vec.getValueSizeInBits().getFixedSize() < VT.getFixedSizeInBits() && Vec.getValueType().getScalarType() == VT.getScalarType() && \"Unsupported vector widening type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5970, __extension__ __PRETTY_FUNCTION__))
;
5971 SDValue Res = ZeroNewElements ? getZeroVector(VT, Subtarget, DAG, dl)
5972 : DAG.getUNDEF(VT);
5973 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, Vec,
5974 DAG.getIntPtrConstant(0, dl));
5975}
5976
5977/// Widen a vector to a larger size with the same scalar type, with the new
5978/// elements either zero or undef.
5979static SDValue widenSubVector(SDValue Vec, bool ZeroNewElements,
5980 const X86Subtarget &Subtarget, SelectionDAG &DAG,
5981 const SDLoc &dl, unsigned WideSizeInBits) {
5982 assert(Vec.getValueSizeInBits() < WideSizeInBits &&(static_cast <bool> (Vec.getValueSizeInBits() < WideSizeInBits
&& (WideSizeInBits % Vec.getScalarValueSizeInBits())
== 0 && "Unsupported vector widening type") ? void (
0) : __assert_fail ("Vec.getValueSizeInBits() < WideSizeInBits && (WideSizeInBits % Vec.getScalarValueSizeInBits()) == 0 && \"Unsupported vector widening type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5984, __extension__ __PRETTY_FUNCTION__))
5983 (WideSizeInBits % Vec.getScalarValueSizeInBits()) == 0 &&(static_cast <bool> (Vec.getValueSizeInBits() < WideSizeInBits
&& (WideSizeInBits % Vec.getScalarValueSizeInBits())
== 0 && "Unsupported vector widening type") ? void (
0) : __assert_fail ("Vec.getValueSizeInBits() < WideSizeInBits && (WideSizeInBits % Vec.getScalarValueSizeInBits()) == 0 && \"Unsupported vector widening type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5984, __extension__ __PRETTY_FUNCTION__))
5984 "Unsupported vector widening type")(static_cast <bool> (Vec.getValueSizeInBits() < WideSizeInBits
&& (WideSizeInBits % Vec.getScalarValueSizeInBits())
== 0 && "Unsupported vector widening type") ? void (
0) : __assert_fail ("Vec.getValueSizeInBits() < WideSizeInBits && (WideSizeInBits % Vec.getScalarValueSizeInBits()) == 0 && \"Unsupported vector widening type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5984, __extension__ __PRETTY_FUNCTION__))
;
5985 unsigned WideNumElts = WideSizeInBits / Vec.getScalarValueSizeInBits();
5986 MVT SVT = Vec.getSimpleValueType().getScalarType();
5987 MVT VT = MVT::getVectorVT(SVT, WideNumElts);
5988 return widenSubVector(VT, Vec, ZeroNewElements, Subtarget, DAG, dl);
5989}
5990
5991// Helper function to collect subvector ops that are concatenated together,
5992// either by ISD::CONCAT_VECTORS or a ISD::INSERT_SUBVECTOR series.
5993// The subvectors in Ops are guaranteed to be the same type.
5994static bool collectConcatOps(SDNode *N, SmallVectorImpl<SDValue> &Ops) {
5995 assert(Ops.empty() && "Expected an empty ops vector")(static_cast <bool> (Ops.empty() && "Expected an empty ops vector"
) ? void (0) : __assert_fail ("Ops.empty() && \"Expected an empty ops vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 5995, __extension__ __PRETTY_FUNCTION__))
;
5996
5997 if (N->getOpcode() == ISD::CONCAT_VECTORS) {
5998 Ops.append(N->op_begin(), N->op_end());
5999 return true;
6000 }
6001
6002 if (N->getOpcode() == ISD::INSERT_SUBVECTOR) {
6003 SDValue Src = N->getOperand(0);
6004 SDValue Sub = N->getOperand(1);
6005 const APInt &Idx = N->getConstantOperandAPInt(2);
6006 EVT VT = Src.getValueType();
6007 EVT SubVT = Sub.getValueType();
6008
6009 // TODO - Handle more general insert_subvector chains.
6010 if (VT.getSizeInBits() == (SubVT.getSizeInBits() * 2) &&
6011 Idx == (VT.getVectorNumElements() / 2)) {
6012 // insert_subvector(insert_subvector(undef, x, lo), y, hi)
6013 if (Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
6014 Src.getOperand(1).getValueType() == SubVT &&
6015 isNullConstant(Src.getOperand(2))) {
6016 Ops.push_back(Src.getOperand(1));
6017 Ops.push_back(Sub);
6018 return true;
6019 }
6020 // insert_subvector(x, extract_subvector(x, lo), hi)
6021 if (Sub.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6022 Sub.getOperand(0) == Src && isNullConstant(Sub.getOperand(1))) {
6023 Ops.append(2, Sub);
6024 return true;
6025 }
6026 }
6027 }
6028
6029 return false;
6030}
6031
6032static std::pair<SDValue, SDValue> splitVector(SDValue Op, SelectionDAG &DAG,
6033 const SDLoc &dl) {
6034 EVT VT = Op.getValueType();
6035 unsigned NumElems = VT.getVectorNumElements();
6036 unsigned SizeInBits = VT.getSizeInBits();
6037 assert((NumElems % 2) == 0 && (SizeInBits % 2) == 0 &&(static_cast <bool> ((NumElems % 2) == 0 && (SizeInBits
% 2) == 0 && "Can't split odd sized vector") ? void (
0) : __assert_fail ("(NumElems % 2) == 0 && (SizeInBits % 2) == 0 && \"Can't split odd sized vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6038, __extension__ __PRETTY_FUNCTION__))
6038 "Can't split odd sized vector")(static_cast <bool> ((NumElems % 2) == 0 && (SizeInBits
% 2) == 0 && "Can't split odd sized vector") ? void (
0) : __assert_fail ("(NumElems % 2) == 0 && (SizeInBits % 2) == 0 && \"Can't split odd sized vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6038, __extension__ __PRETTY_FUNCTION__))
;
6039
6040 SDValue Lo = extractSubVector(Op, 0, DAG, dl, SizeInBits / 2);
6041 SDValue Hi = extractSubVector(Op, NumElems / 2, DAG, dl, SizeInBits / 2);
6042 return std::make_pair(Lo, Hi);
6043}
6044
6045// Split an unary integer op into 2 half sized ops.
6046static SDValue splitVectorIntUnary(SDValue Op, SelectionDAG &DAG) {
6047 EVT VT = Op.getValueType();
6048
6049 // Make sure we only try to split 256/512-bit types to avoid creating
6050 // narrow vectors.
6051 assert((Op.getOperand(0).getValueType().is256BitVector() ||(static_cast <bool> ((Op.getOperand(0).getValueType().is256BitVector
() || Op.getOperand(0).getValueType().is512BitVector()) &&
(VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!"
) ? void (0) : __assert_fail ("(Op.getOperand(0).getValueType().is256BitVector() || Op.getOperand(0).getValueType().is512BitVector()) && (VT.is256BitVector() || VT.is512BitVector()) && \"Unsupported VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6053, __extension__ __PRETTY_FUNCTION__))
6052 Op.getOperand(0).getValueType().is512BitVector()) &&(static_cast <bool> ((Op.getOperand(0).getValueType().is256BitVector
() || Op.getOperand(0).getValueType().is512BitVector()) &&
(VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!"
) ? void (0) : __assert_fail ("(Op.getOperand(0).getValueType().is256BitVector() || Op.getOperand(0).getValueType().is512BitVector()) && (VT.is256BitVector() || VT.is512BitVector()) && \"Unsupported VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6053, __extension__ __PRETTY_FUNCTION__))
6053 (VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!")(static_cast <bool> ((Op.getOperand(0).getValueType().is256BitVector
() || Op.getOperand(0).getValueType().is512BitVector()) &&
(VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!"
) ? void (0) : __assert_fail ("(Op.getOperand(0).getValueType().is256BitVector() || Op.getOperand(0).getValueType().is512BitVector()) && (VT.is256BitVector() || VT.is512BitVector()) && \"Unsupported VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6053, __extension__ __PRETTY_FUNCTION__))
;
6054 assert(Op.getOperand(0).getValueType().getVectorNumElements() ==(static_cast <bool> (Op.getOperand(0).getValueType().getVectorNumElements
() == VT.getVectorNumElements() && "Unexpected VTs!")
? void (0) : __assert_fail ("Op.getOperand(0).getValueType().getVectorNumElements() == VT.getVectorNumElements() && \"Unexpected VTs!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6056, __extension__ __PRETTY_FUNCTION__))
6055 VT.getVectorNumElements() &&(static_cast <bool> (Op.getOperand(0).getValueType().getVectorNumElements
() == VT.getVectorNumElements() && "Unexpected VTs!")
? void (0) : __assert_fail ("Op.getOperand(0).getValueType().getVectorNumElements() == VT.getVectorNumElements() && \"Unexpected VTs!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6056, __extension__ __PRETTY_FUNCTION__))
6056 "Unexpected VTs!")(static_cast <bool> (Op.getOperand(0).getValueType().getVectorNumElements
() == VT.getVectorNumElements() && "Unexpected VTs!")
? void (0) : __assert_fail ("Op.getOperand(0).getValueType().getVectorNumElements() == VT.getVectorNumElements() && \"Unexpected VTs!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6056, __extension__ __PRETTY_FUNCTION__))
;
6057
6058 SDLoc dl(Op);
6059
6060 // Extract the Lo/Hi vectors
6061 SDValue Lo, Hi;
6062 std::tie(Lo, Hi) = splitVector(Op.getOperand(0), DAG, dl);
6063
6064 EVT LoVT, HiVT;
6065 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6066 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
6067 DAG.getNode(Op.getOpcode(), dl, LoVT, Lo),
6068 DAG.getNode(Op.getOpcode(), dl, HiVT, Hi));
6069}
6070
6071/// Break a binary integer operation into 2 half sized ops and then
6072/// concatenate the result back.
6073static SDValue splitVectorIntBinary(SDValue Op, SelectionDAG &DAG) {
6074 EVT VT = Op.getValueType();
6075
6076 // Sanity check that all the types match.
6077 assert(Op.getOperand(0).getValueType() == VT &&(static_cast <bool> (Op.getOperand(0).getValueType() ==
VT && Op.getOperand(1).getValueType() == VT &&
"Unexpected VTs!") ? void (0) : __assert_fail ("Op.getOperand(0).getValueType() == VT && Op.getOperand(1).getValueType() == VT && \"Unexpected VTs!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6078, __extension__ __PRETTY_FUNCTION__))
6078 Op.getOperand(1).getValueType() == VT && "Unexpected VTs!")(static_cast <bool> (Op.getOperand(0).getValueType() ==
VT && Op.getOperand(1).getValueType() == VT &&
"Unexpected VTs!") ? void (0) : __assert_fail ("Op.getOperand(0).getValueType() == VT && Op.getOperand(1).getValueType() == VT && \"Unexpected VTs!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6078, __extension__ __PRETTY_FUNCTION__))
;
6079 assert((VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!")(static_cast <bool> ((VT.is256BitVector() || VT.is512BitVector
()) && "Unsupported VT!") ? void (0) : __assert_fail (
"(VT.is256BitVector() || VT.is512BitVector()) && \"Unsupported VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6079, __extension__ __PRETTY_FUNCTION__))
;
6080
6081 SDLoc dl(Op);
6082
6083 // Extract the LHS Lo/Hi vectors
6084 SDValue LHS1, LHS2;
6085 std::tie(LHS1, LHS2) = splitVector(Op.getOperand(0), DAG, dl);
6086
6087 // Extract the RHS Lo/Hi vectors
6088 SDValue RHS1, RHS2;
6089 std::tie(RHS1, RHS2) = splitVector(Op.getOperand(1), DAG, dl);
6090
6091 EVT LoVT, HiVT;
6092 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6093 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
6094 DAG.getNode(Op.getOpcode(), dl, LoVT, LHS1, RHS1),
6095 DAG.getNode(Op.getOpcode(), dl, HiVT, LHS2, RHS2));
6096}
6097
6098// Helper for splitting operands of an operation to legal target size and
6099// apply a function on each part.
6100// Useful for operations that are available on SSE2 in 128-bit, on AVX2 in
6101// 256-bit and on AVX512BW in 512-bit. The argument VT is the type used for
6102// deciding if/how to split Ops. Ops elements do *not* have to be of type VT.
6103// The argument Builder is a function that will be applied on each split part:
6104// SDValue Builder(SelectionDAG&G, SDLoc, ArrayRef<SDValue>)
6105template <typename F>
6106SDValue SplitOpsAndApply(SelectionDAG &DAG, const X86Subtarget &Subtarget,
6107 const SDLoc &DL, EVT VT, ArrayRef<SDValue> Ops,
6108 F Builder, bool CheckBWI = true) {
6109 assert(Subtarget.hasSSE2() && "Target assumed to support at least SSE2")(static_cast <bool> (Subtarget.hasSSE2() && "Target assumed to support at least SSE2"
) ? void (0) : __assert_fail ("Subtarget.hasSSE2() && \"Target assumed to support at least SSE2\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6109, __extension__ __PRETTY_FUNCTION__))
;
6110 unsigned NumSubs = 1;
6111 if ((CheckBWI && Subtarget.useBWIRegs()) ||
6112 (!CheckBWI && Subtarget.useAVX512Regs())) {
6113 if (VT.getSizeInBits() > 512) {
6114 NumSubs = VT.getSizeInBits() / 512;
6115 assert((VT.getSizeInBits() % 512) == 0 && "Illegal vector size")(static_cast <bool> ((VT.getSizeInBits() % 512) == 0 &&
"Illegal vector size") ? void (0) : __assert_fail ("(VT.getSizeInBits() % 512) == 0 && \"Illegal vector size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6115, __extension__ __PRETTY_FUNCTION__))
;
6116 }
6117 } else if (Subtarget.hasAVX2()) {
6118 if (VT.getSizeInBits() > 256) {
6119 NumSubs = VT.getSizeInBits() / 256;
6120 assert((VT.getSizeInBits() % 256) == 0 && "Illegal vector size")(static_cast <bool> ((VT.getSizeInBits() % 256) == 0 &&
"Illegal vector size") ? void (0) : __assert_fail ("(VT.getSizeInBits() % 256) == 0 && \"Illegal vector size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6120, __extension__ __PRETTY_FUNCTION__))
;
6121 }
6122 } else {
6123 if (VT.getSizeInBits() > 128) {
6124 NumSubs = VT.getSizeInBits() / 128;
6125 assert((VT.getSizeInBits() % 128) == 0 && "Illegal vector size")(static_cast <bool> ((VT.getSizeInBits() % 128) == 0 &&
"Illegal vector size") ? void (0) : __assert_fail ("(VT.getSizeInBits() % 128) == 0 && \"Illegal vector size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6125, __extension__ __PRETTY_FUNCTION__))
;
6126 }
6127 }
6128
6129 if (NumSubs == 1)
6130 return Builder(DAG, DL, Ops);
6131
6132 SmallVector<SDValue, 4> Subs;
6133 for (unsigned i = 0; i != NumSubs; ++i) {
6134 SmallVector<SDValue, 2> SubOps;
6135 for (SDValue Op : Ops) {
6136 EVT OpVT = Op.getValueType();
6137 unsigned NumSubElts = OpVT.getVectorNumElements() / NumSubs;
6138 unsigned SizeSub = OpVT.getSizeInBits() / NumSubs;
6139 SubOps.push_back(extractSubVector(Op, i * NumSubElts, DAG, DL, SizeSub));
6140 }
6141 Subs.push_back(Builder(DAG, DL, SubOps));
6142 }
6143 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
6144}
6145
6146/// Insert i1-subvector to i1-vector.
6147static SDValue insert1BitVector(SDValue Op, SelectionDAG &DAG,
6148 const X86Subtarget &Subtarget) {
6149
6150 SDLoc dl(Op);
6151 SDValue Vec = Op.getOperand(0);
6152 SDValue SubVec = Op.getOperand(1);
6153 SDValue Idx = Op.getOperand(2);
6154 unsigned IdxVal = Op.getConstantOperandVal(2);
6155
6156 // Inserting undef is a nop. We can just return the original vector.
6157 if (SubVec.isUndef())
6158 return Vec;
6159
6160 if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
6161 return Op;
6162
6163 MVT OpVT = Op.getSimpleValueType();
6164 unsigned NumElems = OpVT.getVectorNumElements();
6165 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6166
6167 // Extend to natively supported kshift.
6168 MVT WideOpVT = OpVT;
6169 if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8)
6170 WideOpVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
6171
6172 // Inserting into the lsbs of a zero vector is legal. ISel will insert shifts
6173 // if necessary.
6174 if (IdxVal == 0 && ISD::isBuildVectorAllZeros(Vec.getNode())) {
6175 // May need to promote to a legal type.
6176 Op = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6177 DAG.getConstant(0, dl, WideOpVT),
6178 SubVec, Idx);
6179 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
6180 }
6181
6182 MVT SubVecVT = SubVec.getSimpleValueType();
6183 unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
6184 assert(IdxVal + SubVecNumElems <= NumElems &&(static_cast <bool> (IdxVal + SubVecNumElems <= NumElems
&& IdxVal % SubVecVT.getSizeInBits() == 0 &&
"Unexpected index value in INSERT_SUBVECTOR") ? void (0) : __assert_fail
("IdxVal + SubVecNumElems <= NumElems && IdxVal % SubVecVT.getSizeInBits() == 0 && \"Unexpected index value in INSERT_SUBVECTOR\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6186, __extension__ __PRETTY_FUNCTION__))
6185 IdxVal % SubVecVT.getSizeInBits() == 0 &&(static_cast <bool> (IdxVal + SubVecNumElems <= NumElems
&& IdxVal % SubVecVT.getSizeInBits() == 0 &&
"Unexpected index value in INSERT_SUBVECTOR") ? void (0) : __assert_fail
("IdxVal + SubVecNumElems <= NumElems && IdxVal % SubVecVT.getSizeInBits() == 0 && \"Unexpected index value in INSERT_SUBVECTOR\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6186, __extension__ __PRETTY_FUNCTION__))
6186 "Unexpected index value in INSERT_SUBVECTOR")(static_cast <bool> (IdxVal + SubVecNumElems <= NumElems
&& IdxVal % SubVecVT.getSizeInBits() == 0 &&
"Unexpected index value in INSERT_SUBVECTOR") ? void (0) : __assert_fail
("IdxVal + SubVecNumElems <= NumElems && IdxVal % SubVecVT.getSizeInBits() == 0 && \"Unexpected index value in INSERT_SUBVECTOR\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6186, __extension__ __PRETTY_FUNCTION__))
;
6187
6188 SDValue Undef = DAG.getUNDEF(WideOpVT);
6189
6190 if (IdxVal == 0) {
6191 // Zero lower bits of the Vec
6192 SDValue ShiftBits = DAG.getTargetConstant(SubVecNumElems, dl, MVT::i8);
6193 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec,
6194 ZeroIdx);
6195 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
6196 Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
6197 // Merge them together, SubVec should be zero extended.
6198 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6199 DAG.getConstant(0, dl, WideOpVT),
6200 SubVec, ZeroIdx);
6201 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
6202 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
6203 }
6204
6205 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6206 Undef, SubVec, ZeroIdx);
6207
6208 if (Vec.isUndef()) {
6209 assert(IdxVal != 0 && "Unexpected index")(static_cast <bool> (IdxVal != 0 && "Unexpected index"
) ? void (0) : __assert_fail ("IdxVal != 0 && \"Unexpected index\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6209, __extension__ __PRETTY_FUNCTION__))
;
6210 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6211 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
6212 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
6213 }
6214
6215 if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
6216 assert(IdxVal != 0 && "Unexpected index")(static_cast <bool> (IdxVal != 0 && "Unexpected index"
) ? void (0) : __assert_fail ("IdxVal != 0 && \"Unexpected index\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6216, __extension__ __PRETTY_FUNCTION__))
;
6217 NumElems = WideOpVT.getVectorNumElements();
6218 unsigned ShiftLeft = NumElems - SubVecNumElems;
6219 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
6220 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6221 DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
6222 if (ShiftRight != 0)
6223 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
6224 DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
6225 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
6226 }
6227
6228 // Simple case when we put subvector in the upper part
6229 if (IdxVal + SubVecNumElems == NumElems) {
6230 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6231 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
6232 if (SubVecNumElems * 2 == NumElems) {
6233 // Special case, use legal zero extending insert_subvector. This allows
6234 // isel to optimize when bits are known zero.
6235 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVecVT, Vec, ZeroIdx);
6236 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6237 DAG.getConstant(0, dl, WideOpVT),
6238 Vec, ZeroIdx);
6239 } else {
6240 // Otherwise use explicit shifts to zero the bits.
6241 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6242 Undef, Vec, ZeroIdx);
6243 NumElems = WideOpVT.getVectorNumElements();
6244 SDValue ShiftBits = DAG.getTargetConstant(NumElems - IdxVal, dl, MVT::i8);
6245 Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
6246 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
6247 }
6248 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
6249 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
6250 }
6251
6252 // Inserting into the middle is more complicated.
6253
6254 NumElems = WideOpVT.getVectorNumElements();
6255
6256 // Widen the vector if needed.
6257 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec, ZeroIdx);
6258
6259 unsigned ShiftLeft = NumElems - SubVecNumElems;
6260 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
6261
6262 // Do an optimization for the the most frequently used types.
6263 if (WideOpVT != MVT::v64i1 || Subtarget.is64Bit()) {
6264 APInt Mask0 = APInt::getBitsSet(NumElems, IdxVal, IdxVal + SubVecNumElems);
6265 Mask0.flipAllBits();
6266 SDValue CMask0 = DAG.getConstant(Mask0, dl, MVT::getIntegerVT(NumElems));
6267 SDValue VMask0 = DAG.getNode(ISD::BITCAST, dl, WideOpVT, CMask0);
6268 Vec = DAG.getNode(ISD::AND, dl, WideOpVT, Vec, VMask0);
6269 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6270 DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
6271 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
6272 DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
6273 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
6274
6275 // Reduce to original width if needed.
6276 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
6277 }
6278
6279 // Clear the upper bits of the subvector and move it to its insert position.
6280 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6281 DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
6282 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
6283 DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
6284
6285 // Isolate the bits below the insertion point.
6286 unsigned LowShift = NumElems - IdxVal;
6287 SDValue Low = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec,
6288 DAG.getTargetConstant(LowShift, dl, MVT::i8));
6289 Low = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Low,
6290 DAG.getTargetConstant(LowShift, dl, MVT::i8));
6291
6292 // Isolate the bits after the last inserted bit.
6293 unsigned HighShift = IdxVal + SubVecNumElems;
6294 SDValue High = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec,
6295 DAG.getTargetConstant(HighShift, dl, MVT::i8));
6296 High = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, High,
6297 DAG.getTargetConstant(HighShift, dl, MVT::i8));
6298
6299 // Now OR all 3 pieces together.
6300 Vec = DAG.getNode(ISD::OR, dl, WideOpVT, Low, High);
6301 SubVec = DAG.getNode(ISD::OR, dl, WideOpVT, SubVec, Vec);
6302
6303 // Reduce to original width if needed.
6304 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
6305}
6306
6307static SDValue concatSubVectors(SDValue V1, SDValue V2, SelectionDAG &DAG,
6308 const SDLoc &dl) {
6309 assert(V1.getValueType() == V2.getValueType() && "subvector type mismatch")(static_cast <bool> (V1.getValueType() == V2.getValueType
() && "subvector type mismatch") ? void (0) : __assert_fail
("V1.getValueType() == V2.getValueType() && \"subvector type mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6309, __extension__ __PRETTY_FUNCTION__))
;
6310 EVT SubVT = V1.getValueType();
6311 EVT SubSVT = SubVT.getScalarType();
6312 unsigned SubNumElts = SubVT.getVectorNumElements();
6313 unsigned SubVectorWidth = SubVT.getSizeInBits();
6314 EVT VT = EVT::getVectorVT(*DAG.getContext(), SubSVT, 2 * SubNumElts);
6315 SDValue V = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, dl, SubVectorWidth);
6316 return insertSubVector(V, V2, SubNumElts, DAG, dl, SubVectorWidth);
6317}
6318
6319/// Returns a vector of specified type with all bits set.
6320/// Always build ones vectors as <4 x i32>, <8 x i32> or <16 x i32>.
6321/// Then bitcast to their original type, ensuring they get CSE'd.
6322static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6323 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector()) && "Expected a 128/256/512-bit vector type"
) ? void (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Expected a 128/256/512-bit vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6324, __extension__ __PRETTY_FUNCTION__))
6324 "Expected a 128/256/512-bit vector type")(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector()) && "Expected a 128/256/512-bit vector type"
) ? void (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Expected a 128/256/512-bit vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6324, __extension__ __PRETTY_FUNCTION__))
;
6325
6326 APInt Ones = APInt::getAllOnesValue(32);
6327 unsigned NumElts = VT.getSizeInBits() / 32;
6328 SDValue Vec = DAG.getConstant(Ones, dl, MVT::getVectorVT(MVT::i32, NumElts));
6329 return DAG.getBitcast(VT, Vec);
6330}
6331
6332// Convert *_EXTEND_VECTOR_INREG to *_EXTEND opcode.
6333static unsigned getOpcode_EXTEND(unsigned Opcode) {
6334 switch (Opcode) {
6335 case ISD::ANY_EXTEND:
6336 case ISD::ANY_EXTEND_VECTOR_INREG:
6337 return ISD::ANY_EXTEND;
6338 case ISD::ZERO_EXTEND:
6339 case ISD::ZERO_EXTEND_VECTOR_INREG:
6340 return ISD::ZERO_EXTEND;
6341 case ISD::SIGN_EXTEND:
6342 case ISD::SIGN_EXTEND_VECTOR_INREG:
6343 return ISD::SIGN_EXTEND;
6344 }
6345 llvm_unreachable("Unknown opcode")::llvm::llvm_unreachable_internal("Unknown opcode", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6345)
;
6346}
6347
6348// Convert *_EXTEND to *_EXTEND_VECTOR_INREG opcode.
6349static unsigned getOpcode_EXTEND_VECTOR_INREG(unsigned Opcode) {
6350 switch (Opcode) {
6351 case ISD::ANY_EXTEND:
6352 case ISD::ANY_EXTEND_VECTOR_INREG:
6353 return ISD::ANY_EXTEND_VECTOR_INREG;
6354 case ISD::ZERO_EXTEND:
6355 case ISD::ZERO_EXTEND_VECTOR_INREG:
6356 return ISD::ZERO_EXTEND_VECTOR_INREG;
6357 case ISD::SIGN_EXTEND:
6358 case ISD::SIGN_EXTEND_VECTOR_INREG:
6359 return ISD::SIGN_EXTEND_VECTOR_INREG;
6360 }
6361 llvm_unreachable("Unknown opcode")::llvm::llvm_unreachable_internal("Unknown opcode", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6361)
;
6362}
6363
6364static SDValue getEXTEND_VECTOR_INREG(unsigned Opcode, const SDLoc &DL, EVT VT,
6365 SDValue In, SelectionDAG &DAG) {
6366 EVT InVT = In.getValueType();
6367 assert(VT.isVector() && InVT.isVector() && "Expected vector VTs.")(static_cast <bool> (VT.isVector() && InVT.isVector
() && "Expected vector VTs.") ? void (0) : __assert_fail
("VT.isVector() && InVT.isVector() && \"Expected vector VTs.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6367, __extension__ __PRETTY_FUNCTION__))
;
6368 assert((ISD::ANY_EXTEND == Opcode || ISD::SIGN_EXTEND == Opcode ||(static_cast <bool> ((ISD::ANY_EXTEND == Opcode || ISD::
SIGN_EXTEND == Opcode || ISD::ZERO_EXTEND == Opcode) &&
"Unknown extension opcode") ? void (0) : __assert_fail ("(ISD::ANY_EXTEND == Opcode || ISD::SIGN_EXTEND == Opcode || ISD::ZERO_EXTEND == Opcode) && \"Unknown extension opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6370, __extension__ __PRETTY_FUNCTION__))
6369 ISD::ZERO_EXTEND == Opcode) &&(static_cast <bool> ((ISD::ANY_EXTEND == Opcode || ISD::
SIGN_EXTEND == Opcode || ISD::ZERO_EXTEND == Opcode) &&
"Unknown extension opcode") ? void (0) : __assert_fail ("(ISD::ANY_EXTEND == Opcode || ISD::SIGN_EXTEND == Opcode || ISD::ZERO_EXTEND == Opcode) && \"Unknown extension opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6370, __extension__ __PRETTY_FUNCTION__))
6370 "Unknown extension opcode")(static_cast <bool> ((ISD::ANY_EXTEND == Opcode || ISD::
SIGN_EXTEND == Opcode || ISD::ZERO_EXTEND == Opcode) &&
"Unknown extension opcode") ? void (0) : __assert_fail ("(ISD::ANY_EXTEND == Opcode || ISD::SIGN_EXTEND == Opcode || ISD::ZERO_EXTEND == Opcode) && \"Unknown extension opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6370, __extension__ __PRETTY_FUNCTION__))
;
6371
6372 // For 256-bit vectors, we only need the lower (128-bit) input half.
6373 // For 512-bit vectors, we only need the lower input half or quarter.
6374 if (InVT.getSizeInBits() > 128) {
6375 assert(VT.getSizeInBits() == InVT.getSizeInBits() &&(static_cast <bool> (VT.getSizeInBits() == InVT.getSizeInBits
() && "Expected VTs to be the same size!") ? void (0)
: __assert_fail ("VT.getSizeInBits() == InVT.getSizeInBits() && \"Expected VTs to be the same size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6376, __extension__ __PRETTY_FUNCTION__))
6376 "Expected VTs to be the same size!")(static_cast <bool> (VT.getSizeInBits() == InVT.getSizeInBits
() && "Expected VTs to be the same size!") ? void (0)
: __assert_fail ("VT.getSizeInBits() == InVT.getSizeInBits() && \"Expected VTs to be the same size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6376, __extension__ __PRETTY_FUNCTION__))
;
6377 unsigned Scale = VT.getScalarSizeInBits() / InVT.getScalarSizeInBits();
6378 In = extractSubVector(In, 0, DAG, DL,
6379 std::max(128U, (unsigned)VT.getSizeInBits() / Scale));
6380 InVT = In.getValueType();
6381 }
6382
6383 if (VT.getVectorNumElements() != InVT.getVectorNumElements())
6384 Opcode = getOpcode_EXTEND_VECTOR_INREG(Opcode);
6385
6386 return DAG.getNode(Opcode, DL, VT, In);
6387}
6388
6389// Match (xor X, -1) -> X.
6390// Match extract_subvector(xor X, -1) -> extract_subvector(X).
6391// Match concat_vectors(xor X, -1, xor Y, -1) -> concat_vectors(X, Y).
6392static SDValue IsNOT(SDValue V, SelectionDAG &DAG) {
6393 V = peekThroughBitcasts(V);
6394 if (V.getOpcode() == ISD::XOR &&
6395 ISD::isBuildVectorAllOnes(V.getOperand(1).getNode()))
6396 return V.getOperand(0);
6397 if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6398 (isNullConstant(V.getOperand(1)) || V.getOperand(0).hasOneUse())) {
6399 if (SDValue Not = IsNOT(V.getOperand(0), DAG)) {
6400 Not = DAG.getBitcast(V.getOperand(0).getValueType(), Not);
6401 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Not), V.getValueType(),
6402 Not, V.getOperand(1));
6403 }
6404 }
6405 SmallVector<SDValue, 2> CatOps;
6406 if (collectConcatOps(V.getNode(), CatOps)) {
6407 for (SDValue &CatOp : CatOps) {
6408 SDValue NotCat = IsNOT(CatOp, DAG);
6409 if (!NotCat) return SDValue();
6410 CatOp = DAG.getBitcast(CatOp.getValueType(), NotCat);
6411 }
6412 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(V), V.getValueType(), CatOps);
6413 }
6414 return SDValue();
6415}
6416
6417void llvm::createUnpackShuffleMask(EVT VT, SmallVectorImpl<int> &Mask,
6418 bool Lo, bool Unary) {
6419 assert(VT.getScalarType().isSimple() && (VT.getSizeInBits() % 128) == 0 &&(static_cast <bool> (VT.getScalarType().isSimple() &&
(VT.getSizeInBits() % 128) == 0 && "Illegal vector type to unpack"
) ? void (0) : __assert_fail ("VT.getScalarType().isSimple() && (VT.getSizeInBits() % 128) == 0 && \"Illegal vector type to unpack\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6420, __extension__ __PRETTY_FUNCTION__))
6420 "Illegal vector type to unpack")(static_cast <bool> (VT.getScalarType().isSimple() &&
(VT.getSizeInBits() % 128) == 0 && "Illegal vector type to unpack"
) ? void (0) : __assert_fail ("VT.getScalarType().isSimple() && (VT.getSizeInBits() % 128) == 0 && \"Illegal vector type to unpack\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6420, __extension__ __PRETTY_FUNCTION__))
;
6421 assert(Mask.empty() && "Expected an empty shuffle mask vector")(static_cast <bool> (Mask.empty() && "Expected an empty shuffle mask vector"
) ? void (0) : __assert_fail ("Mask.empty() && \"Expected an empty shuffle mask vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6421, __extension__ __PRETTY_FUNCTION__))
;
6422 int NumElts = VT.getVectorNumElements();
6423 int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6424 for (int i = 0; i < NumElts; ++i) {
6425 unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6426 int Pos = (i % NumEltsInLane) / 2 + LaneStart;
6427 Pos += (Unary ? 0 : NumElts * (i % 2));
6428 Pos += (Lo ? 0 : NumEltsInLane / 2);
6429 Mask.push_back(Pos);
6430 }
6431}
6432
6433/// Similar to unpacklo/unpackhi, but without the 128-bit lane limitation
6434/// imposed by AVX and specific to the unary pattern. Example:
6435/// v8iX Lo --> <0, 0, 1, 1, 2, 2, 3, 3>
6436/// v8iX Hi --> <4, 4, 5, 5, 6, 6, 7, 7>
6437void llvm::createSplat2ShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
6438 bool Lo) {
6439 assert(Mask.empty() && "Expected an empty shuffle mask vector")(static_cast <bool> (Mask.empty() && "Expected an empty shuffle mask vector"
) ? void (0) : __assert_fail ("Mask.empty() && \"Expected an empty shuffle mask vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6439, __extension__ __PRETTY_FUNCTION__))
;
6440 int NumElts = VT.getVectorNumElements();
6441 for (int i = 0; i < NumElts; ++i) {
6442 int Pos = i / 2;
6443 Pos += (Lo ? 0 : NumElts / 2);
6444 Mask.push_back(Pos);
6445 }
6446}
6447
6448/// Returns a vector_shuffle node for an unpackl operation.
6449static SDValue getUnpackl(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
6450 SDValue V1, SDValue V2) {
6451 SmallVector<int, 8> Mask;
6452 createUnpackShuffleMask(VT, Mask, /* Lo = */ true, /* Unary = */ false);
6453 return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
6454}
6455
6456/// Returns a vector_shuffle node for an unpackh operation.
6457static SDValue getUnpackh(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
6458 SDValue V1, SDValue V2) {
6459 SmallVector<int, 8> Mask;
6460 createUnpackShuffleMask(VT, Mask, /* Lo = */ false, /* Unary = */ false);
6461 return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
6462}
6463
6464/// Return a vector_shuffle of the specified vector of zero or undef vector.
6465/// This produces a shuffle where the low element of V2 is swizzled into the
6466/// zero/undef vector, landing at element Idx.
6467/// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
6468static SDValue getShuffleVectorZeroOrUndef(SDValue V2, int Idx,
6469 bool IsZero,
6470 const X86Subtarget &Subtarget,
6471 SelectionDAG &DAG) {
6472 MVT VT = V2.getSimpleValueType();
6473 SDValue V1 = IsZero
6474 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
6475 int NumElems = VT.getVectorNumElements();
6476 SmallVector<int, 16> MaskVec(NumElems);
6477 for (int i = 0; i != NumElems; ++i)
6478 // If this is the insertion idx, put the low elt of V2 here.
6479 MaskVec[i] = (i == Idx) ? NumElems : i;
6480 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, MaskVec);
6481}
6482
6483static const Constant *getTargetConstantFromBasePtr(SDValue Ptr) {
6484 if (Ptr.getOpcode() == X86ISD::Wrapper ||
6485 Ptr.getOpcode() == X86ISD::WrapperRIP)
6486 Ptr = Ptr.getOperand(0);
6487
6488 auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr);
6489 if (!CNode || CNode->isMachineConstantPoolEntry() || CNode->getOffset() != 0)
6490 return nullptr;
6491
6492 return CNode->getConstVal();
6493}
6494
6495static const Constant *getTargetConstantFromNode(LoadSDNode *Load) {
6496 if (!Load || !ISD::isNormalLoad(Load))
6497 return nullptr;
6498 return getTargetConstantFromBasePtr(Load->getBasePtr());
6499}
6500
6501static const Constant *getTargetConstantFromNode(SDValue Op) {
6502 Op = peekThroughBitcasts(Op);
6503 return getTargetConstantFromNode(dyn_cast<LoadSDNode>(Op));
6504}
6505
6506const Constant *
6507X86TargetLowering::getTargetConstantFromLoad(LoadSDNode *LD) const {
6508 assert(LD && "Unexpected null LoadSDNode")(static_cast <bool> (LD && "Unexpected null LoadSDNode"
) ? void (0) : __assert_fail ("LD && \"Unexpected null LoadSDNode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6508, __extension__ __PRETTY_FUNCTION__))
;
6509 return getTargetConstantFromNode(LD);
6510}
6511
6512// Extract raw constant bits from constant pools.
6513static bool getTargetConstantBitsFromNode(SDValue Op, unsigned EltSizeInBits,
6514 APInt &UndefElts,
6515 SmallVectorImpl<APInt> &EltBits,
6516 bool AllowWholeUndefs = true,
6517 bool AllowPartialUndefs = true) {
6518 assert(EltBits.empty() && "Expected an empty EltBits vector")(static_cast <bool> (EltBits.empty() && "Expected an empty EltBits vector"
) ? void (0) : __assert_fail ("EltBits.empty() && \"Expected an empty EltBits vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6518, __extension__ __PRETTY_FUNCTION__))
;
6519
6520 Op = peekThroughBitcasts(Op);
6521
6522 EVT VT = Op.getValueType();
6523 unsigned SizeInBits = VT.getSizeInBits();
6524 assert((SizeInBits % EltSizeInBits) == 0 && "Can't split constant!")(static_cast <bool> ((SizeInBits % EltSizeInBits) == 0 &&
"Can't split constant!") ? void (0) : __assert_fail ("(SizeInBits % EltSizeInBits) == 0 && \"Can't split constant!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6524, __extension__ __PRETTY_FUNCTION__))
;
6525 unsigned NumElts = SizeInBits / EltSizeInBits;
6526
6527 // Bitcast a source array of element bits to the target size.
6528 auto CastBitData = [&](APInt &UndefSrcElts, ArrayRef<APInt> SrcEltBits) {
6529 unsigned NumSrcElts = UndefSrcElts.getBitWidth();
6530 unsigned SrcEltSizeInBits = SrcEltBits[0].getBitWidth();
6531 assert((NumSrcElts * SrcEltSizeInBits) == SizeInBits &&(static_cast <bool> ((NumSrcElts * SrcEltSizeInBits) ==
SizeInBits && "Constant bit sizes don't match") ? void
(0) : __assert_fail ("(NumSrcElts * SrcEltSizeInBits) == SizeInBits && \"Constant bit sizes don't match\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6532, __extension__ __PRETTY_FUNCTION__))
6532 "Constant bit sizes don't match")(static_cast <bool> ((NumSrcElts * SrcEltSizeInBits) ==
SizeInBits && "Constant bit sizes don't match") ? void
(0) : __assert_fail ("(NumSrcElts * SrcEltSizeInBits) == SizeInBits && \"Constant bit sizes don't match\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6532, __extension__ __PRETTY_FUNCTION__))
;
6533
6534 // Don't split if we don't allow undef bits.
6535 bool AllowUndefs = AllowWholeUndefs || AllowPartialUndefs;
6536 if (UndefSrcElts.getBoolValue() && !AllowUndefs)
6537 return false;
6538
6539 // If we're already the right size, don't bother bitcasting.
6540 if (NumSrcElts == NumElts) {
6541 UndefElts = UndefSrcElts;
6542 EltBits.assign(SrcEltBits.begin(), SrcEltBits.end());
6543 return true;
6544 }
6545
6546 // Extract all the undef/constant element data and pack into single bitsets.
6547 APInt UndefBits(SizeInBits, 0);
6548 APInt MaskBits(SizeInBits, 0);
6549
6550 for (unsigned i = 0; i != NumSrcElts; ++i) {
6551 unsigned BitOffset = i * SrcEltSizeInBits;
6552 if (UndefSrcElts[i])
6553 UndefBits.setBits(BitOffset, BitOffset + SrcEltSizeInBits);
6554 MaskBits.insertBits(SrcEltBits[i], BitOffset);
6555 }
6556
6557 // Split the undef/constant single bitset data into the target elements.
6558 UndefElts = APInt(NumElts, 0);
6559 EltBits.resize(NumElts, APInt(EltSizeInBits, 0));
6560
6561 for (unsigned i = 0; i != NumElts; ++i) {
6562 unsigned BitOffset = i * EltSizeInBits;
6563 APInt UndefEltBits = UndefBits.extractBits(EltSizeInBits, BitOffset);
6564
6565 // Only treat an element as UNDEF if all bits are UNDEF.
6566 if (UndefEltBits.isAllOnesValue()) {
6567 if (!AllowWholeUndefs)
6568 return false;
6569 UndefElts.setBit(i);
6570 continue;
6571 }
6572
6573 // If only some bits are UNDEF then treat them as zero (or bail if not
6574 // supported).
6575 if (UndefEltBits.getBoolValue() && !AllowPartialUndefs)
6576 return false;
6577
6578 EltBits[i] = MaskBits.extractBits(EltSizeInBits, BitOffset);
6579 }
6580 return true;
6581 };
6582
6583 // Collect constant bits and insert into mask/undef bit masks.
6584 auto CollectConstantBits = [](const Constant *Cst, APInt &Mask, APInt &Undefs,
6585 unsigned UndefBitIndex) {
6586 if (!Cst)
6587 return false;
6588 if (isa<UndefValue>(Cst)) {
6589 Undefs.setBit(UndefBitIndex);
6590 return true;
6591 }
6592 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
6593 Mask = CInt->getValue();
6594 return true;
6595 }
6596 if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
6597 Mask = CFP->getValueAPF().bitcastToAPInt();
6598 return true;
6599 }
6600 return false;
6601 };
6602
6603 // Handle UNDEFs.
6604 if (Op.isUndef()) {
6605 APInt UndefSrcElts = APInt::getAllOnesValue(NumElts);
6606 SmallVector<APInt, 64> SrcEltBits(NumElts, APInt(EltSizeInBits, 0));
6607 return CastBitData(UndefSrcElts, SrcEltBits);
6608 }
6609
6610 // Extract scalar constant bits.
6611 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) {
6612 APInt UndefSrcElts = APInt::getNullValue(1);
6613 SmallVector<APInt, 64> SrcEltBits(1, Cst->getAPIntValue());
6614 return CastBitData(UndefSrcElts, SrcEltBits);
6615 }
6616 if (auto *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
6617 APInt UndefSrcElts = APInt::getNullValue(1);
6618 APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
6619 SmallVector<APInt, 64> SrcEltBits(1, RawBits);
6620 return CastBitData(UndefSrcElts, SrcEltBits);
6621 }
6622
6623 // Extract constant bits from build vector.
6624 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
6625 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
6626 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
6627
6628 APInt UndefSrcElts(NumSrcElts, 0);
6629 SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
6630 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
6631 const SDValue &Src = Op.getOperand(i);
6632 if (Src.isUndef()) {
6633 UndefSrcElts.setBit(i);
6634 continue;
6635 }
6636 auto *Cst = cast<ConstantSDNode>(Src);
6637 SrcEltBits[i] = Cst->getAPIntValue().zextOrTrunc(SrcEltSizeInBits);
6638 }
6639 return CastBitData(UndefSrcElts, SrcEltBits);
6640 }
6641 if (ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) {
6642 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
6643 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
6644
6645 APInt UndefSrcElts(NumSrcElts, 0);
6646 SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
6647 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
6648 const SDValue &Src = Op.getOperand(i);
6649 if (Src.isUndef()) {
6650 UndefSrcElts.setBit(i);
6651 continue;
6652 }
6653 auto *Cst = cast<ConstantFPSDNode>(Src);
6654 APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
6655 SrcEltBits[i] = RawBits.zextOrTrunc(SrcEltSizeInBits);
6656 }
6657 return CastBitData(UndefSrcElts, SrcEltBits);
6658 }
6659
6660 // Extract constant bits from constant pool vector.
6661 if (auto *Cst = getTargetConstantFromNode(Op)) {
6662 Type *CstTy = Cst->getType();
6663 unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
6664 if (!CstTy->isVectorTy() || (CstSizeInBits % SizeInBits) != 0)
6665 return false;
6666
6667 unsigned SrcEltSizeInBits = CstTy->getScalarSizeInBits();
6668 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
6669
6670 APInt UndefSrcElts(NumSrcElts, 0);
6671 SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
6672 for (unsigned i = 0; i != NumSrcElts; ++i)
6673 if (!CollectConstantBits(Cst->getAggregateElement(i), SrcEltBits[i],
6674 UndefSrcElts, i))
6675 return false;
6676
6677 return CastBitData(UndefSrcElts, SrcEltBits);
6678 }
6679
6680 // Extract constant bits from a broadcasted constant pool scalar.
6681 if (Op.getOpcode() == X86ISD::VBROADCAST_LOAD &&
6682 EltSizeInBits <= VT.getScalarSizeInBits()) {
6683 auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
6684 if (MemIntr->getMemoryVT().getScalarSizeInBits() != VT.getScalarSizeInBits())
6685 return false;
6686
6687 SDValue Ptr = MemIntr->getBasePtr();
6688 if (const Constant *C = getTargetConstantFromBasePtr(Ptr)) {
6689 unsigned SrcEltSizeInBits = C->getType()->getScalarSizeInBits();
6690 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
6691
6692 APInt UndefSrcElts(NumSrcElts, 0);
6693 SmallVector<APInt, 64> SrcEltBits(1, APInt(SrcEltSizeInBits, 0));
6694 if (CollectConstantBits(C, SrcEltBits[0], UndefSrcElts, 0)) {
6695 if (UndefSrcElts[0])
6696 UndefSrcElts.setBits(0, NumSrcElts);
6697 SrcEltBits.append(NumSrcElts - 1, SrcEltBits[0]);
6698 return CastBitData(UndefSrcElts, SrcEltBits);
6699 }
6700 }
6701 }
6702
6703 // Extract constant bits from a subvector broadcast.
6704 if (Op.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) {
6705 auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
6706 SDValue Ptr = MemIntr->getBasePtr();
6707 if (const Constant *Cst = getTargetConstantFromBasePtr(Ptr)) {
6708 Type *CstTy = Cst->getType();
6709 unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
6710 if (!CstTy->isVectorTy() || (SizeInBits % CstSizeInBits) != 0)
6711 return false;
6712 unsigned SubEltSizeInBits = CstTy->getScalarSizeInBits();
6713 unsigned NumSubElts = CstSizeInBits / SubEltSizeInBits;
6714 unsigned NumSubVecs = SizeInBits / CstSizeInBits;
6715 APInt UndefSubElts(NumSubElts, 0);
6716 SmallVector<APInt, 64> SubEltBits(NumSubElts * NumSubVecs,
6717 APInt(SubEltSizeInBits, 0));
6718 for (unsigned i = 0; i != NumSubElts; ++i) {
6719 if (!CollectConstantBits(Cst->getAggregateElement(i), SubEltBits[i],
6720 UndefSubElts, i))
6721 return false;
6722 for (unsigned j = 1; j != NumSubVecs; ++j)
6723 SubEltBits[i + (j * NumSubElts)] = SubEltBits[i];
6724 }
6725 UndefSubElts = APInt::getSplat(NumSubVecs * UndefSubElts.getBitWidth(),
6726 UndefSubElts);
6727 return CastBitData(UndefSubElts, SubEltBits);
6728 }
6729 }
6730
6731 // Extract a rematerialized scalar constant insertion.
6732 if (Op.getOpcode() == X86ISD::VZEXT_MOVL &&
6733 Op.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6734 isa<ConstantSDNode>(Op.getOperand(0).getOperand(0))) {
6735 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
6736 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
6737
6738 APInt UndefSrcElts(NumSrcElts, 0);
6739 SmallVector<APInt, 64> SrcEltBits;
6740 auto *CN = cast<ConstantSDNode>(Op.getOperand(0).getOperand(0));
6741 SrcEltBits.push_back(CN->getAPIntValue().zextOrTrunc(SrcEltSizeInBits));
6742 SrcEltBits.append(NumSrcElts - 1, APInt(SrcEltSizeInBits, 0));
6743 return CastBitData(UndefSrcElts, SrcEltBits);
6744 }
6745
6746 // Insert constant bits from a base and sub vector sources.
6747 if (Op.getOpcode() == ISD::INSERT_SUBVECTOR) {
6748 // If bitcasts to larger elements we might lose track of undefs - don't
6749 // allow any to be safe.
6750 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
6751 bool AllowUndefs = EltSizeInBits >= SrcEltSizeInBits;
6752
6753 APInt UndefSrcElts, UndefSubElts;
6754 SmallVector<APInt, 32> EltSrcBits, EltSubBits;
6755 if (getTargetConstantBitsFromNode(Op.getOperand(1), SrcEltSizeInBits,
6756 UndefSubElts, EltSubBits,
6757 AllowWholeUndefs && AllowUndefs,
6758 AllowPartialUndefs && AllowUndefs) &&
6759 getTargetConstantBitsFromNode(Op.getOperand(0), SrcEltSizeInBits,
6760 UndefSrcElts, EltSrcBits,
6761 AllowWholeUndefs && AllowUndefs,
6762 AllowPartialUndefs && AllowUndefs)) {
6763 unsigned BaseIdx = Op.getConstantOperandVal(2);
6764 UndefSrcElts.insertBits(UndefSubElts, BaseIdx);
6765 for (unsigned i = 0, e = EltSubBits.size(); i != e; ++i)
6766 EltSrcBits[BaseIdx + i] = EltSubBits[i];
6767 return CastBitData(UndefSrcElts, EltSrcBits);
6768 }
6769 }
6770
6771 // Extract constant bits from a subvector's source.
6772 if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6773 // TODO - support extract_subvector through bitcasts.
6774 if (EltSizeInBits != VT.getScalarSizeInBits())
6775 return false;
6776
6777 if (getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
6778 UndefElts, EltBits, AllowWholeUndefs,
6779 AllowPartialUndefs)) {
6780 EVT SrcVT = Op.getOperand(0).getValueType();
6781 unsigned NumSrcElts = SrcVT.getVectorNumElements();
6782 unsigned NumSubElts = VT.getVectorNumElements();
6783 unsigned BaseIdx = Op.getConstantOperandVal(1);
6784 UndefElts = UndefElts.extractBits(NumSubElts, BaseIdx);
6785 if ((BaseIdx + NumSubElts) != NumSrcElts)
6786 EltBits.erase(EltBits.begin() + BaseIdx + NumSubElts, EltBits.end());
6787 if (BaseIdx != 0)
6788 EltBits.erase(EltBits.begin(), EltBits.begin() + BaseIdx);
6789 return true;
6790 }
6791 }
6792
6793 // Extract constant bits from shuffle node sources.
6794 if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(Op)) {
6795 // TODO - support shuffle through bitcasts.
6796 if (EltSizeInBits != VT.getScalarSizeInBits())
6797 return false;
6798
6799 ArrayRef<int> Mask = SVN->getMask();
6800 if ((!AllowWholeUndefs || !AllowPartialUndefs) &&
6801 llvm::any_of(Mask, [](int M) { return M < 0; }))
6802 return false;
6803
6804 APInt UndefElts0, UndefElts1;
6805 SmallVector<APInt, 32> EltBits0, EltBits1;
6806 if (isAnyInRange(Mask, 0, NumElts) &&
6807 !getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
6808 UndefElts0, EltBits0, AllowWholeUndefs,
6809 AllowPartialUndefs))
6810 return false;
6811 if (isAnyInRange(Mask, NumElts, 2 * NumElts) &&
6812 !getTargetConstantBitsFromNode(Op.getOperand(1), EltSizeInBits,
6813 UndefElts1, EltBits1, AllowWholeUndefs,
6814 AllowPartialUndefs))
6815 return false;
6816
6817 UndefElts = APInt::getNullValue(NumElts);
6818 for (int i = 0; i != (int)NumElts; ++i) {
6819 int M = Mask[i];
6820 if (M < 0) {
6821 UndefElts.setBit(i);
6822 EltBits.push_back(APInt::getNullValue(EltSizeInBits));
6823 } else if (M < (int)NumElts) {
6824 if (UndefElts0[M])
6825 UndefElts.setBit(i);
6826 EltBits.push_back(EltBits0[M]);
6827 } else {
6828 if (UndefElts1[M - NumElts])
6829 UndefElts.setBit(i);
6830 EltBits.push_back(EltBits1[M - NumElts]);
6831 }
6832 }
6833 return true;
6834 }
6835
6836 return false;
6837}
6838
6839namespace llvm {
6840namespace X86 {
6841bool isConstantSplat(SDValue Op, APInt &SplatVal, bool AllowPartialUndefs) {
6842 APInt UndefElts;
6843 SmallVector<APInt, 16> EltBits;
6844 if (getTargetConstantBitsFromNode(Op, Op.getScalarValueSizeInBits(),
6845 UndefElts, EltBits, true,
6846 AllowPartialUndefs)) {
6847 int SplatIndex = -1;
6848 for (int i = 0, e = EltBits.size(); i != e; ++i) {
6849 if (UndefElts[i])
6850 continue;
6851 if (0 <= SplatIndex && EltBits[i] != EltBits[SplatIndex]) {
6852 SplatIndex = -1;
6853 break;
6854 }
6855 SplatIndex = i;
6856 }
6857 if (0 <= SplatIndex) {
6858 SplatVal = EltBits[SplatIndex];
6859 return true;
6860 }
6861 }
6862
6863 return false;
6864}
6865} // namespace X86
6866} // namespace llvm
6867
6868static bool getTargetShuffleMaskIndices(SDValue MaskNode,
6869 unsigned MaskEltSizeInBits,
6870 SmallVectorImpl<uint64_t> &RawMask,
6871 APInt &UndefElts) {
6872 // Extract the raw target constant bits.
6873 SmallVector<APInt, 64> EltBits;
6874 if (!getTargetConstantBitsFromNode(MaskNode, MaskEltSizeInBits, UndefElts,
6875 EltBits, /* AllowWholeUndefs */ true,
6876 /* AllowPartialUndefs */ false))
6877 return false;
6878
6879 // Insert the extracted elements into the mask.
6880 for (const APInt &Elt : EltBits)
6881 RawMask.push_back(Elt.getZExtValue());
6882
6883 return true;
6884}
6885
6886/// Create a shuffle mask that matches the PACKSS/PACKUS truncation.
6887/// A multi-stage pack shuffle mask is created by specifying NumStages > 1.
6888/// Note: This ignores saturation, so inputs must be checked first.
6889static void createPackShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
6890 bool Unary, unsigned NumStages = 1) {
6891 assert(Mask.empty() && "Expected an empty shuffle mask vector")(static_cast <bool> (Mask.empty() && "Expected an empty shuffle mask vector"
) ? void (0) : __assert_fail ("Mask.empty() && \"Expected an empty shuffle mask vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6891, __extension__ __PRETTY_FUNCTION__))
;
6892 unsigned NumElts = VT.getVectorNumElements();
6893 unsigned NumLanes = VT.getSizeInBits() / 128;
6894 unsigned NumEltsPerLane = 128 / VT.getScalarSizeInBits();
6895 unsigned Offset = Unary ? 0 : NumElts;
6896 unsigned Repetitions = 1u << (NumStages - 1);
6897 unsigned Increment = 1u << NumStages;
6898 assert((NumEltsPerLane >> NumStages) > 0 && "Illegal packing compaction")(static_cast <bool> ((NumEltsPerLane >> NumStages
) > 0 && "Illegal packing compaction") ? void (0) :
__assert_fail ("(NumEltsPerLane >> NumStages) > 0 && \"Illegal packing compaction\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6898, __extension__ __PRETTY_FUNCTION__))
;
6899
6900 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
6901 for (unsigned Stage = 0; Stage != Repetitions; ++Stage) {
6902 for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
6903 Mask.push_back(Elt + (Lane * NumEltsPerLane));
6904 for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
6905 Mask.push_back(Elt + (Lane * NumEltsPerLane) + Offset);
6906 }
6907 }
6908}
6909
6910// Split the demanded elts of a PACKSS/PACKUS node between its operands.
6911static void getPackDemandedElts(EVT VT, const APInt &DemandedElts,
6912 APInt &DemandedLHS, APInt &DemandedRHS) {
6913 int NumLanes = VT.getSizeInBits() / 128;
6914 int NumElts = DemandedElts.getBitWidth();
6915 int NumInnerElts = NumElts / 2;
6916 int NumEltsPerLane = NumElts / NumLanes;
6917 int NumInnerEltsPerLane = NumInnerElts / NumLanes;
6918
6919 DemandedLHS = APInt::getNullValue(NumInnerElts);
6920 DemandedRHS = APInt::getNullValue(NumInnerElts);
6921
6922 // Map DemandedElts to the packed operands.
6923 for (int Lane = 0; Lane != NumLanes; ++Lane) {
6924 for (int Elt = 0; Elt != NumInnerEltsPerLane; ++Elt) {
6925 int OuterIdx = (Lane * NumEltsPerLane) + Elt;
6926 int InnerIdx = (Lane * NumInnerEltsPerLane) + Elt;
6927 if (DemandedElts[OuterIdx])
6928 DemandedLHS.setBit(InnerIdx);
6929 if (DemandedElts[OuterIdx + NumInnerEltsPerLane])
6930 DemandedRHS.setBit(InnerIdx);
6931 }
6932 }
6933}
6934
6935// Split the demanded elts of a HADD/HSUB node between its operands.
6936static void getHorizDemandedElts(EVT VT, const APInt &DemandedElts,
6937 APInt &DemandedLHS, APInt &DemandedRHS) {
6938 int NumLanes = VT.getSizeInBits() / 128;
6939 int NumElts = DemandedElts.getBitWidth();
6940 int NumEltsPerLane = NumElts / NumLanes;
6941 int HalfEltsPerLane = NumEltsPerLane / 2;
6942
6943 DemandedLHS = APInt::getNullValue(NumElts);
6944 DemandedRHS = APInt::getNullValue(NumElts);
6945
6946 // Map DemandedElts to the horizontal operands.
6947 for (int Idx = 0; Idx != NumElts; ++Idx) {
6948 if (!DemandedElts[Idx])
6949 continue;
6950 int LaneIdx = (Idx / NumEltsPerLane) * NumEltsPerLane;
6951 int LocalIdx = Idx % NumEltsPerLane;
6952 if (LocalIdx < HalfEltsPerLane) {
6953 DemandedLHS.setBit(LaneIdx + 2 * LocalIdx + 0);
6954 DemandedLHS.setBit(LaneIdx + 2 * LocalIdx + 1);
6955 } else {
6956 LocalIdx -= HalfEltsPerLane;
6957 DemandedRHS.setBit(LaneIdx + 2 * LocalIdx + 0);
6958 DemandedRHS.setBit(LaneIdx + 2 * LocalIdx + 1);
6959 }
6960 }
6961}
6962
6963/// Calculates the shuffle mask corresponding to the target-specific opcode.
6964/// If the mask could be calculated, returns it in \p Mask, returns the shuffle
6965/// operands in \p Ops, and returns true.
6966/// Sets \p IsUnary to true if only one source is used. Note that this will set
6967/// IsUnary for shuffles which use a single input multiple times, and in those
6968/// cases it will adjust the mask to only have indices within that single input.
6969/// It is an error to call this with non-empty Mask/Ops vectors.
6970static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
6971 SmallVectorImpl<SDValue> &Ops,
6972 SmallVectorImpl<int> &Mask, bool &IsUnary) {
6973 unsigned NumElems = VT.getVectorNumElements();
6974 unsigned MaskEltSize = VT.getScalarSizeInBits();
6975 SmallVector<uint64_t, 32> RawMask;
6976 APInt RawUndefs;
6977 uint64_t ImmN;
6978
6979 assert(Mask.empty() && "getTargetShuffleMask expects an empty Mask vector")(static_cast <bool> (Mask.empty() && "getTargetShuffleMask expects an empty Mask vector"
) ? void (0) : __assert_fail ("Mask.empty() && \"getTargetShuffleMask expects an empty Mask vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6979, __extension__ __PRETTY_FUNCTION__))
;
6980 assert(Ops.empty() && "getTargetShuffleMask expects an empty Ops vector")(static_cast <bool> (Ops.empty() && "getTargetShuffleMask expects an empty Ops vector"
) ? void (0) : __assert_fail ("Ops.empty() && \"getTargetShuffleMask expects an empty Ops vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6980, __extension__ __PRETTY_FUNCTION__))
;
6981
6982 IsUnary = false;
6983 bool IsFakeUnary = false;
6984 switch (N->getOpcode()) {
6985 case X86ISD::BLENDI:
6986 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6986, __extension__ __PRETTY_FUNCTION__))
;
6987 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6987, __extension__ __PRETTY_FUNCTION__))
;
6988 ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
6989 DecodeBLENDMask(NumElems, ImmN, Mask);
6990 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6991 break;
6992 case X86ISD::SHUFP:
6993 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6993, __extension__ __PRETTY_FUNCTION__))
;
6994 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 6994, __extension__ __PRETTY_FUNCTION__))
;
6995 ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
6996 DecodeSHUFPMask(NumElems, MaskEltSize, ImmN, Mask);
6997 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6998 break;
6999 case X86ISD::INSERTPS:
7000 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7000, __extension__ __PRETTY_FUNCTION__))
;
7001 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7001, __extension__ __PRETTY_FUNCTION__))
;
7002 ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7003 DecodeINSERTPSMask(ImmN, Mask);
7004 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7005 break;
7006 case X86ISD::EXTRQI:
7007 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7007, __extension__ __PRETTY_FUNCTION__))
;
7008 if (isa<ConstantSDNode>(N->getOperand(1)) &&
7009 isa<ConstantSDNode>(N->getOperand(2))) {
7010 int BitLen = N->getConstantOperandVal(1);
7011 int BitIdx = N->getConstantOperandVal(2);
7012 DecodeEXTRQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
7013 IsUnary = true;
7014 }
7015 break;
7016 case X86ISD::INSERTQI:
7017 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7017, __extension__ __PRETTY_FUNCTION__))
;
7018 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7018, __extension__ __PRETTY_FUNCTION__))
;
7019 if (isa<ConstantSDNode>(N->getOperand(2)) &&
7020 isa<ConstantSDNode>(N->getOperand(3))) {
7021 int BitLen = N->getConstantOperandVal(2);
7022 int BitIdx = N->getConstantOperandVal(3);
7023 DecodeINSERTQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
7024 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7025 }
7026 break;
7027 case X86ISD::UNPCKH:
7028 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7028, __extension__ __PRETTY_FUNCTION__))
;
7029 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7029, __extension__ __PRETTY_FUNCTION__))
;
7030 DecodeUNPCKHMask(NumElems, MaskEltSize, Mask);
7031 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7032 break;
7033 case X86ISD::UNPCKL:
7034 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7034, __extension__ __PRETTY_FUNCTION__))
;
7035 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7035, __extension__ __PRETTY_FUNCTION__))
;
7036 DecodeUNPCKLMask(NumElems, MaskEltSize, Mask);
7037 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7038 break;
7039 case X86ISD::MOVHLPS:
7040 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7040, __extension__ __PRETTY_FUNCTION__))
;
7041 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7041, __extension__ __PRETTY_FUNCTION__))
;
7042 DecodeMOVHLPSMask(NumElems, Mask);
7043 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7044 break;
7045 case X86ISD::MOVLHPS:
7046 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7046, __extension__ __PRETTY_FUNCTION__))
;
7047 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7047, __extension__ __PRETTY_FUNCTION__))
;
7048 DecodeMOVLHPSMask(NumElems, Mask);
7049 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7050 break;
7051 case X86ISD::VALIGN:
7052 assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&(static_cast <bool> ((VT.getScalarType() == MVT::i32 ||
VT.getScalarType() == MVT::i64) && "Only 32-bit and 64-bit elements are supported!"
) ? void (0) : __assert_fail ("(VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) && \"Only 32-bit and 64-bit elements are supported!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7053, __extension__ __PRETTY_FUNCTION__))
7053 "Only 32-bit and 64-bit elements are supported!")(static_cast <bool> ((VT.getScalarType() == MVT::i32 ||
VT.getScalarType() == MVT::i64) && "Only 32-bit and 64-bit elements are supported!"
) ? void (0) : __assert_fail ("(VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) && \"Only 32-bit and 64-bit elements are supported!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7053, __extension__ __PRETTY_FUNCTION__))
;
7054 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7054, __extension__ __PRETTY_FUNCTION__))
;
7055 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7055, __extension__ __PRETTY_FUNCTION__))
;
7056 ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7057 DecodeVALIGNMask(NumElems, ImmN, Mask);
7058 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7059 Ops.push_back(N->getOperand(1));
7060 Ops.push_back(N->getOperand(0));
7061 break;
7062 case X86ISD::PALIGNR:
7063 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected")(static_cast <bool> (VT.getScalarType() == MVT::i8 &&
"Byte vector expected") ? void (0) : __assert_fail ("VT.getScalarType() == MVT::i8 && \"Byte vector expected\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7063, __extension__ __PRETTY_FUNCTION__))
;
7064 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7064, __extension__ __PRETTY_FUNCTION__))
;
7065 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7065, __extension__ __PRETTY_FUNCTION__))
;
7066 ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7067 DecodePALIGNRMask(NumElems, ImmN, Mask);
7068 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7069 Ops.push_back(N->getOperand(1));
7070 Ops.push_back(N->getOperand(0));
7071 break;
7072 case X86ISD::VSHLDQ:
7073 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected")(static_cast <bool> (VT.getScalarType() == MVT::i8 &&
"Byte vector expected") ? void (0) : __assert_fail ("VT.getScalarType() == MVT::i8 && \"Byte vector expected\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7073, __extension__ __PRETTY_FUNCTION__))
;
7074 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7074, __extension__ __PRETTY_FUNCTION__))
;
7075 ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7076 DecodePSLLDQMask(NumElems, ImmN, Mask);
7077 IsUnary = true;
7078 break;
7079 case X86ISD::VSRLDQ:
7080 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected")(static_cast <bool> (VT.getScalarType() == MVT::i8 &&
"Byte vector expected") ? void (0) : __assert_fail ("VT.getScalarType() == MVT::i8 && \"Byte vector expected\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7080, __extension__ __PRETTY_FUNCTION__))
;
7081 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7081, __extension__ __PRETTY_FUNCTION__))
;
7082 ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7083 DecodePSRLDQMask(NumElems, ImmN, Mask);
7084 IsUnary = true;
7085 break;
7086 case X86ISD::PSHUFD:
7087 case X86ISD::VPERMILPI:
7088 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7088, __extension__ __PRETTY_FUNCTION__))
;
7089 ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7090 DecodePSHUFMask(NumElems, MaskEltSize, ImmN, Mask);
7091 IsUnary = true;
7092 break;
7093 case X86ISD::PSHUFHW:
7094 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7094, __extension__ __PRETTY_FUNCTION__))
;
7095 ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7096 DecodePSHUFHWMask(NumElems, ImmN, Mask);
7097 IsUnary = true;
7098 break;
7099 case X86ISD::PSHUFLW:
7100 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7100, __extension__ __PRETTY_FUNCTION__))
;
7101 ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7102 DecodePSHUFLWMask(NumElems, ImmN, Mask);
7103 IsUnary = true;
7104 break;
7105 case X86ISD::VZEXT_MOVL:
7106 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7106, __extension__ __PRETTY_FUNCTION__))
;
7107 DecodeZeroMoveLowMask(NumElems, Mask);
7108 IsUnary = true;
7109 break;
7110 case X86ISD::VBROADCAST:
7111 // We only decode broadcasts of same-sized vectors, peeking through to
7112 // extracted subvectors is likely to cause hasOneUse issues with
7113 // SimplifyDemandedBits etc.
7114 if (N->getOperand(0).getValueType() == VT) {
7115 DecodeVectorBroadcast(NumElems, Mask);
7116 IsUnary = true;
7117 break;
7118 }
7119 return false;
7120 case X86ISD::VPERMILPV: {
7121 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7121, __extension__ __PRETTY_FUNCTION__))
;
7122 IsUnary = true;
7123 SDValue MaskNode = N->getOperand(1);
7124 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
7125 RawUndefs)) {
7126 DecodeVPERMILPMask(NumElems, MaskEltSize, RawMask, RawUndefs, Mask);
7127 break;
7128 }
7129 return false;
7130 }
7131 case X86ISD::PSHUFB: {
7132 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected")(static_cast <bool> (VT.getScalarType() == MVT::i8 &&
"Byte vector expected") ? void (0) : __assert_fail ("VT.getScalarType() == MVT::i8 && \"Byte vector expected\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7132, __extension__ __PRETTY_FUNCTION__))
;
7133 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7133, __extension__ __PRETTY_FUNCTION__))
;
7134 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7134, __extension__ __PRETTY_FUNCTION__))
;
7135 IsUnary = true;
7136 SDValue MaskNode = N->getOperand(1);
7137 if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
7138 DecodePSHUFBMask(RawMask, RawUndefs, Mask);
7139 break;
7140 }
7141 return false;
7142 }
7143 case X86ISD::VPERMI:
7144 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7144, __extension__ __PRETTY_FUNCTION__))
;
7145 ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7146 DecodeVPERMMask(NumElems, ImmN, Mask);
7147 IsUnary = true;
7148 break;
7149 case X86ISD::MOVSS:
7150 case X86ISD::MOVSD:
7151 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7151, __extension__ __PRETTY_FUNCTION__))
;
7152 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7152, __extension__ __PRETTY_FUNCTION__))
;
7153 DecodeScalarMoveMask(NumElems, /* IsLoad */ false, Mask);
7154 break;
7155 case X86ISD::VPERM2X128:
7156 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7156, __extension__ __PRETTY_FUNCTION__))
;
7157 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7157, __extension__ __PRETTY_FUNCTION__))
;
7158 ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7159 DecodeVPERM2X128Mask(NumElems, ImmN, Mask);
7160 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7161 break;
7162 case X86ISD::SHUF128:
7163 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7163, __extension__ __PRETTY_FUNCTION__))
;
7164 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7164, __extension__ __PRETTY_FUNCTION__))
;
7165 ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7166 decodeVSHUF64x2FamilyMask(NumElems, MaskEltSize, ImmN, Mask);
7167 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7168 break;
7169 case X86ISD::MOVSLDUP:
7170 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7170, __extension__ __PRETTY_FUNCTION__))
;
7171 DecodeMOVSLDUPMask(NumElems, Mask);
7172 IsUnary = true;
7173 break;
7174 case X86ISD::MOVSHDUP:
7175 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7175, __extension__ __PRETTY_FUNCTION__))
;
7176 DecodeMOVSHDUPMask(NumElems, Mask);
7177 IsUnary = true;
7178 break;
7179 case X86ISD::MOVDDUP:
7180 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7180, __extension__ __PRETTY_FUNCTION__))
;
7181 DecodeMOVDDUPMask(NumElems, Mask);
7182 IsUnary = true;
7183 break;
7184 case X86ISD::VPERMIL2: {
7185 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7185, __extension__ __PRETTY_FUNCTION__))
;
7186 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7186, __extension__ __PRETTY_FUNCTION__))
;
7187 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7188 SDValue MaskNode = N->getOperand(2);
7189 SDValue CtrlNode = N->getOperand(3);
7190 if (ConstantSDNode *CtrlOp = dyn_cast<ConstantSDNode>(CtrlNode)) {
7191 unsigned CtrlImm = CtrlOp->getZExtValue();
7192 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
7193 RawUndefs)) {
7194 DecodeVPERMIL2PMask(NumElems, MaskEltSize, CtrlImm, RawMask, RawUndefs,
7195 Mask);
7196 break;
7197 }
7198 }
7199 return false;
7200 }
7201 case X86ISD::VPPERM: {
7202 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7202, __extension__ __PRETTY_FUNCTION__))
;
7203 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7203, __extension__ __PRETTY_FUNCTION__))
;
7204 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7205 SDValue MaskNode = N->getOperand(2);
7206 if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
7207 DecodeVPPERMMask(RawMask, RawUndefs, Mask);
7208 break;
7209 }
7210 return false;
7211 }
7212 case X86ISD::VPERMV: {
7213 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7213, __extension__ __PRETTY_FUNCTION__))
;
7214 IsUnary = true;
7215 // Unlike most shuffle nodes, VPERMV's mask operand is operand 0.
7216 Ops.push_back(N->getOperand(1));
7217 SDValue MaskNode = N->getOperand(0);
7218 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
7219 RawUndefs)) {
7220 DecodeVPERMVMask(RawMask, RawUndefs, Mask);
7221 break;
7222 }
7223 return false;
7224 }
7225 case X86ISD::VPERMV3: {
7226 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7226, __extension__ __PRETTY_FUNCTION__))
;
7227 assert(N->getOperand(2).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(2).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(2).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7227, __extension__ __PRETTY_FUNCTION__))
;
7228 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(2);
7229 // Unlike most shuffle nodes, VPERMV3's mask operand is the middle one.
7230 Ops.push_back(N->getOperand(0));
7231 Ops.push_back(N->getOperand(2));
7232 SDValue MaskNode = N->getOperand(1);
7233 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
7234 RawUndefs)) {
7235 DecodeVPERMV3Mask(RawMask, RawUndefs, Mask);
7236 break;
7237 }
7238 return false;
7239 }
7240 default: llvm_unreachable("unknown target shuffle node")::llvm::llvm_unreachable_internal("unknown target shuffle node"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7240)
;
7241 }
7242
7243 // Empty mask indicates the decode failed.
7244 if (Mask.empty())
7245 return false;
7246
7247 // Check if we're getting a shuffle mask with zero'd elements.
7248 if (!AllowSentinelZero && isAnyZero(Mask))
7249 return false;
7250
7251 // If we have a fake unary shuffle, the shuffle mask is spread across two
7252 // inputs that are actually the same node. Re-map the mask to always point
7253 // into the first input.
7254 if (IsFakeUnary)
7255 for (int &M : Mask)
7256 if (M >= (int)Mask.size())
7257 M -= Mask.size();
7258
7259 // If we didn't already add operands in the opcode-specific code, default to
7260 // adding 1 or 2 operands starting at 0.
7261 if (Ops.empty()) {
7262 Ops.push_back(N->getOperand(0));
7263 if (!IsUnary || IsFakeUnary)
7264 Ops.push_back(N->getOperand(1));
7265 }
7266
7267 return true;
7268}
7269
7270// Wrapper for getTargetShuffleMask with InUnary;
7271static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
7272 SmallVectorImpl<SDValue> &Ops,
7273 SmallVectorImpl<int> &Mask) {
7274 bool IsUnary;
7275 return getTargetShuffleMask(N, VT, AllowSentinelZero, Ops, Mask, IsUnary);
7276}
7277
7278/// Compute whether each element of a shuffle is zeroable.
7279///
7280/// A "zeroable" vector shuffle element is one which can be lowered to zero.
7281/// Either it is an undef element in the shuffle mask, the element of the input
7282/// referenced is undef, or the element of the input referenced is known to be
7283/// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
7284/// as many lanes with this technique as possible to simplify the remaining
7285/// shuffle.
7286static void computeZeroableShuffleElements(ArrayRef<int> Mask,
7287 SDValue V1, SDValue V2,
7288 APInt &KnownUndef, APInt &KnownZero) {
7289 int Size = Mask.size();
7290 KnownUndef = KnownZero = APInt::getNullValue(Size);
7291
7292 V1 = peekThroughBitcasts(V1);
7293 V2 = peekThroughBitcasts(V2);
7294
7295 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7296 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7297
7298 int VectorSizeInBits = V1.getValueSizeInBits();
7299 int ScalarSizeInBits = VectorSizeInBits / Size;
7300 assert(!(VectorSizeInBits % ScalarSizeInBits) && "Illegal shuffle mask size")(static_cast <bool> (!(VectorSizeInBits % ScalarSizeInBits
) && "Illegal shuffle mask size") ? void (0) : __assert_fail
("!(VectorSizeInBits % ScalarSizeInBits) && \"Illegal shuffle mask size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7300, __extension__ __PRETTY_FUNCTION__))
;
7301
7302 for (int i = 0; i < Size; ++i) {
7303 int M = Mask[i];
7304 // Handle the easy cases.
7305 if (M < 0) {
7306 KnownUndef.setBit(i);
7307 continue;
7308 }
7309 if ((M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
7310 KnownZero.setBit(i);
7311 continue;
7312 }
7313
7314 // Determine shuffle input and normalize the mask.
7315 SDValue V = M < Size ? V1 : V2;
7316 M %= Size;
7317
7318 // Currently we can only search BUILD_VECTOR for UNDEF/ZERO elements.
7319 if (V.getOpcode() != ISD::BUILD_VECTOR)
7320 continue;
7321
7322 // If the BUILD_VECTOR has fewer elements then the bitcasted portion of
7323 // the (larger) source element must be UNDEF/ZERO.
7324 if ((Size % V.getNumOperands()) == 0) {
7325 int Scale = Size / V->getNumOperands();
7326 SDValue Op = V.getOperand(M / Scale);
7327 if (Op.isUndef())
7328 KnownUndef.setBit(i);
7329 if (X86::isZeroNode(Op))
7330 KnownZero.setBit(i);
7331 else if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
7332 APInt Val = Cst->getAPIntValue();
7333 Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
7334 if (Val == 0)
7335 KnownZero.setBit(i);
7336 } else if (ConstantFPSDNode *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
7337 APInt Val = Cst->getValueAPF().bitcastToAPInt();
7338 Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
7339 if (Val == 0)
7340 KnownZero.setBit(i);
7341 }
7342 continue;
7343 }
7344
7345 // If the BUILD_VECTOR has more elements then all the (smaller) source
7346 // elements must be UNDEF or ZERO.
7347 if ((V.getNumOperands() % Size) == 0) {
7348 int Scale = V->getNumOperands() / Size;
7349 bool AllUndef = true;
7350 bool AllZero = true;
7351 for (int j = 0; j < Scale; ++j) {
7352 SDValue Op = V.getOperand((M * Scale) + j);
7353 AllUndef &= Op.isUndef();
7354 AllZero &= X86::isZeroNode(Op);
7355 }
7356 if (AllUndef)
7357 KnownUndef.setBit(i);
7358 if (AllZero)
7359 KnownZero.setBit(i);
7360 continue;
7361 }
7362 }
7363}
7364
7365/// Decode a target shuffle mask and inputs and see if any values are
7366/// known to be undef or zero from their inputs.
7367/// Returns true if the target shuffle mask was decoded.
7368/// FIXME: Merge this with computeZeroableShuffleElements?
7369static bool getTargetShuffleAndZeroables(SDValue N, SmallVectorImpl<int> &Mask,
7370 SmallVectorImpl<SDValue> &Ops,
7371 APInt &KnownUndef, APInt &KnownZero) {
7372 bool IsUnary;
7373 if (!isTargetShuffle(N.getOpcode()))
7374 return false;
7375
7376 MVT VT = N.getSimpleValueType();
7377 if (!getTargetShuffleMask(N.getNode(), VT, true, Ops, Mask, IsUnary))
7378 return false;
7379
7380 int Size = Mask.size();
7381 SDValue V1 = Ops[0];
7382 SDValue V2 = IsUnary ? V1 : Ops[1];
7383 KnownUndef = KnownZero = APInt::getNullValue(Size);
7384
7385 V1 = peekThroughBitcasts(V1);
7386 V2 = peekThroughBitcasts(V2);
7387
7388 assert((VT.getSizeInBits() % Size) == 0 &&(static_cast <bool> ((VT.getSizeInBits() % Size) == 0 &&
"Illegal split of shuffle value type") ? void (0) : __assert_fail
("(VT.getSizeInBits() % Size) == 0 && \"Illegal split of shuffle value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7389, __extension__ __PRETTY_FUNCTION__))
7389 "Illegal split of shuffle value type")(static_cast <bool> ((VT.getSizeInBits() % Size) == 0 &&
"Illegal split of shuffle value type") ? void (0) : __assert_fail
("(VT.getSizeInBits() % Size) == 0 && \"Illegal split of shuffle value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7389, __extension__ __PRETTY_FUNCTION__))
;
7390 unsigned EltSizeInBits = VT.getSizeInBits() / Size;
7391
7392 // Extract known constant input data.
7393 APInt UndefSrcElts[2];
7394 SmallVector<APInt, 32> SrcEltBits[2];
7395 bool IsSrcConstant[2] = {
7396 getTargetConstantBitsFromNode(V1, EltSizeInBits, UndefSrcElts[0],
7397 SrcEltBits[0], true, false),
7398 getTargetConstantBitsFromNode(V2, EltSizeInBits, UndefSrcElts[1],
7399 SrcEltBits[1], true, false)};
7400
7401 for (int i = 0; i < Size; ++i) {
7402 int M = Mask[i];
7403
7404 // Already decoded as SM_SentinelZero / SM_SentinelUndef.
7405 if (M < 0) {
7406 assert(isUndefOrZero(M) && "Unknown shuffle sentinel value!")(static_cast <bool> (isUndefOrZero(M) && "Unknown shuffle sentinel value!"
) ? void (0) : __assert_fail ("isUndefOrZero(M) && \"Unknown shuffle sentinel value!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7406, __extension__ __PRETTY_FUNCTION__))
;
7407 if (SM_SentinelUndef == M)
7408 KnownUndef.setBit(i);
7409 if (SM_SentinelZero == M)
7410 KnownZero.setBit(i);
7411 continue;
7412 }
7413
7414 // Determine shuffle input and normalize the mask.
7415 unsigned SrcIdx = M / Size;
7416 SDValue V = M < Size ? V1 : V2;
7417 M %= Size;
7418
7419 // We are referencing an UNDEF input.
7420 if (V.isUndef()) {
7421 KnownUndef.setBit(i);
7422 continue;
7423 }
7424
7425 // SCALAR_TO_VECTOR - only the first element is defined, and the rest UNDEF.
7426 // TODO: We currently only set UNDEF for integer types - floats use the same
7427 // registers as vectors and many of the scalar folded loads rely on the
7428 // SCALAR_TO_VECTOR pattern.
7429 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7430 (Size % V.getValueType().getVectorNumElements()) == 0) {
7431 int Scale = Size / V.getValueType().getVectorNumElements();
7432 int Idx = M / Scale;
7433 if (Idx != 0 && !VT.isFloatingPoint())
7434 KnownUndef.setBit(i);
7435 else if (Idx == 0 && X86::isZeroNode(V.getOperand(0)))
7436 KnownZero.setBit(i);
7437 continue;
7438 }
7439
7440 // INSERT_SUBVECTOR - to widen vectors we often insert them into UNDEF
7441 // base vectors.
7442 if (V.getOpcode() == ISD::INSERT_SUBVECTOR) {
7443 SDValue Vec = V.getOperand(0);
7444 int NumVecElts = Vec.getValueType().getVectorNumElements();
7445 if (Vec.isUndef() && Size == NumVecElts) {
7446 int Idx = V.getConstantOperandVal(2);
7447 int NumSubElts = V.getOperand(1).getValueType().getVectorNumElements();
7448 if (M < Idx || (Idx + NumSubElts) <= M)
7449 KnownUndef.setBit(i);
7450 }
7451 continue;
7452 }
7453
7454 // Attempt to extract from the source's constant bits.
7455 if (IsSrcConstant[SrcIdx]) {
7456 if (UndefSrcElts[SrcIdx][M])
7457 KnownUndef.setBit(i);
7458 else if (SrcEltBits[SrcIdx][M] == 0)
7459 KnownZero.setBit(i);
7460 }
7461 }
7462
7463 assert(VT.getVectorNumElements() == (unsigned)Size &&(static_cast <bool> (VT.getVectorNumElements() == (unsigned
)Size && "Different mask size from vector size!") ? void
(0) : __assert_fail ("VT.getVectorNumElements() == (unsigned)Size && \"Different mask size from vector size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7464, __extension__ __PRETTY_FUNCTION__))
7464 "Different mask size from vector size!")(static_cast <bool> (VT.getVectorNumElements() == (unsigned
)Size && "Different mask size from vector size!") ? void
(0) : __assert_fail ("VT.getVectorNumElements() == (unsigned)Size && \"Different mask size from vector size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7464, __extension__ __PRETTY_FUNCTION__))
;
7465 return true;
7466}
7467
7468// Replace target shuffle mask elements with known undef/zero sentinels.
7469static void resolveTargetShuffleFromZeroables(SmallVectorImpl<int> &Mask,
7470 const APInt &KnownUndef,
7471 const APInt &KnownZero,
7472 bool ResolveKnownZeros= true) {
7473 unsigned NumElts = Mask.size();
7474 assert(KnownUndef.getBitWidth() == NumElts &&(static_cast <bool> (KnownUndef.getBitWidth() == NumElts
&& KnownZero.getBitWidth() == NumElts && "Shuffle mask size mismatch"
) ? void (0) : __assert_fail ("KnownUndef.getBitWidth() == NumElts && KnownZero.getBitWidth() == NumElts && \"Shuffle mask size mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7475, __extension__ __PRETTY_FUNCTION__))
7475 KnownZero.getBitWidth() == NumElts && "Shuffle mask size mismatch")(static_cast <bool> (KnownUndef.getBitWidth() == NumElts
&& KnownZero.getBitWidth() == NumElts && "Shuffle mask size mismatch"
) ? void (0) : __assert_fail ("KnownUndef.getBitWidth() == NumElts && KnownZero.getBitWidth() == NumElts && \"Shuffle mask size mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7475, __extension__ __PRETTY_FUNCTION__))
;
7476
7477 for (unsigned i = 0; i != NumElts; ++i) {
7478 if (KnownUndef[i])
7479 Mask[i] = SM_SentinelUndef;
7480 else if (ResolveKnownZeros && KnownZero[i])
7481 Mask[i] = SM_SentinelZero;
7482 }
7483}
7484
7485// Extract target shuffle mask sentinel elements to known undef/zero bitmasks.
7486static void resolveZeroablesFromTargetShuffle(const SmallVectorImpl<int> &Mask,
7487 APInt &KnownUndef,
7488 APInt &KnownZero) {
7489 unsigned NumElts = Mask.size();
7490 KnownUndef = KnownZero = APInt::getNullValue(NumElts);
7491
7492 for (unsigned i = 0; i != NumElts; ++i) {
7493 int M = Mask[i];
7494 if (SM_SentinelUndef == M)
7495 KnownUndef.setBit(i);
7496 if (SM_SentinelZero == M)
7497 KnownZero.setBit(i);
7498 }
7499}
7500
7501// Forward declaration (for getFauxShuffleMask recursive check).
7502// TODO: Use DemandedElts variant.
7503static bool getTargetShuffleInputs(SDValue Op, SmallVectorImpl<SDValue> &Inputs,
7504 SmallVectorImpl<int> &Mask,
7505 const SelectionDAG &DAG, unsigned Depth,
7506 bool ResolveKnownElts);
7507
7508// Attempt to decode ops that could be represented as a shuffle mask.
7509// The decoded shuffle mask may contain a different number of elements to the
7510// destination value type.
7511static bool getFauxShuffleMask(SDValue N, const APInt &DemandedElts,
7512 SmallVectorImpl<int> &Mask,
7513 SmallVectorImpl<SDValue> &Ops,
7514 const SelectionDAG &DAG, unsigned Depth,
7515 bool ResolveKnownElts) {
7516 Mask.clear();
7517 Ops.clear();
7518
7519 MVT VT = N.getSimpleValueType();
7520 unsigned NumElts = VT.getVectorNumElements();
7521 unsigned NumSizeInBits = VT.getSizeInBits();
7522 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
7523 if ((NumBitsPerElt % 8) != 0 || (NumSizeInBits % 8) != 0)
7524 return false;
7525 assert(NumElts == DemandedElts.getBitWidth() && "Unexpected vector size")(static_cast <bool> (NumElts == DemandedElts.getBitWidth
() && "Unexpected vector size") ? void (0) : __assert_fail
("NumElts == DemandedElts.getBitWidth() && \"Unexpected vector size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7525, __extension__ __PRETTY_FUNCTION__))
;
7526 unsigned NumSizeInBytes = NumSizeInBits / 8;
7527 unsigned NumBytesPerElt = NumBitsPerElt / 8;
7528
7529 unsigned Opcode = N.getOpcode();
7530 switch (Opcode) {
7531 case ISD::VECTOR_SHUFFLE: {
7532 // Don't treat ISD::VECTOR_SHUFFLE as a target shuffle so decode it here.
7533 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(N)->getMask();
7534 if (isUndefOrInRange(ShuffleMask, 0, 2 * NumElts)) {
7535 Mask.append(ShuffleMask.begin(), ShuffleMask.end());
7536 Ops.push_back(N.getOperand(0));
7537 Ops.push_back(N.getOperand(1));
7538 return true;
7539 }
7540 return false;
7541 }
7542 case ISD::AND:
7543 case X86ISD::ANDNP: {
7544 // Attempt to decode as a per-byte mask.
7545 APInt UndefElts;
7546 SmallVector<APInt, 32> EltBits;
7547 SDValue N0 = N.getOperand(0);
7548 SDValue N1 = N.getOperand(1);
7549 bool IsAndN = (X86ISD::ANDNP == Opcode);
7550 uint64_t ZeroMask = IsAndN ? 255 : 0;
7551 if (!getTargetConstantBitsFromNode(IsAndN ? N0 : N1, 8, UndefElts, EltBits))
7552 return false;
7553 for (int i = 0, e = (int)EltBits.size(); i != e; ++i) {
7554 if (UndefElts[i]) {
7555 Mask.push_back(SM_SentinelUndef);
7556 continue;
7557 }
7558 const APInt &ByteBits = EltBits[i];
7559 if (ByteBits != 0 && ByteBits != 255)
7560 return false;
7561 Mask.push_back(ByteBits == ZeroMask ? SM_SentinelZero : i);
7562 }
7563 Ops.push_back(IsAndN ? N1 : N0);
7564 return true;
7565 }
7566 case ISD::OR: {
7567 // Handle OR(SHUFFLE,SHUFFLE) case where one source is zero and the other
7568 // is a valid shuffle index.
7569 SDValue N0 = peekThroughBitcasts(N.getOperand(0));
7570 SDValue N1 = peekThroughBitcasts(N.getOperand(1));
7571 if (!N0.getValueType().isVector() || !N1.getValueType().isVector())
7572 return false;
7573 SmallVector<int, 64> SrcMask0, SrcMask1;
7574 SmallVector<SDValue, 2> SrcInputs0, SrcInputs1;
7575 if (!getTargetShuffleInputs(N0, SrcInputs0, SrcMask0, DAG, Depth + 1,
7576 true) ||
7577 !getTargetShuffleInputs(N1, SrcInputs1, SrcMask1, DAG, Depth + 1,
7578 true))
7579 return false;
7580
7581 size_t MaskSize = std::max(SrcMask0.size(), SrcMask1.size());
7582 SmallVector<int, 64> Mask0, Mask1;
7583 narrowShuffleMaskElts(MaskSize / SrcMask0.size(), SrcMask0, Mask0);
7584 narrowShuffleMaskElts(MaskSize / SrcMask1.size(), SrcMask1, Mask1);
7585 for (int i = 0; i != (int)MaskSize; ++i) {
7586 // NOTE: Don't handle SM_SentinelUndef, as we can end up in infinite
7587 // loops converting between OR and BLEND shuffles due to
7588 // canWidenShuffleElements merging away undef elements, meaning we
7589 // fail to recognise the OR as the undef element isn't known zero.
7590 if (Mask0[i] == SM_SentinelZero && Mask1[i] == SM_SentinelZero)
7591 Mask.push_back(SM_SentinelZero);
7592 else if (Mask1[i] == SM_SentinelZero)
7593 Mask.push_back(i);
7594 else if (Mask0[i] == SM_SentinelZero)
7595 Mask.push_back(i + MaskSize);
7596 else
7597 return false;
7598 }
7599 Ops.push_back(N0);
7600 Ops.push_back(N1);
7601 return true;
7602 }
7603 case ISD::INSERT_SUBVECTOR: {
7604 SDValue Src = N.getOperand(0);
7605 SDValue Sub = N.getOperand(1);
7606 EVT SubVT = Sub.getValueType();
7607 unsigned NumSubElts = SubVT.getVectorNumElements();
7608 if (!N->isOnlyUserOf(Sub.getNode()))
7609 return false;
7610 uint64_t InsertIdx = N.getConstantOperandVal(2);
7611 // Handle INSERT_SUBVECTOR(SRC0, EXTRACT_SUBVECTOR(SRC1)).
7612 if (Sub.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
7613 Sub.getOperand(0).getValueType() == VT) {
7614 uint64_t ExtractIdx = Sub.getConstantOperandVal(1);
7615 for (int i = 0; i != (int)NumElts; ++i)
7616 Mask.push_back(i);
7617 for (int i = 0; i != (int)NumSubElts; ++i)
7618 Mask[InsertIdx + i] = NumElts + ExtractIdx + i;
7619 Ops.push_back(Src);
7620 Ops.push_back(Sub.getOperand(0));
7621 return true;
7622 }
7623 // Handle INSERT_SUBVECTOR(SRC0, SHUFFLE(SRC1)).
7624 SmallVector<int, 64> SubMask;
7625 SmallVector<SDValue, 2> SubInputs;
7626 if (!getTargetShuffleInputs(peekThroughOneUseBitcasts(Sub), SubInputs,
7627 SubMask, DAG, Depth + 1, ResolveKnownElts))
7628 return false;
7629
7630 // Subvector shuffle inputs must not be larger than the subvector.
7631 if (llvm::any_of(SubInputs, [SubVT](SDValue SubInput) {
7632 return SubVT.getFixedSizeInBits() <
7633 SubInput.getValueSizeInBits().getFixedSize();
7634 }))
7635 return false;
7636
7637 if (SubMask.size() != NumSubElts) {
7638 assert(((SubMask.size() % NumSubElts) == 0 ||(static_cast <bool> (((SubMask.size() % NumSubElts) == 0
|| (NumSubElts % SubMask.size()) == 0) && "Illegal submask scale"
) ? void (0) : __assert_fail ("((SubMask.size() % NumSubElts) == 0 || (NumSubElts % SubMask.size()) == 0) && \"Illegal submask scale\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7639, __extension__ __PRETTY_FUNCTION__))
7639 (NumSubElts % SubMask.size()) == 0) && "Illegal submask scale")(static_cast <bool> (((SubMask.size() % NumSubElts) == 0
|| (NumSubElts % SubMask.size()) == 0) && "Illegal submask scale"
) ? void (0) : __assert_fail ("((SubMask.size() % NumSubElts) == 0 || (NumSubElts % SubMask.size()) == 0) && \"Illegal submask scale\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7639, __extension__ __PRETTY_FUNCTION__))
;
7640 if ((NumSubElts % SubMask.size()) == 0) {
7641 int Scale = NumSubElts / SubMask.size();
7642 SmallVector<int,64> ScaledSubMask;
7643 narrowShuffleMaskElts(Scale, SubMask, ScaledSubMask);
7644 SubMask = ScaledSubMask;
7645 } else {
7646 int Scale = SubMask.size() / NumSubElts;
7647 NumSubElts = SubMask.size();
7648 NumElts *= Scale;
7649 InsertIdx *= Scale;
7650 }
7651 }
7652 Ops.push_back(Src);
7653 Ops.append(SubInputs.begin(), SubInputs.end());
7654 if (ISD::isBuildVectorAllZeros(Src.getNode()))
7655 Mask.append(NumElts, SM_SentinelZero);
7656 else
7657 for (int i = 0; i != (int)NumElts; ++i)
7658 Mask.push_back(i);
7659 for (int i = 0; i != (int)NumSubElts; ++i) {
7660 int M = SubMask[i];
7661 if (0 <= M) {
7662 int InputIdx = M / NumSubElts;
7663 M = (NumElts * (1 + InputIdx)) + (M % NumSubElts);
7664 }
7665 Mask[i + InsertIdx] = M;
7666 }
7667 return true;
7668 }
7669 case X86ISD::PINSRB:
7670 case X86ISD::PINSRW:
7671 case ISD::SCALAR_TO_VECTOR:
7672 case ISD::INSERT_VECTOR_ELT: {
7673 // Match against a insert_vector_elt/scalar_to_vector of an extract from a
7674 // vector, for matching src/dst vector types.
7675 SDValue Scl = N.getOperand(Opcode == ISD::SCALAR_TO_VECTOR ? 0 : 1);
7676
7677 unsigned DstIdx = 0;
7678 if (Opcode != ISD::SCALAR_TO_VECTOR) {
7679 // Check we have an in-range constant insertion index.
7680 if (!isa<ConstantSDNode>(N.getOperand(2)) ||
7681 N.getConstantOperandAPInt(2).uge(NumElts))
7682 return false;
7683 DstIdx = N.getConstantOperandVal(2);
7684
7685 // Attempt to recognise an INSERT*(VEC, 0, DstIdx) shuffle pattern.
7686 if (X86::isZeroNode(Scl)) {
7687 Ops.push_back(N.getOperand(0));
7688 for (unsigned i = 0; i != NumElts; ++i)
7689 Mask.push_back(i == DstIdx ? SM_SentinelZero : (int)i);
7690 return true;
7691 }
7692 }
7693
7694 // Peek through trunc/aext/zext.
7695 // TODO: aext shouldn't require SM_SentinelZero padding.
7696 // TODO: handle shift of scalars.
7697 unsigned MinBitsPerElt = Scl.getScalarValueSizeInBits();
7698 while (Scl.getOpcode() == ISD::TRUNCATE ||
7699 Scl.getOpcode() == ISD::ANY_EXTEND ||
7700 Scl.getOpcode() == ISD::ZERO_EXTEND) {
7701 Scl = Scl.getOperand(0);
7702 MinBitsPerElt =
7703 std::min<unsigned>(MinBitsPerElt, Scl.getScalarValueSizeInBits());
7704 }
7705 if ((MinBitsPerElt % 8) != 0)
7706 return false;
7707
7708 // Attempt to find the source vector the scalar was extracted from.
7709 SDValue SrcExtract;
7710 if ((Scl.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
7711 Scl.getOpcode() == X86ISD::PEXTRW ||
7712 Scl.getOpcode() == X86ISD::PEXTRB) &&
7713 Scl.getOperand(0).getValueSizeInBits() == NumSizeInBits) {
7714 SrcExtract = Scl;
7715 }
7716 if (!SrcExtract || !isa<ConstantSDNode>(SrcExtract.getOperand(1)))
7717 return false;
7718
7719 SDValue SrcVec = SrcExtract.getOperand(0);
7720 EVT SrcVT = SrcVec.getValueType();
7721 if (!SrcVT.getScalarType().isByteSized())
7722 return false;
7723 unsigned SrcIdx = SrcExtract.getConstantOperandVal(1);
7724 unsigned SrcByte = SrcIdx * (SrcVT.getScalarSizeInBits() / 8);
7725 unsigned DstByte = DstIdx * NumBytesPerElt;
7726 MinBitsPerElt =
7727 std::min<unsigned>(MinBitsPerElt, SrcVT.getScalarSizeInBits());
7728
7729 // Create 'identity' byte level shuffle mask and then add inserted bytes.
7730 if (Opcode == ISD::SCALAR_TO_VECTOR) {
7731 Ops.push_back(SrcVec);
7732 Mask.append(NumSizeInBytes, SM_SentinelUndef);
7733 } else {
7734 Ops.push_back(SrcVec);
7735 Ops.push_back(N.getOperand(0));
7736 for (int i = 0; i != (int)NumSizeInBytes; ++i)
7737 Mask.push_back(NumSizeInBytes + i);
7738 }
7739
7740 unsigned MinBytesPerElts = MinBitsPerElt / 8;
7741 MinBytesPerElts = std::min(MinBytesPerElts, NumBytesPerElt);
7742 for (unsigned i = 0; i != MinBytesPerElts; ++i)
7743 Mask[DstByte + i] = SrcByte + i;
7744 for (unsigned i = MinBytesPerElts; i < NumBytesPerElt; ++i)
7745 Mask[DstByte + i] = SM_SentinelZero;
7746 return true;
7747 }
7748 case X86ISD::PACKSS:
7749 case X86ISD::PACKUS: {
7750 SDValue N0 = N.getOperand(0);
7751 SDValue N1 = N.getOperand(1);
7752 assert(N0.getValueType().getVectorNumElements() == (NumElts / 2) &&(static_cast <bool> (N0.getValueType().getVectorNumElements
() == (NumElts / 2) && N1.getValueType().getVectorNumElements
() == (NumElts / 2) && "Unexpected input value type")
? void (0) : __assert_fail ("N0.getValueType().getVectorNumElements() == (NumElts / 2) && N1.getValueType().getVectorNumElements() == (NumElts / 2) && \"Unexpected input value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7754, __extension__ __PRETTY_FUNCTION__))
7753 N1.getValueType().getVectorNumElements() == (NumElts / 2) &&(static_cast <bool> (N0.getValueType().getVectorNumElements
() == (NumElts / 2) && N1.getValueType().getVectorNumElements
() == (NumElts / 2) && "Unexpected input value type")
? void (0) : __assert_fail ("N0.getValueType().getVectorNumElements() == (NumElts / 2) && N1.getValueType().getVectorNumElements() == (NumElts / 2) && \"Unexpected input value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7754, __extension__ __PRETTY_FUNCTION__))
7754 "Unexpected input value type")(static_cast <bool> (N0.getValueType().getVectorNumElements
() == (NumElts / 2) && N1.getValueType().getVectorNumElements
() == (NumElts / 2) && "Unexpected input value type")
? void (0) : __assert_fail ("N0.getValueType().getVectorNumElements() == (NumElts / 2) && N1.getValueType().getVectorNumElements() == (NumElts / 2) && \"Unexpected input value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7754, __extension__ __PRETTY_FUNCTION__))
;
7755
7756 APInt EltsLHS, EltsRHS;
7757 getPackDemandedElts(VT, DemandedElts, EltsLHS, EltsRHS);
7758
7759 // If we know input saturation won't happen (or we don't care for particular
7760 // lanes), we can treat this as a truncation shuffle.
7761 bool Offset0 = false, Offset1 = false;
7762 if (Opcode == X86ISD::PACKSS) {
7763 if ((!(N0.isUndef() || EltsLHS.isNullValue()) &&
7764 DAG.ComputeNumSignBits(N0, EltsLHS, Depth + 1) <= NumBitsPerElt) ||
7765 (!(N1.isUndef() || EltsRHS.isNullValue()) &&
7766 DAG.ComputeNumSignBits(N1, EltsRHS, Depth + 1) <= NumBitsPerElt))
7767 return false;
7768 // We can't easily fold ASHR into a shuffle, but if it was feeding a
7769 // PACKSS then it was likely being used for sign-extension for a
7770 // truncation, so just peek through and adjust the mask accordingly.
7771 if (N0.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N0.getNode()) &&
7772 N0.getConstantOperandAPInt(1) == NumBitsPerElt) {
7773 Offset0 = true;
7774 N0 = N0.getOperand(0);
7775 }
7776 if (N1.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N1.getNode()) &&
7777 N1.getConstantOperandAPInt(1) == NumBitsPerElt) {
7778 Offset1 = true;
7779 N1 = N1.getOperand(0);
7780 }
7781 } else {
7782 APInt ZeroMask = APInt::getHighBitsSet(2 * NumBitsPerElt, NumBitsPerElt);
7783 if ((!(N0.isUndef() || EltsLHS.isNullValue()) &&
7784 !DAG.MaskedValueIsZero(N0, ZeroMask, EltsLHS, Depth + 1)) ||
7785 (!(N1.isUndef() || EltsRHS.isNullValue()) &&
7786 !DAG.MaskedValueIsZero(N1, ZeroMask, EltsRHS, Depth + 1)))
7787 return false;
7788 }
7789
7790 bool IsUnary = (N0 == N1);
7791
7792 Ops.push_back(N0);
7793 if (!IsUnary)
7794 Ops.push_back(N1);
7795
7796 createPackShuffleMask(VT, Mask, IsUnary);
7797
7798 if (Offset0 || Offset1) {
7799 for (int &M : Mask)
7800 if ((Offset0 && isInRange(M, 0, NumElts)) ||
7801 (Offset1 && isInRange(M, NumElts, 2 * NumElts)))
7802 ++M;
7803 }
7804 return true;
7805 }
7806 case X86ISD::VTRUNC: {
7807 SDValue Src = N.getOperand(0);
7808 EVT SrcVT = Src.getValueType();
7809 // Truncated source must be a simple vector.
7810 if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
7811 (SrcVT.getScalarSizeInBits() % 8) != 0)
7812 return false;
7813 unsigned NumSrcElts = SrcVT.getVectorNumElements();
7814 unsigned NumBitsPerSrcElt = SrcVT.getScalarSizeInBits();
7815 unsigned Scale = NumBitsPerSrcElt / NumBitsPerElt;
7816 assert((NumBitsPerSrcElt % NumBitsPerElt) == 0 && "Illegal truncation")(static_cast <bool> ((NumBitsPerSrcElt % NumBitsPerElt)
== 0 && "Illegal truncation") ? void (0) : __assert_fail
("(NumBitsPerSrcElt % NumBitsPerElt) == 0 && \"Illegal truncation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7816, __extension__ __PRETTY_FUNCTION__))
;
7817 for (unsigned i = 0; i != NumSrcElts; ++i)
7818 Mask.push_back(i * Scale);
7819 Mask.append(NumElts - NumSrcElts, SM_SentinelZero);
7820 Ops.push_back(Src);
7821 return true;
7822 }
7823 case X86ISD::VSHLI:
7824 case X86ISD::VSRLI: {
7825 uint64_t ShiftVal = N.getConstantOperandVal(1);
7826 // Out of range bit shifts are guaranteed to be zero.
7827 if (NumBitsPerElt <= ShiftVal) {
7828 Mask.append(NumElts, SM_SentinelZero);
7829 return true;
7830 }
7831
7832 // We can only decode 'whole byte' bit shifts as shuffles.
7833 if ((ShiftVal % 8) != 0)
7834 break;
7835
7836 uint64_t ByteShift = ShiftVal / 8;
7837 Ops.push_back(N.getOperand(0));
7838
7839 // Clear mask to all zeros and insert the shifted byte indices.
7840 Mask.append(NumSizeInBytes, SM_SentinelZero);
7841
7842 if (X86ISD::VSHLI == Opcode) {
7843 for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
7844 for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
7845 Mask[i + j] = i + j - ByteShift;
7846 } else {
7847 for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
7848 for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
7849 Mask[i + j - ByteShift] = i + j;
7850 }
7851 return true;
7852 }
7853 case X86ISD::VROTLI:
7854 case X86ISD::VROTRI: {
7855 // We can only decode 'whole byte' bit rotates as shuffles.
7856 uint64_t RotateVal = N.getConstantOperandAPInt(1).urem(NumBitsPerElt);
7857 if ((RotateVal % 8) != 0)
7858 return false;
7859 Ops.push_back(N.getOperand(0));
7860 int Offset = RotateVal / 8;
7861 Offset = (X86ISD::VROTLI == Opcode ? NumBytesPerElt - Offset : Offset);
7862 for (int i = 0; i != (int)NumElts; ++i) {
7863 int BaseIdx = i * NumBytesPerElt;
7864 for (int j = 0; j != (int)NumBytesPerElt; ++j) {
7865 Mask.push_back(BaseIdx + ((Offset + j) % NumBytesPerElt));
7866 }
7867 }
7868 return true;
7869 }
7870 case X86ISD::VBROADCAST: {
7871 SDValue Src = N.getOperand(0);
7872 if (!Src.getSimpleValueType().isVector()) {
7873 if (Src.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7874 !isNullConstant(Src.getOperand(1)) ||
7875 Src.getOperand(0).getValueType().getScalarType() !=
7876 VT.getScalarType())
7877 return false;
7878 Src = Src.getOperand(0);
7879 }
7880 Ops.push_back(Src);
7881 Mask.append(NumElts, 0);
7882 return true;
7883 }
7884 case ISD::ZERO_EXTEND:
7885 case ISD::ANY_EXTEND:
7886 case ISD::ZERO_EXTEND_VECTOR_INREG:
7887 case ISD::ANY_EXTEND_VECTOR_INREG: {
7888 SDValue Src = N.getOperand(0);
7889 EVT SrcVT = Src.getValueType();
7890
7891 // Extended source must be a simple vector.
7892 if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
7893 (SrcVT.getScalarSizeInBits() % 8) != 0)
7894 return false;
7895
7896 bool IsAnyExtend =
7897 (ISD::ANY_EXTEND == Opcode || ISD::ANY_EXTEND_VECTOR_INREG == Opcode);
7898 DecodeZeroExtendMask(SrcVT.getScalarSizeInBits(), NumBitsPerElt, NumElts,
7899 IsAnyExtend, Mask);
7900 Ops.push_back(Src);
7901 return true;
7902 }
7903 }
7904
7905 return false;
7906}
7907
7908/// Removes unused/repeated shuffle source inputs and adjusts the shuffle mask.
7909static void resolveTargetShuffleInputsAndMask(SmallVectorImpl<SDValue> &Inputs,
7910 SmallVectorImpl<int> &Mask) {
7911 int MaskWidth = Mask.size();
7912 SmallVector<SDValue, 16> UsedInputs;
7913 for (int i = 0, e = Inputs.size(); i < e; ++i) {
7914 int lo = UsedInputs.size() * MaskWidth;
7915 int hi = lo + MaskWidth;
7916
7917 // Strip UNDEF input usage.
7918 if (Inputs[i].isUndef())
7919 for (int &M : Mask)
7920 if ((lo <= M) && (M < hi))
7921 M = SM_SentinelUndef;
7922
7923 // Check for unused inputs.
7924 if (none_of(Mask, [lo, hi](int i) { return (lo <= i) && (i < hi); })) {
7925 for (int &M : Mask)
7926 if (lo <= M)
7927 M -= MaskWidth;
7928 continue;
7929 }
7930
7931 // Check for repeated inputs.
7932 bool IsRepeat = false;
7933 for (int j = 0, ue = UsedInputs.size(); j != ue; ++j) {
7934 if (UsedInputs[j] != Inputs[i])
7935 continue;
7936 for (int &M : Mask)
7937 if (lo <= M)
7938 M = (M < hi) ? ((M - lo) + (j * MaskWidth)) : (M - MaskWidth);
7939 IsRepeat = true;
7940 break;
7941 }
7942 if (IsRepeat)
7943 continue;
7944
7945 UsedInputs.push_back(Inputs[i]);
7946 }
7947 Inputs = UsedInputs;
7948}
7949
7950/// Calls getTargetShuffleAndZeroables to resolve a target shuffle mask's inputs
7951/// and then sets the SM_SentinelUndef and SM_SentinelZero values.
7952/// Returns true if the target shuffle mask was decoded.
7953static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
7954 SmallVectorImpl<SDValue> &Inputs,
7955 SmallVectorImpl<int> &Mask,
7956 APInt &KnownUndef, APInt &KnownZero,
7957 const SelectionDAG &DAG, unsigned Depth,
7958 bool ResolveKnownElts) {
7959 EVT VT = Op.getValueType();
7960 if (!VT.isSimple() || !VT.isVector())
7961 return false;
7962
7963 if (getTargetShuffleAndZeroables(Op, Mask, Inputs, KnownUndef, KnownZero)) {
7964 if (ResolveKnownElts)
7965 resolveTargetShuffleFromZeroables(Mask, KnownUndef, KnownZero);
7966 return true;
7967 }
7968 if (getFauxShuffleMask(Op, DemandedElts, Mask, Inputs, DAG, Depth,
7969 ResolveKnownElts)) {
7970 resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
7971 return true;
7972 }
7973 return false;
7974}
7975
7976static bool getTargetShuffleInputs(SDValue Op, SmallVectorImpl<SDValue> &Inputs,
7977 SmallVectorImpl<int> &Mask,
7978 const SelectionDAG &DAG, unsigned Depth = 0,
7979 bool ResolveKnownElts = true) {
7980 EVT VT = Op.getValueType();
7981 if (!VT.isSimple() || !VT.isVector())
7982 return false;
7983
7984 APInt KnownUndef, KnownZero;
7985 unsigned NumElts = Op.getValueType().getVectorNumElements();
7986 APInt DemandedElts = APInt::getAllOnesValue(NumElts);
7987 return getTargetShuffleInputs(Op, DemandedElts, Inputs, Mask, KnownUndef,
7988 KnownZero, DAG, Depth, ResolveKnownElts);
7989}
7990
7991// Attempt to create a scalar/subvector broadcast from the base MemSDNode.
7992static SDValue getBROADCAST_LOAD(unsigned Opcode, const SDLoc &DL, EVT VT,
7993 EVT MemVT, MemSDNode *Mem, unsigned Offset,
7994 SelectionDAG &DAG) {
7995 assert((Opcode == X86ISD::VBROADCAST_LOAD ||(static_cast <bool> ((Opcode == X86ISD::VBROADCAST_LOAD
|| Opcode == X86ISD::SUBV_BROADCAST_LOAD) && "Unknown broadcast load type"
) ? void (0) : __assert_fail ("(Opcode == X86ISD::VBROADCAST_LOAD || Opcode == X86ISD::SUBV_BROADCAST_LOAD) && \"Unknown broadcast load type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7997, __extension__ __PRETTY_FUNCTION__))
7996 Opcode == X86ISD::SUBV_BROADCAST_LOAD) &&(static_cast <bool> ((Opcode == X86ISD::VBROADCAST_LOAD
|| Opcode == X86ISD::SUBV_BROADCAST_LOAD) && "Unknown broadcast load type"
) ? void (0) : __assert_fail ("(Opcode == X86ISD::VBROADCAST_LOAD || Opcode == X86ISD::SUBV_BROADCAST_LOAD) && \"Unknown broadcast load type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7997, __extension__ __PRETTY_FUNCTION__))
7997 "Unknown broadcast load type")(static_cast <bool> ((Opcode == X86ISD::VBROADCAST_LOAD
|| Opcode == X86ISD::SUBV_BROADCAST_LOAD) && "Unknown broadcast load type"
) ? void (0) : __assert_fail ("(Opcode == X86ISD::VBROADCAST_LOAD || Opcode == X86ISD::SUBV_BROADCAST_LOAD) && \"Unknown broadcast load type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 7997, __extension__ __PRETTY_FUNCTION__))
;
7998
7999 // Ensure this is a simple (non-atomic, non-voltile), temporal read memop.
8000 if (!Mem || !Mem->readMem() || !Mem->isSimple() || Mem->isNonTemporal())
8001 return SDValue();
8002
8003 SDValue Ptr =
8004 DAG.getMemBasePlusOffset(Mem->getBasePtr(), TypeSize::Fixed(Offset), DL);
8005 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8006 SDValue Ops[] = {Mem->getChain(), Ptr};
8007 SDValue BcstLd = DAG.getMemIntrinsicNode(
8008 Opcode, DL, Tys, Ops, MemVT,
8009 DAG.getMachineFunction().getMachineMemOperand(
8010 Mem->getMemOperand(), Offset, MemVT.getStoreSize()));
8011 DAG.makeEquivalentMemoryOrdering(SDValue(Mem, 1), BcstLd.getValue(1));
8012 return BcstLd;
8013}
8014
8015/// Returns the scalar element that will make up the i'th
8016/// element of the result of the vector shuffle.
8017static SDValue getShuffleScalarElt(SDValue Op, unsigned Index,
8018 SelectionDAG &DAG, unsigned Depth) {
8019 if (Depth >= SelectionDAG::MaxRecursionDepth)
8020 return SDValue(); // Limit search depth.
8021
8022 EVT VT = Op.getValueType();
8023 unsigned Opcode = Op.getOpcode();
8024 unsigned NumElems = VT.getVectorNumElements();
8025
8026 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
8027 if (auto *SV = dyn_cast<ShuffleVectorSDNode>(Op)) {
8028 int Elt = SV->getMaskElt(Index);
8029
8030 if (Elt < 0)
8031 return DAG.getUNDEF(VT.getVectorElementType());
8032
8033 SDValue Src = (Elt < (int)NumElems) ? SV->getOperand(0) : SV->getOperand(1);
8034 return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
8035 }
8036
8037 // Recurse into target specific vector shuffles to find scalars.
8038 if (isTargetShuffle(Opcode)) {
8039 MVT ShufVT = VT.getSimpleVT();
8040 MVT ShufSVT = ShufVT.getVectorElementType();
8041 int NumElems = (int)ShufVT.getVectorNumElements();
8042 SmallVector<int, 16> ShuffleMask;
8043 SmallVector<SDValue, 16> ShuffleOps;
8044 if (!getTargetShuffleMask(Op.getNode(), ShufVT, true, ShuffleOps,
8045 ShuffleMask))
8046 return SDValue();
8047
8048 int Elt = ShuffleMask[Index];
8049 if (Elt == SM_SentinelZero)
8050 return ShufSVT.isInteger() ? DAG.getConstant(0, SDLoc(Op), ShufSVT)
8051 : DAG.getConstantFP(+0.0, SDLoc(Op), ShufSVT);
8052 if (Elt == SM_SentinelUndef)
8053 return DAG.getUNDEF(ShufSVT);
8054
8055 assert(0 <= Elt && Elt < (2 * NumElems) && "Shuffle index out of range")(static_cast <bool> (0 <= Elt && Elt < (2
* NumElems) && "Shuffle index out of range") ? void (
0) : __assert_fail ("0 <= Elt && Elt < (2 * NumElems) && \"Shuffle index out of range\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8055, __extension__ __PRETTY_FUNCTION__))
;
8056 SDValue Src = (Elt < NumElems) ? ShuffleOps[0] : ShuffleOps[1];
8057 return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
8058 }
8059
8060 // Recurse into insert_subvector base/sub vector to find scalars.
8061 if (Opcode == ISD::INSERT_SUBVECTOR) {
8062 SDValue Vec = Op.getOperand(0);
8063 SDValue Sub = Op.getOperand(1);
8064 uint64_t SubIdx = Op.getConstantOperandVal(2);
8065 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
8066
8067 if (SubIdx <= Index && Index < (SubIdx + NumSubElts))
8068 return getShuffleScalarElt(Sub, Index - SubIdx, DAG, Depth + 1);
8069 return getShuffleScalarElt(Vec, Index, DAG, Depth + 1);
8070 }
8071
8072 // Recurse into concat_vectors sub vector to find scalars.
8073 if (Opcode == ISD::CONCAT_VECTORS) {
8074 EVT SubVT = Op.getOperand(0).getValueType();
8075 unsigned NumSubElts = SubVT.getVectorNumElements();
8076 uint64_t SubIdx = Index / NumSubElts;
8077 uint64_t SubElt = Index % NumSubElts;
8078 return getShuffleScalarElt(Op.getOperand(SubIdx), SubElt, DAG, Depth + 1);
8079 }
8080
8081 // Recurse into extract_subvector src vector to find scalars.
8082 if (Opcode == ISD::EXTRACT_SUBVECTOR) {
8083 SDValue Src = Op.getOperand(0);
8084 uint64_t SrcIdx = Op.getConstantOperandVal(1);
8085 return getShuffleScalarElt(Src, Index + SrcIdx, DAG, Depth + 1);
8086 }
8087
8088 // We only peek through bitcasts of the same vector width.
8089 if (Opcode == ISD::BITCAST) {
8090 SDValue Src = Op.getOperand(0);
8091 EVT SrcVT = Src.getValueType();
8092 if (SrcVT.isVector() && SrcVT.getVectorNumElements() == NumElems)
8093 return getShuffleScalarElt(Src, Index, DAG, Depth + 1);
8094 return SDValue();
8095 }
8096
8097 // Actual nodes that may contain scalar elements
8098
8099 // For insert_vector_elt - either return the index matching scalar or recurse
8100 // into the base vector.
8101 if (Opcode == ISD::INSERT_VECTOR_ELT &&
8102 isa<ConstantSDNode>(Op.getOperand(2))) {
8103 if (Op.getConstantOperandAPInt(2) == Index)
8104 return Op.getOperand(1);
8105 return getShuffleScalarElt(Op.getOperand(0), Index, DAG, Depth + 1);
8106 }
8107
8108 if (Opcode == ISD::SCALAR_TO_VECTOR)
8109 return (Index == 0) ? Op.getOperand(0)
8110 : DAG.getUNDEF(VT.getVectorElementType());
8111
8112 if (Opcode == ISD::BUILD_VECTOR)
8113 return Op.getOperand(Index);
8114
8115 return SDValue();
8116}
8117
8118// Use PINSRB/PINSRW/PINSRD to create a build vector.
8119static SDValue LowerBuildVectorAsInsert(SDValue Op, const APInt &NonZeroMask,
8120 unsigned NumNonZero, unsigned NumZero,
8121 SelectionDAG &DAG,
8122 const X86Subtarget &Subtarget) {
8123 MVT VT = Op.getSimpleValueType();
8124 unsigned NumElts = VT.getVectorNumElements();
8125 assert(((VT == MVT::v8i16 && Subtarget.hasSSE2()) ||(static_cast <bool> (((VT == MVT::v8i16 && Subtarget
.hasSSE2()) || ((VT == MVT::v16i8 || VT == MVT::v4i32) &&
Subtarget.hasSSE41())) && "Illegal vector insertion"
) ? void (0) : __assert_fail ("((VT == MVT::v8i16 && Subtarget.hasSSE2()) || ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) && \"Illegal vector insertion\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8127, __extension__ __PRETTY_FUNCTION__))
8126 ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) &&(static_cast <bool> (((VT == MVT::v8i16 && Subtarget
.hasSSE2()) || ((VT == MVT::v16i8 || VT == MVT::v4i32) &&
Subtarget.hasSSE41())) && "Illegal vector insertion"
) ? void (0) : __assert_fail ("((VT == MVT::v8i16 && Subtarget.hasSSE2()) || ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) && \"Illegal vector insertion\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8127, __extension__ __PRETTY_FUNCTION__))
8127 "Illegal vector insertion")(static_cast <bool> (((VT == MVT::v8i16 && Subtarget
.hasSSE2()) || ((VT == MVT::v16i8 || VT == MVT::v4i32) &&
Subtarget.hasSSE41())) && "Illegal vector insertion"
) ? void (0) : __assert_fail ("((VT == MVT::v8i16 && Subtarget.hasSSE2()) || ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) && \"Illegal vector insertion\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8127, __extension__ __PRETTY_FUNCTION__))
;
8128
8129 SDLoc dl(Op);
8130 SDValue V;
8131 bool First = true;
8132
8133 for (unsigned i = 0; i < NumElts; ++i) {
8134 bool IsNonZero = NonZeroMask[i];
8135 if (!IsNonZero)
8136 continue;
8137
8138 // If the build vector contains zeros or our first insertion is not the
8139 // first index then insert into zero vector to break any register
8140 // dependency else use SCALAR_TO_VECTOR.
8141 if (First) {
8142 First = false;
8143 if (NumZero || 0 != i)
8144 V = getZeroVector(VT, Subtarget, DAG, dl);
8145 else {
8146 assert(0 == i && "Expected insertion into zero-index")(static_cast <bool> (0 == i && "Expected insertion into zero-index"
) ? void (0) : __assert_fail ("0 == i && \"Expected insertion into zero-index\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8146, __extension__ __PRETTY_FUNCTION__))
;
8147 V = DAG.getAnyExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
8148 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, V);
8149 V = DAG.getBitcast(VT, V);
8150 continue;
8151 }
8152 }
8153 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V, Op.getOperand(i),
8154 DAG.getIntPtrConstant(i, dl));
8155 }
8156
8157 return V;
8158}
8159
8160/// Custom lower build_vector of v16i8.
8161static SDValue LowerBuildVectorv16i8(SDValue Op, const APInt &NonZeroMask,
8162 unsigned NumNonZero, unsigned NumZero,
8163 SelectionDAG &DAG,
8164 const X86Subtarget &Subtarget) {
8165 if (NumNonZero > 8 && !Subtarget.hasSSE41())
8166 return SDValue();
8167
8168 // SSE4.1 - use PINSRB to insert each byte directly.
8169 if (Subtarget.hasSSE41())
8170 return LowerBuildVectorAsInsert(Op, NonZeroMask, NumNonZero, NumZero, DAG,
8171 Subtarget);
8172
8173 SDLoc dl(Op);
8174 SDValue V;
8175
8176 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
8177 for (unsigned i = 0; i < 16; i += 2) {
8178 bool ThisIsNonZero = NonZeroMask[i];
8179 bool NextIsNonZero = NonZeroMask[i + 1];
8180 if (!ThisIsNonZero && !NextIsNonZero)
8181 continue;
8182
8183 // FIXME: Investigate combining the first 4 bytes as a i32 instead.
8184 SDValue Elt;
8185 if (ThisIsNonZero) {
8186 if (NumZero || NextIsNonZero)
8187 Elt = DAG.getZExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
8188 else
8189 Elt = DAG.getAnyExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
8190 }
8191
8192 if (NextIsNonZero) {
8193 SDValue NextElt = Op.getOperand(i + 1);
8194 if (i == 0 && NumZero)
8195 NextElt = DAG.getZExtOrTrunc(NextElt, dl, MVT::i32);
8196 else
8197 NextElt = DAG.getAnyExtOrTrunc(NextElt, dl, MVT::i32);
8198 NextElt = DAG.getNode(ISD::SHL, dl, MVT::i32, NextElt,
8199 DAG.getConstant(8, dl, MVT::i8));
8200 if (ThisIsNonZero)
8201 Elt = DAG.getNode(ISD::OR, dl, MVT::i32, NextElt, Elt);
8202 else
8203 Elt = NextElt;
8204 }
8205
8206 // If our first insertion is not the first index or zeros are needed, then
8207 // insert into zero vector. Otherwise, use SCALAR_TO_VECTOR (leaves high
8208 // elements undefined).
8209 if (!V) {
8210 if (i != 0 || NumZero)
8211 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
8212 else {
8213 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Elt);
8214 V = DAG.getBitcast(MVT::v8i16, V);
8215 continue;
8216 }
8217 }
8218 Elt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Elt);
8219 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, Elt,
8220 DAG.getIntPtrConstant(i / 2, dl));
8221 }
8222
8223 return DAG.getBitcast(MVT::v16i8, V);
8224}
8225
8226/// Custom lower build_vector of v8i16.
8227static SDValue LowerBuildVectorv8i16(SDValue Op, const APInt &NonZeroMask,
8228 unsigned NumNonZero, unsigned NumZero,
8229 SelectionDAG &DAG,
8230 const X86Subtarget &Subtarget) {
8231 if (NumNonZero > 4 && !Subtarget.hasSSE41())
8232 return SDValue();
8233
8234 // Use PINSRW to insert each byte directly.
8235 return LowerBuildVectorAsInsert(Op, NonZeroMask, NumNonZero, NumZero, DAG,
8236 Subtarget);
8237}
8238
8239/// Custom lower build_vector of v4i32 or v4f32.
8240static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
8241 const X86Subtarget &Subtarget) {
8242 // If this is a splat of a pair of elements, use MOVDDUP (unless the target
8243 // has XOP; in that case defer lowering to potentially use VPERMIL2PS).
8244 // Because we're creating a less complicated build vector here, we may enable
8245 // further folding of the MOVDDUP via shuffle transforms.
8246 if (Subtarget.hasSSE3() && !Subtarget.hasXOP() &&
8247 Op.getOperand(0) == Op.getOperand(2) &&
8248 Op.getOperand(1) == Op.getOperand(3) &&
8249 Op.getOperand(0) != Op.getOperand(1)) {
8250 SDLoc DL(Op);
8251 MVT VT = Op.getSimpleValueType();
8252 MVT EltVT = VT.getVectorElementType();
8253 // Create a new build vector with the first 2 elements followed by undef
8254 // padding, bitcast to v2f64, duplicate, and bitcast back.
8255 SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
8256 DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
8257 SDValue NewBV = DAG.getBitcast(MVT::v2f64, DAG.getBuildVector(VT, DL, Ops));
8258 SDValue Dup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, NewBV);
8259 return DAG.getBitcast(VT, Dup);
8260 }
8261
8262 // Find all zeroable elements.
8263 std::bitset<4> Zeroable, Undefs;
8264 for (int i = 0; i < 4; ++i) {
8265 SDValue Elt = Op.getOperand(i);
8266 Undefs[i] = Elt.isUndef();
8267 Zeroable[i] = (Elt.isUndef() || X86::isZeroNode(Elt));
8268 }
8269 assert(Zeroable.size() - Zeroable.count() > 1 &&(static_cast <bool> (Zeroable.size() - Zeroable.count()
> 1 && "We expect at least two non-zero elements!"
) ? void (0) : __assert_fail ("Zeroable.size() - Zeroable.count() > 1 && \"We expect at least two non-zero elements!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8270, __extension__ __PRETTY_FUNCTION__))
8270 "We expect at least two non-zero elements!")(static_cast <bool> (Zeroable.size() - Zeroable.count()
> 1 && "We expect at least two non-zero elements!"
) ? void (0) : __assert_fail ("Zeroable.size() - Zeroable.count() > 1 && \"We expect at least two non-zero elements!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8270, __extension__ __PRETTY_FUNCTION__))
;
8271
8272 // We only know how to deal with build_vector nodes where elements are either
8273 // zeroable or extract_vector_elt with constant index.
8274 SDValue FirstNonZero;
8275 unsigned FirstNonZeroIdx;
8276 for (unsigned i = 0; i < 4; ++i) {
8277 if (Zeroable[i])
8278 continue;
8279 SDValue Elt = Op.getOperand(i);
8280 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8281 !isa<ConstantSDNode>(Elt.getOperand(1)))
8282 return SDValue();
8283 // Make sure that this node is extracting from a 128-bit vector.
8284 MVT VT = Elt.getOperand(0).getSimpleValueType();
8285 if (!VT.is128BitVector())
8286 return SDValue();
8287 if (!FirstNonZero.getNode()) {
8288 FirstNonZero = Elt;
8289 FirstNonZeroIdx = i;
8290 }
8291 }
8292
8293 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!")(static_cast <bool> (FirstNonZero.getNode() && "Unexpected build vector of all zeros!"
) ? void (0) : __assert_fail ("FirstNonZero.getNode() && \"Unexpected build vector of all zeros!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8293, __extension__ __PRETTY_FUNCTION__))
;
8294 SDValue V1 = FirstNonZero.getOperand(0);
8295 MVT VT = V1.getSimpleValueType();
8296
8297 // See if this build_vector can be lowered as a blend with zero.
8298 SDValue Elt;
8299 unsigned EltMaskIdx, EltIdx;
8300 int Mask[4];
8301 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
8302 if (Zeroable[EltIdx]) {
8303 // The zero vector will be on the right hand side.
8304 Mask[EltIdx] = EltIdx+4;
8305 continue;
8306 }
8307
8308 Elt = Op->getOperand(EltIdx);
8309 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
8310 EltMaskIdx = Elt.getConstantOperandVal(1);
8311 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
8312 break;
8313 Mask[EltIdx] = EltIdx;
8314 }
8315
8316 if (EltIdx == 4) {
8317 // Let the shuffle legalizer deal with blend operations.
8318 SDValue VZeroOrUndef = (Zeroable == Undefs)
8319 ? DAG.getUNDEF(VT)
8320 : getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
8321 if (V1.getSimpleValueType() != VT)
8322 V1 = DAG.getBitcast(VT, V1);
8323 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZeroOrUndef, Mask);
8324 }
8325
8326 // See if we can lower this build_vector to a INSERTPS.
8327 if (!Subtarget.hasSSE41())
8328 return SDValue();
8329
8330 SDValue V2 = Elt.getOperand(0);
8331 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
8332 V1 = SDValue();
8333
8334 bool CanFold = true;
8335 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
8336 if (Zeroable[i])
8337 continue;
8338
8339 SDValue Current = Op->getOperand(i);
8340 SDValue SrcVector = Current->getOperand(0);
8341 if (!V1.getNode())
8342 V1 = SrcVector;
8343 CanFold = (SrcVector == V1) && (Current.getConstantOperandAPInt(1) == i);
8344 }
8345
8346 if (!CanFold)
8347 return SDValue();
8348
8349 assert(V1.getNode() && "Expected at least two non-zero elements!")(static_cast <bool> (V1.getNode() && "Expected at least two non-zero elements!"
) ? void (0) : __assert_fail ("V1.getNode() && \"Expected at least two non-zero elements!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8349, __extension__ __PRETTY_FUNCTION__))
;
8350 if (V1.getSimpleValueType() != MVT::v4f32)
8351 V1 = DAG.getBitcast(MVT::v4f32, V1);
8352 if (V2.getSimpleValueType() != MVT::v4f32)
8353 V2 = DAG.getBitcast(MVT::v4f32, V2);
8354
8355 // Ok, we can emit an INSERTPS instruction.
8356 unsigned ZMask = Zeroable.to_ulong();
8357
8358 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
8359 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!")(static_cast <bool> ((InsertPSMask & ~0xFFu) == 0 &&
"Invalid mask!") ? void (0) : __assert_fail ("(InsertPSMask & ~0xFFu) == 0 && \"Invalid mask!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8359, __extension__ __PRETTY_FUNCTION__))
;
8360 SDLoc DL(Op);
8361 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8362 DAG.getIntPtrConstant(InsertPSMask, DL, true));
8363 return DAG.getBitcast(VT, Result);
8364}
8365
8366/// Return a vector logical shift node.
8367static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, unsigned NumBits,
8368 SelectionDAG &DAG, const TargetLowering &TLI,
8369 const SDLoc &dl) {
8370 assert(VT.is128BitVector() && "Unknown type for VShift")(static_cast <bool> (VT.is128BitVector() && "Unknown type for VShift"
) ? void (0) : __assert_fail ("VT.is128BitVector() && \"Unknown type for VShift\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8370, __extension__ __PRETTY_FUNCTION__))
;
8371 MVT ShVT = MVT::v16i8;
8372 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
8373 SrcOp = DAG.getBitcast(ShVT, SrcOp);
8374 assert(NumBits % 8 == 0 && "Only support byte sized shifts")(static_cast <bool> (NumBits % 8 == 0 && "Only support byte sized shifts"
) ? void (0) : __assert_fail ("NumBits % 8 == 0 && \"Only support byte sized shifts\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8374, __extension__ __PRETTY_FUNCTION__))
;
8375 SDValue ShiftVal = DAG.getTargetConstant(NumBits / 8, dl, MVT::i8);
8376 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
8377}
8378
8379static SDValue LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, const SDLoc &dl,
8380 SelectionDAG &DAG) {
8381
8382 // Check if the scalar load can be widened into a vector load. And if
8383 // the address is "base + cst" see if the cst can be "absorbed" into
8384 // the shuffle mask.
8385 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
26
Assuming 'LD' is non-null
27
Taking true branch
8386 SDValue Ptr = LD->getBasePtr();
28
Value assigned to 'Ptr.Node'
8387 if (!ISD::isNormalLoad(LD) || !LD->isSimple())
29
Taking false branch
8388 return SDValue();
8389 EVT PVT = LD->getValueType(0);
8390 if (PVT != MVT::i32 && PVT != MVT::f32)
30
Taking false branch
8391 return SDValue();
8392
8393 int FI = -1;
8394 int64_t Offset = 0;
8395 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
31
Calling 'dyn_cast<llvm::FrameIndexSDNode, llvm::SDValue>'
46
Returning from 'dyn_cast<llvm::FrameIndexSDNode, llvm::SDValue>'
47
Assuming 'FINode' is null
48
Taking false branch
8396 FI = FINode->getIndex();
8397 Offset = 0;
8398 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
49
Assuming the condition is true
8399 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
50
Calling 'SDValue::getOperand'
8400 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
8401 Offset = Ptr.getConstantOperandVal(1);
8402 Ptr = Ptr.getOperand(0);
8403 } else {
8404 return SDValue();
8405 }
8406
8407 // FIXME: 256-bit vector instructions don't require a strict alignment,
8408 // improve this code to support it better.
8409 Align RequiredAlign(VT.getSizeInBits() / 8);
8410 SDValue Chain = LD->getChain();
8411 // Make sure the stack object alignment is at least 16 or 32.
8412 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8413 MaybeAlign InferredAlign = DAG.InferPtrAlign(Ptr);
8414 if (!InferredAlign || *InferredAlign < RequiredAlign) {
8415 if (MFI.isFixedObjectIndex(FI)) {
8416 // Can't change the alignment. FIXME: It's possible to compute
8417 // the exact stack offset and reference FI + adjust offset instead.
8418 // If someone *really* cares about this. That's the way to implement it.
8419 return SDValue();
8420 } else {
8421 MFI.setObjectAlignment(FI, RequiredAlign);
8422 }
8423 }
8424
8425 // (Offset % 16 or 32) must be multiple of 4. Then address is then
8426 // Ptr + (Offset & ~15).
8427 if (Offset < 0)
8428 return SDValue();
8429 if ((Offset % RequiredAlign.value()) & 3)
8430 return SDValue();
8431 int64_t StartOffset = Offset & ~int64_t(RequiredAlign.value() - 1);
8432 if (StartOffset) {
8433 SDLoc DL(Ptr);
8434 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
8435 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
8436 }
8437
8438 int EltNo = (Offset - StartOffset) >> 2;
8439 unsigned NumElems = VT.getVectorNumElements();
8440
8441 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
8442 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
8443 LD->getPointerInfo().getWithOffset(StartOffset));
8444
8445 SmallVector<int, 8> Mask(NumElems, EltNo);
8446
8447 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), Mask);
8448 }
8449
8450 return SDValue();
8451}
8452
8453// Recurse to find a LoadSDNode source and the accumulated ByteOffest.
8454static bool findEltLoadSrc(SDValue Elt, LoadSDNode *&Ld, int64_t &ByteOffset) {
8455 if (ISD::isNON_EXTLoad(Elt.getNode())) {
8456 auto *BaseLd = cast<LoadSDNode>(Elt);
8457 if (!BaseLd->isSimple())
8458 return false;
8459 Ld = BaseLd;
8460 ByteOffset = 0;
8461 return true;
8462 }
8463
8464 switch (Elt.getOpcode()) {
8465 case ISD::BITCAST:
8466 case ISD::TRUNCATE:
8467 case ISD::SCALAR_TO_VECTOR:
8468 return findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset);
8469 case ISD::SRL:
8470 if (auto *IdxC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
8471 uint64_t Idx = IdxC->getZExtValue();
8472 if ((Idx % 8) == 0 && findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset)) {
8473 ByteOffset += Idx / 8;
8474 return true;
8475 }
8476 }
8477 break;
8478 case ISD::EXTRACT_VECTOR_ELT:
8479 if (auto *IdxC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
8480 SDValue Src = Elt.getOperand(0);
8481 unsigned SrcSizeInBits = Src.getScalarValueSizeInBits();
8482 unsigned DstSizeInBits = Elt.getScalarValueSizeInBits();
8483 if (DstSizeInBits == SrcSizeInBits && (SrcSizeInBits % 8) == 0 &&
8484 findEltLoadSrc(Src, Ld, ByteOffset)) {
8485 uint64_t Idx = IdxC->getZExtValue();
8486 ByteOffset += Idx * (SrcSizeInBits / 8);
8487 return true;
8488 }
8489 }
8490 break;
8491 }
8492
8493 return false;
8494}
8495
8496/// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
8497/// elements can be replaced by a single large load which has the same value as
8498/// a build_vector or insert_subvector whose loaded operands are 'Elts'.
8499///
8500/// Example: <load i32 *a, load i32 *a+4, zero, undef> -> zextload a
8501static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
8502 const SDLoc &DL, SelectionDAG &DAG,
8503 const X86Subtarget &Subtarget,
8504 bool IsAfterLegalize) {
8505 if ((VT.getScalarSizeInBits() % 8) != 0)
8506 return SDValue();
8507
8508 unsigned NumElems = Elts.size();
8509
8510 int LastLoadedElt = -1;
8511 APInt LoadMask = APInt::getNullValue(NumElems);
8512 APInt ZeroMask = APInt::getNullValue(NumElems);
8513 APInt UndefMask = APInt::getNullValue(NumElems);
8514
8515 SmallVector<LoadSDNode*, 8> Loads(NumElems, nullptr);
8516 SmallVector<int64_t, 8> ByteOffsets(NumElems, 0);
8517
8518 // For each element in the initializer, see if we've found a load, zero or an
8519 // undef.
8520 for (unsigned i = 0; i < NumElems; ++i) {
8521 SDValue Elt = peekThroughBitcasts(Elts[i]);
8522 if (!Elt.getNode())
8523 return SDValue();
8524 if (Elt.isUndef()) {
8525 UndefMask.setBit(i);
8526 continue;
8527 }
8528 if (X86::isZeroNode(Elt) || ISD::isBuildVectorAllZeros(Elt.getNode())) {
8529 ZeroMask.setBit(i);
8530 continue;
8531 }
8532
8533 // Each loaded element must be the correct fractional portion of the
8534 // requested vector load.
8535 unsigned EltSizeInBits = Elt.getValueSizeInBits();
8536 if ((NumElems * EltSizeInBits) != VT.getSizeInBits())
8537 return SDValue();
8538
8539 if (!findEltLoadSrc(Elt, Loads[i], ByteOffsets[i]) || ByteOffsets[i] < 0)
8540 return SDValue();
8541 unsigned LoadSizeInBits = Loads[i]->getValueSizeInBits(0);
8542 if (((ByteOffsets[i] * 8) + EltSizeInBits) > LoadSizeInBits)
8543 return SDValue();
8544
8545 LoadMask.setBit(i);
8546 LastLoadedElt = i;
8547 }
8548 assert((ZeroMask.countPopulation() + UndefMask.countPopulation() +(static_cast <bool> ((ZeroMask.countPopulation() + UndefMask
.countPopulation() + LoadMask.countPopulation()) == NumElems &&
"Incomplete element masks") ? void (0) : __assert_fail ("(ZeroMask.countPopulation() + UndefMask.countPopulation() + LoadMask.countPopulation()) == NumElems && \"Incomplete element masks\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8550, __extension__ __PRETTY_FUNCTION__))
8549 LoadMask.countPopulation()) == NumElems &&(static_cast <bool> ((ZeroMask.countPopulation() + UndefMask
.countPopulation() + LoadMask.countPopulation()) == NumElems &&
"Incomplete element masks") ? void (0) : __assert_fail ("(ZeroMask.countPopulation() + UndefMask.countPopulation() + LoadMask.countPopulation()) == NumElems && \"Incomplete element masks\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8550, __extension__ __PRETTY_FUNCTION__))
8550 "Incomplete element masks")(static_cast <bool> ((ZeroMask.countPopulation() + UndefMask
.countPopulation() + LoadMask.countPopulation()) == NumElems &&
"Incomplete element masks") ? void (0) : __assert_fail ("(ZeroMask.countPopulation() + UndefMask.countPopulation() + LoadMask.countPopulation()) == NumElems && \"Incomplete element masks\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8550, __extension__ __PRETTY_FUNCTION__))
;
8551
8552 // Handle Special Cases - all undef or undef/zero.
8553 if (UndefMask.countPopulation() == NumElems)
8554 return DAG.getUNDEF(VT);
8555 if ((ZeroMask.countPopulation() + UndefMask.countPopulation()) == NumElems)
8556 return VT.isInteger() ? DAG.getConstant(0, DL, VT)
8557 : DAG.getConstantFP(0.0, DL, VT);
8558
8559 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8560 int FirstLoadedElt = LoadMask.countTrailingZeros();
8561 SDValue EltBase = peekThroughBitcasts(Elts[FirstLoadedElt]);
8562 EVT EltBaseVT = EltBase.getValueType();
8563 assert(EltBaseVT.getSizeInBits() == EltBaseVT.getStoreSizeInBits() &&(static_cast <bool> (EltBaseVT.getSizeInBits() == EltBaseVT
.getStoreSizeInBits() && "Register/Memory size mismatch"
) ? void (0) : __assert_fail ("EltBaseVT.getSizeInBits() == EltBaseVT.getStoreSizeInBits() && \"Register/Memory size mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8564, __extension__ __PRETTY_FUNCTION__))
8564 "Register/Memory size mismatch")(static_cast <bool> (EltBaseVT.getSizeInBits() == EltBaseVT
.getStoreSizeInBits() && "Register/Memory size mismatch"
) ? void (0) : __assert_fail ("EltBaseVT.getSizeInBits() == EltBaseVT.getStoreSizeInBits() && \"Register/Memory size mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8564, __extension__ __PRETTY_FUNCTION__))
;
8565 LoadSDNode *LDBase = Loads[FirstLoadedElt];
8566 assert(LDBase && "Did not find base load for merging consecutive loads")(static_cast <bool> (LDBase && "Did not find base load for merging consecutive loads"
) ? void (0) : __assert_fail ("LDBase && \"Did not find base load for merging consecutive loads\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8566, __extension__ __PRETTY_FUNCTION__))
;
8567 unsigned BaseSizeInBits = EltBaseVT.getStoreSizeInBits();
8568 unsigned BaseSizeInBytes = BaseSizeInBits / 8;
8569 int NumLoadedElts = (1 + LastLoadedElt - FirstLoadedElt);
8570 int LoadSizeInBits = NumLoadedElts * BaseSizeInBits;
8571 assert((BaseSizeInBits % 8) == 0 && "Sub-byte element loads detected")(static_cast <bool> ((BaseSizeInBits % 8) == 0 &&
"Sub-byte element loads detected") ? void (0) : __assert_fail
("(BaseSizeInBits % 8) == 0 && \"Sub-byte element loads detected\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8571, __extension__ __PRETTY_FUNCTION__))
;
8572
8573 // TODO: Support offsetting the base load.
8574 if (ByteOffsets[FirstLoadedElt] != 0)
8575 return SDValue();
8576
8577 // Check to see if the element's load is consecutive to the base load
8578 // or offset from a previous (already checked) load.
8579 auto CheckConsecutiveLoad = [&](LoadSDNode *Base, int EltIdx) {
8580 LoadSDNode *Ld = Loads[EltIdx];
8581 int64_t ByteOffset = ByteOffsets[EltIdx];
8582 if (ByteOffset && (ByteOffset % BaseSizeInBytes) == 0) {
8583 int64_t BaseIdx = EltIdx - (ByteOffset / BaseSizeInBytes);
8584 return (0 <= BaseIdx && BaseIdx < (int)NumElems && LoadMask[BaseIdx] &&
8585 Loads[BaseIdx] == Ld && ByteOffsets[BaseIdx] == 0);
8586 }
8587 return DAG.areNonVolatileConsecutiveLoads(Ld, Base, BaseSizeInBytes,
8588 EltIdx - FirstLoadedElt);
8589 };
8590
8591 // Consecutive loads can contain UNDEFS but not ZERO elements.
8592 // Consecutive loads with UNDEFs and ZEROs elements require a
8593 // an additional shuffle stage to clear the ZERO elements.
8594 bool IsConsecutiveLoad = true;
8595 bool IsConsecutiveLoadWithZeros = true;
8596 for (int i = FirstLoadedElt + 1; i <= LastLoadedElt; ++i) {
8597 if (LoadMask[i]) {
8598 if (!CheckConsecutiveLoad(LDBase, i)) {
8599 IsConsecutiveLoad = false;
8600 IsConsecutiveLoadWithZeros = false;
8601 break;
8602 }
8603 } else if (ZeroMask[i]) {
8604 IsConsecutiveLoad = false;
8605 }
8606 }
8607
8608 auto CreateLoad = [&DAG, &DL, &Loads](EVT VT, LoadSDNode *LDBase) {
8609 auto MMOFlags = LDBase->getMemOperand()->getFlags();
8610 assert(LDBase->isSimple() &&(static_cast <bool> (LDBase->isSimple() && "Cannot merge volatile or atomic loads."
) ? void (0) : __assert_fail ("LDBase->isSimple() && \"Cannot merge volatile or atomic loads.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8611, __extension__ __PRETTY_FUNCTION__))
8611 "Cannot merge volatile or atomic loads.")(static_cast <bool> (LDBase->isSimple() && "Cannot merge volatile or atomic loads."
) ? void (0) : __assert_fail ("LDBase->isSimple() && \"Cannot merge volatile or atomic loads.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8611, __extension__ __PRETTY_FUNCTION__))
;
8612 SDValue NewLd =
8613 DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
8614 LDBase->getPointerInfo(), LDBase->getOriginalAlign(),
8615 MMOFlags);
8616 for (auto *LD : Loads)
8617 if (LD)
8618 DAG.makeEquivalentMemoryOrdering(LD, NewLd);
8619 return NewLd;
8620 };
8621
8622 // Check if the base load is entirely dereferenceable.
8623 bool IsDereferenceable = LDBase->getPointerInfo().isDereferenceable(
8624 VT.getSizeInBits() / 8, *DAG.getContext(), DAG.getDataLayout());
8625
8626 // LOAD - all consecutive load/undefs (must start/end with a load or be
8627 // entirely dereferenceable). If we have found an entire vector of loads and
8628 // undefs, then return a large load of the entire vector width starting at the
8629 // base pointer. If the vector contains zeros, then attempt to shuffle those
8630 // elements.
8631 if (FirstLoadedElt == 0 &&
8632 (NumLoadedElts == (int)NumElems || IsDereferenceable) &&
8633 (IsConsecutiveLoad || IsConsecutiveLoadWithZeros)) {
8634 if (IsAfterLegalize && !TLI.isOperationLegal(ISD::LOAD, VT))
8635 return SDValue();
8636
8637 // Don't create 256-bit non-temporal aligned loads without AVX2 as these
8638 // will lower to regular temporal loads and use the cache.
8639 if (LDBase->isNonTemporal() && LDBase->getAlignment() >= 32 &&
8640 VT.is256BitVector() && !Subtarget.hasInt256())
8641 return SDValue();
8642
8643 if (NumElems == 1)
8644 return DAG.getBitcast(VT, Elts[FirstLoadedElt]);
8645
8646 if (!ZeroMask)
8647 return CreateLoad(VT, LDBase);
8648
8649 // IsConsecutiveLoadWithZeros - we need to create a shuffle of the loaded
8650 // vector and a zero vector to clear out the zero elements.
8651 if (!IsAfterLegalize && VT.isVector()) {
8652 unsigned NumMaskElts = VT.getVectorNumElements();
8653 if ((NumMaskElts % NumElems) == 0) {
8654 unsigned Scale = NumMaskElts / NumElems;
8655 SmallVector<int, 4> ClearMask(NumMaskElts, -1);
8656 for (unsigned i = 0; i < NumElems; ++i) {
8657 if (UndefMask[i])
8658 continue;
8659 int Offset = ZeroMask[i] ? NumMaskElts : 0;
8660 for (unsigned j = 0; j != Scale; ++j)
8661 ClearMask[(i * Scale) + j] = (i * Scale) + j + Offset;
8662 }
8663 SDValue V = CreateLoad(VT, LDBase);
8664 SDValue Z = VT.isInteger() ? DAG.getConstant(0, DL, VT)
8665 : DAG.getConstantFP(0.0, DL, VT);
8666 return DAG.getVectorShuffle(VT, DL, V, Z, ClearMask);
8667 }
8668 }
8669 }
8670
8671 // If the upper half of a ymm/zmm load is undef then just load the lower half.
8672 if (VT.is256BitVector() || VT.is512BitVector()) {
8673 unsigned HalfNumElems = NumElems / 2;
8674 if (UndefMask.extractBits(HalfNumElems, HalfNumElems).isAllOnesValue()) {
8675 EVT HalfVT =
8676 EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), HalfNumElems);
8677 SDValue HalfLD =
8678 EltsFromConsecutiveLoads(HalfVT, Elts.drop_back(HalfNumElems), DL,
8679 DAG, Subtarget, IsAfterLegalize);
8680 if (HalfLD)
8681 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT),
8682 HalfLD, DAG.getIntPtrConstant(0, DL));
8683 }
8684 }
8685
8686 // VZEXT_LOAD - consecutive 32/64-bit load/undefs followed by zeros/undefs.
8687 if (IsConsecutiveLoad && FirstLoadedElt == 0 &&
8688 (LoadSizeInBits == 32 || LoadSizeInBits == 64) &&
8689 ((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))) {
8690 MVT VecSVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(LoadSizeInBits)
8691 : MVT::getIntegerVT(LoadSizeInBits);
8692 MVT VecVT = MVT::getVectorVT(VecSVT, VT.getSizeInBits() / LoadSizeInBits);
8693 // Allow v4f32 on SSE1 only targets.
8694 // FIXME: Add more isel patterns so we can just use VT directly.
8695 if (!Subtarget.hasSSE2() && VT == MVT::v4f32)
8696 VecVT = MVT::v4f32;
8697 if (TLI.isTypeLegal(VecVT)) {
8698 SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
8699 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
8700 SDValue ResNode = DAG.getMemIntrinsicNode(
8701 X86ISD::VZEXT_LOAD, DL, Tys, Ops, VecSVT, LDBase->getPointerInfo(),
8702 LDBase->getOriginalAlign(), MachineMemOperand::MOLoad);
8703 for (auto *LD : Loads)
8704 if (LD)
8705 DAG.makeEquivalentMemoryOrdering(LD, ResNode);
8706 return DAG.getBitcast(VT, ResNode);
8707 }
8708 }
8709
8710 // BROADCAST - match the smallest possible repetition pattern, load that
8711 // scalar/subvector element and then broadcast to the entire vector.
8712 if (ZeroMask.isNullValue() && isPowerOf2_32(NumElems) && Subtarget.hasAVX() &&
8713 (VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector())) {
8714 for (unsigned SubElems = 1; SubElems < NumElems; SubElems *= 2) {
8715 unsigned RepeatSize = SubElems * BaseSizeInBits;
8716 unsigned ScalarSize = std::min(RepeatSize, 64u);
8717 if (!Subtarget.hasAVX2() && ScalarSize < 32)
8718 continue;
8719
8720 // Don't attempt a 1:N subvector broadcast - it should be caught by
8721 // combineConcatVectorOps, else will cause infinite loops.
8722 if (RepeatSize > ScalarSize && SubElems == 1)
8723 continue;
8724
8725 bool Match = true;
8726 SmallVector<SDValue, 8> RepeatedLoads(SubElems, DAG.getUNDEF(EltBaseVT));
8727 for (unsigned i = 0; i != NumElems && Match; ++i) {
8728 if (!LoadMask[i])
8729 continue;
8730 SDValue Elt = peekThroughBitcasts(Elts[i]);
8731 if (RepeatedLoads[i % SubElems].isUndef())
8732 RepeatedLoads[i % SubElems] = Elt;
8733 else
8734 Match &= (RepeatedLoads[i % SubElems] == Elt);
8735 }
8736
8737 // We must have loads at both ends of the repetition.
8738 Match &= !RepeatedLoads.front().isUndef();
8739 Match &= !RepeatedLoads.back().isUndef();
8740 if (!Match)
8741 continue;
8742
8743 EVT RepeatVT =
8744 VT.isInteger() && (RepeatSize != 64 || TLI.isTypeLegal(MVT::i64))
8745 ? EVT::getIntegerVT(*DAG.getContext(), ScalarSize)
8746 : EVT::getFloatingPointVT(ScalarSize);
8747 if (RepeatSize > ScalarSize)
8748 RepeatVT = EVT::getVectorVT(*DAG.getContext(), RepeatVT,
8749 RepeatSize / ScalarSize);
8750 EVT BroadcastVT =
8751 EVT::getVectorVT(*DAG.getContext(), RepeatVT.getScalarType(),
8752 VT.getSizeInBits() / ScalarSize);
8753 if (TLI.isTypeLegal(BroadcastVT)) {
8754 if (SDValue RepeatLoad = EltsFromConsecutiveLoads(
8755 RepeatVT, RepeatedLoads, DL, DAG, Subtarget, IsAfterLegalize)) {
8756 SDValue Broadcast = RepeatLoad;
8757 if (RepeatSize > ScalarSize) {
8758 while (Broadcast.getValueSizeInBits() < VT.getSizeInBits())
8759 Broadcast = concatSubVectors(Broadcast, Broadcast, DAG, DL);
8760 } else {
8761 Broadcast =
8762 DAG.getNode(X86ISD::VBROADCAST, DL, BroadcastVT, RepeatLoad);
8763 }
8764 return DAG.getBitcast(VT, Broadcast);
8765 }
8766 }
8767 }
8768 }
8769
8770 return SDValue();
8771}
8772
8773// Combine a vector ops (shuffles etc.) that is equal to build_vector load1,
8774// load2, load3, load4, <0, 1, 2, 3> into a vector load if the load addresses
8775// are consecutive, non-overlapping, and in the right order.
8776static SDValue combineToConsecutiveLoads(EVT VT, SDValue Op, const SDLoc &DL,
8777 SelectionDAG &DAG,
8778 const X86Subtarget &Subtarget,
8779 bool IsAfterLegalize) {
8780 SmallVector<SDValue, 64> Elts;
8781 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
8782 if (SDValue Elt = getShuffleScalarElt(Op, i, DAG, 0)) {
8783 Elts.push_back(Elt);
8784 continue;
8785 }
8786 return SDValue();
8787 }
8788 assert(Elts.size() == VT.getVectorNumElements())(static_cast <bool> (Elts.size() == VT.getVectorNumElements
()) ? void (0) : __assert_fail ("Elts.size() == VT.getVectorNumElements()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8788, __extension__ __PRETTY_FUNCTION__))
;
8789 return EltsFromConsecutiveLoads(VT, Elts, DL, DAG, Subtarget,
8790 IsAfterLegalize);
8791}
8792
8793static Constant *getConstantVector(MVT VT, const APInt &SplatValue,
8794 unsigned SplatBitSize, LLVMContext &C) {
8795 unsigned ScalarSize = VT.getScalarSizeInBits();
8796 unsigned NumElm = SplatBitSize / ScalarSize;
8797
8798 SmallVector<Constant *, 32> ConstantVec;
8799 for (unsigned i = 0; i < NumElm; i++) {
8800 APInt Val = SplatValue.extractBits(ScalarSize, ScalarSize * i);
8801 Constant *Const;
8802 if (VT.isFloatingPoint()) {
8803 if (ScalarSize == 32) {
8804 Const = ConstantFP::get(C, APFloat(APFloat::IEEEsingle(), Val));
8805 } else {
8806 assert(ScalarSize == 64 && "Unsupported floating point scalar size")(static_cast <bool> (ScalarSize == 64 && "Unsupported floating point scalar size"
) ? void (0) : __assert_fail ("ScalarSize == 64 && \"Unsupported floating point scalar size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8806, __extension__ __PRETTY_FUNCTION__))
;
8807 Const = ConstantFP::get(C, APFloat(APFloat::IEEEdouble(), Val));
8808 }
8809 } else
8810 Const = Constant::getIntegerValue(Type::getIntNTy(C, ScalarSize), Val);
8811 ConstantVec.push_back(Const);
8812 }
8813 return ConstantVector::get(ArrayRef<Constant *>(ConstantVec));
8814}
8815
8816static bool isFoldableUseOfShuffle(SDNode *N) {
8817 for (auto *U : N->uses()) {
8818 unsigned Opc = U->getOpcode();
8819 // VPERMV/VPERMV3 shuffles can never fold their index operands.
8820 if (Opc == X86ISD::VPERMV && U->getOperand(0).getNode() == N)
8821 return false;
8822 if (Opc == X86ISD::VPERMV3 && U->getOperand(1).getNode() == N)
8823 return false;
8824 if (isTargetShuffle(Opc))
8825 return true;
8826 if (Opc == ISD::BITCAST) // Ignore bitcasts
8827 return isFoldableUseOfShuffle(U);
8828 if (N->hasOneUse())
8829 return true;
8830 }
8831 return false;
8832}
8833
8834/// Attempt to use the vbroadcast instruction to generate a splat value
8835/// from a splat BUILD_VECTOR which uses:
8836/// a. A single scalar load, or a constant.
8837/// b. Repeated pattern of constants (e.g. <0,1,0,1> or <0,1,2,3,0,1,2,3>).
8838///
8839/// The VBROADCAST node is returned when a pattern is found,
8840/// or SDValue() otherwise.
8841static SDValue lowerBuildVectorAsBroadcast(BuildVectorSDNode *BVOp,
8842 const X86Subtarget &Subtarget,
8843 SelectionDAG &DAG) {
8844 // VBROADCAST requires AVX.
8845 // TODO: Splats could be generated for non-AVX CPUs using SSE
8846 // instructions, but there's less potential gain for only 128-bit vectors.
8847 if (!Subtarget.hasAVX())
8848 return SDValue();
8849
8850 MVT VT = BVOp->getSimpleValueType(0);
8851 unsigned NumElts = VT.getVectorNumElements();
8852 SDLoc dl(BVOp);
8853
8854 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector()) && "Unsupported vector type for broadcast."
) ? void (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Unsupported vector type for broadcast.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8855, __extension__ __PRETTY_FUNCTION__))
8855 "Unsupported vector type for broadcast.")(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector()) && "Unsupported vector type for broadcast."
) ? void (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Unsupported vector type for broadcast.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8855, __extension__ __PRETTY_FUNCTION__))
;
8856
8857 // See if the build vector is a repeating sequence of scalars (inc. splat).
8858 SDValue Ld;
8859 BitVector UndefElements;
8860 SmallVector<SDValue, 16> Sequence;
8861 if (BVOp->getRepeatedSequence(Sequence, &UndefElements)) {
8862 assert((NumElts % Sequence.size()) == 0 && "Sequence doesn't fit.")(static_cast <bool> ((NumElts % Sequence.size()) == 0 &&
"Sequence doesn't fit.") ? void (0) : __assert_fail ("(NumElts % Sequence.size()) == 0 && \"Sequence doesn't fit.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 8862, __extension__ __PRETTY_FUNCTION__))
;
8863 if (Sequence.size() == 1)
8864 Ld = Sequence[0];
8865 }
8866
8867 // Attempt to use VBROADCASTM
8868 // From this pattern:
8869 // a. t0 = (zext_i64 (bitcast_i8 v2i1 X))
8870 // b. t1 = (build_vector t0 t0)
8871 //
8872 // Create (VBROADCASTM v2i1 X)
8873 if (!Sequence.empty() && Subtarget.hasCDI()) {
8874 // If not a splat, are the upper sequence values zeroable?
8875 unsigned SeqLen = Sequence.size();
8876 bool UpperZeroOrUndef =
8877 SeqLen == 1 ||
8878 llvm::all_of(makeArrayRef(Sequence).drop_front(), [](SDValue V) {
8879 return !V || V.isUndef() || isNullConstant(V);
8880 });
8881 SDValue Op0 = Sequence[0];
8882 if (UpperZeroOrUndef && ((Op0.getOpcode() == ISD::BITCAST) ||
8883 (Op0.getOpcode() == ISD::ZERO_EXTEND &&
8884 Op0.getOperand(0).getOpcode() == ISD::BITCAST))) {
8885 SDValue BOperand = Op0.getOpcode() == ISD::BITCAST
8886 ? Op0.getOperand(0)
8887 : Op0.getOperand(0).getOperand(0);
8888 MVT MaskVT = BOperand.getSimpleValueType();
8889 MVT EltType = MVT::getIntegerVT(VT.getScalarSizeInBits() * SeqLen);
8890 if ((EltType == MVT::i64 && MaskVT == MVT::v8i1) || // for broadcastmb2q
8891 (EltType == MVT::i32 && MaskVT == MVT::v16i1)) { // for broadcastmw2d
8892 MVT BcstVT = MVT::getVectorVT(EltType, NumElts / SeqLen);
8893 if (!VT.is512BitVector() && !Subtarget.hasVLX()) {
8894 unsigned Scale = 512 / VT.getSizeInBits();
8895 BcstVT = MVT::getVectorVT(EltType, Scale * (NumElts / SeqLen));
8896 }
8897 SDValue Bcst = DAG.getNode(X86ISD::VBROADCASTM, dl, BcstVT, BOperand);
8898 if (BcstVT.getSizeInBits() != VT.getSizeInBits())
8899 Bcst = extractSubVector(Bcst, 0, DAG, dl, VT.getSizeInBits());
8900 return DAG.getBitcast(VT, Bcst);
8901 }
8902 }
8903 }
8904
8905 unsigned NumUndefElts = UndefElements.count();
8906 if (!Ld || (NumElts - NumUndefElts) <= 1) {
8907 APInt SplatValue, Undef;
8908 unsigned SplatBitSize;
8909 bool HasUndef;
8910 // Check if this is a repeated constant pattern suitable for broadcasting.
8911 if (BVOp->isConstantSplat(SplatValue, Undef, SplatBitSize, HasUndef) &&
8912 SplatBitSize > VT.getScalarSizeInBits() &&
8913 SplatBitSize < VT.getSizeInBits()) {
8914 // Avoid replacing with broadcast when it's a use of a shuffle
8915 // instruction to preserve the present custom lowering of shuffles.
8916 if (isFoldableUseOfShuffle(BVOp))
8917 return SDValue();
8918 // replace BUILD_VECTOR with broadcast of the repeated constants.
8919 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8920 LLVMContext *Ctx = DAG.getContext();
8921 MVT PVT = TLI.getPointerTy(DAG.getDataLayout());
8922 if (Subtarget.hasAVX()) {
8923 if (SplatBitSize == 32 || SplatBitSize == 64 ||
8924 (SplatBitSize < 32 && Subtarget.hasAVX2())) {
8925 // Splatted value can fit in one INTEGER constant in constant pool.
8926 // Load the constant and broadcast it.
8927 MVT CVT = MVT::getIntegerVT(SplatBitSize);
8928 Type *ScalarTy = Type::getIntNTy(*Ctx, SplatBitSize);
8929 Constant *C = Constant::getIntegerValue(ScalarTy, SplatValue);
8930 SDValue CP = DAG.getConstantPool(C, PVT);
8931 unsigned Repeat = VT.getSizeInBits() / SplatBitSize;
8932
8933 Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
8934 SDVTList Tys =
8935 DAG.getVTList(MVT::getVectorVT(CVT, Repeat), MVT::Other);
8936 SDValue Ops[] = {DAG.getEntryNode(), CP};
8937 MachinePointerInfo MPI =
8938 MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
8939 SDValue Brdcst = DAG.getMemIntrinsicNode(
8940 X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT, MPI, Alignment,
8941 MachineMemOperand::MOLoad);
8942 return DAG.getBitcast(VT, Brdcst);
8943 }
8944 if (SplatBitSize > 64) {
8945 // Load the vector of constants and broadcast it.
8946 Constant *VecC = getConstantVector(VT, SplatValue, SplatBitSize,
8947 *Ctx);
8948 SDValue VCP = DAG.getConstantPool(VecC, PVT);
8949 unsigned NumElm = SplatBitSize / VT.getScalarSizeInBits();
8950 MVT VVT = MVT::getVectorVT(VT.getScalarType(), NumElm);
8951 Align Alignment = cast<ConstantPoolSDNode>(VCP)->getAlign();
8952 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8953 SDValue Ops[] = {DAG.getEntryNode(), VCP};
8954 MachinePointerInfo MPI =
8955 MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
8956 return DAG.getMemIntrinsicNode(
8957 X86ISD::SUBV_BROADCAST_LOAD, dl, Tys, Ops, VVT, MPI, Alignment,
8958 MachineMemOperand::MOLoad);
8959 }
8960 }
8961 }
8962
8963 // If we are moving a scalar into a vector (Ld must be set and all elements
8964 // but 1 are undef) and that operation is not obviously supported by
8965 // vmovd/vmovq/vmovss/vmovsd, then keep trying to form a broadcast.
8966 // That's better than general shuffling and may eliminate a load to GPR and
8967 // move from scalar to vector register.
8968 if (!Ld || NumElts - NumUndefElts != 1)
8969 return SDValue();
8970 unsigned ScalarSize = Ld.getValueSizeInBits();
8971 if (!(UndefElements[0] || (ScalarSize != 32 && ScalarSize != 64)))
8972 return SDValue();
8973 }
8974
8975 bool ConstSplatVal =
8976 (Ld.getOpcode() == ISD::Constant || Ld.getOpcode() == ISD::ConstantFP);
8977 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
8978
8979 // TODO: Handle broadcasts of non-constant sequences.
8980
8981 // Make sure that all of the users of a non-constant load are from the
8982 // BUILD_VECTOR node.
8983 // FIXME: Is the use count needed for non-constant, non-load case?
8984 if (!ConstSplatVal && !IsLoad && !BVOp->isOnlyUserOf(Ld.getNode()))
8985 return SDValue();
8986
8987 unsigned ScalarSize = Ld.getValueSizeInBits();
8988 bool IsGE256 = (VT.getSizeInBits() >= 256);
8989
8990 // When optimizing for size, generate up to 5 extra bytes for a broadcast
8991 // instruction to save 8 or more bytes of constant pool data.
8992 // TODO: If multiple splats are generated to load the same constant,
8993 // it may be detrimental to overall size. There needs to be a way to detect
8994 // that condition to know if this is truly a size win.
8995 bool OptForSize = DAG.shouldOptForSize();
8996
8997 // Handle broadcasting a single constant scalar from the constant pool
8998 // into a vector.
8999 // On Sandybridge (no AVX2), it is still better to load a constant vector
9000 // from the constant pool and not to broadcast it from a scalar.
9001 // But override that restriction when optimizing for size.
9002 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
9003 if (ConstSplatVal && (Subtarget.hasAVX2() || OptForSize)) {
9004 EVT CVT = Ld.getValueType();
9005 assert(!CVT.isVector() && "Must not broadcast a vector type")(static_cast <bool> (!CVT.isVector() && "Must not broadcast a vector type"
) ? void (0) : __assert_fail ("!CVT.isVector() && \"Must not broadcast a vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 9005, __extension__ __PRETTY_FUNCTION__))
;
9006
9007 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
9008 // For size optimization, also splat v2f64 and v2i64, and for size opt
9009 // with AVX2, also splat i8 and i16.
9010 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
9011 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
9012 (OptForSize && (ScalarSize == 64 || Subtarget.hasAVX2()))) {
9013 const Constant *C = nullptr;
9014 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
9015 C = CI->getConstantIntValue();
9016 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
9017 C = CF->getConstantFPValue();
9018
9019 assert(C && "Invalid constant type")(static_cast <bool> (C && "Invalid constant type"
) ? void (0) : __assert_fail ("C && \"Invalid constant type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 9019, __extension__ __PRETTY_FUNCTION__))
;
9020
9021 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9022 SDValue CP =
9023 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
9024 Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
9025
9026 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
9027 SDValue Ops[] = {DAG.getEntryNode(), CP};
9028 MachinePointerInfo MPI =
9029 MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
9030 return DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT,
9031 MPI, Alignment, MachineMemOperand::MOLoad);
9032 }
9033 }
9034
9035 // Handle AVX2 in-register broadcasts.
9036 if (!IsLoad && Subtarget.hasInt256() &&
9037 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
9038 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
9039
9040 // The scalar source must be a normal load.
9041 if (!IsLoad)
9042 return SDValue();
9043
9044 // Make sure the non-chain result is only used by this build vector.
9045 if (!Ld->hasNUsesOfValue(NumElts - NumUndefElts, 0))
9046 return SDValue();
9047
9048 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
9049 (Subtarget.hasVLX() && ScalarSize == 64)) {
9050 auto *LN = cast<LoadSDNode>(Ld);
9051 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
9052 SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
9053 SDValue BCast =
9054 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
9055 LN->getMemoryVT(), LN->getMemOperand());
9056 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
9057 return BCast;
9058 }
9059
9060 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
9061 // double since there is no vbroadcastsd xmm
9062 if (Subtarget.hasInt256() && Ld.getValueType().isInteger() &&
9063 (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)) {
9064 auto *LN = cast<LoadSDNode>(Ld);
9065 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
9066 SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
9067 SDValue BCast =
9068 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
9069 LN->getMemoryVT(), LN->getMemOperand());
9070 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
9071 return BCast;
9072 }
9073
9074 // Unsupported broadcast.
9075 return SDValue();
9076}
9077
9078/// For an EXTRACT_VECTOR_ELT with a constant index return the real
9079/// underlying vector and index.
9080///
9081/// Modifies \p ExtractedFromVec to the real vector and returns the real
9082/// index.
9083static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
9084 SDValue ExtIdx) {
9085 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
9086 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
9087 return Idx;
9088
9089 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
9090 // lowered this:
9091 // (extract_vector_elt (v8f32 %1), Constant<6>)
9092 // to:
9093 // (extract_vector_elt (vector_shuffle<2,u,u,u>
9094 // (extract_subvector (v8f32 %0), Constant<4>),
9095 // undef)
9096 // Constant<0>)
9097 // In this case the vector is the extract_subvector expression and the index
9098 // is 2, as specified by the shuffle.
9099 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
9100 SDValue ShuffleVec = SVOp->getOperand(0);
9101 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
9102 assert(ShuffleVecVT.getVectorElementType() ==(static_cast <bool> (ShuffleVecVT.getVectorElementType(
) == ExtractedFromVec.getSimpleValueType().getVectorElementType
()) ? void (0) : __assert_fail ("ShuffleVecVT.getVectorElementType() == ExtractedFromVec.getSimpleValueType().getVectorElementType()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 9103, __extension__ __PRETTY_FUNCTION__))
9103 ExtractedFromVec.getSimpleValueType().getVectorElementType())(static_cast <bool> (ShuffleVecVT.getVectorElementType(
) == ExtractedFromVec.getSimpleValueType().getVectorElementType
()) ? void (0) : __assert_fail ("ShuffleVecVT.getVectorElementType() == ExtractedFromVec.getSimpleValueType().getVectorElementType()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 9103, __extension__ __PRETTY_FUNCTION__))
;
9104
9105 int ShuffleIdx = SVOp->getMaskElt(Idx);
9106 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
9107 ExtractedFromVec = ShuffleVec;
9108 return ShuffleIdx;
9109 }
9110 return Idx;
9111}
9112
9113static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
9114 MVT VT = Op.getSimpleValueType();
9115
9116 // Skip if insert_vec_elt is not supported.
9117 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9118 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
9119 return SDValue();
9120
9121 SDLoc DL(Op);
9122 unsigned NumElems = Op.getNumOperands();
9123
9124 SDValue VecIn1;
9125 SDValue VecIn2;
9126 SmallVector<unsigned, 4> InsertIndices;
9127 SmallVector<int, 8> Mask(NumElems, -1);
9128
9129 for (unsigned i = 0; i != NumElems; ++i) {
9130 unsigned Opc = Op.getOperand(i).getOpcode();
9131
9132 if (Opc == ISD::UNDEF)
9133 continue;
9134
9135 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
9136 // Quit if more than 1 elements need inserting.
9137 if (InsertIndices.size() > 1)
9138 return SDValue();
9139
9140 InsertIndices.push_back(i);
9141 continue;
9142 }
9143
9144 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
9145 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
9146
9147 // Quit if non-constant index.
9148 if (!isa<ConstantSDNode>(ExtIdx))
9149 return SDValue();
9150 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
9151
9152 // Quit if extracted from vector of different type.
9153 if (ExtractedFromVec.getValueType() != VT)
9154 return SDValue();
9155
9156 if (!VecIn1.getNode())
9157 VecIn1 = ExtractedFromVec;
9158 else if (VecIn1 != ExtractedFromVec) {
9159 if (!VecIn2.getNode())
9160 VecIn2 = ExtractedFromVec;
9161 else if (VecIn2 != ExtractedFromVec)
9162 // Quit if more than 2 vectors to shuffle
9163 return SDValue();
9164 }
9165
9166 if (ExtractedFromVec == VecIn1)
9167 Mask[i] = Idx;
9168 else if (ExtractedFromVec == VecIn2)
9169 Mask[i] = Idx + NumElems;
9170 }
9171
9172 if (!VecIn1.getNode())
9173 return SDValue();
9174
9175 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9176 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, Mask);
9177
9178 for (unsigned Idx : InsertIndices)
9179 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
9180 DAG.getIntPtrConstant(Idx, DL));
9181
9182 return NV;
9183}
9184
9185// Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
9186static SDValue LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG,
9187 const X86Subtarget &Subtarget) {
9188
9189 MVT VT = Op.getSimpleValueType();
9190 assert((VT.getVectorElementType() == MVT::i1) &&(static_cast <bool> ((VT.getVectorElementType() == MVT::
i1) && "Unexpected type in LowerBUILD_VECTORvXi1!") ?
void (0) : __assert_fail ("(VT.getVectorElementType() == MVT::i1) && \"Unexpected type in LowerBUILD_VECTORvXi1!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 9191, __extension__ __PRETTY_FUNCTION__))
9191 "Unexpected type in LowerBUILD_VECTORvXi1!")(static_cast <bool> ((VT.getVectorElementType() == MVT::
i1) && "Unexpected type in LowerBUILD_VECTORvXi1!") ?
void (0) : __assert_fail ("(VT.getVectorElementType() == MVT::i1) && \"Unexpected type in LowerBUILD_VECTORvXi1!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 9191, __extension__ __PRETTY_FUNCTION__))
;
9192
9193 SDLoc dl(Op);
9194 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
9195 ISD::isBuildVectorAllOnes(Op.getNode()))
9196 return Op;
9197
9198 uint64_t Immediate = 0;
9199 SmallVector<unsigned, 16> NonConstIdx;
9200 bool IsSplat = true;
9201 bool HasConstElts = false;
9202 int SplatIdx = -1;
9203 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
9204 SDValue In = Op.getOperand(idx);
9205 if (In.isUndef())
9206 continue;
9207 if (auto *InC = dyn_cast<ConstantSDNode>(In)) {
9208 Immediate |= (InC->getZExtValue() & 0x1) << idx;
9209 HasConstElts = true;
9210 } else {
9211 NonConstIdx.push_back(idx);
9212 }
9213 if (SplatIdx < 0)
9214 SplatIdx = idx;
9215 else if (In != Op.getOperand(SplatIdx))
9216 IsSplat = false;
9217 }
9218
9219 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
9220 if (IsSplat) {
9221 // The build_vector allows the scalar element to be larger than the vector
9222 // element type. We need to mask it to use as a condition unless we know
9223 // the upper bits are zero.
9224 // FIXME: Use computeKnownBits instead of checking specific opcode?
9225 SDValue Cond = Op.getOperand(SplatIdx);
9226 assert(Cond.getValueType() == MVT::i8 && "Unexpected VT!")(static_cast <bool> (Cond.getValueType() == MVT::i8 &&
"Unexpected VT!") ? void (0) : __assert_fail ("Cond.getValueType() == MVT::i8 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 9226, __extension__ __PRETTY_FUNCTION__))
;
9227 if (Cond.getOpcode() != ISD::SETCC)
9228 Cond = DAG.getNode(ISD::AND, dl, MVT::i8, Cond,
9229 DAG.getConstant(1, dl, MVT::i8));
9230
9231 // Perform the select in the scalar domain so we can use cmov.
9232 if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
9233 SDValue Select = DAG.getSelect(dl, MVT::i32, Cond,
9234 DAG.getAllOnesConstant(dl, MVT::i32),
9235 DAG.getConstant(0, dl, MVT::i32));
9236 Select = DAG.getBitcast(MVT::v32i1, Select);
9237 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Select, Select);
9238 } else {
9239 MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
9240 SDValue Select = DAG.getSelect(dl, ImmVT, Cond,
9241 DAG.getAllOnesConstant(dl, ImmVT),
9242 DAG.getConstant(0, dl, ImmVT));
9243 MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
9244 Select = DAG.getBitcast(VecVT, Select);
9245 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Select,
9246 DAG.getIntPtrConstant(0, dl));
9247 }
9248 }
9249
9250 // insert elements one by one
9251 SDValue DstVec;
9252 if (HasConstElts) {
9253 if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
9254 SDValue ImmL = DAG.getConstant(Lo_32(Immediate), dl, MVT::i32);
9255 SDValue ImmH = DAG.getConstant(Hi_32(Immediate), dl, MVT::i32);
9256 ImmL = DAG.getBitcast(MVT::v32i1, ImmL);
9257 ImmH = DAG.getBitcast(MVT::v32i1, ImmH);
9258 DstVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, ImmL, ImmH);
9259 } else {
9260 MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
9261 SDValue Imm = DAG.getConstant(Immediate, dl, ImmVT);
9262 MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
9263 DstVec = DAG.getBitcast(VecVT, Imm);
9264 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, DstVec,
9265 DAG.getIntPtrConstant(0, dl));
9266 }
9267 } else
9268 DstVec = DAG.getUNDEF(VT);
9269
9270 for (unsigned i = 0, e = NonConstIdx.size(); i != e; ++i) {
9271 unsigned InsertIdx = NonConstIdx[i];
9272 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
9273 Op.getOperand(InsertIdx),
9274 DAG.getIntPtrConstant(InsertIdx, dl));
9275 }
9276 return DstVec;
9277}
9278
9279LLVM_ATTRIBUTE_UNUSED__attribute__((__unused__)) static bool isHorizOp(unsigned Opcode) {
9280 switch (Opcode) {
9281 case X86ISD::PACKSS:
9282 case X86ISD::PACKUS:
9283 case X86ISD::FHADD:
9284 case X86ISD::FHSUB:
9285 case X86ISD::HADD:
9286 case X86ISD::HSUB:
9287 return true;
9288 }
9289 return false;
9290}
9291
9292/// This is a helper function of LowerToHorizontalOp().
9293/// This function checks that the build_vector \p N in input implements a
9294/// 128-bit partial horizontal operation on a 256-bit vector, but that operation
9295/// may not match the layout of an x86 256-bit horizontal instruction.
9296/// In other words, if this returns true, then some extraction/insertion will
9297/// be required to produce a valid horizontal instruction.
9298///
9299/// Parameter \p Opcode defines the kind of horizontal operation to match.
9300/// For example, if \p Opcode is equal to ISD::ADD, then this function
9301/// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
9302/// is equal to ISD::SUB, then this function checks if this is a horizontal
9303/// arithmetic sub.
9304///
9305/// This function only analyzes elements of \p N whose indices are
9306/// in range [BaseIdx, LastIdx).
9307///
9308/// TODO: This function was originally used to match both real and fake partial
9309/// horizontal operations, but the index-matching logic is incorrect for that.
9310/// See the corrected implementation in isHopBuildVector(). Can we reduce this
9311/// code because it is only used for partial h-op matching now?
9312static bool isHorizontalBinOpPart(const BuildVectorSDNode *N, unsigned Opcode,
9313 SelectionDAG &DAG,
9314 unsigned BaseIdx, unsigned LastIdx,
9315 SDValue &V0, SDValue &V1) {
9316 EVT VT = N->getValueType(0);
9317 assert(VT.is256BitVector() && "Only use for matching partial 256-bit h-ops")(static_cast <bool> (VT.is256BitVector() && "Only use for matching partial 256-bit h-ops"
) ? void (0) : __assert_fail ("VT.is256BitVector() && \"Only use for matching partial 256-bit h-ops\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 9317, __extension__ __PRETTY_FUNCTION__))
;
9318 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!")(static_cast <bool> (BaseIdx * 2 <= LastIdx &&
"Invalid Indices in input!") ? void (0) : __assert_fail ("BaseIdx * 2 <= LastIdx && \"Invalid Indices in input!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 9318, __extension__ __PRETTY_FUNCTION__))
;
9319 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&(static_cast <bool> (VT.isVector() && VT.getVectorNumElements
() >= LastIdx && "Invalid Vector in input!") ? void
(0) : __assert_fail ("VT.isVector() && VT.getVectorNumElements() >= LastIdx && \"Invalid Vector in input!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 9320, __extension__ __PRETTY_FUNCTION__))
9320 "Invalid Vector in input!")(static_cast <bool> (VT.isVector() && VT.getVectorNumElements
() >= LastIdx && "Invalid Vector in input!") ? void
(0) : __assert_fail ("VT.isVector() && VT.getVectorNumElements() >= LastIdx && \"Invalid Vector in input!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 9320, __extension__ __PRETTY_FUNCTION__))
;
9321
9322 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
9323 bool CanFold = true;
9324 unsigned ExpectedVExtractIdx = BaseIdx;
9325 unsigned NumElts = LastIdx - BaseIdx;
9326 V0 = DAG.getUNDEF(VT);
9327 V1 = DAG.getUNDEF(VT);
9328
9329 // Check if N implements a horizontal binop.
9330 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
9331 SDValue Op = N->getOperand(i + BaseIdx);
9332
9333 // Skip UNDEFs.
9334 if (Op->isUndef()) {
9335 // Update the expected vector extract index.
9336 if (i * 2 == NumElts)
9337 ExpectedVExtractIdx = BaseIdx;
9338 ExpectedVExtractIdx += 2;
9339 continue;
9340 }
9341
9342 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
9343
9344 if (!CanFold)
9345 break;
9346
9347 SDValue Op0 = Op.getOperand(0);
9348 SDValue Op1 = Op.getOperand(1);
9349
9350 // Try to match the following pattern:
9351 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
9352 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9353 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9354 Op0.getOperand(0) == Op1.getOperand(0) &&
9355 isa<ConstantSDNode>(Op0.getOperand(1)) &&
9356 isa<ConstantSDNode>(Op1.getOperand(1)));
9357 if (!CanFold)
9358 break;
9359
9360 unsigned I0 = Op0.getConstantOperandVal(1);
9361 unsigned I1 = Op1.getConstantOperandVal(1);
9362
9363 if (i * 2 < NumElts) {
9364 if (V0.isUndef()) {
9365 V0 = Op0.getOperand(0);
9366 if (V0.getValueType() != VT)
9367 return false;
9368 }
9369 } else {
9370 if (V1.isUndef()) {
9371 V1 = Op0.getOperand(0);
9372 if (V1.getValueType() != VT)
9373 return false;
9374 }
9375 if (i * 2 == NumElts)
9376 ExpectedVExtractIdx = BaseIdx;
9377 }
9378
9379 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
9380 if (I0 == ExpectedVExtractIdx)
9381 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
9382 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
9383 // Try to match the following dag sequence:
9384 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
9385 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
9386 } else
9387 CanFold = false;
9388
9389 ExpectedVExtractIdx += 2;
9390 }
9391
9392 return CanFold;
9393}
9394
9395/// Emit a sequence of two 128-bit horizontal add/sub followed by
9396/// a concat_vector.
9397///
9398/// This is a helper function of LowerToHorizontalOp().
9399/// This function expects two 256-bit vectors called V0 and V1.
9400/// At first, each vector is split into two separate 128-bit vectors.
9401/// Then, the resulting 128-bit vectors are used to implement two
9402/// horizontal binary operations.
9403///
9404/// The kind of horizontal binary operation is defined by \p X86Opcode.
9405///
9406/// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
9407/// the two new horizontal binop.
9408/// When Mode is set, the first horizontal binop dag node would take as input
9409/// the lower 128-bit of V0 and the upper 128-bit of V0. The second
9410/// horizontal binop dag node would take as input the lower 128-bit of V1
9411/// and the upper 128-bit of V1.
9412/// Example:
9413/// HADD V0_LO, V0_HI
9414/// HADD V1_LO, V1_HI
9415///
9416/// Otherwise, the first horizontal binop dag node takes as input the lower
9417/// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
9418/// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
9419/// Example:
9420/// HADD V0_LO, V1_LO
9421/// HADD V0_HI, V1_HI
9422///
9423/// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
9424/// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
9425/// the upper 128-bits of the result.
9426static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
9427 const SDLoc &DL, SelectionDAG &DAG,
9428 unsigned X86Opcode, bool Mode,
9429 bool isUndefLO, bool isUndefHI) {
9430 MVT VT = V0.getSimpleValueType();
9431 assert(VT.is256BitVector() && VT == V1.getSimpleValueType() &&(static_cast <bool> (VT.is256BitVector() && VT ==
V1.getSimpleValueType() && "Invalid nodes in input!"
) ? void (0) : __assert_fail ("VT.is256BitVector() && VT == V1.getSimpleValueType() && \"Invalid nodes in input!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 9432, __extension__ __PRETTY_FUNCTION__))
9432 "Invalid nodes in input!")(static_cast <bool> (VT.is256BitVector() && VT ==
V1.getSimpleValueType() && "Invalid nodes in input!"
) ? void (0) : __assert_fail ("VT.is256BitVector() && VT == V1.getSimpleValueType() && \"Invalid nodes in input!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 9432, __extension__ __PRETTY_FUNCTION__))
;
9433
9434 unsigned NumElts = VT.getVectorNumElements();
9435 SDValue V0_LO = extract128BitVector(V0, 0, DAG, DL);
9436 SDValue V0_HI = extract128BitVector(V0, NumElts/2, DAG, DL);
9437 SDValue V1_LO = extract128BitVector(V1, 0, DAG, DL);
9438 SDValue V1_HI = extract128BitVector(V1, NumElts/2, DAG, DL);
9439 MVT NewVT = V0_LO.getSimpleValueType();
9440
9441 SDValue LO = DAG.getUNDEF(NewVT);
9442 SDValue HI = DAG.getUNDEF(NewVT);
9443
9444 if (Mode) {
9445 // Don't emit a horizontal binop if the result is expected to be UNDEF.
9446 if (!isUndefLO && !V0->isUndef())
9447 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
9448 if (!isUndefHI && !V1->isUndef())
9449 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
9450 } else {
9451 // Don't emit a horizontal binop if the result is expected to be UNDEF.
9452 if (!isUndefLO && (!V0_LO->isUndef() || !V1_LO->isUndef()))
9453 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
9454
9455 if (!isUndefHI && (!V0_HI->isUndef() || !V1_HI->isUndef()))
9456 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
9457 }
9458
9459 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
9460}
9461
9462/// Returns true iff \p BV builds a vector with the result equivalent to
9463/// the result of ADDSUB/SUBADD operation.
9464/// If true is returned then the operands of ADDSUB = Opnd0 +- Opnd1
9465/// (SUBADD = Opnd0 -+ Opnd1) operation are written to the parameters
9466/// \p Opnd0 and \p Opnd1.
9467static bool isAddSubOrSubAdd(const BuildVectorSDNode *BV,
9468 const X86Subtarget &Subtarget, SelectionDAG &DAG,
9469 SDValue &Opnd0, SDValue &Opnd1,
9470 unsigned &NumExtracts,
9471 bool &IsSubAdd) {
9472
9473 MVT VT = BV->getSimpleValueType(0);
9474 if (!Subtarget.hasSSE3() || !VT.isFloatingPoint())
9475 return false;
9476
9477 unsigned NumElts = VT.getVectorNumElements();
9478 SDValue InVec0 = DAG.getUNDEF(VT);
9479 SDValue InVec1 = DAG.getUNDEF(VT);
9480
9481 NumExtracts = 0;
9482
9483 // Odd-numbered elements in the input build vector are obtained from
9484 // adding/subtracting two integer/float elements.
9485 // Even-numbered elements in the input build vector are obtained from
9486 // subtracting/adding two integer/float elements.
9487 unsigned Opc[2] = {0, 0};
9488 for (unsigned i = 0, e = NumElts; i != e; ++i) {
9489 SDValue Op = BV->getOperand(i);
9490
9491 // Skip 'undef' values.
9492 unsigned Opcode = Op.getOpcode();
9493 if (Opcode == ISD::UNDEF)
9494 continue;
9495
9496 // Early exit if we found an unexpected opcode.
9497 if (Opcode != ISD::FADD && Opcode != ISD::FSUB)
9498 return false;
9499
9500 SDValue Op0 = Op.getOperand(0);
9501 SDValue Op1 = Op.getOperand(1);
9502
9503 // Try to match the following pattern:
9504 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
9505 // Early exit if we cannot match that sequence.
9506 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9507 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9508 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
9509 Op0.getOperand(1) != Op1.getOperand(1))
9510 return false;
9511
9512 unsigned I0 = Op0.getConstantOperandVal(1);
9513 if (I0 != i)
9514 return false;
9515
9516 // We found a valid add/sub node, make sure its the same opcode as previous
9517 // elements for this parity.
9518 if (Opc[i % 2] != 0 && Opc[i % 2] != Opcode)
9519 return false;
9520 Opc[i % 2] = Opcode;
9521
9522 // Update InVec0 and InVec1.
9523 if (InVec0.isUndef()) {
9524 InVec0 = Op0.getOperand(0);
9525 if (InVec0.getSimpleValueType() != VT)
9526 return false;
9527 }
9528 if (InVec1.isUndef()) {
9529 InVec1 = Op1.getOperand(0);
9530 if (InVec1.getSimpleValueType() != VT)
9531 return false;
9532 }
9533
9534 // Make sure that operands in input to each add/sub node always
9535 // come from a same pair of vectors.
9536 if (InVec0 != Op0.getOperand(0)) {
9537 if (Opcode == ISD::FSUB)
9538 return false;
9539
9540 // FADD is commutable. Try to commute the operands
9541 // and then test again.
9542 std::swap(Op0, Op1);
9543 if (InVec0 != Op0.getOperand(0))
9544 return false;
9545 }
9546
9547 if (InVec1 != Op1.getOperand(0))
9548 return false;
9549
9550 // Increment the number of extractions done.
9551 ++NumExtracts;
9552 }
9553
9554 // Ensure we have found an opcode for both parities and that they are
9555 // different. Don't try to fold this build_vector into an ADDSUB/SUBADD if the
9556 // inputs are undef.
9557 if (!Opc[0] || !Opc[1] || Opc[0] == Opc[1] ||
9558 InVec0.isUndef() || InVec1.isUndef())
9559 return false;
9560
9561 IsSubAdd = Opc[0] == ISD::FADD;
9562
9563 Opnd0 = InVec0;
9564 Opnd1 = InVec1;
9565 return true;
9566}
9567
9568/// Returns true if is possible to fold MUL and an idiom that has already been
9569/// recognized as ADDSUB/SUBADD(\p Opnd0, \p Opnd1) into
9570/// FMADDSUB/FMSUBADD(x, y, \p Opnd1). If (and only if) true is returned, the
9571/// operands of FMADDSUB/FMSUBADD are written to parameters \p Opnd0, \p Opnd1, \p Opnd2.
9572///
9573/// Prior to calling this function it should be known that there is some
9574/// SDNode that potentially can be replaced with an X86ISD::ADDSUB operation
9575/// using \p Opnd0 and \p Opnd1 as operands. Also, this method is called
9576/// before replacement of such SDNode with ADDSUB operation. Thus the number
9577/// of \p Opnd0 uses is expected to be equal to 2.
9578/// For example, this function may be called for the following IR:
9579/// %AB = fmul fast <2 x double> %A, %B
9580/// %Sub = fsub fast <2 x double> %AB, %C
9581/// %Add = fadd fast <2 x double> %AB, %C
9582/// %Addsub = shufflevector <2 x double> %Sub, <2 x double> %Add,
9583/// <2 x i32> <i32 0, i32 3>
9584/// There is a def for %Addsub here, which potentially can be replaced by
9585/// X86ISD::ADDSUB operation:
9586/// %Addsub = X86ISD::ADDSUB %AB, %C
9587/// and such ADDSUB can further be replaced with FMADDSUB:
9588/// %Addsub = FMADDSUB %A, %B, %C.
9589///
9590/// The main reason why this method is called before the replacement of the
9591/// recognized ADDSUB idiom with ADDSUB operation is that such replacement
9592/// is illegal sometimes. E.g. 512-bit ADDSUB is not available, while 512-bit
9593/// FMADDSUB is.
9594static bool isFMAddSubOrFMSubAdd(const X86Subtarget &Subtarget,
9595 SelectionDAG &DAG,
9596 SDValue &Opnd0, SDValue &Opnd1, SDValue &Opnd2,
9597 unsigned ExpectedUses) {
9598 if (Opnd0.getOpcode() != ISD::FMUL ||
9599 !Opnd0->hasNUsesOfValue(ExpectedUses, 0) || !Subtarget.hasAnyFMA())
9600 return false;
9601
9602 // FIXME: These checks must match the similar ones in
9603 // DAGCombiner::visitFADDForFMACombine. It would be good to have one
9604 // function that would answer if it is Ok to fuse MUL + ADD to FMADD
9605 // or MUL + ADDSUB to FMADDSUB.
9606 const TargetOptions &Options = DAG.getTarget().Options;
9607 bool AllowFusion =
9608 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
9609 if (!AllowFusion)
9610 return false;
9611
9612 Opnd2 = Opnd1;
9613 Opnd1 = Opnd0.getOperand(1);
9614 Opnd0 = Opnd0.getOperand(0);
9615
9616 return true;
9617}
9618
9619/// Try to fold a build_vector that performs an 'addsub' or 'fmaddsub' or
9620/// 'fsubadd' operation accordingly to X86ISD::ADDSUB or X86ISD::FMADDSUB or
9621/// X86ISD::FMSUBADD node.
9622static SDValue lowerToAddSubOrFMAddSub(const BuildVectorSDNode *BV,
9623 const X86Subtarget &Subtarget,
9624 SelectionDAG &DAG) {
9625 SDValue Opnd0, Opnd1;
9626 unsigned NumExtracts;
9627 bool IsSubAdd;
9628 if (!isAddSubOrSubAdd(BV, Subtarget, DAG, Opnd0, Opnd1, NumExtracts,
9629 IsSubAdd))
9630 return SDValue();
9631
9632 MVT VT = BV->getSimpleValueType(0);
9633 SDLoc DL(BV);
9634
9635 // Try to generate X86ISD::FMADDSUB node here.
9636 SDValue Opnd2;
9637 if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, NumExtracts)) {
9638 unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
9639 return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
9640 }
9641
9642 // We only support ADDSUB.
9643 if (IsSubAdd)
9644 return SDValue();
9645
9646 // Do not generate X86ISD::ADDSUB node for 512-bit types even though
9647 // the ADDSUB idiom has been successfully recognized. There are no known
9648 // X86 targets with 512-bit ADDSUB instructions!
9649 // 512-bit ADDSUB idiom recognition was needed only as part of FMADDSUB idiom
9650 // recognition.
9651 if (VT.is512BitVector())
9652 return SDValue();
9653
9654 return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
9655}
9656
9657static bool isHopBuildVector(const BuildVectorSDNode *BV, SelectionDAG &DAG,
9658 unsigned &HOpcode, SDValue &V0, SDValue &V1) {
9659 // Initialize outputs to known values.
9660 MVT VT = BV->getSimpleValueType(0);
9661 HOpcode = ISD::DELETED_NODE;
9662 V0 = DAG.getUNDEF(VT);
9663 V1 = DAG.getUNDEF(VT);
9664
9665 // x86 256-bit horizontal ops are defined in a non-obvious way. Each 128-bit
9666 // half of the result is calculated independently from the 128-bit halves of
9667 // the inputs, so that makes the index-checking logic below more complicated.
9668 unsigned NumElts = VT.getVectorNumElements();
9669 unsigned GenericOpcode = ISD::DELETED_NODE;
9670 unsigned Num128BitChunks = VT.is256BitVector() ? 2 : 1;
9671 unsigned NumEltsIn128Bits = NumElts / Num128BitChunks;
9672 unsigned NumEltsIn64Bits = NumEltsIn128Bits / 2;
9673 for (unsigned i = 0; i != Num128BitChunks; ++i) {
9674 for (unsigned j = 0; j != NumEltsIn128Bits; ++j) {
9675 // Ignore undef elements.
9676 SDValue Op = BV->getOperand(i * NumEltsIn128Bits + j);
9677 if (Op.isUndef())
9678 continue;
9679
9680 // If there's an opcode mismatch, we're done.
9681 if (HOpcode != ISD::DELETED_NODE && Op.getOpcode() != GenericOpcode)
9682 return false;
9683
9684 // Initialize horizontal opcode.
9685 if (HOpcode == ISD::DELETED_NODE) {
9686 GenericOpcode = Op.getOpcode();
9687 switch (GenericOpcode) {
9688 case ISD::ADD: HOpcode = X86ISD::HADD; break;
9689 case ISD::SUB: HOpcode = X86ISD::HSUB; break;
9690 case ISD::FADD: HOpcode = X86ISD::FHADD; break;
9691 case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
9692 default: return false;
9693 }
9694 }
9695
9696 SDValue Op0 = Op.getOperand(0);
9697 SDValue Op1 = Op.getOperand(1);
9698 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9699 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9700 Op0.getOperand(0) != Op1.getOperand(0) ||
9701 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
9702 !isa<ConstantSDNode>(Op1.getOperand(1)) || !Op.hasOneUse())
9703 return false;
9704
9705 // The source vector is chosen based on which 64-bit half of the
9706 // destination vector is being calculated.
9707 if (j < NumEltsIn64Bits) {
9708 if (V0.isUndef())
9709 V0 = Op0.getOperand(0);
9710 } else {
9711 if (V1.isUndef())
9712 V1 = Op0.getOperand(0);
9713 }
9714
9715 SDValue SourceVec = (j < NumEltsIn64Bits) ? V0 : V1;
9716 if (SourceVec != Op0.getOperand(0))
9717 return false;
9718
9719 // op (extract_vector_elt A, I), (extract_vector_elt A, I+1)
9720 unsigned ExtIndex0 = Op0.getConstantOperandVal(1);
9721 unsigned ExtIndex1 = Op1.getConstantOperandVal(1);
9722 unsigned ExpectedIndex = i * NumEltsIn128Bits +
9723 (j % NumEltsIn64Bits) * 2;
9724 if (ExpectedIndex == ExtIndex0 && ExtIndex1 == ExtIndex0 + 1)
9725 continue;
9726
9727 // If this is not a commutative op, this does not match.
9728 if (GenericOpcode != ISD::ADD && GenericOpcode != ISD::FADD)
9729 return false;
9730
9731 // Addition is commutative, so try swapping the extract indexes.
9732 // op (extract_vector_elt A, I+1), (extract_vector_elt A, I)
9733 if (ExpectedIndex == ExtIndex1 && ExtIndex0 == ExtIndex1 + 1)
9734 continue;
9735
9736 // Extract indexes do not match horizontal requirement.
9737 return false;
9738 }
9739 }
9740 // We matched. Opcode and operands are returned by reference as arguments.
9741 return true;
9742}
9743
9744static SDValue getHopForBuildVector(const BuildVectorSDNode *BV,
9745 SelectionDAG &DAG, unsigned HOpcode,
9746 SDValue V0, SDValue V1) {
9747 // If either input vector is not the same size as the build vector,
9748 // extract/insert the low bits to the correct size.
9749 // This is free (examples: zmm --> xmm, xmm --> ymm).
9750 MVT VT = BV->getSimpleValueType(0);
9751 unsigned Width = VT.getSizeInBits();
9752 if (V0.getValueSizeInBits() > Width)
9753 V0 = extractSubVector(V0, 0, DAG, SDLoc(BV), Width);
9754 else if (V0.getValueSizeInBits() < Width)
9755 V0 = insertSubVector(DAG.getUNDEF(VT), V0, 0, DAG, SDLoc(BV), Width);
9756
9757 if (V1.getValueSizeInBits() > Width)
9758 V1 = extractSubVector(V1, 0, DAG, SDLoc(BV), Width);
9759 else if (V1.getValueSizeInBits() < Width)
9760 V1 = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, SDLoc(BV), Width);
9761
9762 unsigned NumElts = VT.getVectorNumElements();
9763 APInt DemandedElts = APInt::getAllOnesValue(NumElts);
9764 for (unsigned i = 0; i != NumElts; ++i)
9765 if (BV->getOperand(i).isUndef())
9766 DemandedElts.clearBit(i);
9767
9768 // If we don't need the upper xmm, then perform as a xmm hop.
9769 unsigned HalfNumElts = NumElts / 2;
9770 if (VT.is256BitVector() && DemandedElts.lshr(HalfNumElts) == 0) {
9771 MVT HalfVT = VT.getHalfNumVectorElementsVT();
9772 V0 = extractSubVector(V0, 0, DAG, SDLoc(BV), 128);
9773 V1 = extractSubVector(V1, 0, DAG, SDLoc(BV), 128);
9774 SDValue Half = DAG.getNode(HOpcode, SDLoc(BV), HalfVT, V0, V1);
9775 return insertSubVector(DAG.getUNDEF(VT), Half, 0, DAG, SDLoc(BV), 256);
9776 }
9777
9778 return DAG.getNode(HOpcode, SDLoc(BV), VT, V0, V1);
9779}
9780
9781/// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
9782static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
9783 const X86Subtarget &Subtarget,
9784 SelectionDAG &DAG) {
9785 // We need at least 2 non-undef elements to make this worthwhile by default.
9786 unsigned NumNonUndefs =
9787 count_if(BV->op_values(), [](SDValue V) { return !V.isUndef(); });
9788 if (NumNonUndefs < 2)
9789 return SDValue();
9790
9791 // There are 4 sets of horizontal math operations distinguished by type:
9792 // int/FP at 128-bit/256-bit. Each type was introduced with a different
9793 // subtarget feature. Try to match those "native" patterns first.
9794 MVT VT = BV->getSimpleValueType(0);
9795 if (((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget.hasSSE3()) ||
9796 ((VT == MVT::v8i16 || VT == MVT::v4i32) && Subtarget.hasSSSE3()) ||
9797 ((VT == MVT::v8f32 || VT == MVT::v4f64) && Subtarget.hasAVX()) ||
9798 ((VT == MVT::v16i16 || VT == MVT::v8i32) && Subtarget.hasAVX2())) {
9799 unsigned HOpcode;
9800 SDValue V0, V1;
9801 if (isHopBuildVector(BV, DAG, HOpcode, V0, V1))
9802 return getHopForBuildVector(BV, DAG, HOpcode, V0, V1);
9803 }
9804
9805 // Try harder to match 256-bit ops by using extract/concat.
9806 if (!Subtarget.hasAVX() || !VT.is256BitVector())
9807 return SDValue();
9808
9809 // Count the number of UNDEF operands in the build_vector in input.
9810 unsigned NumElts = VT.getVectorNumElements();
9811 unsigned Half = NumElts / 2;
9812 unsigned NumUndefsLO = 0;
9813 unsigned NumUndefsHI = 0;
9814 for (unsigned i = 0, e = Half; i != e; ++i)
9815 if (BV->getOperand(i)->isUndef())
9816 NumUndefsLO++;
9817
9818 for (unsigned i = Half, e = NumElts; i != e; ++i)
9819 if (BV->getOperand(i)->isUndef())
9820 NumUndefsHI++;
9821
9822 SDLoc DL(BV);
9823 SDValue InVec0, InVec1;
9824 if (VT == MVT::v8i32 || VT == MVT::v16i16) {
9825 SDValue InVec2, InVec3;
9826 unsigned X86Opcode;
9827 bool CanFold = true;
9828
9829 if (isHorizontalBinOpPart(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
9830 isHorizontalBinOpPart(BV, ISD::ADD, DAG, Half, NumElts, InVec2,
9831 InVec3) &&
9832 ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
9833 ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
9834 X86Opcode = X86ISD::HADD;
9835 else if (isHorizontalBinOpPart(BV, ISD::SUB, DAG, 0, Half, InVec0,
9836 InVec1) &&
9837 isHorizontalBinOpPart(BV, ISD::SUB, DAG, Half, NumElts, InVec2,
9838 InVec3) &&
9839 ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
9840 ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
9841 X86Opcode = X86ISD::HSUB;
9842 else
9843 CanFold = false;
9844
9845 if (CanFold) {
9846 // Do not try to expand this build_vector into a pair of horizontal
9847 // add/sub if we can emit a pair of scalar add/sub.
9848 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
9849 return SDValue();
9850
9851 // Convert this build_vector into a pair of horizontal binops followed by
9852 // a concat vector. We must adjust the outputs from the partial horizontal
9853 // matching calls above to account for undefined vector halves.
9854 SDValue V0 = InVec0.isUndef() ? InVec2 : InVec0;
9855 SDValue V1 = InVec1.isUndef() ? InVec3 : InVec1;
9856 assert((!V0.isUndef() || !V1.isUndef()) && "Horizontal-op of undefs?")(static_cast <bool> ((!V0.isUndef() || !V1.isUndef()) &&
"Horizontal-op of undefs?") ? void (0) : __assert_fail ("(!V0.isUndef() || !V1.isUndef()) && \"Horizontal-op of undefs?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 9856, __extension__ __PRETTY_FUNCTION__))
;
9857 bool isUndefLO = NumUndefsLO == Half;
9858 bool isUndefHI = NumUndefsHI == Half;
9859 return ExpandHorizontalBinOp(V0, V1, DL, DAG, X86Opcode, false, isUndefLO,
9860 isUndefHI);
9861 }
9862 }
9863
9864 if (VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
9865 VT == MVT::v16i16) {
9866 unsigned X86Opcode;
9867 if (isHorizontalBinOpPart(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
9868 X86Opcode = X86ISD::HADD;
9869 else if (isHorizontalBinOpPart(BV, ISD::SUB, DAG, 0, NumElts, InVec0,
9870 InVec1))
9871 X86Opcode = X86ISD::HSUB;
9872 else if (isHorizontalBinOpPart(BV, ISD::FADD, DAG, 0, NumElts, InVec0,
9873 InVec1))
9874 X86Opcode = X86ISD::FHADD;
9875 else if (isHorizontalBinOpPart(BV, ISD::FSUB, DAG, 0, NumElts, InVec0,
9876 InVec1))
9877 X86Opcode = X86ISD::FHSUB;
9878 else
9879 return SDValue();
9880
9881 // Don't try to expand this build_vector into a pair of horizontal add/sub
9882 // if we can simply emit a pair of scalar add/sub.
9883 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
9884 return SDValue();
9885
9886 // Convert this build_vector into two horizontal add/sub followed by
9887 // a concat vector.
9888 bool isUndefLO = NumUndefsLO == Half;
9889 bool isUndefHI = NumUndefsHI == Half;
9890 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
9891 isUndefLO, isUndefHI);
9892 }
9893
9894 return SDValue();
9895}
9896
9897static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
9898 SelectionDAG &DAG);
9899
9900/// If a BUILD_VECTOR's source elements all apply the same bit operation and
9901/// one of their operands is constant, lower to a pair of BUILD_VECTOR and
9902/// just apply the bit to the vectors.
9903/// NOTE: Its not in our interest to start make a general purpose vectorizer
9904/// from this, but enough scalar bit operations are created from the later
9905/// legalization + scalarization stages to need basic support.
9906static SDValue lowerBuildVectorToBitOp(BuildVectorSDNode *Op,
9907 const X86Subtarget &Subtarget,
9908 SelectionDAG &DAG) {
9909 SDLoc DL(Op);
9910 MVT VT = Op->getSimpleValueType(0);
9911 unsigned NumElems = VT.getVectorNumElements();
9912 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9913
9914 // Check that all elements have the same opcode.
9915 // TODO: Should we allow UNDEFS and if so how many?
9916 unsigned Opcode = Op->getOperand(0).getOpcode();
9917 for (unsigned i = 1; i < NumElems; ++i)
9918 if (Opcode != Op->getOperand(i).getOpcode())
9919 return SDValue();
9920
9921 // TODO: We may be able to add support for other Ops (ADD/SUB + shifts).
9922 bool IsShift = false;
9923 switch (Opcode) {
9924 default:
9925 return SDValue();
9926 case ISD::SHL:
9927 case ISD::SRL:
9928 case ISD::SRA:
9929 IsShift = true;
9930 break;
9931 case ISD::AND:
9932 case ISD::XOR:
9933 case ISD::OR:
9934 // Don't do this if the buildvector is a splat - we'd replace one
9935 // constant with an entire vector.
9936 if (Op->getSplatValue())
9937 return SDValue();
9938 if (!TLI.isOperationLegalOrPromote(Opcode, VT))
9939 return SDValue();
9940 break;
9941 }
9942
9943 SmallVector<SDValue, 4> LHSElts, RHSElts;
9944 for (SDValue Elt : Op->ops()) {
9945 SDValue LHS = Elt.getOperand(0);
9946 SDValue RHS = Elt.getOperand(1);
9947
9948 // We expect the canonicalized RHS operand to be the constant.
9949 if (!isa<ConstantSDNode>(RHS))
9950 return SDValue();
9951
9952 // Extend shift amounts.
9953 if (RHS.getValueSizeInBits() != VT.getScalarSizeInBits()) {
9954 if (!IsShift)
9955 return SDValue();
9956 RHS = DAG.getZExtOrTrunc(RHS, DL, VT.getScalarType());
9957 }
9958
9959 LHSElts.push_back(LHS);
9960 RHSElts.push_back(RHS);
9961 }
9962
9963 // Limit to shifts by uniform immediates.
9964 // TODO: Only accept vXi8/vXi64 special cases?
9965 // TODO: Permit non-uniform XOP/AVX2/MULLO cases?
9966 if (IsShift && any_of(RHSElts, [&](SDValue V) { return RHSElts[0] != V; }))
9967 return SDValue();
9968
9969 SDValue LHS = DAG.getBuildVector(VT, DL, LHSElts);
9970 SDValue RHS = DAG.getBuildVector(VT, DL, RHSElts);
9971 SDValue Res = DAG.getNode(Opcode, DL, VT, LHS, RHS);
9972
9973 if (!IsShift)
9974 return Res;
9975
9976 // Immediately lower the shift to ensure the constant build vector doesn't
9977 // get converted to a constant pool before the shift is lowered.
9978 return LowerShift(Res, Subtarget, DAG);
9979}
9980
9981/// Create a vector constant without a load. SSE/AVX provide the bare minimum
9982/// functionality to do this, so it's all zeros, all ones, or some derivation
9983/// that is cheap to calculate.
9984static SDValue materializeVectorConstant(SDValue Op, SelectionDAG &DAG,
9985 const X86Subtarget &Subtarget) {
9986 SDLoc DL(Op);
9987 MVT VT = Op.getSimpleValueType();
9988
9989 // Vectors containing all zeros can be matched by pxor and xorps.
9990 if (ISD::isBuildVectorAllZeros(Op.getNode()))
9991 return Op;
9992
9993 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
9994 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
9995 // vpcmpeqd on 256-bit vectors.
9996 if (Subtarget.hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
9997 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
9998 return Op;
9999
10000 return getOnesVector(VT, DAG, DL);
10001 }
10002
10003 return SDValue();
10004}
10005
10006/// Look for opportunities to create a VPERMV/VPERMILPV/PSHUFB variable permute
10007/// from a vector of source values and a vector of extraction indices.
10008/// The vectors might be manipulated to match the type of the permute op.
10009static SDValue createVariablePermute(MVT VT, SDValue SrcVec, SDValue IndicesVec,
10010 SDLoc &DL, SelectionDAG &DAG,
10011 const X86Subtarget &Subtarget) {
10012 MVT ShuffleVT = VT;
10013 EVT IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
10014 unsigned NumElts = VT.getVectorNumElements();
10015 unsigned SizeInBits = VT.getSizeInBits();
10016
10017 // Adjust IndicesVec to match VT size.
10018 assert(IndicesVec.getValueType().getVectorNumElements() >= NumElts &&(static_cast <bool> (IndicesVec.getValueType().getVectorNumElements
() >= NumElts && "Illegal variable permute mask size"
) ? void (0) : __assert_fail ("IndicesVec.getValueType().getVectorNumElements() >= NumElts && \"Illegal variable permute mask size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10019, __extension__ __PRETTY_FUNCTION__))
10019 "Illegal variable permute mask size")(static_cast <bool> (IndicesVec.getValueType().getVectorNumElements
() >= NumElts && "Illegal variable permute mask size"
) ? void (0) : __assert_fail ("IndicesVec.getValueType().getVectorNumElements() >= NumElts && \"Illegal variable permute mask size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10019, __extension__ __PRETTY_FUNCTION__))
;
10020 if (IndicesVec.getValueType().getVectorNumElements() > NumElts) {
10021 // Narrow/widen the indices vector to the correct size.
10022 if (IndicesVec.getValueSizeInBits() > SizeInBits)
10023 IndicesVec = extractSubVector(IndicesVec, 0, DAG, SDLoc(IndicesVec),
10024 NumElts * VT.getScalarSizeInBits());
10025 else if (IndicesVec.getValueSizeInBits() < SizeInBits)
10026 IndicesVec = widenSubVector(IndicesVec, false, Subtarget, DAG,
10027 SDLoc(IndicesVec), SizeInBits);
10028 // Zero-extend the index elements within the vector.
10029 if (IndicesVec.getValueType().getVectorNumElements() > NumElts)
10030 IndicesVec = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(IndicesVec),
10031 IndicesVT, IndicesVec);
10032 }
10033 IndicesVec = DAG.getZExtOrTrunc(IndicesVec, SDLoc(IndicesVec), IndicesVT);
10034
10035 // Handle SrcVec that don't match VT type.
10036 if (SrcVec.getValueSizeInBits() != SizeInBits) {
10037 if ((SrcVec.getValueSizeInBits() % SizeInBits) == 0) {
10038 // Handle larger SrcVec by treating it as a larger permute.
10039 unsigned Scale = SrcVec.getValueSizeInBits() / SizeInBits;
10040 VT = MVT::getVectorVT(VT.getScalarType(), Scale * NumElts);
10041 IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
10042 IndicesVec = widenSubVector(IndicesVT.getSimpleVT(), IndicesVec, false,
10043 Subtarget, DAG, SDLoc(IndicesVec));
10044 SDValue NewSrcVec =
10045 createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
10046 if (NewSrcVec)
10047 return extractSubVector(NewSrcVec, 0, DAG, DL, SizeInBits);
10048 return SDValue();
10049 } else if (SrcVec.getValueSizeInBits() < SizeInBits) {
10050 // Widen smaller SrcVec to match VT.
10051 SrcVec = widenSubVector(VT, SrcVec, false, Subtarget, DAG, SDLoc(SrcVec));
10052 } else
10053 return SDValue();
10054 }
10055
10056 auto ScaleIndices = [&DAG](SDValue Idx, uint64_t Scale) {
10057 assert(isPowerOf2_64(Scale) && "Illegal variable permute shuffle scale")(static_cast <bool> (isPowerOf2_64(Scale) && "Illegal variable permute shuffle scale"
) ? void (0) : __assert_fail ("isPowerOf2_64(Scale) && \"Illegal variable permute shuffle scale\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10057, __extension__ __PRETTY_FUNCTION__))
;
10058 EVT SrcVT = Idx.getValueType();
10059 unsigned NumDstBits = SrcVT.getScalarSizeInBits() / Scale;
10060 uint64_t IndexScale = 0;
10061 uint64_t IndexOffset = 0;
10062
10063 // If we're scaling a smaller permute op, then we need to repeat the
10064 // indices, scaling and offsetting them as well.
10065 // e.g. v4i32 -> v16i8 (Scale = 4)
10066 // IndexScale = v4i32 Splat(4 << 24 | 4 << 16 | 4 << 8 | 4)
10067 // IndexOffset = v4i32 Splat(3 << 24 | 2 << 16 | 1 << 8 | 0)
10068 for (uint64_t i = 0; i != Scale; ++i) {
10069 IndexScale |= Scale << (i * NumDstBits);
10070 IndexOffset |= i << (i * NumDstBits);
10071 }
10072
10073 Idx = DAG.getNode(ISD::MUL, SDLoc(Idx), SrcVT, Idx,
10074 DAG.getConstant(IndexScale, SDLoc(Idx), SrcVT));
10075 Idx = DAG.getNode(ISD::ADD, SDLoc(Idx), SrcVT, Idx,
10076 DAG.getConstant(IndexOffset, SDLoc(Idx), SrcVT));
10077 return Idx;
10078 };
10079
10080 unsigned Opcode = 0;
10081 switch (VT.SimpleTy) {
10082 default:
10083 break;
10084 case MVT::v16i8:
10085 if (Subtarget.hasSSSE3())
10086 Opcode = X86ISD::PSHUFB;
10087 break;
10088 case MVT::v8i16:
10089 if (Subtarget.hasVLX() && Subtarget.hasBWI())
10090 Opcode = X86ISD::VPERMV;
10091 else if (Subtarget.hasSSSE3()) {
10092 Opcode = X86ISD::PSHUFB;
10093 ShuffleVT = MVT::v16i8;
10094 }
10095 break;
10096 case MVT::v4f32:
10097 case MVT::v4i32:
10098 if (Subtarget.hasAVX()) {
10099 Opcode = X86ISD::VPERMILPV;
10100 ShuffleVT = MVT::v4f32;
10101 } else if (Subtarget.hasSSSE3()) {
10102 Opcode = X86ISD::PSHUFB;
10103 ShuffleVT = MVT::v16i8;
10104 }
10105 break;
10106 case MVT::v2f64:
10107 case MVT::v2i64:
10108 if (Subtarget.hasAVX()) {
10109 // VPERMILPD selects using bit#1 of the index vector, so scale IndicesVec.
10110 IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
10111 Opcode = X86ISD::VPERMILPV;
10112 ShuffleVT = MVT::v2f64;
10113 } else if (Subtarget.hasSSE41()) {
10114 // SSE41 can compare v2i64 - select between indices 0 and 1.
10115 return DAG.getSelectCC(
10116 DL, IndicesVec,
10117 getZeroVector(IndicesVT.getSimpleVT(), Subtarget, DAG, DL),
10118 DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {0, 0}),
10119 DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {1, 1}),
10120 ISD::CondCode::SETEQ);
10121 }
10122 break;
10123 case MVT::v32i8:
10124 if (Subtarget.hasVLX() && Subtarget.hasVBMI())
10125 Opcode = X86ISD::VPERMV;
10126 else if (Subtarget.hasXOP()) {
10127 SDValue LoSrc = extract128BitVector(SrcVec, 0, DAG, DL);
10128 SDValue HiSrc = extract128BitVector(SrcVec, 16, DAG, DL);
10129 SDValue LoIdx = extract128BitVector(IndicesVec, 0, DAG, DL);
10130 SDValue HiIdx = extract128BitVector(IndicesVec, 16, DAG, DL);
10131 return DAG.getNode(
10132 ISD::CONCAT_VECTORS, DL, VT,
10133 DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, LoIdx),
10134 DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, HiIdx));
10135 } else if (Subtarget.hasAVX()) {
10136 SDValue Lo = extract128BitVector(SrcVec, 0, DAG, DL);
10137 SDValue Hi = extract128BitVector(SrcVec, 16, DAG, DL);
10138 SDValue LoLo = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Lo);
10139 SDValue HiHi = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Hi, Hi);
10140 auto PSHUFBBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
10141 ArrayRef<SDValue> Ops) {
10142 // Permute Lo and Hi and then select based on index range.
10143 // This works as SHUFB uses bits[3:0] to permute elements and we don't
10144 // care about the bit[7] as its just an index vector.
10145 SDValue Idx = Ops[2];
10146 EVT VT = Idx.getValueType();
10147 return DAG.getSelectCC(DL, Idx, DAG.getConstant(15, DL, VT),
10148 DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[1], Idx),
10149 DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[0], Idx),
10150 ISD::CondCode::SETGT);
10151 };
10152 SDValue Ops[] = {LoLo, HiHi, IndicesVec};
10153 return SplitOpsAndApply(DAG, Subtarget, DL, MVT::v32i8, Ops,
10154 PSHUFBBuilder);
10155 }
10156 break;
10157 case MVT::v16i16:
10158 if (Subtarget.hasVLX() && Subtarget.hasBWI())
10159 Opcode = X86ISD::VPERMV;
10160 else if (Subtarget.hasAVX()) {
10161 // Scale to v32i8 and perform as v32i8.
10162 IndicesVec = ScaleIndices(IndicesVec, 2);
10163 return DAG.getBitcast(
10164 VT, createVariablePermute(
10165 MVT::v32i8, DAG.getBitcast(MVT::v32i8, SrcVec),
10166 DAG.getBitcast(MVT::v32i8, IndicesVec), DL, DAG, Subtarget));
10167 }
10168 break;
10169 case MVT::v8f32:
10170 case MVT::v8i32:
10171 if (Subtarget.hasAVX2())
10172 Opcode = X86ISD::VPERMV;
10173 else if (Subtarget.hasAVX()) {
10174 SrcVec = DAG.getBitcast(MVT::v8f32, SrcVec);
10175 SDValue LoLo = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
10176 {0, 1, 2, 3, 0, 1, 2, 3});
10177 SDValue HiHi = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
10178 {4, 5, 6, 7, 4, 5, 6, 7});
10179 if (Subtarget.hasXOP())
10180 return DAG.getBitcast(
10181 VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v8f32, LoLo, HiHi,
10182 IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
10183 // Permute Lo and Hi and then select based on index range.
10184 // This works as VPERMILPS only uses index bits[0:1] to permute elements.
10185 SDValue Res = DAG.getSelectCC(
10186 DL, IndicesVec, DAG.getConstant(3, DL, MVT::v8i32),
10187 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, HiHi, IndicesVec),
10188 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, LoLo, IndicesVec),
10189 ISD::CondCode::SETGT);
10190 return DAG.getBitcast(VT, Res);
10191 }
10192 break;
10193 case MVT::v4i64:
10194 case MVT::v4f64:
10195 if (Subtarget.hasAVX512()) {
10196 if (!Subtarget.hasVLX()) {
10197 MVT WidenSrcVT = MVT::getVectorVT(VT.getScalarType(), 8);
10198 SrcVec = widenSubVector(WidenSrcVT, SrcVec, false, Subtarget, DAG,
10199 SDLoc(SrcVec));
10200 IndicesVec = widenSubVector(MVT::v8i64, IndicesVec, false, Subtarget,
10201 DAG, SDLoc(IndicesVec));
10202 SDValue Res = createVariablePermute(WidenSrcVT, SrcVec, IndicesVec, DL,
10203 DAG, Subtarget);
10204 return extract256BitVector(Res, 0, DAG, DL);
10205 }
10206 Opcode = X86ISD::VPERMV;
10207 } else if (Subtarget.hasAVX()) {
10208 SrcVec = DAG.getBitcast(MVT::v4f64, SrcVec);
10209 SDValue LoLo =
10210 DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {0, 1, 0, 1});
10211 SDValue HiHi =
10212 DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {2, 3, 2, 3});
10213 // VPERMIL2PD selects with bit#1 of the index vector, so scale IndicesVec.
10214 IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
10215 if (Subtarget.hasXOP())
10216 return DAG.getBitcast(
10217 VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v4f64, LoLo, HiHi,
10218 IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
10219 // Permute Lo and Hi and then select based on index range.
10220 // This works as VPERMILPD only uses index bit[1] to permute elements.
10221 SDValue Res = DAG.getSelectCC(
10222 DL, IndicesVec, DAG.getConstant(2, DL, MVT::v4i64),
10223 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, HiHi, IndicesVec),
10224 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, LoLo, IndicesVec),
10225 ISD::CondCode::SETGT);
10226 return DAG.getBitcast(VT, Res);
10227 }
10228 break;
10229 case MVT::v64i8:
10230 if (Subtarget.hasVBMI())
10231 Opcode = X86ISD::VPERMV;
10232 break;
10233 case MVT::v32i16:
10234 if (Subtarget.hasBWI())
10235 Opcode = X86ISD::VPERMV;
10236 break;
10237 case MVT::v16f32:
10238 case MVT::v16i32:
10239 case MVT::v8f64:
10240 case MVT::v8i64:
10241 if (Subtarget.hasAVX512())
10242 Opcode = X86ISD::VPERMV;
10243 break;
10244 }
10245 if (!Opcode)
10246 return SDValue();
10247
10248 assert((VT.getSizeInBits() == ShuffleVT.getSizeInBits()) &&(static_cast <bool> ((VT.getSizeInBits() == ShuffleVT.getSizeInBits
()) && (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits
()) == 0 && "Illegal variable permute shuffle type") ?
void (0) : __assert_fail ("(VT.getSizeInBits() == ShuffleVT.getSizeInBits()) && (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits()) == 0 && \"Illegal variable permute shuffle type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10250, __extension__ __PRETTY_FUNCTION__))
10249 (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits()) == 0 &&(static_cast <bool> ((VT.getSizeInBits() == ShuffleVT.getSizeInBits
()) && (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits
()) == 0 && "Illegal variable permute shuffle type") ?
void (0) : __assert_fail ("(VT.getSizeInBits() == ShuffleVT.getSizeInBits()) && (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits()) == 0 && \"Illegal variable permute shuffle type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10250, __extension__ __PRETTY_FUNCTION__))
10250 "Illegal variable permute shuffle type")(static_cast <bool> ((VT.getSizeInBits() == ShuffleVT.getSizeInBits
()) && (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits
()) == 0 && "Illegal variable permute shuffle type") ?
void (0) : __assert_fail ("(VT.getSizeInBits() == ShuffleVT.getSizeInBits()) && (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits()) == 0 && \"Illegal variable permute shuffle type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10250, __extension__ __PRETTY_FUNCTION__))
;
10251
10252 uint64_t Scale = VT.getScalarSizeInBits() / ShuffleVT.getScalarSizeInBits();
10253 if (Scale > 1)
10254 IndicesVec = ScaleIndices(IndicesVec, Scale);
10255
10256 EVT ShuffleIdxVT = EVT(ShuffleVT).changeVectorElementTypeToInteger();
10257 IndicesVec = DAG.getBitcast(ShuffleIdxVT, IndicesVec);
10258
10259 SrcVec = DAG.getBitcast(ShuffleVT, SrcVec);
10260 SDValue Res = Opcode == X86ISD::VPERMV
10261 ? DAG.getNode(Opcode, DL, ShuffleVT, IndicesVec, SrcVec)
10262 : DAG.getNode(Opcode, DL, ShuffleVT, SrcVec, IndicesVec);
10263 return DAG.getBitcast(VT, Res);
10264}
10265
10266// Tries to lower a BUILD_VECTOR composed of extract-extract chains that can be
10267// reasoned to be a permutation of a vector by indices in a non-constant vector.
10268// (build_vector (extract_elt V, (extract_elt I, 0)),
10269// (extract_elt V, (extract_elt I, 1)),
10270// ...
10271// ->
10272// (vpermv I, V)
10273//
10274// TODO: Handle undefs
10275// TODO: Utilize pshufb and zero mask blending to support more efficient
10276// construction of vectors with constant-0 elements.
10277static SDValue
10278LowerBUILD_VECTORAsVariablePermute(SDValue V, SelectionDAG &DAG,
10279 const X86Subtarget &Subtarget) {
10280 SDValue SrcVec, IndicesVec;
10281 // Check for a match of the permute source vector and permute index elements.
10282 // This is done by checking that the i-th build_vector operand is of the form:
10283 // (extract_elt SrcVec, (extract_elt IndicesVec, i)).
10284 for (unsigned Idx = 0, E = V.getNumOperands(); Idx != E; ++Idx) {
10285 SDValue Op = V.getOperand(Idx);
10286 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10287 return SDValue();
10288
10289 // If this is the first extract encountered in V, set the source vector,
10290 // otherwise verify the extract is from the previously defined source
10291 // vector.
10292 if (!SrcVec)
10293 SrcVec = Op.getOperand(0);
10294 else if (SrcVec != Op.getOperand(0))
10295 return SDValue();
10296 SDValue ExtractedIndex = Op->getOperand(1);
10297 // Peek through extends.
10298 if (ExtractedIndex.getOpcode() == ISD::ZERO_EXTEND ||
10299 ExtractedIndex.getOpcode() == ISD::SIGN_EXTEND)
10300 ExtractedIndex = ExtractedIndex.getOperand(0);
10301 if (ExtractedIndex.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10302 return SDValue();
10303
10304 // If this is the first extract from the index vector candidate, set the
10305 // indices vector, otherwise verify the extract is from the previously
10306 // defined indices vector.
10307 if (!IndicesVec)
10308 IndicesVec = ExtractedIndex.getOperand(0);
10309 else if (IndicesVec != ExtractedIndex.getOperand(0))
10310 return SDValue();
10311
10312 auto *PermIdx = dyn_cast<ConstantSDNode>(ExtractedIndex.getOperand(1));
10313 if (!PermIdx || PermIdx->getAPIntValue() != Idx)
10314 return SDValue();
10315 }
10316
10317 SDLoc DL(V);
10318 MVT VT = V.getSimpleValueType();
10319 return createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
10320}
10321
10322SDValue
10323X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
10324 SDLoc dl(Op);
10325
10326 MVT VT = Op.getSimpleValueType();
10327 MVT EltVT = VT.getVectorElementType();
10328 unsigned NumElems = Op.getNumOperands();
10329
10330 // Generate vectors for predicate vectors.
10331 if (VT.getVectorElementType() == MVT::i1 && Subtarget.hasAVX512())
1
Taking false branch
10332 return LowerBUILD_VECTORvXi1(Op, DAG, Subtarget);
10333
10334 if (SDValue VectorConstant = materializeVectorConstant(Op, DAG, Subtarget))
2
Taking false branch
10335 return VectorConstant;
10336
10337 unsigned EVTBits = EltVT.getSizeInBits();
10338 APInt UndefMask = APInt::getNullValue(NumElems);
10339 APInt ZeroMask = APInt::getNullValue(NumElems);
10340 APInt NonZeroMask = APInt::getNullValue(NumElems);
10341 bool IsAllConstants = true;
10342 SmallSet<SDValue, 8> Values;
10343 unsigned NumConstants = NumElems;
10344 for (unsigned i = 0; i
2.1
'i' is < 'NumElems'
2.1
'i' is < 'NumElems'
2.1
'i' is < 'NumElems'
< NumElems
; ++i) {
3
Loop condition is true. Entering loop body
8
Assuming 'i' is >= 'NumElems'
9
Loop condition is false. Execution continues on line 10363
10345 SDValue Elt = Op.getOperand(i);
10346 if (Elt.isUndef()) {
4
Taking false branch
10347 UndefMask.setBit(i);
10348 continue;
10349 }
10350 Values.insert(Elt);
10351 if (!isa<ConstantSDNode>(Elt) && !isa<ConstantFPSDNode>(Elt)) {
5
Assuming 'Elt' is a 'ConstantSDNode'
10352 IsAllConstants = false;
10353 NumConstants--;
10354 }
10355 if (X86::isZeroNode(Elt)) {
6
Assuming the condition is false
7
Taking false branch
10356 ZeroMask.setBit(i);
10357 } else {
10358 NonZeroMask.setBit(i);
10359 }
10360 }
10361
10362 // All undef vector. Return an UNDEF. All zero vectors were handled above.
10363 if (NonZeroMask == 0) {
10
Taking false branch
10364 assert(UndefMask.isAllOnesValue() && "Fully undef mask expected")(static_cast <bool> (UndefMask.isAllOnesValue() &&
"Fully undef mask expected") ? void (0) : __assert_fail ("UndefMask.isAllOnesValue() && \"Fully undef mask expected\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10364, __extension__ __PRETTY_FUNCTION__))
;
10365 return DAG.getUNDEF(VT);
10366 }
10367
10368 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
11
The object is a 'BuildVectorSDNode'
10369
10370 // If the upper elts of a ymm/zmm are undef/zero then we might be better off
10371 // lowering to a smaller build vector and padding with undef/zero.
10372 if ((VT.is256BitVector() || VT.is512BitVector()) &&
10373 !isFoldableUseOfShuffle(BV)) {
10374 unsigned UpperElems = NumElems / 2;
10375 APInt UndefOrZeroMask = UndefMask | ZeroMask;
10376 unsigned NumUpperUndefsOrZeros = UndefOrZeroMask.countLeadingOnes();
10377 if (NumUpperUndefsOrZeros >= UpperElems) {
10378 if (VT.is512BitVector() &&
10379 NumUpperUndefsOrZeros >= (NumElems - (NumElems / 4)))
10380 UpperElems = NumElems - (NumElems / 4);
10381 bool UndefUpper = UndefMask.countLeadingOnes() >= UpperElems;
10382 MVT LowerVT = MVT::getVectorVT(EltVT, NumElems - UpperElems);
10383 SDValue NewBV =
10384 DAG.getBuildVector(LowerVT, dl, Op->ops().drop_back(UpperElems));
10385 return widenSubVector(VT, NewBV, !UndefUpper, Subtarget, DAG, dl);
10386 }
10387 }
10388
10389 if (SDValue AddSub = lowerToAddSubOrFMAddSub(BV, Subtarget, DAG))
12
Taking false branch
10390 return AddSub;
10391 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
13
Taking false branch
10392 return HorizontalOp;
10393 if (SDValue Broadcast = lowerBuildVectorAsBroadcast(BV, Subtarget, DAG))
14
Taking false branch
10394 return Broadcast;
10395 if (SDValue BitOp = lowerBuildVectorToBitOp(BV, Subtarget, DAG))
15
Taking false branch
10396 return BitOp;
10397
10398 unsigned NumZero = ZeroMask.countPopulation();
10399 unsigned NumNonZero = NonZeroMask.countPopulation();
10400
10401 // If we are inserting one variable into a vector of non-zero constants, try
10402 // to avoid loading each constant element as a scalar. Load the constants as a
10403 // vector and then insert the variable scalar element. If insertion is not
10404 // supported, fall back to a shuffle to get the scalar blended with the
10405 // constants. Insertion into a zero vector is handled as a special-case
10406 // somewhere below here.
10407 if (NumConstants == NumElems - 1 && NumNonZero != 1 &&
16
Taking false branch
10408 (isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT) ||
10409 isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))) {
10410 // Create an all-constant vector. The variable element in the old
10411 // build vector is replaced by undef in the constant vector. Save the
10412 // variable scalar element and its index for use in the insertelement.
10413 LLVMContext &Context = *DAG.getContext();
10414 Type *EltType = Op.getValueType().getScalarType().getTypeForEVT(Context);
10415 SmallVector<Constant *, 16> ConstVecOps(NumElems, UndefValue::get(EltType));
10416 SDValue VarElt;
10417 SDValue InsIndex;
10418 for (unsigned i = 0; i != NumElems; ++i) {
10419 SDValue Elt = Op.getOperand(i);
10420 if (auto *C = dyn_cast<ConstantSDNode>(Elt))
10421 ConstVecOps[i] = ConstantInt::get(Context, C->getAPIntValue());
10422 else if (auto *C = dyn_cast<ConstantFPSDNode>(Elt))
10423 ConstVecOps[i] = ConstantFP::get(Context, C->getValueAPF());
10424 else if (!Elt.isUndef()) {
10425 assert(!VarElt.getNode() && !InsIndex.getNode() &&(static_cast <bool> (!VarElt.getNode() && !InsIndex
.getNode() && "Expected one variable element in this vector"
) ? void (0) : __assert_fail ("!VarElt.getNode() && !InsIndex.getNode() && \"Expected one variable element in this vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10426, __extension__ __PRETTY_FUNCTION__))
10426 "Expected one variable element in this vector")(static_cast <bool> (!VarElt.getNode() && !InsIndex
.getNode() && "Expected one variable element in this vector"
) ? void (0) : __assert_fail ("!VarElt.getNode() && !InsIndex.getNode() && \"Expected one variable element in this vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10426, __extension__ __PRETTY_FUNCTION__))
;
10427 VarElt = Elt;
10428 InsIndex = DAG.getVectorIdxConstant(i, dl);
10429 }
10430 }
10431 Constant *CV = ConstantVector::get(ConstVecOps);
10432 SDValue DAGConstVec = DAG.getConstantPool(CV, VT);
10433
10434 // The constants we just created may not be legal (eg, floating point). We
10435 // must lower the vector right here because we can not guarantee that we'll
10436 // legalize it before loading it. This is also why we could not just create
10437 // a new build vector here. If the build vector contains illegal constants,
10438 // it could get split back up into a series of insert elements.
10439 // TODO: Improve this by using shorter loads with broadcast/VZEXT_LOAD.
10440 SDValue LegalDAGConstVec = LowerConstantPool(DAGConstVec, DAG);
10441 MachineFunction &MF = DAG.getMachineFunction();
10442 MachinePointerInfo MPI = MachinePointerInfo::getConstantPool(MF);
10443 SDValue Ld = DAG.getLoad(VT, dl, DAG.getEntryNode(), LegalDAGConstVec, MPI);
10444 unsigned InsertC = cast<ConstantSDNode>(InsIndex)->getZExtValue();
10445 unsigned NumEltsInLow128Bits = 128 / VT.getScalarSizeInBits();
10446 if (InsertC < NumEltsInLow128Bits)
10447 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ld, VarElt, InsIndex);
10448
10449 // There's no good way to insert into the high elements of a >128-bit
10450 // vector, so use shuffles to avoid an extract/insert sequence.
10451 assert(VT.getSizeInBits() > 128 && "Invalid insertion index?")(static_cast <bool> (VT.getSizeInBits() > 128 &&
"Invalid insertion index?") ? void (0) : __assert_fail ("VT.getSizeInBits() > 128 && \"Invalid insertion index?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10451, __extension__ __PRETTY_FUNCTION__))
;
10452 assert(Subtarget.hasAVX() && "Must have AVX with >16-byte vector")(static_cast <bool> (Subtarget.hasAVX() && "Must have AVX with >16-byte vector"
) ? void (0) : __assert_fail ("Subtarget.hasAVX() && \"Must have AVX with >16-byte vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10452, __extension__ __PRETTY_FUNCTION__))
;
10453 SmallVector<int, 8> ShuffleMask;
10454 unsigned NumElts = VT.getVectorNumElements();
10455 for (unsigned i = 0; i != NumElts; ++i)
10456 ShuffleMask.push_back(i == InsertC ? NumElts : i);
10457 SDValue S2V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, VarElt);
10458 return DAG.getVectorShuffle(VT, dl, Ld, S2V, ShuffleMask);
10459 }
10460
10461 // Special case for single non-zero, non-undef, element.
10462 if (NumNonZero == 1) {
17
Assuming 'NumNonZero' is not equal to 1
18
Taking false branch
10463 unsigned Idx = NonZeroMask.countTrailingZeros();
10464 SDValue Item = Op.getOperand(Idx);
10465
10466 // If we have a constant or non-constant insertion into the low element of
10467 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
10468 // the rest of the elements. This will be matched as movd/movq/movss/movsd
10469 // depending on what the source datatype is.
10470 if (Idx == 0) {
10471 if (NumZero == 0)
10472 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
10473
10474 if (EltVT == MVT::i32 || EltVT == MVT::f32 || EltVT == MVT::f64 ||
10475 (EltVT == MVT::i64 && Subtarget.is64Bit())) {
10476 assert((VT.is128BitVector() || VT.is256BitVector() ||(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector()) && "Expected an SSE value type!"
) ? void (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Expected an SSE value type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10478, __extension__ __PRETTY_FUNCTION__))
10477 VT.is512BitVector()) &&(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector()) && "Expected an SSE value type!"
) ? void (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Expected an SSE value type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10478, __extension__ __PRETTY_FUNCTION__))
10478 "Expected an SSE value type!")(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector()) && "Expected an SSE value type!"
) ? void (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Expected an SSE value type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10478, __extension__ __PRETTY_FUNCTION__))
;
10479 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
10480 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
10481 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
10482 }
10483
10484 // We can't directly insert an i8 or i16 into a vector, so zero extend
10485 // it to i32 first.
10486 if (EltVT == MVT::i16 || EltVT == MVT::i8) {
10487 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
10488 MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
10489 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, Item);
10490 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
10491 return DAG.getBitcast(VT, Item);
10492 }
10493 }
10494
10495 // Is it a vector logical left shift?
10496 if (NumElems == 2 && Idx == 1 &&
10497 X86::isZeroNode(Op.getOperand(0)) &&
10498 !X86::isZeroNode(Op.getOperand(1))) {
10499 unsigned NumBits = VT.getSizeInBits();
10500 return getVShift(true, VT,
10501 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10502 VT, Op.getOperand(1)),
10503 NumBits/2, DAG, *this, dl);
10504 }
10505
10506 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
10507 return SDValue();
10508
10509 // Otherwise, if this is a vector with i32 or f32 elements, and the element
10510 // is a non-constant being inserted into an element other than the low one,
10511 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
10512 // movd/movss) to move this into the low element, then shuffle it into
10513 // place.
10514 if (EVTBits == 32) {
10515 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
10516 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
10517 }
10518 }
10519
10520 // Splat is obviously ok. Let legalizer expand it to a shuffle.
10521 if (Values.size() == 1) {
19
Assuming the condition is true
20
Taking true branch
10522 if (EVTBits == 32) {
21
Assuming 'EVTBits' is equal to 32
22
Taking true branch
10523 // Instead of a shuffle like this:
10524 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
10525 // Check if it's possible to issue this instead.
10526 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
10527 unsigned Idx = NonZeroMask.countTrailingZeros();
10528 SDValue Item = Op.getOperand(Idx);
10529 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
23
Assuming the condition is true
24
Taking true branch
10530 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
25
Calling 'LowerAsSplatVectorLoad'
10531 }
10532 return SDValue();
10533 }
10534
10535 // A vector full of immediates; various special cases are already
10536 // handled, so this is best done with a single constant-pool load.
10537 if (IsAllConstants)
10538 return SDValue();
10539
10540 if (SDValue V = LowerBUILD_VECTORAsVariablePermute(Op, DAG, Subtarget))
10541 return V;
10542
10543 // See if we can use a vector load to get all of the elements.
10544 {
10545 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElems);
10546 if (SDValue LD =
10547 EltsFromConsecutiveLoads(VT, Ops, dl, DAG, Subtarget, false))
10548 return LD;
10549 }
10550
10551 // If this is a splat of pairs of 32-bit elements, we can use a narrower
10552 // build_vector and broadcast it.
10553 // TODO: We could probably generalize this more.
10554 if (Subtarget.hasAVX2() && EVTBits == 32 && Values.size() == 2) {
10555 SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
10556 DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
10557 auto CanSplat = [](SDValue Op, unsigned NumElems, ArrayRef<SDValue> Ops) {
10558 // Make sure all the even/odd operands match.
10559 for (unsigned i = 2; i != NumElems; ++i)
10560 if (Ops[i % 2] != Op.getOperand(i))
10561 return false;
10562 return true;
10563 };
10564 if (CanSplat(Op, NumElems, Ops)) {
10565 MVT WideEltVT = VT.isFloatingPoint() ? MVT::f64 : MVT::i64;
10566 MVT NarrowVT = MVT::getVectorVT(EltVT, 4);
10567 // Create a new build vector and cast to v2i64/v2f64.
10568 SDValue NewBV = DAG.getBitcast(MVT::getVectorVT(WideEltVT, 2),
10569 DAG.getBuildVector(NarrowVT, dl, Ops));
10570 // Broadcast from v2i64/v2f64 and cast to final VT.
10571 MVT BcastVT = MVT::getVectorVT(WideEltVT, NumElems / 2);
10572 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, dl, BcastVT,
10573 NewBV));
10574 }
10575 }
10576
10577 // For AVX-length vectors, build the individual 128-bit pieces and use
10578 // shuffles to put them in place.
10579 if (VT.getSizeInBits() > 128) {
10580 MVT HVT = MVT::getVectorVT(EltVT, NumElems / 2);
10581
10582 // Build both the lower and upper subvector.
10583 SDValue Lower =
10584 DAG.getBuildVector(HVT, dl, Op->ops().slice(0, NumElems / 2));
10585 SDValue Upper = DAG.getBuildVector(
10586 HVT, dl, Op->ops().slice(NumElems / 2, NumElems /2));
10587
10588 // Recreate the wider vector with the lower and upper part.
10589 return concatSubVectors(Lower, Upper, DAG, dl);
10590 }
10591
10592 // Let legalizer expand 2-wide build_vectors.
10593 if (EVTBits == 64) {
10594 if (NumNonZero == 1) {
10595 // One half is zero or undef.
10596 unsigned Idx = NonZeroMask.countTrailingZeros();
10597 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
10598 Op.getOperand(Idx));
10599 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
10600 }
10601 return SDValue();
10602 }
10603
10604 // If element VT is < 32 bits, convert it to inserts into a zero vector.
10605 if (EVTBits == 8 && NumElems == 16)
10606 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeroMask, NumNonZero, NumZero,
10607 DAG, Subtarget))
10608 return V;
10609
10610 if (EVTBits == 16 && NumElems == 8)
10611 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeroMask, NumNonZero, NumZero,
10612 DAG, Subtarget))
10613 return V;
10614
10615 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
10616 if (EVTBits == 32 && NumElems == 4)
10617 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget))
10618 return V;
10619
10620 // If element VT is == 32 bits, turn it into a number of shuffles.
10621 if (NumElems == 4 && NumZero > 0) {
10622 SmallVector<SDValue, 8> Ops(NumElems);
10623 for (unsigned i = 0; i < 4; ++i) {
10624 bool isZero = !NonZeroMask[i];
10625 if (isZero)
10626 Ops[i] = getZeroVector(VT, Subtarget, DAG, dl);
10627 else
10628 Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
10629 }
10630
10631 for (unsigned i = 0; i < 2; ++i) {
10632 switch (NonZeroMask.extractBitsAsZExtValue(2, i * 2)) {
10633 default: llvm_unreachable("Unexpected NonZero count")::llvm::llvm_unreachable_internal("Unexpected NonZero count",
"/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10633)
;
10634 case 0:
10635 Ops[i] = Ops[i*2]; // Must be a zero vector.
10636 break;
10637 case 1:
10638 Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2+1], Ops[i*2]);
10639 break;
10640 case 2:
10641 Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
10642 break;
10643 case 3:
10644 Ops[i] = getUnpackl(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
10645 break;
10646 }
10647 }
10648
10649 bool Reverse1 = NonZeroMask.extractBitsAsZExtValue(2, 0) == 2;
10650 bool Reverse2 = NonZeroMask.extractBitsAsZExtValue(2, 2) == 2;
10651 int MaskVec[] = {
10652 Reverse1 ? 1 : 0,
10653 Reverse1 ? 0 : 1,
10654 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
10655 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
10656 };
10657 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], MaskVec);
10658 }
10659
10660 assert(Values.size() > 1 && "Expected non-undef and non-splat vector")(static_cast <bool> (Values.size() > 1 && "Expected non-undef and non-splat vector"
) ? void (0) : __assert_fail ("Values.size() > 1 && \"Expected non-undef and non-splat vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10660, __extension__ __PRETTY_FUNCTION__))
;
10661
10662 // Check for a build vector from mostly shuffle plus few inserting.
10663 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
10664 return Sh;
10665
10666 // For SSE 4.1, use insertps to put the high elements into the low element.
10667 if (Subtarget.hasSSE41()) {
10668 SDValue Result;
10669 if (!Op.getOperand(0).isUndef())
10670 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
10671 else
10672 Result = DAG.getUNDEF(VT);
10673
10674 for (unsigned i = 1; i < NumElems; ++i) {
10675 if (Op.getOperand(i).isUndef()) continue;
10676 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
10677 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
10678 }
10679 return Result;
10680 }
10681
10682 // Otherwise, expand into a number of unpckl*, start by extending each of
10683 // our (non-undef) elements to the full vector width with the element in the
10684 // bottom slot of the vector (which generates no code for SSE).
10685 SmallVector<SDValue, 8> Ops(NumElems);
10686 for (unsigned i = 0; i < NumElems; ++i) {
10687 if (!Op.getOperand(i).isUndef())
10688 Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
10689 else
10690 Ops[i] = DAG.getUNDEF(VT);
10691 }
10692
10693 // Next, we iteratively mix elements, e.g. for v4f32:
10694 // Step 1: unpcklps 0, 1 ==> X: <?, ?, 1, 0>
10695 // : unpcklps 2, 3 ==> Y: <?, ?, 3, 2>
10696 // Step 2: unpcklpd X, Y ==> <3, 2, 1, 0>
10697 for (unsigned Scale = 1; Scale < NumElems; Scale *= 2) {
10698 // Generate scaled UNPCKL shuffle mask.
10699 SmallVector<int, 16> Mask;
10700 for(unsigned i = 0; i != Scale; ++i)
10701 Mask.push_back(i);
10702 for (unsigned i = 0; i != Scale; ++i)
10703 Mask.push_back(NumElems+i);
10704 Mask.append(NumElems - Mask.size(), SM_SentinelUndef);
10705
10706 for (unsigned i = 0, e = NumElems / (2 * Scale); i != e; ++i)
10707 Ops[i] = DAG.getVectorShuffle(VT, dl, Ops[2*i], Ops[(2*i)+1], Mask);
10708 }
10709 return Ops[0];
10710}
10711
10712// 256-bit AVX can use the vinsertf128 instruction
10713// to create 256-bit vectors from two other 128-bit ones.
10714// TODO: Detect subvector broadcast here instead of DAG combine?
10715static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
10716 const X86Subtarget &Subtarget) {
10717 SDLoc dl(Op);
10718 MVT ResVT = Op.getSimpleValueType();
10719
10720 assert((ResVT.is256BitVector() ||(static_cast <bool> ((ResVT.is256BitVector() || ResVT.is512BitVector
()) && "Value type must be 256-/512-bit wide") ? void
(0) : __assert_fail ("(ResVT.is256BitVector() || ResVT.is512BitVector()) && \"Value type must be 256-/512-bit wide\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10721, __extension__ __PRETTY_FUNCTION__))
10721 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide")(static_cast <bool> ((ResVT.is256BitVector() || ResVT.is512BitVector
()) && "Value type must be 256-/512-bit wide") ? void
(0) : __assert_fail ("(ResVT.is256BitVector() || ResVT.is512BitVector()) && \"Value type must be 256-/512-bit wide\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10721, __extension__ __PRETTY_FUNCTION__))
;
10722
10723 unsigned NumOperands = Op.getNumOperands();
10724 unsigned NumZero = 0;
10725 unsigned NumNonZero = 0;
10726 unsigned NonZeros = 0;
10727 for (unsigned i = 0; i != NumOperands; ++i) {
10728 SDValue SubVec = Op.getOperand(i);
10729 if (SubVec.isUndef())
10730 continue;
10731 if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
10732 ++NumZero;
10733 else {
10734 assert(i < sizeof(NonZeros) * CHAR_BIT)(static_cast <bool> (i < sizeof(NonZeros) * 8) ? void
(0) : __assert_fail ("i < sizeof(NonZeros) * CHAR_BIT", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10734, __extension__ __PRETTY_FUNCTION__))
; // Ensure the shift is in range.
10735 NonZeros |= 1 << i;
10736 ++NumNonZero;
10737 }
10738 }
10739
10740 // If we have more than 2 non-zeros, build each half separately.
10741 if (NumNonZero > 2) {
10742 MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
10743 ArrayRef<SDUse> Ops = Op->ops();
10744 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10745 Ops.slice(0, NumOperands/2));
10746 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10747 Ops.slice(NumOperands/2));
10748 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
10749 }
10750
10751 // Otherwise, build it up through insert_subvectors.
10752 SDValue Vec = NumZero ? getZeroVector(ResVT, Subtarget, DAG, dl)
10753 : DAG.getUNDEF(ResVT);
10754
10755 MVT SubVT = Op.getOperand(0).getSimpleValueType();
10756 unsigned NumSubElems = SubVT.getVectorNumElements();
10757 for (unsigned i = 0; i != NumOperands; ++i) {
10758 if ((NonZeros & (1 << i)) == 0)
10759 continue;
10760
10761 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec,
10762 Op.getOperand(i),
10763 DAG.getIntPtrConstant(i * NumSubElems, dl));
10764 }
10765
10766 return Vec;
10767}
10768
10769// Returns true if the given node is a type promotion (by concatenating i1
10770// zeros) of the result of a node that already zeros all upper bits of
10771// k-register.
10772// TODO: Merge this with LowerAVXCONCAT_VECTORS?
10773static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
10774 const X86Subtarget &Subtarget,
10775 SelectionDAG & DAG) {
10776 SDLoc dl(Op);
10777 MVT ResVT = Op.getSimpleValueType();
10778 unsigned NumOperands = Op.getNumOperands();
10779
10780 assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&(static_cast <bool> (NumOperands > 1 && isPowerOf2_32
(NumOperands) && "Unexpected number of operands in CONCAT_VECTORS"
) ? void (0) : __assert_fail ("NumOperands > 1 && isPowerOf2_32(NumOperands) && \"Unexpected number of operands in CONCAT_VECTORS\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10781, __extension__ __PRETTY_FUNCTION__))
10781 "Unexpected number of operands in CONCAT_VECTORS")(static_cast <bool> (NumOperands > 1 && isPowerOf2_32
(NumOperands) && "Unexpected number of operands in CONCAT_VECTORS"
) ? void (0) : __assert_fail ("NumOperands > 1 && isPowerOf2_32(NumOperands) && \"Unexpected number of operands in CONCAT_VECTORS\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10781, __extension__ __PRETTY_FUNCTION__))
;
10782
10783 uint64_t Zeros = 0;
10784 uint64_t NonZeros = 0;
10785 for (unsigned i = 0; i != NumOperands; ++i) {
10786 SDValue SubVec = Op.getOperand(i);
10787 if (SubVec.isUndef())
10788 continue;
10789 assert(i < sizeof(NonZeros) * CHAR_BIT)(static_cast <bool> (i < sizeof(NonZeros) * 8) ? void
(0) : __assert_fail ("i < sizeof(NonZeros) * CHAR_BIT", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10789, __extension__ __PRETTY_FUNCTION__))
; // Ensure the shift is in range.
10790 if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
10791 Zeros |= (uint64_t)1 << i;
10792 else
10793 NonZeros |= (uint64_t)1 << i;
10794 }
10795
10796 unsigned NumElems = ResVT.getVectorNumElements();
10797
10798 // If we are inserting non-zero vector and there are zeros in LSBs and undef
10799 // in the MSBs we need to emit a KSHIFTL. The generic lowering to
10800 // insert_subvector will give us two kshifts.
10801 if (isPowerOf2_64(NonZeros) && Zeros != 0 && NonZeros > Zeros &&
10802 Log2_64(NonZeros) != NumOperands - 1) {
10803 MVT ShiftVT = ResVT;
10804 if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8)
10805 ShiftVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
10806 unsigned Idx = Log2_64(NonZeros);
10807 SDValue SubVec = Op.getOperand(Idx);
10808 unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
10809 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ShiftVT,
10810 DAG.getUNDEF(ShiftVT), SubVec,
10811 DAG.getIntPtrConstant(0, dl));
10812 Op = DAG.getNode(X86ISD::KSHIFTL, dl, ShiftVT, SubVec,
10813 DAG.getTargetConstant(Idx * SubVecNumElts, dl, MVT::i8));
10814 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResVT, Op,
10815 DAG.getIntPtrConstant(0, dl));
10816 }
10817
10818 // If there are zero or one non-zeros we can handle this very simply.
10819 if (NonZeros == 0 || isPowerOf2_64(NonZeros)) {
10820 SDValue Vec = Zeros ? DAG.getConstant(0, dl, ResVT) : DAG.getUNDEF(ResVT);
10821 if (!NonZeros)
10822 return Vec;
10823 unsigned Idx = Log2_64(NonZeros);
10824 SDValue SubVec = Op.getOperand(Idx);
10825 unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
10826 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, SubVec,
10827 DAG.getIntPtrConstant(Idx * SubVecNumElts, dl));
10828 }
10829
10830 if (NumOperands > 2) {
10831 MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
10832 ArrayRef<SDUse> Ops = Op->ops();
10833 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10834 Ops.slice(0, NumOperands/2));
10835 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10836 Ops.slice(NumOperands/2));
10837 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
10838 }
10839
10840 assert(countPopulation(NonZeros) == 2 && "Simple cases not handled?")(static_cast <bool> (countPopulation(NonZeros) == 2 &&
"Simple cases not handled?") ? void (0) : __assert_fail ("countPopulation(NonZeros) == 2 && \"Simple cases not handled?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10840, __extension__ __PRETTY_FUNCTION__))
;
10841
10842 if (ResVT.getVectorNumElements() >= 16)
10843 return Op; // The operation is legal with KUNPCK
10844
10845 SDValue Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT,
10846 DAG.getUNDEF(ResVT), Op.getOperand(0),
10847 DAG.getIntPtrConstant(0, dl));
10848 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, Op.getOperand(1),
10849 DAG.getIntPtrConstant(NumElems/2, dl));
10850}
10851
10852static SDValue LowerCONCAT_VECTORS(SDValue Op,
10853 const X86Subtarget &Subtarget,
10854 SelectionDAG &DAG) {
10855 MVT VT = Op.getSimpleValueType();
10856 if (VT.getVectorElementType() == MVT::i1)
10857 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
10858
10859 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||(static_cast <bool> ((VT.is256BitVector() && Op
.getNumOperands() == 2) || (VT.is512BitVector() && (Op
.getNumOperands() == 2 || Op.getNumOperands() == 4))) ? void (
0) : __assert_fail ("(VT.is256BitVector() && Op.getNumOperands() == 2) || (VT.is512BitVector() && (Op.getNumOperands() == 2 || Op.getNumOperands() == 4))"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10861, __extension__ __PRETTY_FUNCTION__))
10860 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||(static_cast <bool> ((VT.is256BitVector() && Op
.getNumOperands() == 2) || (VT.is512BitVector() && (Op
.getNumOperands() == 2 || Op.getNumOperands() == 4))) ? void (
0) : __assert_fail ("(VT.is256BitVector() && Op.getNumOperands() == 2) || (VT.is512BitVector() && (Op.getNumOperands() == 2 || Op.getNumOperands() == 4))"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10861, __extension__ __PRETTY_FUNCTION__))
10861 Op.getNumOperands() == 4)))(static_cast <bool> ((VT.is256BitVector() && Op
.getNumOperands() == 2) || (VT.is512BitVector() && (Op
.getNumOperands() == 2 || Op.getNumOperands() == 4))) ? void (
0) : __assert_fail ("(VT.is256BitVector() && Op.getNumOperands() == 2) || (VT.is512BitVector() && (Op.getNumOperands() == 2 || Op.getNumOperands() == 4))"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10861, __extension__ __PRETTY_FUNCTION__))
;
10862
10863 // AVX can use the vinsertf128 instruction to create 256-bit vectors
10864 // from two other 128-bit ones.
10865
10866 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
10867 return LowerAVXCONCAT_VECTORS(Op, DAG, Subtarget);
10868}
10869
10870//===----------------------------------------------------------------------===//
10871// Vector shuffle lowering
10872//
10873// This is an experimental code path for lowering vector shuffles on x86. It is
10874// designed to handle arbitrary vector shuffles and blends, gracefully
10875// degrading performance as necessary. It works hard to recognize idiomatic
10876// shuffles and lower them to optimal instruction patterns without leaving
10877// a framework that allows reasonably efficient handling of all vector shuffle
10878// patterns.
10879//===----------------------------------------------------------------------===//
10880
10881/// Tiny helper function to identify a no-op mask.
10882///
10883/// This is a somewhat boring predicate function. It checks whether the mask
10884/// array input, which is assumed to be a single-input shuffle mask of the kind
10885/// used by the X86 shuffle instructions (not a fully general
10886/// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
10887/// in-place shuffle are 'no-op's.
10888static bool isNoopShuffleMask(ArrayRef<int> Mask) {
10889 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
10890 assert(Mask[i] >= -1 && "Out of bound mask element!")(static_cast <bool> (Mask[i] >= -1 && "Out of bound mask element!"
) ? void (0) : __assert_fail ("Mask[i] >= -1 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10890, __extension__ __PRETTY_FUNCTION__))
;
10891 if (Mask[i] >= 0 && Mask[i] != i)
10892 return false;
10893 }
10894 return true;
10895}
10896
10897/// Test whether there are elements crossing LaneSizeInBits lanes in this
10898/// shuffle mask.
10899///
10900/// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
10901/// and we routinely test for these.
10902static bool isLaneCrossingShuffleMask(unsigned LaneSizeInBits,
10903 unsigned ScalarSizeInBits,
10904 ArrayRef<int> Mask) {
10905 assert(LaneSizeInBits && ScalarSizeInBits &&(static_cast <bool> (LaneSizeInBits && ScalarSizeInBits
&& (LaneSizeInBits % ScalarSizeInBits) == 0 &&
"Illegal shuffle lane size") ? void (0) : __assert_fail ("LaneSizeInBits && ScalarSizeInBits && (LaneSizeInBits % ScalarSizeInBits) == 0 && \"Illegal shuffle lane size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10907, __extension__ __PRETTY_FUNCTION__))
10906 (LaneSizeInBits % ScalarSizeInBits) == 0 &&(static_cast <bool> (LaneSizeInBits && ScalarSizeInBits
&& (LaneSizeInBits % ScalarSizeInBits) == 0 &&
"Illegal shuffle lane size") ? void (0) : __assert_fail ("LaneSizeInBits && ScalarSizeInBits && (LaneSizeInBits % ScalarSizeInBits) == 0 && \"Illegal shuffle lane size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10907, __extension__ __PRETTY_FUNCTION__))
10907 "Illegal shuffle lane size")(static_cast <bool> (LaneSizeInBits && ScalarSizeInBits
&& (LaneSizeInBits % ScalarSizeInBits) == 0 &&
"Illegal shuffle lane size") ? void (0) : __assert_fail ("LaneSizeInBits && ScalarSizeInBits && (LaneSizeInBits % ScalarSizeInBits) == 0 && \"Illegal shuffle lane size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10907, __extension__ __PRETTY_FUNCTION__))
;
10908 int LaneSize = LaneSizeInBits / ScalarSizeInBits;
10909 int Size = Mask.size();
10910 for (int i = 0; i < Size; ++i)
10911 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10912 return true;
10913 return false;
10914}
10915
10916/// Test whether there are elements crossing 128-bit lanes in this
10917/// shuffle mask.
10918static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
10919 return isLaneCrossingShuffleMask(128, VT.getScalarSizeInBits(), Mask);
10920}
10921
10922/// Test whether elements in each LaneSizeInBits lane in this shuffle mask come
10923/// from multiple lanes - this is different to isLaneCrossingShuffleMask to
10924/// better support 'repeated mask + lane permute' style shuffles.
10925static bool isMultiLaneShuffleMask(unsigned LaneSizeInBits,
10926 unsigned ScalarSizeInBits,
10927 ArrayRef<int> Mask) {
10928 assert(LaneSizeInBits && ScalarSizeInBits &&(static_cast <bool> (LaneSizeInBits && ScalarSizeInBits
&& (LaneSizeInBits % ScalarSizeInBits) == 0 &&
"Illegal shuffle lane size") ? void (0) : __assert_fail ("LaneSizeInBits && ScalarSizeInBits && (LaneSizeInBits % ScalarSizeInBits) == 0 && \"Illegal shuffle lane size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10930, __extension__ __PRETTY_FUNCTION__))
10929 (LaneSizeInBits % ScalarSizeInBits) == 0 &&(static_cast <bool> (LaneSizeInBits && ScalarSizeInBits
&& (LaneSizeInBits % ScalarSizeInBits) == 0 &&
"Illegal shuffle lane size") ? void (0) : __assert_fail ("LaneSizeInBits && ScalarSizeInBits && (LaneSizeInBits % ScalarSizeInBits) == 0 && \"Illegal shuffle lane size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10930, __extension__ __PRETTY_FUNCTION__))
10930 "Illegal shuffle lane size")(static_cast <bool> (LaneSizeInBits && ScalarSizeInBits
&& (LaneSizeInBits % ScalarSizeInBits) == 0 &&
"Illegal shuffle lane size") ? void (0) : __assert_fail ("LaneSizeInBits && ScalarSizeInBits && (LaneSizeInBits % ScalarSizeInBits) == 0 && \"Illegal shuffle lane size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10930, __extension__ __PRETTY_FUNCTION__))
;
10931 int NumElts = Mask.size();
10932 int NumEltsPerLane = LaneSizeInBits / ScalarSizeInBits;
10933 int NumLanes = NumElts / NumEltsPerLane;
10934 if (NumLanes > 1) {
10935 for (int i = 0; i != NumLanes; ++i) {
10936 int SrcLane = -1;
10937 for (int j = 0; j != NumEltsPerLane; ++j) {
10938 int M = Mask[(i * NumEltsPerLane) + j];
10939 if (M < 0)
10940 continue;
10941 int Lane = (M % NumElts) / NumEltsPerLane;
10942 if (SrcLane >= 0 && SrcLane != Lane)
10943 return true;
10944 SrcLane = Lane;
10945 }
10946 }
10947 }
10948 return false;
10949}
10950
10951/// Test whether a shuffle mask is equivalent within each sub-lane.
10952///
10953/// This checks a shuffle mask to see if it is performing the same
10954/// lane-relative shuffle in each sub-lane. This trivially implies
10955/// that it is also not lane-crossing. It may however involve a blend from the
10956/// same lane of a second vector.
10957///
10958/// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
10959/// non-trivial to compute in the face of undef lanes. The representation is
10960/// suitable for use with existing 128-bit shuffles as entries from the second
10961/// vector have been remapped to [LaneSize, 2*LaneSize).
10962static bool isRepeatedShuffleMask(unsigned LaneSizeInBits, MVT VT,
10963 ArrayRef<int> Mask,
10964 SmallVectorImpl<int> &RepeatedMask) {
10965 auto LaneSize = LaneSizeInBits / VT.getScalarSizeInBits();
10966 RepeatedMask.assign(LaneSize, -1);
10967 int Size = Mask.size();
10968 for (int i = 0; i < Size; ++i) {
10969 assert(Mask[i] == SM_SentinelUndef || Mask[i] >= 0)(static_cast <bool> (Mask[i] == SM_SentinelUndef || Mask
[i] >= 0) ? void (0) : __assert_fail ("Mask[i] == SM_SentinelUndef || Mask[i] >= 0"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 10969, __extension__ __PRETTY_FUNCTION__))
;
10970 if (Mask[i] < 0)
10971 continue;
10972 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
10973 // This entry crosses lanes, so there is no way to model this shuffle.
10974 return false;
10975
10976 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
10977 // Adjust second vector indices to start at LaneSize instead of Size.
10978 int LocalM = Mask[i] < Size ? Mask[i] % LaneSize
10979 : Mask[i] % LaneSize + LaneSize;
10980 if (RepeatedMask[i % LaneSize] < 0)
10981 // This is the first non-undef entry in this slot of a 128-bit lane.
10982 RepeatedMask[i % LaneSize] = LocalM;
10983 else if (RepeatedMask[i % LaneSize] != LocalM)
10984 // Found a mismatch with the repeated mask.
10985 return false;
10986 }
10987 return true;
10988}
10989
10990/// Test whether a shuffle mask is equivalent within each 128-bit lane.
10991static bool
10992is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
10993 SmallVectorImpl<int> &RepeatedMask) {
10994 return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
10995}
10996
10997static bool
10998is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask) {
10999 SmallVector<int, 32> RepeatedMask;
11000 return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
11001}
11002
11003/// Test whether a shuffle mask is equivalent within each 256-bit lane.
11004static bool
11005is256BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
11006 SmallVectorImpl<int> &RepeatedMask) {
11007 return isRepeatedShuffleMask(256, VT, Mask, RepeatedMask);
11008}
11009
11010/// Test whether a target shuffle mask is equivalent within each sub-lane.
11011/// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
11012static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits,
11013 unsigned EltSizeInBits,
11014 ArrayRef<int> Mask,
11015 SmallVectorImpl<int> &RepeatedMask) {
11016 int LaneSize = LaneSizeInBits / EltSizeInBits;
11017 RepeatedMask.assign(LaneSize, SM_SentinelUndef);
11018 int Size = Mask.size();
11019 for (int i = 0; i < Size; ++i) {
11020 assert(isUndefOrZero(Mask[i]) || (Mask[i] >= 0))(static_cast <bool> (isUndefOrZero(Mask[i]) || (Mask[i]
>= 0)) ? void (0) : __assert_fail ("isUndefOrZero(Mask[i]) || (Mask[i] >= 0)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11020, __extension__ __PRETTY_FUNCTION__))
;
11021 if (Mask[i] == SM_SentinelUndef)
11022 continue;
11023 if (Mask[i] == SM_SentinelZero) {
11024 if (!isUndefOrZero(RepeatedMask[i % LaneSize]))
11025 return false;
11026 RepeatedMask[i % LaneSize] = SM_SentinelZero;
11027 continue;
11028 }
11029 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
11030 // This entry crosses lanes, so there is no way to model this shuffle.
11031 return false;
11032
11033 // Handle the in-lane shuffles by detecting if and when they repeat. Adjust
11034 // later vector indices to start at multiples of LaneSize instead of Size.
11035 int LaneM = Mask[i] / Size;
11036 int LocalM = (Mask[i] % LaneSize) + (LaneM * LaneSize);
11037 if (RepeatedMask[i % LaneSize] == SM_SentinelUndef)
11038 // This is the first non-undef entry in this slot of a 128-bit lane.
11039 RepeatedMask[i % LaneSize] = LocalM;
11040 else if (RepeatedMask[i % LaneSize] != LocalM)
11041 // Found a mismatch with the repeated mask.
11042 return false;
11043 }
11044 return true;
11045}
11046
11047/// Test whether a target shuffle mask is equivalent within each sub-lane.
11048/// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
11049static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits, MVT VT,
11050 ArrayRef<int> Mask,
11051 SmallVectorImpl<int> &RepeatedMask) {
11052 return isRepeatedTargetShuffleMask(LaneSizeInBits, VT.getScalarSizeInBits(),
11053 Mask, RepeatedMask);
11054}
11055
11056/// Checks whether the vector elements referenced by two shuffle masks are
11057/// equivalent.
11058static bool IsElementEquivalent(int MaskSize, SDValue Op, SDValue ExpectedOp,
11059 int Idx, int ExpectedIdx) {
11060 assert(0 <= Idx && Idx < MaskSize && 0 <= ExpectedIdx &&(static_cast <bool> (0 <= Idx && Idx < MaskSize
&& 0 <= ExpectedIdx && ExpectedIdx < MaskSize
&& "Out of range element index") ? void (0) : __assert_fail
("0 <= Idx && Idx < MaskSize && 0 <= ExpectedIdx && ExpectedIdx < MaskSize && \"Out of range element index\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11061, __extension__ __PRETTY_FUNCTION__))
11061 ExpectedIdx < MaskSize && "Out of range element index")(static_cast <bool> (0 <= Idx && Idx < MaskSize
&& 0 <= ExpectedIdx && ExpectedIdx < MaskSize
&& "Out of range element index") ? void (0) : __assert_fail
("0 <= Idx && Idx < MaskSize && 0 <= ExpectedIdx && ExpectedIdx < MaskSize && \"Out of range element index\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11061, __extension__ __PRETTY_FUNCTION__))
;
11062 if (!Op || !ExpectedOp || Op.getOpcode() != ExpectedOp.getOpcode())
11063 return false;
11064
11065 switch (Op.getOpcode()) {
11066 case ISD::BUILD_VECTOR:
11067 // If the values are build vectors, we can look through them to find
11068 // equivalent inputs that make the shuffles equivalent.
11069 // TODO: Handle MaskSize != Op.getNumOperands()?
11070 if (MaskSize == (int)Op.getNumOperands() &&
11071 MaskSize == (int)ExpectedOp.getNumOperands())
11072 return Op.getOperand(Idx) == ExpectedOp.getOperand(ExpectedIdx);
11073 break;
11074 case X86ISD::VBROADCAST:
11075 case X86ISD::VBROADCAST_LOAD:
11076 // TODO: Handle MaskSize != Op.getValueType().getVectorNumElements()?
11077 return (Op == ExpectedOp &&
11078 (int)Op.getValueType().getVectorNumElements() == MaskSize);
11079 case X86ISD::HADD:
11080 case X86ISD::HSUB:
11081 case X86ISD::FHADD:
11082 case X86ISD::FHSUB:
11083 case X86ISD::PACKSS:
11084 case X86ISD::PACKUS:
11085 // HOP(X,X) can refer to the elt from the lower/upper half of a lane.
11086 // TODO: Handle MaskSize != NumElts?
11087 // TODO: Handle HOP(X,Y) vs HOP(Y,X) equivalence cases.
11088 if (Op == ExpectedOp && Op.getOperand(0) == Op.getOperand(1)) {
11089 MVT VT = Op.getSimpleValueType();
11090 int NumElts = VT.getVectorNumElements();
11091 if (MaskSize == NumElts) {
11092 int NumLanes = VT.getSizeInBits() / 128;
11093 int NumEltsPerLane = NumElts / NumLanes;
11094 int NumHalfEltsPerLane = NumEltsPerLane / 2;
11095 bool SameLane =
11096 (Idx / NumEltsPerLane) == (ExpectedIdx / NumEltsPerLane);
11097 bool SameElt =
11098 (Idx % NumHalfEltsPerLane) == (ExpectedIdx % NumHalfEltsPerLane);
11099 return SameLane && SameElt;
11100 }
11101 }
11102 break;
11103 }
11104
11105 return false;
11106}
11107
11108/// Checks whether a shuffle mask is equivalent to an explicit list of
11109/// arguments.
11110///
11111/// This is a fast way to test a shuffle mask against a fixed pattern:
11112///
11113/// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
11114///
11115/// It returns true if the mask is exactly as wide as the argument list, and
11116/// each element of the mask is either -1 (signifying undef) or the value given
11117/// in the argument.
11118static bool isShuffleEquivalent(ArrayRef<int> Mask, ArrayRef<int> ExpectedMask,
11119 SDValue V1 = SDValue(),
11120 SDValue V2 = SDValue()) {
11121 int Size = Mask.size();
11122 if (Size != (int)ExpectedMask.size())
11123 return false;
11124
11125 for (int i = 0; i < Size; ++i) {
11126 assert(Mask[i] >= -1 && "Out of bound mask element!")(static_cast <bool> (Mask[i] >= -1 && "Out of bound mask element!"
) ? void (0) : __assert_fail ("Mask[i] >= -1 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11126, __extension__ __PRETTY_FUNCTION__))
;
11127 int MaskIdx = Mask[i];
11128 int ExpectedIdx = ExpectedMask[i];
11129 if (0 <= MaskIdx && MaskIdx != ExpectedIdx) {
11130 SDValue MaskV = MaskIdx < Size ? V1 : V2;
11131 SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
11132 MaskIdx = MaskIdx < Size ? MaskIdx : (MaskIdx - Size);
11133 ExpectedIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
11134 if (!IsElementEquivalent(Size, MaskV, ExpectedV, MaskIdx, ExpectedIdx))
11135 return false;
11136 }
11137 }
11138 return true;
11139}
11140
11141/// Checks whether a target shuffle mask is equivalent to an explicit pattern.
11142///
11143/// The masks must be exactly the same width.
11144///
11145/// If an element in Mask matches SM_SentinelUndef (-1) then the corresponding
11146/// value in ExpectedMask is always accepted. Otherwise the indices must match.
11147///
11148/// SM_SentinelZero is accepted as a valid negative index but must match in
11149/// both.
11150static bool isTargetShuffleEquivalent(MVT VT, ArrayRef<int> Mask,
11151 ArrayRef<int> ExpectedMask,
11152 SDValue V1 = SDValue(),
11153 SDValue V2 = SDValue()) {
11154 int Size = Mask.size();
11155 if (Size != (int)ExpectedMask.size())
11156 return false;
11157 assert(isUndefOrZeroOrInRange(ExpectedMask, 0, 2 * Size) &&(static_cast <bool> (isUndefOrZeroOrInRange(ExpectedMask
, 0, 2 * Size) && "Illegal target shuffle mask") ? void
(0) : __assert_fail ("isUndefOrZeroOrInRange(ExpectedMask, 0, 2 * Size) && \"Illegal target shuffle mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11158, __extension__ __PRETTY_FUNCTION__))
11158 "Illegal target shuffle mask")(static_cast <bool> (isUndefOrZeroOrInRange(ExpectedMask
, 0, 2 * Size) && "Illegal target shuffle mask") ? void
(0) : __assert_fail ("isUndefOrZeroOrInRange(ExpectedMask, 0, 2 * Size) && \"Illegal target shuffle mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11158, __extension__ __PRETTY_FUNCTION__))
;
11159
11160 // Check for out-of-range target shuffle mask indices.
11161 if (!isUndefOrZeroOrInRange(Mask, 0, 2 * Size))
11162 return false;
11163
11164 // Don't use V1/V2 if they're not the same size as the shuffle mask type.
11165 if (V1 && V1.getValueSizeInBits() != VT.getSizeInBits())
11166 V1 = SDValue();
11167 if (V2 && V2.getValueSizeInBits() != VT.getSizeInBits())
11168 V2 = SDValue();
11169
11170 for (int i = 0; i < Size; ++i) {
11171 int MaskIdx = Mask[i];
11172 int ExpectedIdx = ExpectedMask[i];
11173 if (MaskIdx == SM_SentinelUndef || MaskIdx == ExpectedIdx)
11174 continue;
11175 if (0 <= MaskIdx && 0 <= ExpectedIdx) {
11176 SDValue MaskV = MaskIdx < Size ? V1 : V2;
11177 SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
11178 MaskIdx = MaskIdx < Size ? MaskIdx : (MaskIdx - Size);
11179 ExpectedIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
11180 if (IsElementEquivalent(Size, MaskV, ExpectedV, MaskIdx, ExpectedIdx))
11181 continue;
11182 }
11183 // TODO - handle SM_Sentinel equivalences.
11184 return false;
11185 }
11186 return true;
11187}
11188
11189// Attempt to create a shuffle mask from a VSELECT condition mask.
11190static bool createShuffleMaskFromVSELECT(SmallVectorImpl<int> &Mask,
11191 SDValue Cond) {
11192 EVT CondVT = Cond.getValueType();
11193 unsigned EltSizeInBits = CondVT.getScalarSizeInBits();
11194 unsigned NumElts = CondVT.getVectorNumElements();
11195
11196 APInt UndefElts;
11197 SmallVector<APInt, 32> EltBits;
11198 if (!getTargetConstantBitsFromNode(Cond, EltSizeInBits, UndefElts, EltBits,
11199 true, false))
11200 return false;
11201
11202 Mask.resize(NumElts, SM_SentinelUndef);
11203
11204 for (int i = 0; i != (int)NumElts; ++i) {
11205 Mask[i] = i;
11206 // Arbitrarily choose from the 2nd operand if the select condition element
11207 // is undef.
11208 // TODO: Can we do better by matching patterns such as even/odd?
11209 if (UndefElts[i] || EltBits[i].isNullValue())
11210 Mask[i] += NumElts;
11211 }
11212
11213 return true;
11214}
11215
11216// Check if the shuffle mask is suitable for the AVX vpunpcklwd or vpunpckhwd
11217// instructions.
11218static bool isUnpackWdShuffleMask(ArrayRef<int> Mask, MVT VT) {
11219 if (VT != MVT::v8i32 && VT != MVT::v8f32)
11220 return false;
11221
11222 SmallVector<int, 8> Unpcklwd;
11223 createUnpackShuffleMask(MVT::v8i16, Unpcklwd, /* Lo = */ true,
11224 /* Unary = */ false);
11225 SmallVector<int, 8> Unpckhwd;
11226 createUnpackShuffleMask(MVT::v8i16, Unpckhwd, /* Lo = */ false,
11227 /* Unary = */ false);
11228 bool IsUnpackwdMask = (isTargetShuffleEquivalent(VT, Mask, Unpcklwd) ||
11229 isTargetShuffleEquivalent(VT, Mask, Unpckhwd));
11230 return IsUnpackwdMask;
11231}
11232
11233static bool is128BitUnpackShuffleMask(ArrayRef<int> Mask) {
11234 // Create 128-bit vector type based on mask size.
11235 MVT EltVT = MVT::getIntegerVT(128 / Mask.size());
11236 MVT VT = MVT::getVectorVT(EltVT, Mask.size());
11237
11238 // We can't assume a canonical shuffle mask, so try the commuted version too.
11239 SmallVector<int, 4> CommutedMask(Mask.begin(), Mask.end());
11240 ShuffleVectorSDNode::commuteMask(CommutedMask);
11241
11242 // Match any of unary/binary or low/high.
11243 for (unsigned i = 0; i != 4; ++i) {
11244 SmallVector<int, 16> UnpackMask;
11245 createUnpackShuffleMask(VT, UnpackMask, (i >> 1) % 2, i % 2);
11246 if (isTargetShuffleEquivalent(VT, Mask, UnpackMask) ||
11247 isTargetShuffleEquivalent(VT, CommutedMask, UnpackMask))
11248 return true;
11249 }
11250 return false;
11251}
11252
11253/// Return true if a shuffle mask chooses elements identically in its top and
11254/// bottom halves. For example, any splat mask has the same top and bottom
11255/// halves. If an element is undefined in only one half of the mask, the halves
11256/// are not considered identical.
11257static bool hasIdenticalHalvesShuffleMask(ArrayRef<int> Mask) {
11258 assert(Mask.size() % 2 == 0 && "Expecting even number of elements in mask")(static_cast <bool> (Mask.size() % 2 == 0 && "Expecting even number of elements in mask"
) ? void (0) : __assert_fail ("Mask.size() % 2 == 0 && \"Expecting even number of elements in mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11258, __extension__ __PRETTY_FUNCTION__))
;
11259 unsigned HalfSize = Mask.size() / 2;
11260 for (unsigned i = 0; i != HalfSize; ++i) {
11261 if (Mask[i] != Mask[i + HalfSize])
11262 return false;
11263 }
11264 return true;
11265}
11266
11267/// Get a 4-lane 8-bit shuffle immediate for a mask.
11268///
11269/// This helper function produces an 8-bit shuffle immediate corresponding to
11270/// the ubiquitous shuffle encoding scheme used in x86 instructions for
11271/// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
11272/// example.
11273///
11274/// NB: We rely heavily on "undef" masks preserving the input lane.
11275static unsigned getV4X86ShuffleImm(ArrayRef<int> Mask) {
11276 assert(Mask.size() == 4 && "Only 4-lane shuffle masks")(static_cast <bool> (Mask.size() == 4 && "Only 4-lane shuffle masks"
) ? void (0) : __assert_fail ("Mask.size() == 4 && \"Only 4-lane shuffle masks\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11276, __extension__ __PRETTY_FUNCTION__))
;
11277 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!")(static_cast <bool> (Mask[0] >= -1 && Mask[0
] < 4 && "Out of bound mask element!") ? void (0) :
__assert_fail ("Mask[0] >= -1 && Mask[0] < 4 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11277, __extension__ __PRETTY_FUNCTION__))
;
11278 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!")(static_cast <bool> (Mask[1] >= -1 && Mask[1
] < 4 && "Out of bound mask element!") ? void (0) :
__assert_fail ("Mask[1] >= -1 && Mask[1] < 4 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11278, __extension__ __PRETTY_FUNCTION__))
;
11279 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!")(static_cast <bool> (Mask[2] >= -1 && Mask[2
] < 4 && "Out of bound mask element!") ? void (0) :
__assert_fail ("Mask[2] >= -1 && Mask[2] < 4 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11279, __extension__ __PRETTY_FUNCTION__))
;
11280 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!")(static_cast <bool> (Mask[3] >= -1 && Mask[3
] < 4 && "Out of bound mask element!") ? void (0) :
__assert_fail ("Mask[3] >= -1 && Mask[3] < 4 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11280, __extension__ __PRETTY_FUNCTION__))
;
11281
11282 // If the mask only uses one non-undef element, then fully 'splat' it to
11283 // improve later broadcast matching.
11284 int FirstIndex = find_if(Mask, [](int M) { return M >= 0; }) - Mask.begin();
11285 assert(0 <= FirstIndex && FirstIndex < 4 && "All undef shuffle mask")(static_cast <bool> (0 <= FirstIndex && FirstIndex
< 4 && "All undef shuffle mask") ? void (0) : __assert_fail
("0 <= FirstIndex && FirstIndex < 4 && \"All undef shuffle mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11285, __extension__ __PRETTY_FUNCTION__))
;
11286
11287 int FirstElt = Mask[FirstIndex];
11288 if (all_of(Mask, [FirstElt](int M) { return M < 0 || M == FirstElt; }))
11289 return (FirstElt << 6) | (FirstElt << 4) | (FirstElt << 2) | FirstElt;
11290
11291 unsigned Imm = 0;
11292 Imm |= (Mask[0] < 0 ? 0 : Mask[0]) << 0;
11293 Imm |= (Mask[1] < 0 ? 1 : Mask[1]) << 2;
11294 Imm |= (Mask[2] < 0 ? 2 : Mask[2]) << 4;
11295 Imm |= (Mask[3] < 0 ? 3 : Mask[3]) << 6;
11296 return Imm;
11297}
11298
11299static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, const SDLoc &DL,
11300 SelectionDAG &DAG) {
11301 return DAG.getTargetConstant(getV4X86ShuffleImm(Mask), DL, MVT::i8);
11302}
11303
11304// The Shuffle result is as follow:
11305// 0*a[0]0*a[1]...0*a[n] , n >=0 where a[] elements in a ascending order.
11306// Each Zeroable's element correspond to a particular Mask's element.
11307// As described in computeZeroableShuffleElements function.
11308//
11309// The function looks for a sub-mask that the nonzero elements are in
11310// increasing order. If such sub-mask exist. The function returns true.
11311static bool isNonZeroElementsInOrder(const APInt &Zeroable,
11312 ArrayRef<int> Mask, const EVT &VectorType,
11313 bool &IsZeroSideLeft) {
11314 int NextElement = -1;
11315 // Check if the Mask's nonzero elements are in increasing order.
11316 for (int i = 0, e = Mask.size(); i < e; i++) {
11317 // Checks if the mask's zeros elements are built from only zeros.
11318 assert(Mask[i] >= -1 && "Out of bound mask element!")(static_cast <bool> (Mask[i] >= -1 && "Out of bound mask element!"
) ? void (0) : __assert_fail ("Mask[i] >= -1 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11318, __extension__ __PRETTY_FUNCTION__))
;
11319 if (Mask[i] < 0)
11320 return false;
11321 if (Zeroable[i])
11322 continue;
11323 // Find the lowest non zero element
11324 if (NextElement < 0) {
11325 NextElement = Mask[i] != 0 ? VectorType.getVectorNumElements() : 0;
11326 IsZeroSideLeft = NextElement != 0;
11327 }
11328 // Exit if the mask's non zero elements are not in increasing order.
11329 if (NextElement != Mask[i])
11330 return false;
11331 NextElement++;
11332 }
11333 return true;
11334}
11335
11336/// Try to lower a shuffle with a single PSHUFB of V1 or V2.
11337static SDValue lowerShuffleWithPSHUFB(const SDLoc &DL, MVT VT,
11338 ArrayRef<int> Mask, SDValue V1,
11339 SDValue V2, const APInt &Zeroable,
11340 const X86Subtarget &Subtarget,
11341 SelectionDAG &DAG) {
11342 int Size = Mask.size();
11343 int LaneSize = 128 / VT.getScalarSizeInBits();
11344 const int NumBytes = VT.getSizeInBits() / 8;
11345 const int NumEltBytes = VT.getScalarSizeInBits() / 8;
11346
11347 assert((Subtarget.hasSSSE3() && VT.is128BitVector()) ||(static_cast <bool> ((Subtarget.hasSSSE3() && VT
.is128BitVector()) || (Subtarget.hasAVX2() && VT.is256BitVector
()) || (Subtarget.hasBWI() && VT.is512BitVector())) ?
void (0) : __assert_fail ("(Subtarget.hasSSSE3() && VT.is128BitVector()) || (Subtarget.hasAVX2() && VT.is256BitVector()) || (Subtarget.hasBWI() && VT.is512BitVector())"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11349, __extension__ __PRETTY_FUNCTION__))
11348 (Subtarget.hasAVX2() && VT.is256BitVector()) ||(static_cast <bool> ((Subtarget.hasSSSE3() && VT
.is128BitVector()) || (Subtarget.hasAVX2() && VT.is256BitVector
()) || (Subtarget.hasBWI() && VT.is512BitVector())) ?
void (0) : __assert_fail ("(Subtarget.hasSSSE3() && VT.is128BitVector()) || (Subtarget.hasAVX2() && VT.is256BitVector()) || (Subtarget.hasBWI() && VT.is512BitVector())"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11349, __extension__ __PRETTY_FUNCTION__))
11349 (Subtarget.hasBWI() && VT.is512BitVector()))(static_cast <bool> ((Subtarget.hasSSSE3() && VT
.is128BitVector()) || (Subtarget.hasAVX2() && VT.is256BitVector
()) || (Subtarget.hasBWI() && VT.is512BitVector())) ?
void (0) : __assert_fail ("(Subtarget.hasSSSE3() && VT.is128BitVector()) || (Subtarget.hasAVX2() && VT.is256BitVector()) || (Subtarget.hasBWI() && VT.is512BitVector())"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11349, __extension__ __PRETTY_FUNCTION__))
;
11350
11351 SmallVector<SDValue, 64> PSHUFBMask(NumBytes);
11352 // Sign bit set in i8 mask means zero element.
11353 SDValue ZeroMask = DAG.getConstant(0x80, DL, MVT::i8);
11354
11355 SDValue V;
11356 for (int i = 0; i < NumBytes; ++i) {
11357 int M = Mask[i / NumEltBytes];
11358 if (M < 0) {
11359 PSHUFBMask[i] = DAG.getUNDEF(MVT::i8);
11360 continue;
11361 }
11362 if (Zeroable[i / NumEltBytes]) {
11363 PSHUFBMask[i] = ZeroMask;
11364 continue;
11365 }
11366
11367 // We can only use a single input of V1 or V2.
11368 SDValue SrcV = (M >= Size ? V2 : V1);
11369 if (V && V != SrcV)
11370 return SDValue();
11371 V = SrcV;
11372 M %= Size;
11373
11374 // PSHUFB can't cross lanes, ensure this doesn't happen.
11375 if ((M / LaneSize) != ((i / NumEltBytes) / LaneSize))
11376 return SDValue();
11377
11378 M = M % LaneSize;
11379 M = M * NumEltBytes + (i % NumEltBytes);
11380 PSHUFBMask[i] = DAG.getConstant(M, DL, MVT::i8);
11381 }
11382 assert(V && "Failed to find a source input")(static_cast <bool> (V && "Failed to find a source input"
) ? void (0) : __assert_fail ("V && \"Failed to find a source input\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11382, __extension__ __PRETTY_FUNCTION__))
;
11383
11384 MVT I8VT = MVT::getVectorVT(MVT::i8, NumBytes);
11385 return DAG.getBitcast(
11386 VT, DAG.getNode(X86ISD::PSHUFB, DL, I8VT, DAG.getBitcast(I8VT, V),
11387 DAG.getBuildVector(I8VT, DL, PSHUFBMask)));
11388}
11389
11390static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
11391 const X86Subtarget &Subtarget, SelectionDAG &DAG,
11392 const SDLoc &dl);
11393
11394// X86 has dedicated shuffle that can be lowered to VEXPAND
11395static SDValue lowerShuffleToEXPAND(const SDLoc &DL, MVT VT,
11396 const APInt &Zeroable,
11397 ArrayRef<int> Mask, SDValue &V1,
11398 SDValue &V2, SelectionDAG &DAG,
11399 const X86Subtarget &Subtarget) {
11400 bool IsLeftZeroSide = true;
11401 if (!isNonZeroElementsInOrder(Zeroable, Mask, V1.getValueType(),
11402 IsLeftZeroSide))
11403 return SDValue();
11404 unsigned VEXPANDMask = (~Zeroable).getZExtValue();
11405 MVT IntegerType =
11406 MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
11407 SDValue MaskNode = DAG.getConstant(VEXPANDMask, DL, IntegerType);
11408 unsigned NumElts = VT.getVectorNumElements();
11409 assert((NumElts == 4 || NumElts == 8 || NumElts == 16) &&(static_cast <bool> ((NumElts == 4 || NumElts == 8 || NumElts
== 16) && "Unexpected number of vector elements") ? void
(0) : __assert_fail ("(NumElts == 4 || NumElts == 8 || NumElts == 16) && \"Unexpected number of vector elements\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11410, __extension__ __PRETTY_FUNCTION__))
11410 "Unexpected number of vector elements")(static_cast <bool> ((NumElts == 4 || NumElts == 8 || NumElts
== 16) && "Unexpected number of vector elements") ? void
(0) : __assert_fail ("(NumElts == 4 || NumElts == 8 || NumElts == 16) && \"Unexpected number of vector elements\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11410, __extension__ __PRETTY_FUNCTION__))
;
11411 SDValue VMask = getMaskNode(MaskNode, MVT::getVectorVT(MVT::i1, NumElts),
11412 Subtarget, DAG, DL);
11413 SDValue ZeroVector = getZeroVector(VT, Subtarget, DAG, DL);
11414 SDValue ExpandedVector = IsLeftZeroSide ? V2 : V1;
11415 return DAG.getNode(X86ISD::EXPAND, DL, VT, ExpandedVector, ZeroVector, VMask);
11416}
11417
11418static bool matchShuffleWithUNPCK(MVT VT, SDValue &V1, SDValue &V2,
11419 unsigned &UnpackOpcode, bool IsUnary,
11420 ArrayRef<int> TargetMask, const SDLoc &DL,
11421 SelectionDAG &DAG,
11422 const X86Subtarget &Subtarget) {
11423 int NumElts = VT.getVectorNumElements();
11424
11425 bool Undef1 = true, Undef2 = true, Zero1 = true, Zero2 = true;
11426 for (int i = 0; i != NumElts; i += 2) {
11427 int M1 = TargetMask[i + 0];
11428 int M2 = TargetMask[i + 1];
11429 Undef1 &= (SM_SentinelUndef == M1);
11430 Undef2 &= (SM_SentinelUndef == M2);
11431 Zero1 &= isUndefOrZero(M1);
11432 Zero2 &= isUndefOrZero(M2);
11433 }
11434 assert(!((Undef1 || Zero1) && (Undef2 || Zero2)) &&(static_cast <bool> (!((Undef1 || Zero1) && (Undef2
|| Zero2)) && "Zeroable shuffle detected") ? void (0
) : __assert_fail ("!((Undef1 || Zero1) && (Undef2 || Zero2)) && \"Zeroable shuffle detected\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11435, __extension__ __PRETTY_FUNCTION__))
11435 "Zeroable shuffle detected")(static_cast <bool> (!((Undef1 || Zero1) && (Undef2
|| Zero2)) && "Zeroable shuffle detected") ? void (0
) : __assert_fail ("!((Undef1 || Zero1) && (Undef2 || Zero2)) && \"Zeroable shuffle detected\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11435, __extension__ __PRETTY_FUNCTION__))
;
11436
11437 // Attempt to match the target mask against the unpack lo/hi mask patterns.
11438 SmallVector<int, 64> Unpckl, Unpckh;
11439 createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, IsUnary);
11440 if (isTargetShuffleEquivalent(VT, TargetMask, Unpckl, V1,
11441 (IsUnary ? V1 : V2))) {
11442 UnpackOpcode = X86ISD::UNPCKL;
11443 V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
11444 V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
11445 return true;
11446 }
11447
11448 createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, IsUnary);
11449 if (isTargetShuffleEquivalent(VT, TargetMask, Unpckh, V1,
11450 (IsUnary ? V1 : V2))) {
11451 UnpackOpcode = X86ISD::UNPCKH;
11452 V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
11453 V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
11454 return true;
11455 }
11456
11457 // If an unary shuffle, attempt to match as an unpack lo/hi with zero.
11458 if (IsUnary && (Zero1 || Zero2)) {
11459 // Don't bother if we can blend instead.
11460 if ((Subtarget.hasSSE41() || VT == MVT::v2i64 || VT == MVT::v2f64) &&
11461 isSequentialOrUndefOrZeroInRange(TargetMask, 0, NumElts, 0))
11462 return false;
11463
11464 bool MatchLo = true, MatchHi = true;
11465 for (int i = 0; (i != NumElts) && (MatchLo || MatchHi); ++i) {
11466 int M = TargetMask[i];
11467
11468 // Ignore if the input is known to be zero or the index is undef.
11469 if ((((i & 1) == 0) && Zero1) || (((i & 1) == 1) && Zero2) ||
11470 (M == SM_SentinelUndef))
11471 continue;
11472
11473 MatchLo &= (M == Unpckl[i]);
11474 MatchHi &= (M == Unpckh[i]);
11475 }
11476
11477 if (MatchLo || MatchHi) {
11478 UnpackOpcode = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
11479 V2 = Zero2 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
11480 V1 = Zero1 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
11481 return true;
11482 }
11483 }
11484
11485 // If a binary shuffle, commute and try again.
11486 if (!IsUnary) {
11487 ShuffleVectorSDNode::commuteMask(Unpckl);
11488 if (isTargetShuffleEquivalent(VT, TargetMask, Unpckl)) {
11489 UnpackOpcode = X86ISD::UNPCKL;
11490 std::swap(V1, V2);
11491 return true;
11492 }
11493
11494 ShuffleVectorSDNode::commuteMask(Unpckh);
11495 if (isTargetShuffleEquivalent(VT, TargetMask, Unpckh)) {
11496 UnpackOpcode = X86ISD::UNPCKH;
11497 std::swap(V1, V2);
11498 return true;
11499 }
11500 }
11501
11502 return false;
11503}
11504
11505// X86 has dedicated unpack instructions that can handle specific blend
11506// operations: UNPCKH and UNPCKL.
11507static SDValue lowerShuffleWithUNPCK(const SDLoc &DL, MVT VT,
11508 ArrayRef<int> Mask, SDValue V1, SDValue V2,
11509 SelectionDAG &DAG) {
11510 SmallVector<int, 8> Unpckl;
11511 createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, /* Unary = */ false);
11512 if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
11513 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
11514
11515 SmallVector<int, 8> Unpckh;
11516 createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, /* Unary = */ false);
11517 if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
11518 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
11519
11520 // Commute and try again.
11521 ShuffleVectorSDNode::commuteMask(Unpckl);
11522 if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
11523 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
11524
11525 ShuffleVectorSDNode::commuteMask(Unpckh);
11526 if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
11527 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
11528
11529 return SDValue();
11530}
11531
11532/// Check if the mask can be mapped to a preliminary shuffle (vperm 64-bit)
11533/// followed by unpack 256-bit.
11534static SDValue lowerShuffleWithUNPCK256(const SDLoc &DL, MVT VT,
11535 ArrayRef<int> Mask, SDValue V1,
11536 SDValue V2, SelectionDAG &DAG) {
11537 SmallVector<int, 32> Unpckl, Unpckh;
11538 createSplat2ShuffleMask(VT, Unpckl, /* Lo */ true);
11539 createSplat2ShuffleMask(VT, Unpckh, /* Lo */ false);
11540
11541 unsigned UnpackOpcode;
11542 if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
11543 UnpackOpcode = X86ISD::UNPCKL;
11544 else if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
11545 UnpackOpcode = X86ISD::UNPCKH;
11546 else
11547 return SDValue();
11548
11549 // This is a "natural" unpack operation (rather than the 128-bit sectored
11550 // operation implemented by AVX). We need to rearrange 64-bit chunks of the
11551 // input in order to use the x86 instruction.
11552 V1 = DAG.getVectorShuffle(MVT::v4f64, DL, DAG.getBitcast(MVT::v4f64, V1),
11553 DAG.getUNDEF(MVT::v4f64), {0, 2, 1, 3});
11554 V1 = DAG.getBitcast(VT, V1);
11555 return DAG.getNode(UnpackOpcode, DL, VT, V1, V1);
11556}
11557
11558// Check if the mask can be mapped to a TRUNCATE or VTRUNC, truncating the
11559// source into the lower elements and zeroing the upper elements.
11560static bool matchShuffleAsVTRUNC(MVT &SrcVT, MVT &DstVT, MVT VT,
11561 ArrayRef<int> Mask, const APInt &Zeroable,
11562 const X86Subtarget &Subtarget) {
11563 if (!VT.is512BitVector() && !Subtarget.hasVLX())
11564 return false;
11565
11566 unsigned NumElts = Mask.size();
11567 unsigned EltSizeInBits = VT.getScalarSizeInBits();
11568 unsigned MaxScale = 64 / EltSizeInBits;
11569
11570 for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
11571 unsigned SrcEltBits = EltSizeInBits * Scale;
11572 if (SrcEltBits < 32 && !Subtarget.hasBWI())
11573 continue;
11574 unsigned NumSrcElts = NumElts / Scale;
11575 if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale))
11576 continue;
11577 unsigned UpperElts = NumElts - NumSrcElts;
11578 if (!Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnesValue())
11579 continue;
11580 SrcVT = MVT::getIntegerVT(EltSizeInBits * Scale);
11581 SrcVT = MVT::getVectorVT(SrcVT, NumSrcElts);
11582 DstVT = MVT::getIntegerVT(EltSizeInBits);
11583 if ((NumSrcElts * EltSizeInBits) >= 128) {
11584 // ISD::TRUNCATE
11585 DstVT = MVT::getVectorVT(DstVT, NumSrcElts);
11586 } else {
11587 // X86ISD::VTRUNC
11588 DstVT = MVT::getVectorVT(DstVT, 128 / EltSizeInBits);
11589 }
11590 return true;
11591 }
11592
11593 return false;
11594}
11595
11596// Helper to create TRUNCATE/VTRUNC nodes, optionally with zero/undef upper
11597// element padding to the final DstVT.
11598static SDValue getAVX512TruncNode(const SDLoc &DL, MVT DstVT, SDValue Src,
11599 const X86Subtarget &Subtarget,
11600 SelectionDAG &DAG, bool ZeroUppers) {
11601 MVT SrcVT = Src.getSimpleValueType();
11602 MVT DstSVT = DstVT.getScalarType();
11603 unsigned NumDstElts = DstVT.getVectorNumElements();
11604 unsigned NumSrcElts = SrcVT.getVectorNumElements();
11605 unsigned DstEltSizeInBits = DstVT.getScalarSizeInBits();
11606
11607 if (!DAG.getTargetLoweringInfo().isTypeLegal(SrcVT))
11608 return SDValue();
11609
11610 // Perform a direct ISD::TRUNCATE if possible.
11611 if (NumSrcElts == NumDstElts)
11612 return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Src);
11613
11614 if (NumSrcElts > NumDstElts) {
11615 MVT TruncVT = MVT::getVectorVT(DstSVT, NumSrcElts);
11616 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Src);
11617 return extractSubVector(Trunc, 0, DAG, DL, DstVT.getSizeInBits());
11618 }
11619
11620 if ((NumSrcElts * DstEltSizeInBits) >= 128) {
11621 MVT TruncVT = MVT::getVectorVT(DstSVT, NumSrcElts);
11622 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Src);
11623 return widenSubVector(Trunc, ZeroUppers, Subtarget, DAG, DL,
11624 DstVT.getSizeInBits());
11625 }
11626
11627 // Non-VLX targets must truncate from a 512-bit type, so we need to
11628 // widen, truncate and then possibly extract the original subvector.
11629 if (!Subtarget.hasVLX() && !SrcVT.is512BitVector()) {
11630 SDValue NewSrc = widenSubVector(Src, ZeroUppers, Subtarget, DAG, DL, 512);
11631 return getAVX512TruncNode(DL, DstVT, NewSrc, Subtarget, DAG, ZeroUppers);
11632 }
11633
11634 // Fallback to a X86ISD::VTRUNC, padding if necessary.
11635 MVT TruncVT = MVT::getVectorVT(DstSVT, 128 / DstEltSizeInBits);
11636 SDValue Trunc = DAG.getNode(X86ISD::VTRUNC, DL, TruncVT, Src);
11637 if (DstVT != TruncVT)
11638 Trunc = widenSubVector(Trunc, ZeroUppers, Subtarget, DAG, DL,
11639 DstVT.getSizeInBits());
11640 return Trunc;
11641}
11642
11643// Try to lower trunc+vector_shuffle to a vpmovdb or a vpmovdw instruction.
11644//
11645// An example is the following:
11646//
11647// t0: ch = EntryToken
11648// t2: v4i64,ch = CopyFromReg t0, Register:v4i64 %0
11649// t25: v4i32 = truncate t2
11650// t41: v8i16 = bitcast t25
11651// t21: v8i16 = BUILD_VECTOR undef:i16, undef:i16, undef:i16, undef:i16,
11652// Constant:i16<0>, Constant:i16<0>, Constant:i16<0>, Constant:i16<0>
11653// t51: v8i16 = vector_shuffle<0,2,4,6,12,13,14,15> t41, t21
11654// t18: v2i64 = bitcast t51
11655//
11656// One can just use a single vpmovdw instruction, without avx512vl we need to
11657// use the zmm variant and extract the lower subvector, padding with zeroes.
11658// TODO: Merge with lowerShuffleAsVTRUNC.
11659static SDValue lowerShuffleWithVPMOV(const SDLoc &DL, MVT VT, SDValue V1,
11660 SDValue V2, ArrayRef<int> Mask,
11661 const APInt &Zeroable,
11662 const X86Subtarget &Subtarget,
11663 SelectionDAG &DAG) {
11664 assert((VT == MVT::v16i8 || VT == MVT::v8i16) && "Unexpected VTRUNC type")(static_cast <bool> ((VT == MVT::v16i8 || VT == MVT::v8i16
) && "Unexpected VTRUNC type") ? void (0) : __assert_fail
("(VT == MVT::v16i8 || VT == MVT::v8i16) && \"Unexpected VTRUNC type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11664, __extension__ __PRETTY_FUNCTION__))
;
11665 if (!Subtarget.hasAVX512())
11666 return SDValue();
11667
11668 unsigned NumElts = VT.getVectorNumElements();
11669 unsigned EltSizeInBits = VT.getScalarSizeInBits();
11670 unsigned MaxScale = 64 / EltSizeInBits;
11671 for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
11672 unsigned NumSrcElts = NumElts / Scale;
11673 unsigned UpperElts = NumElts - NumSrcElts;
11674 if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale) ||
11675 !Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnesValue())
11676 continue;
11677
11678 SDValue Src = V1;
11679 if (!Src.hasOneUse())
11680 return SDValue();
11681
11682 Src = peekThroughOneUseBitcasts(Src);
11683 if (Src.getOpcode() != ISD::TRUNCATE ||
11684 Src.getScalarValueSizeInBits() != (EltSizeInBits * Scale))
11685 return SDValue();
11686 Src = Src.getOperand(0);
11687
11688 // VPMOVWB is only available with avx512bw.
11689 MVT SrcVT = Src.getSimpleValueType();
11690 if (SrcVT.getVectorElementType() == MVT::i16 && VT == MVT::v16i8 &&
11691 !Subtarget.hasBWI())
11692 return SDValue();
11693
11694 bool UndefUppers = isUndefInRange(Mask, NumSrcElts, UpperElts);
11695 return getAVX512TruncNode(DL, VT, Src, Subtarget, DAG, !UndefUppers);
11696 }
11697
11698 return SDValue();
11699}
11700
11701// Attempt to match binary shuffle patterns as a truncate.
11702static SDValue lowerShuffleAsVTRUNC(const SDLoc &DL, MVT VT, SDValue V1,
11703 SDValue V2, ArrayRef<int> Mask,
11704 const APInt &Zeroable,
11705 const X86Subtarget &Subtarget,
11706 SelectionDAG &DAG) {
11707 assert((VT.is128BitVector() || VT.is256BitVector()) &&(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
()) && "Unexpected VTRUNC type") ? void (0) : __assert_fail
("(VT.is128BitVector() || VT.is256BitVector()) && \"Unexpected VTRUNC type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11708, __extension__ __PRETTY_FUNCTION__))
11708 "Unexpected VTRUNC type")(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
()) && "Unexpected VTRUNC type") ? void (0) : __assert_fail
("(VT.is128BitVector() || VT.is256BitVector()) && \"Unexpected VTRUNC type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11708, __extension__ __PRETTY_FUNCTION__))
;
11709 if (!Subtarget.hasAVX512())
11710 return SDValue();
11711
11712 unsigned NumElts = VT.getVectorNumElements();
11713 unsigned EltSizeInBits = VT.getScalarSizeInBits();
11714 unsigned MaxScale = 64 / EltSizeInBits;
11715 for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
11716 // TODO: Support non-BWI VPMOVWB truncations?
11717 unsigned SrcEltBits = EltSizeInBits * Scale;
11718 if (SrcEltBits < 32 && !Subtarget.hasBWI())
11719 continue;
11720
11721 // Match shuffle <0,Scale,2*Scale,..,undef_or_zero,undef_or_zero,...>
11722 // Bail if the V2 elements are undef.
11723 unsigned NumHalfSrcElts = NumElts / Scale;
11724 unsigned NumSrcElts = 2 * NumHalfSrcElts;
11725 if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale) ||
11726 isUndefInRange(Mask, NumHalfSrcElts, NumHalfSrcElts))
11727 continue;
11728
11729 // The elements beyond the truncation must be undef/zero.
11730 unsigned UpperElts = NumElts - NumSrcElts;
11731 if (UpperElts > 0 &&
11732 !Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnesValue())
11733 continue;
11734 bool UndefUppers =
11735 UpperElts > 0 && isUndefInRange(Mask, NumSrcElts, UpperElts);
11736
11737 // As we're using both sources then we need to concat them together
11738 // and truncate from the double-sized src.
11739 MVT ConcatVT = MVT::getVectorVT(VT.getScalarType(), NumElts * 2);
11740 SDValue Src = DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatVT, V1, V2);
11741
11742 MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
11743 MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
11744 Src = DAG.getBitcast(SrcVT, Src);
11745 return getAVX512TruncNode(DL, VT, Src, Subtarget, DAG, !UndefUppers);
11746 }
11747
11748 return SDValue();
11749}
11750
11751/// Check whether a compaction lowering can be done by dropping even
11752/// elements and compute how many times even elements must be dropped.
11753///
11754/// This handles shuffles which take every Nth element where N is a power of
11755/// two. Example shuffle masks:
11756///
11757/// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
11758/// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
11759/// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
11760/// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
11761/// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
11762/// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
11763///
11764/// Any of these lanes can of course be undef.
11765///
11766/// This routine only supports N <= 3.
11767/// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
11768/// for larger N.
11769///
11770/// \returns N above, or the number of times even elements must be dropped if
11771/// there is such a number. Otherwise returns zero.
11772static int canLowerByDroppingEvenElements(ArrayRef<int> Mask,
11773 bool IsSingleInput) {
11774 // The modulus for the shuffle vector entries is based on whether this is
11775 // a single input or not.
11776 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
11777 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&(static_cast <bool> (isPowerOf2_32((uint32_t)ShuffleModulus
) && "We should only be called with masks with a power-of-2 size!"
) ? void (0) : __assert_fail ("isPowerOf2_32((uint32_t)ShuffleModulus) && \"We should only be called with masks with a power-of-2 size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11778, __extension__ __PRETTY_FUNCTION__))
11778 "We should only be called with masks with a power-of-2 size!")(static_cast <bool> (isPowerOf2_32((uint32_t)ShuffleModulus
) && "We should only be called with masks with a power-of-2 size!"
) ? void (0) : __assert_fail ("isPowerOf2_32((uint32_t)ShuffleModulus) && \"We should only be called with masks with a power-of-2 size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11778, __extension__ __PRETTY_FUNCTION__))
;
11779
11780 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
11781
11782 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
11783 // and 2^3 simultaneously. This is because we may have ambiguity with
11784 // partially undef inputs.
11785 bool ViableForN[3] = {true, true, true};
11786
11787 for (int i = 0, e = Mask.size(); i < e; ++i) {
11788 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
11789 // want.
11790 if (Mask[i] < 0)
11791 continue;
11792
11793 bool IsAnyViable = false;
11794 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
11795 if (ViableForN[j]) {
11796 uint64_t N = j + 1;
11797
11798 // The shuffle mask must be equal to (i * 2^N) % M.
11799 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
11800 IsAnyViable = true;
11801 else
11802 ViableForN[j] = false;
11803 }
11804 // Early exit if we exhaust the possible powers of two.
11805 if (!IsAnyViable)
11806 break;
11807 }
11808
11809 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
11810 if (ViableForN[j])
11811 return j + 1;
11812
11813 // Return 0 as there is no viable power of two.
11814 return 0;
11815}
11816
11817// X86 has dedicated pack instructions that can handle specific truncation
11818// operations: PACKSS and PACKUS.
11819// Checks for compaction shuffle masks if MaxStages > 1.
11820// TODO: Add support for matching multiple PACKSS/PACKUS stages.
11821static bool matchShuffleWithPACK(MVT VT, MVT &SrcVT, SDValue &V1, SDValue &V2,
11822 unsigned &PackOpcode, ArrayRef<int> TargetMask,
11823 const SelectionDAG &DAG,
11824 const X86Subtarget &Subtarget,
11825 unsigned MaxStages = 1) {
11826 unsigned NumElts = VT.getVectorNumElements();
11827 unsigned BitSize = VT.getScalarSizeInBits();
11828 assert(0 < MaxStages && MaxStages <= 3 && (BitSize << MaxStages) <= 64 &&(static_cast <bool> (0 < MaxStages && MaxStages
<= 3 && (BitSize << MaxStages) <= 64 &&
"Illegal maximum compaction") ? void (0) : __assert_fail ("0 < MaxStages && MaxStages <= 3 && (BitSize << MaxStages) <= 64 && \"Illegal maximum compaction\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11829, __extension__ __PRETTY_FUNCTION__))
11829 "Illegal maximum compaction")(static_cast <bool> (0 < MaxStages && MaxStages
<= 3 && (BitSize << MaxStages) <= 64 &&
"Illegal maximum compaction") ? void (0) : __assert_fail ("0 < MaxStages && MaxStages <= 3 && (BitSize << MaxStages) <= 64 && \"Illegal maximum compaction\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11829, __extension__ __PRETTY_FUNCTION__))
;
11830
11831 auto MatchPACK = [&](SDValue N1, SDValue N2, MVT PackVT) {
11832 unsigned NumSrcBits = PackVT.getScalarSizeInBits();
11833 unsigned NumPackedBits = NumSrcBits - BitSize;
11834 N1 = peekThroughBitcasts(N1);
11835 N2 = peekThroughBitcasts(N2);
11836 unsigned NumBits1 = N1.getScalarValueSizeInBits();
11837 unsigned NumBits2 = N2.getScalarValueSizeInBits();
11838 bool IsZero1 = llvm::isNullOrNullSplat(N1, /*AllowUndefs*/ false);
11839 bool IsZero2 = llvm::isNullOrNullSplat(N2, /*AllowUndefs*/ false);
11840 if ((!N1.isUndef() && !IsZero1 && NumBits1 != NumSrcBits) ||
11841 (!N2.isUndef() && !IsZero2 && NumBits2 != NumSrcBits))
11842 return false;
11843 if (Subtarget.hasSSE41() || BitSize == 8) {
11844 APInt ZeroMask = APInt::getHighBitsSet(NumSrcBits, NumPackedBits);
11845 if ((N1.isUndef() || IsZero1 || DAG.MaskedValueIsZero(N1, ZeroMask)) &&
11846 (N2.isUndef() || IsZero2 || DAG.MaskedValueIsZero(N2, ZeroMask))) {
11847 V1 = N1;
11848 V2 = N2;
11849 SrcVT = PackVT;
11850 PackOpcode = X86ISD::PACKUS;
11851 return true;
11852 }
11853 }
11854 bool IsAllOnes1 = llvm::isAllOnesOrAllOnesSplat(N1, /*AllowUndefs*/ false);
11855 bool IsAllOnes2 = llvm::isAllOnesOrAllOnesSplat(N2, /*AllowUndefs*/ false);
11856 if ((N1.isUndef() || IsZero1 || IsAllOnes1 ||
11857 DAG.ComputeNumSignBits(N1) > NumPackedBits) &&
11858 (N2.isUndef() || IsZero2 || IsAllOnes2 ||
11859 DAG.ComputeNumSignBits(N2) > NumPackedBits)) {
11860 V1 = N1;
11861 V2 = N2;
11862 SrcVT = PackVT;
11863 PackOpcode = X86ISD::PACKSS;
11864 return true;
11865 }
11866 return false;
11867 };
11868
11869 // Attempt to match against wider and wider compaction patterns.
11870 for (unsigned NumStages = 1; NumStages <= MaxStages; ++NumStages) {
11871 MVT PackSVT = MVT::getIntegerVT(BitSize << NumStages);
11872 MVT PackVT = MVT::getVectorVT(PackSVT, NumElts >> NumStages);
11873
11874 // Try binary shuffle.
11875 SmallVector<int, 32> BinaryMask;
11876 createPackShuffleMask(VT, BinaryMask, false, NumStages);
11877 if (isTargetShuffleEquivalent(VT, TargetMask, BinaryMask, V1, V2))
11878 if (MatchPACK(V1, V2, PackVT))
11879 return true;
11880
11881 // Try unary shuffle.
11882 SmallVector<int, 32> UnaryMask;
11883 createPackShuffleMask(VT, UnaryMask, true, NumStages);
11884 if (isTargetShuffleEquivalent(VT, TargetMask, UnaryMask, V1))
11885 if (MatchPACK(V1, V1, PackVT))
11886 return true;
11887 }
11888
11889 return false;
11890}
11891
11892static SDValue lowerShuffleWithPACK(const SDLoc &DL, MVT VT, ArrayRef<int> Mask,
11893 SDValue V1, SDValue V2, SelectionDAG &DAG,
11894 const X86Subtarget &Subtarget) {
11895 MVT PackVT;
11896 unsigned PackOpcode;
11897 unsigned SizeBits = VT.getSizeInBits();
11898 unsigned EltBits = VT.getScalarSizeInBits();
11899 unsigned MaxStages = Log2_32(64 / EltBits);
11900 if (!matchShuffleWithPACK(VT, PackVT, V1, V2, PackOpcode, Mask, DAG,
11901 Subtarget, MaxStages))
11902 return SDValue();
11903
11904 unsigned CurrentEltBits = PackVT.getScalarSizeInBits();
11905 unsigned NumStages = Log2_32(CurrentEltBits / EltBits);
11906
11907 // Don't lower multi-stage packs on AVX512, truncation is better.
11908 if (NumStages != 1 && SizeBits == 128 && Subtarget.hasVLX())
11909 return SDValue();
11910
11911 // Pack to the largest type possible:
11912 // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
11913 unsigned MaxPackBits = 16;
11914 if (CurrentEltBits > 16 &&
11915 (PackOpcode == X86ISD::PACKSS || Subtarget.hasSSE41()))
11916 MaxPackBits = 32;
11917
11918 // Repeatedly pack down to the target size.
11919 SDValue Res;
11920 for (unsigned i = 0; i != NumStages; ++i) {
11921 unsigned SrcEltBits = std::min(MaxPackBits, CurrentEltBits);
11922 unsigned NumSrcElts = SizeBits / SrcEltBits;
11923 MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
11924 MVT DstSVT = MVT::getIntegerVT(SrcEltBits / 2);
11925 MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
11926 MVT DstVT = MVT::getVectorVT(DstSVT, NumSrcElts * 2);
11927 Res = DAG.getNode(PackOpcode, DL, DstVT, DAG.getBitcast(SrcVT, V1),
11928 DAG.getBitcast(SrcVT, V2));
11929 V1 = V2 = Res;
11930 CurrentEltBits /= 2;
11931 }
11932 assert(Res && Res.getValueType() == VT &&(static_cast <bool> (Res && Res.getValueType() ==
VT && "Failed to lower compaction shuffle") ? void (
0) : __assert_fail ("Res && Res.getValueType() == VT && \"Failed to lower compaction shuffle\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11933, __extension__ __PRETTY_FUNCTION__))
11933 "Failed to lower compaction shuffle")(static_cast <bool> (Res && Res.getValueType() ==
VT && "Failed to lower compaction shuffle") ? void (
0) : __assert_fail ("Res && Res.getValueType() == VT && \"Failed to lower compaction shuffle\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 11933, __extension__ __PRETTY_FUNCTION__))
;
11934 return Res;
11935}
11936
11937/// Try to emit a bitmask instruction for a shuffle.
11938///
11939/// This handles cases where we can model a blend exactly as a bitmask due to
11940/// one of the inputs being zeroable.
11941static SDValue lowerShuffleAsBitMask(const SDLoc &DL, MVT VT, SDValue V1,
11942 SDValue V2, ArrayRef<int> Mask,
11943 const APInt &Zeroable,
11944 const X86Subtarget &Subtarget,
11945 SelectionDAG &DAG) {
11946 MVT MaskVT = VT;
11947 MVT EltVT = VT.getVectorElementType();
11948 SDValue Zero, AllOnes;
11949 // Use f64 if i64 isn't legal.
11950 if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
11951 EltVT = MVT::f64;
11952 MaskVT = MVT::getVectorVT(EltVT, Mask.size());
11953 }
11954
11955 MVT LogicVT = VT;
11956 if (EltVT == MVT::f32 || EltVT == MVT::f64) {
11957 Zero = DAG.getConstantFP(0.0, DL, EltVT);
11958 APFloat AllOnesValue = APFloat::getAllOnesValue(
11959 SelectionDAG::EVTToAPFloatSemantics(EltVT), EltVT.getSizeInBits());
11960 AllOnes = DAG.getConstantFP(AllOnesValue, DL, EltVT);
11961 LogicVT =
11962 MVT::getVectorVT(EltVT == MVT::f64 ? MVT::i64 : MVT::i32, Mask.size());
11963 } else {
11964 Zero = DAG.getConstant(0, DL, EltVT);
11965 AllOnes = DAG.getAllOnesConstant(DL, EltVT);
11966 }
11967
11968 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
11969 SDValue V;
11970 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
11971 if (Zeroable[i])
11972 continue;
11973 if (Mask[i] % Size != i)
11974 return SDValue(); // Not a blend.
11975 if (!V)
11976 V = Mask[i] < Size ? V1 : V2;
11977 else if (V != (Mask[i] < Size ? V1 : V2))
11978 return SDValue(); // Can only let one input through the mask.
11979
11980 VMaskOps[i] = AllOnes;
11981 }
11982 if (!V)
11983 return SDValue(); // No non-zeroable elements!
11984
11985 SDValue VMask = DAG.getBuildVector(MaskVT, DL, VMaskOps);
11986 VMask = DAG.getBitcast(LogicVT, VMask);
11987 V = DAG.getBitcast(LogicVT, V);
11988 SDValue And = DAG.getNode(ISD::AND, DL, LogicVT, V, VMask);
11989 return DAG.getBitcast(VT, And);
11990}
11991
11992/// Try to emit a blend instruction for a shuffle using bit math.
11993///
11994/// This is used as a fallback approach when first class blend instructions are
11995/// unavailable. Currently it is only suitable for integer vectors, but could
11996/// be generalized for floating point vectors if desirable.
11997static SDValue lowerShuffleAsBitBlend(const SDLoc &DL, MVT VT, SDValue V1,
11998 SDValue V2, ArrayRef<int> Mask,
11999 SelectionDAG &DAG) {
12000 assert(VT.isInteger() && "Only supports integer vector types!")(static_cast <bool> (VT.isInteger() && "Only supports integer vector types!"
) ? void (0) : __assert_fail ("VT.isInteger() && \"Only supports integer vector types!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12000, __extension__ __PRETTY_FUNCTION__))
;
12001 MVT EltVT = VT.getVectorElementType();
12002 SDValue Zero = DAG.getConstant(0, DL, EltVT);
12003 SDValue AllOnes = DAG.getAllOnesConstant(DL, EltVT);
12004 SmallVector<SDValue, 16> MaskOps;
12005 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
12006 if (Mask[i] >= 0 && Mask[i] != i && Mask[i] != i + Size)
12007 return SDValue(); // Shuffled input!
12008 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
12009 }
12010
12011 SDValue V1Mask = DAG.getBuildVector(VT, DL, MaskOps);
12012 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
12013 V2 = DAG.getNode(X86ISD::ANDNP, DL, VT, V1Mask, V2);
12014 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
12015}
12016
12017static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
12018 SDValue PreservedSrc,
12019 const X86Subtarget &Subtarget,
12020 SelectionDAG &DAG);
12021
12022static bool matchShuffleAsBlend(SDValue V1, SDValue V2,
12023 MutableArrayRef<int> Mask,
12024 const APInt &Zeroable, bool &ForceV1Zero,
12025 bool &ForceV2Zero, uint64_t &BlendMask) {
12026 bool V1IsZeroOrUndef =
12027 V1.isUndef() || ISD::isBuildVectorAllZeros(V1.getNode());
12028 bool V2IsZeroOrUndef =
12029 V2.isUndef() || ISD::isBuildVectorAllZeros(V2.getNode());
12030
12031 BlendMask = 0;
12032 ForceV1Zero = false, ForceV2Zero = false;
12033 assert(Mask.size() <= 64 && "Shuffle mask too big for blend mask")(static_cast <bool> (Mask.size() <= 64 && "Shuffle mask too big for blend mask"
) ? void (0) : __assert_fail ("Mask.size() <= 64 && \"Shuffle mask too big for blend mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12033, __extension__ __PRETTY_FUNCTION__))
;
12034
12035 // Attempt to generate the binary blend mask. If an input is zero then
12036 // we can use any lane.
12037 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
12038 int M = Mask[i];
12039 if (M == SM_SentinelUndef)
12040 continue;
12041 if (M == i)
12042 continue;
12043 if (M == i + Size) {
12044 BlendMask |= 1ull << i;
12045 continue;
12046 }
12047 if (Zeroable[i]) {
12048 if (V1IsZeroOrUndef) {
12049 ForceV1Zero = true;
12050 Mask[i] = i;
12051 continue;
12052 }
12053 if (V2IsZeroOrUndef) {
12054 ForceV2Zero = true;
12055 BlendMask |= 1ull << i;
12056 Mask[i] = i + Size;
12057 continue;
12058 }
12059 }
12060 return false;
12061 }
12062 return true;
12063}
12064
12065static uint64_t scaleVectorShuffleBlendMask(uint64_t BlendMask, int Size,
12066 int Scale) {
12067 uint64_t ScaledMask = 0;
12068 for (int i = 0; i != Size; ++i)
12069 if (BlendMask & (1ull << i))
12070 ScaledMask |= ((1ull << Scale) - 1) << (i * Scale);
12071 return ScaledMask;
12072}
12073
12074/// Try to emit a blend instruction for a shuffle.
12075///
12076/// This doesn't do any checks for the availability of instructions for blending
12077/// these values. It relies on the availability of the X86ISD::BLENDI pattern to
12078/// be matched in the backend with the type given. What it does check for is
12079/// that the shuffle mask is a blend, or convertible into a blend with zero.
12080static SDValue lowerShuffleAsBlend(const SDLoc &DL, MVT VT, SDValue V1,
12081 SDValue V2, ArrayRef<int> Original,
12082 const APInt &Zeroable,
12083 const X86Subtarget &Subtarget,
12084 SelectionDAG &DAG) {
12085 uint64_t BlendMask = 0;
12086 bool ForceV1Zero = false, ForceV2Zero = false;
12087 SmallVector<int, 64> Mask(Original.begin(), Original.end());
12088 if (!matchShuffleAsBlend(V1, V2, Mask, Zeroable, ForceV1Zero, ForceV2Zero,
12089 BlendMask))
12090 return SDValue();
12091
12092 // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
12093 if (ForceV1Zero)
12094 V1 = getZeroVector(VT, Subtarget, DAG, DL);
12095 if (ForceV2Zero)
12096 V2 = getZeroVector(VT, Subtarget, DAG, DL);
12097
12098 switch (VT.SimpleTy) {
12099 case MVT::v4i64:
12100 case MVT::v8i32:
12101 assert(Subtarget.hasAVX2() && "256-bit integer blends require AVX2!")(static_cast <bool> (Subtarget.hasAVX2() && "256-bit integer blends require AVX2!"
) ? void (0) : __assert_fail ("Subtarget.hasAVX2() && \"256-bit integer blends require AVX2!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12101, __extension__ __PRETTY_FUNCTION__))
;
12102 LLVM_FALLTHROUGH[[gnu::fallthrough]];
12103 case MVT::v4f64:
12104 case MVT::v8f32:
12105 assert(Subtarget.hasAVX() && "256-bit float blends require AVX!")(static_cast <bool> (Subtarget.hasAVX() && "256-bit float blends require AVX!"
) ? void (0) : __assert_fail ("Subtarget.hasAVX() && \"256-bit float blends require AVX!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12105, __extension__ __PRETTY_FUNCTION__))
;
12106 LLVM_FALLTHROUGH[[gnu::fallthrough]];
12107 case MVT::v2f64:
12108 case MVT::v2i64:
12109 case MVT::v4f32:
12110 case MVT::v4i32:
12111 case MVT::v8i16:
12112 assert(Subtarget.hasSSE41() && "128-bit blends require SSE41!")(static_cast <bool> (Subtarget.hasSSE41() && "128-bit blends require SSE41!"
) ? void (0) : __assert_fail ("Subtarget.hasSSE41() && \"128-bit blends require SSE41!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12112, __extension__ __PRETTY_FUNCTION__))
;
12113 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
12114 DAG.getTargetConstant(BlendMask, DL, MVT::i8));
12115 case MVT::v16i16: {
12116 assert(Subtarget.hasAVX2() && "v16i16 blends require AVX2!")(static_cast <bool> (Subtarget.hasAVX2() && "v16i16 blends require AVX2!"
) ? void (0) : __assert_fail ("Subtarget.hasAVX2() && \"v16i16 blends require AVX2!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12116, __extension__ __PRETTY_FUNCTION__))
;
12117 SmallVector<int, 8> RepeatedMask;
12118 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
12119 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
12120 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!")(static_cast <bool> (RepeatedMask.size() == 8 &&
"Repeated mask size doesn't match!") ? void (0) : __assert_fail
("RepeatedMask.size() == 8 && \"Repeated mask size doesn't match!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12120, __extension__ __PRETTY_FUNCTION__))
;
12121 BlendMask = 0;
12122 for (int i = 0; i < 8; ++i)
12123 if (RepeatedMask[i] >= 8)
12124 BlendMask |= 1ull << i;
12125 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
12126 DAG.getTargetConstant(BlendMask, DL, MVT::i8));
12127 }
12128 // Use PBLENDW for lower/upper lanes and then blend lanes.
12129 // TODO - we should allow 2 PBLENDW here and leave shuffle combine to
12130 // merge to VSELECT where useful.
12131 uint64_t LoMask = BlendMask & 0xFF;
12132 uint64_t HiMask = (BlendMask >> 8) & 0xFF;
12133 if (LoMask == 0 || LoMask == 255 || HiMask == 0 || HiMask == 255) {
12134 SDValue Lo = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
12135 DAG.getTargetConstant(LoMask, DL, MVT::i8));
12136 SDValue Hi = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
12137 DAG.getTargetConstant(HiMask, DL, MVT::i8));
12138 return DAG.getVectorShuffle(
12139 MVT::v16i16, DL, Lo, Hi,
12140 {0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31});
12141 }
12142 LLVM_FALLTHROUGH[[gnu::fallthrough]];
12143 }
12144 case MVT::v32i8:
12145 assert(Subtarget.hasAVX2() && "256-bit byte-blends require AVX2!")(static_cast <bool> (Subtarget.hasAVX2() && "256-bit byte-blends require AVX2!"
) ? void (0) : __assert_fail ("Subtarget.hasAVX2() && \"256-bit byte-blends require AVX2!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12145, __extension__ __PRETTY_FUNCTION__))
;
12146 LLVM_FALLTHROUGH[[gnu::fallthrough]];
12147 case MVT::v16i8: {
12148 assert(Subtarget.hasSSE41() && "128-bit byte-blends require SSE41!")(static_cast <bool> (Subtarget.hasSSE41() && "128-bit byte-blends require SSE41!"
) ? void (0) : __assert_fail ("Subtarget.hasSSE41() && \"128-bit byte-blends require SSE41!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12148, __extension__ __PRETTY_FUNCTION__))
;
12149
12150 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
12151 if (SDValue Masked = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
12152 Subtarget, DAG))
12153 return Masked;
12154
12155 if (Subtarget.hasBWI() && Subtarget.hasVLX()) {
12156 MVT IntegerType =
12157 MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
12158 SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
12159 return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
12160 }
12161
12162 // If we have VPTERNLOG, we can use that as a bit blend.
12163 if (Subtarget.hasVLX())
12164 if (SDValue BitBlend =
12165 lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
12166 return BitBlend;
12167
12168 // Scale the blend by the number of bytes per element.
12169 int Scale = VT.getScalarSizeInBits() / 8;
12170
12171 // This form of blend is always done on bytes. Compute the byte vector
12172 // type.
12173 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
12174
12175 // x86 allows load folding with blendvb from the 2nd source operand. But
12176 // we are still using LLVM select here (see comment below), so that's V1.
12177 // If V2 can be load-folded and V1 cannot be load-folded, then commute to
12178 // allow that load-folding possibility.
12179 if (!ISD::isNormalLoad(V1.getNode()) && ISD::isNormalLoad(V2.getNode())) {
12180 ShuffleVectorSDNode::commuteMask(Mask);
12181 std::swap(V1, V2);
12182 }
12183
12184 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
12185 // mix of LLVM's code generator and the x86 backend. We tell the code
12186 // generator that boolean values in the elements of an x86 vector register
12187 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
12188 // mapping a select to operand #1, and 'false' mapping to operand #2. The
12189 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
12190 // of the element (the remaining are ignored) and 0 in that high bit would
12191 // mean operand #1 while 1 in the high bit would mean operand #2. So while
12192 // the LLVM model for boolean values in vector elements gets the relevant
12193 // bit set, it is set backwards and over constrained relative to x86's
12194 // actual model.
12195 SmallVector<SDValue, 32> VSELECTMask;
12196 for (int i = 0, Size = Mask.size(); i < Size; ++i)
12197 for (int j = 0; j < Scale; ++j)
12198 VSELECTMask.push_back(
12199 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
12200 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
12201 MVT::i8));
12202
12203 V1 = DAG.getBitcast(BlendVT, V1);
12204 V2 = DAG.getBitcast(BlendVT, V2);
12205 return DAG.getBitcast(
12206 VT,
12207 DAG.getSelect(DL, BlendVT, DAG.getBuildVector(BlendVT, DL, VSELECTMask),
12208 V1, V2));
12209 }
12210 case MVT::v16f32:
12211 case MVT::v8f64:
12212 case MVT::v8i64:
12213 case MVT::v16i32:
12214 case MVT::v32i16:
12215 case MVT::v64i8: {
12216 // Attempt to lower to a bitmask if we can. Only if not optimizing for size.
12217 bool OptForSize = DAG.shouldOptForSize();
12218 if (!OptForSize) {
12219 if (SDValue Masked = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
12220 Subtarget, DAG))
12221 return Masked;
12222 }
12223
12224 // Otherwise load an immediate into a GPR, cast to k-register, and use a
12225 // masked move.
12226 MVT IntegerType =
12227 MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
12228 SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
12229 return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
12230 }
12231 default:
12232 llvm_unreachable("Not a supported integer vector type!")::llvm::llvm_unreachable_internal("Not a supported integer vector type!"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12232)
;
12233 }
12234}
12235
12236/// Try to lower as a blend of elements from two inputs followed by
12237/// a single-input permutation.
12238///
12239/// This matches the pattern where we can blend elements from two inputs and
12240/// then reduce the shuffle to a single-input permutation.
12241static SDValue lowerShuffleAsBlendAndPermute(const SDLoc &DL, MVT VT,
12242 SDValue V1, SDValue V2,
12243 ArrayRef<int> Mask,
12244 SelectionDAG &DAG,
12245 bool ImmBlends = false) {
12246 // We build up the blend mask while checking whether a blend is a viable way
12247 // to reduce the shuffle.
12248 SmallVector<int, 32> BlendMask(Mask.size(), -1);
12249 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
12250
12251 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
12252 if (Mask[i] < 0)
12253 continue;
12254
12255 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.")(static_cast <bool> (Mask[i] < Size * 2 && "Shuffle input is out of bounds."
) ? void (0) : __assert_fail ("Mask[i] < Size * 2 && \"Shuffle input is out of bounds.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12255, __extension__ __PRETTY_FUNCTION__))
;
12256
12257 if (BlendMask[Mask[i] % Size] < 0)
12258 BlendMask[Mask[i] % Size] = Mask[i];
12259 else if (BlendMask[Mask[i] % Size] != Mask[i])
12260 return SDValue(); // Can't blend in the needed input!
12261
12262 PermuteMask[i] = Mask[i] % Size;
12263 }
12264
12265 // If only immediate blends, then bail if the blend mask can't be widened to
12266 // i16.
12267 unsigned EltSize = VT.getScalarSizeInBits();
12268 if (ImmBlends && EltSize == 8 && !canWidenShuffleElements(BlendMask))
12269 return SDValue();
12270
12271 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
12272 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
12273}
12274
12275/// Try to lower as an unpack of elements from two inputs followed by
12276/// a single-input permutation.
12277///
12278/// This matches the pattern where we can unpack elements from two inputs and
12279/// then reduce the shuffle to a single-input (wider) permutation.
12280static SDValue lowerShuffleAsUNPCKAndPermute(const SDLoc &DL, MVT VT,
12281 SDValue V1, SDValue V2,
12282 ArrayRef<int> Mask,
12283 SelectionDAG &DAG) {
12284 int NumElts = Mask.size();
12285 int NumLanes = VT.getSizeInBits() / 128;
12286 int NumLaneElts = NumElts / NumLanes;
12287 int NumHalfLaneElts = NumLaneElts / 2;
12288
12289 bool MatchLo = true, MatchHi = true;
12290 SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
12291
12292 // Determine UNPCKL/UNPCKH type and operand order.
12293 for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
12294 for (int Elt = 0; Elt != NumLaneElts; ++Elt) {
12295 int M = Mask[Lane + Elt];
12296 if (M < 0)
12297 continue;
12298
12299 SDValue &Op = Ops[Elt & 1];
12300 if (M < NumElts && (Op.isUndef() || Op == V1))
12301 Op = V1;
12302 else if (NumElts <= M && (Op.isUndef() || Op == V2))
12303 Op = V2;
12304 else
12305 return SDValue();
12306
12307 int Lo = Lane, Mid = Lane + NumHalfLaneElts, Hi = Lane + NumLaneElts;
12308 MatchLo &= isUndefOrInRange(M, Lo, Mid) ||
12309 isUndefOrInRange(M, NumElts + Lo, NumElts + Mid);
12310 MatchHi &= isUndefOrInRange(M, Mid, Hi) ||
12311 isUndefOrInRange(M, NumElts + Mid, NumElts + Hi);
12312 if (!MatchLo && !MatchHi)
12313 return SDValue();
12314 }
12315 }
12316 assert((MatchLo ^ MatchHi) && "Failed to match UNPCKLO/UNPCKHI")(static_cast <bool> ((MatchLo ^ MatchHi) && "Failed to match UNPCKLO/UNPCKHI"
) ? void (0) : __assert_fail ("(MatchLo ^ MatchHi) && \"Failed to match UNPCKLO/UNPCKHI\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12316, __extension__ __PRETTY_FUNCTION__))
;
12317
12318 // Now check that each pair of elts come from the same unpack pair
12319 // and set the permute mask based on each pair.
12320 // TODO - Investigate cases where we permute individual elements.
12321 SmallVector<int, 32> PermuteMask(NumElts, -1);
12322 for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
12323 for (int Elt = 0; Elt != NumLaneElts; Elt += 2) {
12324 int M0 = Mask[Lane + Elt + 0];
12325 int M1 = Mask[Lane + Elt + 1];
12326 if (0 <= M0 && 0 <= M1 &&
12327 (M0 % NumHalfLaneElts) != (M1 % NumHalfLaneElts))
12328 return SDValue();
12329 if (0 <= M0)
12330 PermuteMask[Lane + Elt + 0] = Lane + (2 * (M0 % NumHalfLaneElts));
12331 if (0 <= M1)
12332 PermuteMask[Lane + Elt + 1] = Lane + (2 * (M1 % NumHalfLaneElts)) + 1;
12333 }
12334 }
12335
12336 unsigned UnpckOp = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
12337 SDValue Unpck = DAG.getNode(UnpckOp, DL, VT, Ops);
12338 return DAG.getVectorShuffle(VT, DL, Unpck, DAG.getUNDEF(VT), PermuteMask);
12339}
12340
12341/// Helper to form a PALIGNR-based rotate+permute, merging 2 inputs and then
12342/// permuting the elements of the result in place.
12343static SDValue lowerShuffleAsByteRotateAndPermute(
12344 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
12345 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
12346 if ((VT.is128BitVector() && !Subtarget.hasSSSE3()) ||
12347 (VT.is256BitVector() && !Subtarget.hasAVX2()) ||
12348 (VT.is512BitVector() && !Subtarget.hasBWI()))
12349 return SDValue();
12350
12351 // We don't currently support lane crossing permutes.
12352 if (is128BitLaneCrossingShuffleMask(VT, Mask))
12353 return SDValue();
12354
12355 int Scale = VT.getScalarSizeInBits() / 8;
12356 int NumLanes = VT.getSizeInBits() / 128;
12357 int NumElts = VT.getVectorNumElements();
12358 int NumEltsPerLane = NumElts / NumLanes;
12359
12360 // Determine range of mask elts.
12361 bool Blend1 = true;
12362 bool Blend2 = true;
12363 std::pair<int, int> Range1 = std::make_pair(INT_MAX2147483647, INT_MIN(-2147483647 -1));
12364 std::pair<int, int> Range2 = std::make_pair(INT_MAX2147483647, INT_MIN(-2147483647 -1));
12365 for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
12366 for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
12367 int M = Mask[Lane + Elt];
12368 if (M < 0)
12369 continue;
12370 if (M < NumElts) {
12371 Blend1 &= (M == (Lane + Elt));
12372 assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask")(static_cast <bool> (Lane <= M && M < (Lane
+ NumEltsPerLane) && "Out of range mask") ? void (0)
: __assert_fail ("Lane <= M && M < (Lane + NumEltsPerLane) && \"Out of range mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12372, __extension__ __PRETTY_FUNCTION__))
;
12373 M = M % NumEltsPerLane;
12374 Range1.first = std::min(Range1.first, M);
12375 Range1.second = std::max(Range1.second, M);
12376 } else {
12377 M -= NumElts;
12378 Blend2 &= (M == (Lane + Elt));
12379 assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask")(static_cast <bool> (Lane <= M && M < (Lane
+ NumEltsPerLane) && "Out of range mask") ? void (0)
: __assert_fail ("Lane <= M && M < (Lane + NumEltsPerLane) && \"Out of range mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12379, __extension__ __PRETTY_FUNCTION__))
;
12380 M = M % NumEltsPerLane;
12381 Range2.first = std::min(Range2.first, M);
12382 Range2.second = std::max(Range2.second, M);
12383 }
12384 }
12385 }
12386
12387 // Bail if we don't need both elements.
12388 // TODO - it might be worth doing this for unary shuffles if the permute
12389 // can be widened.
12390 if (!(0 <= Range1.first && Range1.second < NumEltsPerLane) ||
12391 !(0 <= Range2.first && Range2.second < NumEltsPerLane))
12392 return SDValue();
12393
12394 if (VT.getSizeInBits() > 128 && (Blend1 || Blend2))
12395 return SDValue();
12396
12397 // Rotate the 2 ops so we can access both ranges, then permute the result.
12398 auto RotateAndPermute = [&](SDValue Lo, SDValue Hi, int RotAmt, int Ofs) {
12399 MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
12400 SDValue Rotate = DAG.getBitcast(
12401 VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, DAG.getBitcast(ByteVT, Hi),
12402 DAG.getBitcast(ByteVT, Lo),
12403 DAG.getTargetConstant(Scale * RotAmt, DL, MVT::i8)));
12404 SmallVector<int, 64> PermMask(NumElts, SM_SentinelUndef);
12405 for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
12406 for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
12407 int M = Mask[Lane + Elt];
12408 if (M < 0)
12409 continue;
12410 if (M < NumElts)
12411 PermMask[Lane + Elt] = Lane + ((M + Ofs - RotAmt) % NumEltsPerLane);
12412 else
12413 PermMask[Lane + Elt] = Lane + ((M - Ofs - RotAmt) % NumEltsPerLane);
12414 }
12415 }
12416 return DAG.getVectorShuffle(VT, DL, Rotate, DAG.getUNDEF(VT), PermMask);
12417 };
12418
12419 // Check if the ranges are small enough to rotate from either direction.
12420 if (Range2.second < Range1.first)
12421 return RotateAndPermute(V1, V2, Range1.first, 0);
12422 if (Range1.second < Range2.first)
12423 return RotateAndPermute(V2, V1, Range2.first, NumElts);
12424 return SDValue();
12425}
12426
12427/// Generic routine to decompose a shuffle and blend into independent
12428/// blends and permutes.
12429///
12430/// This matches the extremely common pattern for handling combined
12431/// shuffle+blend operations on newer X86 ISAs where we have very fast blend
12432/// operations. It will try to pick the best arrangement of shuffles and
12433/// blends. For vXi8/vXi16 shuffles we may use unpack instead of blend.
12434static SDValue lowerShuffleAsDecomposedShuffleMerge(
12435 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
12436 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
12437 int NumElts = Mask.size();
12438 int NumLanes = VT.getSizeInBits() / 128;
12439 int NumEltsPerLane = NumElts / NumLanes;
12440
12441 // Shuffle the input elements into the desired positions in V1 and V2 and
12442 // unpack/blend them together.
12443 bool IsAlternating = true;
12444 SmallVector<int, 32> V1Mask(NumElts, -1);
12445 SmallVector<int, 32> V2Mask(NumElts, -1);
12446 SmallVector<int, 32> FinalMask(NumElts, -1);
12447 for (int i = 0; i < NumElts; ++i) {
12448 int M = Mask[i];
12449 if (M >= 0 && M < NumElts) {
12450 V1Mask[i] = M;
12451 FinalMask[i] = i;
12452 IsAlternating &= (i & 1) == 0;
12453 } else if (M >= NumElts) {
12454 V2Mask[i] = M - NumElts;
12455 FinalMask[i] = i + NumElts;
12456 IsAlternating &= (i & 1) == 1;
12457 }
12458 }
12459
12460 // Try to lower with the simpler initial blend/unpack/rotate strategies unless
12461 // one of the input shuffles would be a no-op. We prefer to shuffle inputs as
12462 // the shuffle may be able to fold with a load or other benefit. However, when
12463 // we'll have to do 2x as many shuffles in order to achieve this, a 2-input
12464 // pre-shuffle first is a better strategy.
12465 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask)) {
12466 // Only prefer immediate blends to unpack/rotate.
12467 if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
12468 DAG, true))
12469 return BlendPerm;
12470 if (SDValue UnpackPerm = lowerShuffleAsUNPCKAndPermute(DL, VT, V1, V2, Mask,
12471 DAG))
12472 return UnpackPerm;
12473 if (SDValue RotatePerm = lowerShuffleAsByteRotateAndPermute(
12474 DL, VT, V1, V2, Mask, Subtarget, DAG))
12475 return RotatePerm;
12476 // Unpack/rotate failed - try again with variable blends.
12477 if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
12478 DAG))
12479 return BlendPerm;
12480 }
12481
12482 // If the final mask is an alternating blend of vXi8/vXi16, convert to an
12483 // UNPCKL(SHUFFLE, SHUFFLE) pattern.
12484 // TODO: It doesn't have to be alternating - but each lane mustn't have more
12485 // than half the elements coming from each source.
12486 if (IsAlternating && VT.getScalarSizeInBits() < 32) {
12487 V1Mask.assign(NumElts, -1);
12488 V2Mask.assign(NumElts, -1);
12489 FinalMask.assign(NumElts, -1);
12490 for (int i = 0; i != NumElts; i += NumEltsPerLane)
12491 for (int j = 0; j != NumEltsPerLane; ++j) {
12492 int M = Mask[i + j];
12493 if (M >= 0 && M < NumElts) {
12494 V1Mask[i + (j / 2)] = M;
12495 FinalMask[i + j] = i + (j / 2);
12496 } else if (M >= NumElts) {
12497 V2Mask[i + (j / 2)] = M - NumElts;
12498 FinalMask[i + j] = i + (j / 2) + NumElts;
12499 }
12500 }
12501 }
12502
12503 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
12504 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
12505 return DAG.getVectorShuffle(VT, DL, V1, V2, FinalMask);
12506}
12507
12508/// Try to lower a vector shuffle as a bit rotation.
12509///
12510/// Look for a repeated rotation pattern in each sub group.
12511/// Returns a ISD::ROTL element rotation amount or -1 if failed.
12512static int matchShuffleAsBitRotate(ArrayRef<int> Mask, int NumSubElts) {
12513 int NumElts = Mask.size();
12514 assert((NumElts % NumSubElts) == 0 && "Illegal shuffle mask")(static_cast <bool> ((NumElts % NumSubElts) == 0 &&
"Illegal shuffle mask") ? void (0) : __assert_fail ("(NumElts % NumSubElts) == 0 && \"Illegal shuffle mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12514, __extension__ __PRETTY_FUNCTION__))
;
12515
12516 int RotateAmt = -1;
12517 for (int i = 0; i != NumElts; i += NumSubElts) {
12518 for (int j = 0; j != NumSubElts; ++j) {
12519 int M = Mask[i + j];
12520 if (M < 0)
12521 continue;
12522 if (!isInRange(M, i, i + NumSubElts))
12523 return -1;
12524 int Offset = (NumSubElts - (M - (i + j))) % NumSubElts;
12525 if (0 <= RotateAmt && Offset != RotateAmt)
12526 return -1;
12527 RotateAmt = Offset;
12528 }
12529 }
12530 return RotateAmt;
12531}
12532
12533static int matchShuffleAsBitRotate(MVT &RotateVT, int EltSizeInBits,
12534 const X86Subtarget &Subtarget,
12535 ArrayRef<int> Mask) {
12536 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!")(static_cast <bool> (!isNoopShuffleMask(Mask) &&
"We shouldn't lower no-op shuffles!") ? void (0) : __assert_fail
("!isNoopShuffleMask(Mask) && \"We shouldn't lower no-op shuffles!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12536, __extension__ __PRETTY_FUNCTION__))
;
12537 assert(EltSizeInBits < 64 && "Can't rotate 64-bit integers")(static_cast <bool> (EltSizeInBits < 64 && "Can't rotate 64-bit integers"
) ? void (0) : __assert_fail ("EltSizeInBits < 64 && \"Can't rotate 64-bit integers\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12537, __extension__ __PRETTY_FUNCTION__))
;
12538
12539 // AVX512 only has vXi32/vXi64 rotates, so limit the rotation sub group size.
12540 int MinSubElts = Subtarget.hasAVX512() ? std::max(32 / EltSizeInBits, 2) : 2;
12541 int MaxSubElts = 64 / EltSizeInBits;
12542 for (int NumSubElts = MinSubElts; NumSubElts <= MaxSubElts; NumSubElts *= 2) {
12543 int RotateAmt = matchShuffleAsBitRotate(Mask, NumSubElts);
12544 if (RotateAmt < 0)
12545 continue;
12546
12547 int NumElts = Mask.size();
12548 MVT RotateSVT = MVT::getIntegerVT(EltSizeInBits * NumSubElts);
12549 RotateVT = MVT::getVectorVT(RotateSVT, NumElts / NumSubElts);
12550 return RotateAmt * EltSizeInBits;
12551 }
12552
12553 return -1;
12554}
12555
12556/// Lower shuffle using X86ISD::VROTLI rotations.
12557static SDValue lowerShuffleAsBitRotate(const SDLoc &DL, MVT VT, SDValue V1,
12558 ArrayRef<int> Mask,
12559 const X86Subtarget &Subtarget,
12560 SelectionDAG &DAG) {
12561 // Only XOP + AVX512 targets have bit rotation instructions.
12562 // If we at least have SSSE3 (PSHUFB) then we shouldn't attempt to use this.
12563 bool IsLegal =
12564 (VT.is128BitVector() && Subtarget.hasXOP()) || Subtarget.hasAVX512();
12565 if (!IsLegal && Subtarget.hasSSE3())
12566 return SDValue();
12567
12568 MVT RotateVT;
12569 int RotateAmt = matchShuffleAsBitRotate(RotateVT, VT.getScalarSizeInBits(),
12570 Subtarget, Mask);
12571 if (RotateAmt < 0)
12572 return SDValue();
12573
12574 // For pre-SSSE3 targets, if we are shuffling vXi8 elts then ISD::ROTL,
12575 // expanded to OR(SRL,SHL), will be more efficient, but if they can
12576 // widen to vXi16 or more then existing lowering should will be better.
12577 if (!IsLegal) {
12578 if ((RotateAmt % 16) == 0)
12579 return SDValue();
12580 // TODO: Use getTargetVShiftByConstNode.
12581 unsigned ShlAmt = RotateAmt;
12582 unsigned SrlAmt = RotateVT.getScalarSizeInBits() - RotateAmt;
12583 V1 = DAG.getBitcast(RotateVT, V1);
12584 SDValue SHL = DAG.getNode(X86ISD::VSHLI, DL, RotateVT, V1,
12585 DAG.getTargetConstant(ShlAmt, DL, MVT::i8));
12586 SDValue SRL = DAG.getNode(X86ISD::VSRLI, DL, RotateVT, V1,
12587 DAG.getTargetConstant(SrlAmt, DL, MVT::i8));
12588 SDValue Rot = DAG.getNode(ISD::OR, DL, RotateVT, SHL, SRL);
12589 return DAG.getBitcast(VT, Rot);
12590 }
12591
12592 SDValue Rot =
12593 DAG.getNode(X86ISD::VROTLI, DL, RotateVT, DAG.getBitcast(RotateVT, V1),
12594 DAG.getTargetConstant(RotateAmt, DL, MVT::i8));
12595 return DAG.getBitcast(VT, Rot);
12596}
12597
12598/// Try to match a vector shuffle as an element rotation.
12599///
12600/// This is used for support PALIGNR for SSSE3 or VALIGND/Q for AVX512.
12601static int matchShuffleAsElementRotate(SDValue &V1, SDValue &V2,
12602 ArrayRef<int> Mask) {
12603 int NumElts = Mask.size();
12604
12605 // We need to detect various ways of spelling a rotation:
12606 // [11, 12, 13, 14, 15, 0, 1, 2]
12607 // [-1, 12, 13, 14, -1, -1, 1, -1]
12608 // [-1, -1, -1, -1, -1, -1, 1, 2]
12609 // [ 3, 4, 5, 6, 7, 8, 9, 10]
12610 // [-1, 4, 5, 6, -1, -1, 9, -1]
12611 // [-1, 4, 5, 6, -1, -1, -1, -1]
12612 int Rotation = 0;
12613 SDValue Lo, Hi;
12614 for (int i = 0; i < NumElts; ++i) {
12615 int M = Mask[i];
12616 assert((M == SM_SentinelUndef || (0 <= M && M < (2*NumElts))) &&(static_cast <bool> ((M == SM_SentinelUndef || (0 <=
M && M < (2*NumElts))) && "Unexpected mask index."
) ? void (0) : __assert_fail ("(M == SM_SentinelUndef || (0 <= M && M < (2*NumElts))) && \"Unexpected mask index.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12617, __extension__ __PRETTY_FUNCTION__))
12617 "Unexpected mask index.")(static_cast <bool> ((M == SM_SentinelUndef || (0 <=
M && M < (2*NumElts))) && "Unexpected mask index."
) ? void (0) : __assert_fail ("(M == SM_SentinelUndef || (0 <= M && M < (2*NumElts))) && \"Unexpected mask index.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12617, __extension__ __PRETTY_FUNCTION__))
;
12618 if (M < 0)
12619 continue;
12620
12621 // Determine where a rotated vector would have started.
12622 int StartIdx = i - (M % NumElts);
12623 if (StartIdx == 0)
12624 // The identity rotation isn't interesting, stop.
12625 return -1;
12626
12627 // If we found the tail of a vector the rotation must be the missing
12628 // front. If we found the head of a vector, it must be how much of the
12629 // head.
12630 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumElts - StartIdx;
12631
12632 if (Rotation == 0)
12633 Rotation = CandidateRotation;
12634 else if (Rotation != CandidateRotation)
12635 // The rotations don't match, so we can't match this mask.
12636 return -1;
12637
12638 // Compute which value this mask is pointing at.
12639 SDValue MaskV = M < NumElts ? V1 : V2;
12640
12641 // Compute which of the two target values this index should be assigned
12642 // to. This reflects whether the high elements are remaining or the low
12643 // elements are remaining.
12644 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
12645
12646 // Either set up this value if we've not encountered it before, or check
12647 // that it remains consistent.
12648 if (!TargetV)
12649 TargetV = MaskV;
12650 else if (TargetV != MaskV)
12651 // This may be a rotation, but it pulls from the inputs in some
12652 // unsupported interleaving.
12653 return -1;
12654 }
12655
12656 // Check that we successfully analyzed the mask, and normalize the results.
12657 assert(Rotation != 0 && "Failed to locate a viable rotation!")(static_cast <bool> (Rotation != 0 && "Failed to locate a viable rotation!"
) ? void (0) : __assert_fail ("Rotation != 0 && \"Failed to locate a viable rotation!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12657, __extension__ __PRETTY_FUNCTION__))
;
12658 assert((Lo || Hi) && "Failed to find a rotated input vector!")(static_cast <bool> ((Lo || Hi) && "Failed to find a rotated input vector!"
) ? void (0) : __assert_fail ("(Lo || Hi) && \"Failed to find a rotated input vector!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12658, __extension__ __PRETTY_FUNCTION__))
;
12659 if (!Lo)
12660 Lo = Hi;
12661 else if (!Hi)
12662 Hi = Lo;
12663
12664 V1 = Lo;
12665 V2 = Hi;
12666
12667 return Rotation;
12668}
12669
12670/// Try to lower a vector shuffle as a byte rotation.
12671///
12672/// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
12673/// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
12674/// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
12675/// try to generically lower a vector shuffle through such an pattern. It
12676/// does not check for the profitability of lowering either as PALIGNR or
12677/// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
12678/// This matches shuffle vectors that look like:
12679///
12680/// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
12681///
12682/// Essentially it concatenates V1 and V2, shifts right by some number of
12683/// elements, and takes the low elements as the result. Note that while this is
12684/// specified as a *right shift* because x86 is little-endian, it is a *left
12685/// rotate* of the vector lanes.
12686static int matchShuffleAsByteRotate(MVT VT, SDValue &V1, SDValue &V2,
12687 ArrayRef<int> Mask) {
12688 // Don't accept any shuffles with zero elements.
12689 if (isAnyZero(Mask))
12690 return -1;
12691
12692 // PALIGNR works on 128-bit lanes.
12693 SmallVector<int, 16> RepeatedMask;
12694 if (!is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedMask))
12695 return -1;
12696
12697 int Rotation = matchShuffleAsElementRotate(V1, V2, RepeatedMask);
12698 if (Rotation <= 0)
12699 return -1;
12700
12701 // PALIGNR rotates bytes, so we need to scale the
12702 // rotation based on how many bytes are in the vector lane.
12703 int NumElts = RepeatedMask.size();
12704 int Scale = 16 / NumElts;
12705 return Rotation * Scale;
12706}
12707
12708static SDValue lowerShuffleAsByteRotate(const SDLoc &DL, MVT VT, SDValue V1,
12709 SDValue V2, ArrayRef<int> Mask,
12710 const X86Subtarget &Subtarget,
12711 SelectionDAG &DAG) {
12712 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!")(static_cast <bool> (!isNoopShuffleMask(Mask) &&
"We shouldn't lower no-op shuffles!") ? void (0) : __assert_fail
("!isNoopShuffleMask(Mask) && \"We shouldn't lower no-op shuffles!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12712, __extension__ __PRETTY_FUNCTION__))
;
12713
12714 SDValue Lo = V1, Hi = V2;
12715 int ByteRotation = matchShuffleAsByteRotate(VT, Lo, Hi, Mask);
12716 if (ByteRotation <= 0)
12717 return SDValue();
12718
12719 // Cast the inputs to i8 vector of correct length to match PALIGNR or
12720 // PSLLDQ/PSRLDQ.
12721 MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
12722 Lo = DAG.getBitcast(ByteVT, Lo);
12723 Hi = DAG.getBitcast(ByteVT, Hi);
12724
12725 // SSSE3 targets can use the palignr instruction.
12726 if (Subtarget.hasSSSE3()) {
12727 assert((!VT.is512BitVector() || Subtarget.hasBWI()) &&(static_cast <bool> ((!VT.is512BitVector() || Subtarget
.hasBWI()) && "512-bit PALIGNR requires BWI instructions"
) ? void (0) : __assert_fail ("(!VT.is512BitVector() || Subtarget.hasBWI()) && \"512-bit PALIGNR requires BWI instructions\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12728, __extension__ __PRETTY_FUNCTION__))
12728 "512-bit PALIGNR requires BWI instructions")(static_cast <bool> ((!VT.is512BitVector() || Subtarget
.hasBWI()) && "512-bit PALIGNR requires BWI instructions"
) ? void (0) : __assert_fail ("(!VT.is512BitVector() || Subtarget.hasBWI()) && \"512-bit PALIGNR requires BWI instructions\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12728, __extension__ __PRETTY_FUNCTION__))
;
12729 return DAG.getBitcast(
12730 VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, Lo, Hi,
12731 DAG.getTargetConstant(ByteRotation, DL, MVT::i8)));
12732 }
12733
12734 assert(VT.is128BitVector() &&(static_cast <bool> (VT.is128BitVector() && "Rotate-based lowering only supports 128-bit lowering!"
) ? void (0) : __assert_fail ("VT.is128BitVector() && \"Rotate-based lowering only supports 128-bit lowering!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12735, __extension__ __PRETTY_FUNCTION__))
12735 "Rotate-based lowering only supports 128-bit lowering!")(static_cast <bool> (VT.is128BitVector() && "Rotate-based lowering only supports 128-bit lowering!"
) ? void (0) : __assert_fail ("VT.is128BitVector() && \"Rotate-based lowering only supports 128-bit lowering!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12735, __extension__ __PRETTY_FUNCTION__))
;
12736 assert(Mask.size() <= 16 &&(static_cast <bool> (Mask.size() <= 16 && "Can shuffle at most 16 bytes in a 128-bit vector!"
) ? void (0) : __assert_fail ("Mask.size() <= 16 && \"Can shuffle at most 16 bytes in a 128-bit vector!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12737, __extension__ __PRETTY_FUNCTION__))
12737 "Can shuffle at most 16 bytes in a 128-bit vector!")(static_cast <bool> (Mask.size() <= 16 && "Can shuffle at most 16 bytes in a 128-bit vector!"
) ? void (0) : __assert_fail ("Mask.size() <= 16 && \"Can shuffle at most 16 bytes in a 128-bit vector!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12737, __extension__ __PRETTY_FUNCTION__))
;
12738 assert(ByteVT == MVT::v16i8 &&(static_cast <bool> (ByteVT == MVT::v16i8 && "SSE2 rotate lowering only needed for v16i8!"
) ? void (0) : __assert_fail ("ByteVT == MVT::v16i8 && \"SSE2 rotate lowering only needed for v16i8!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12739, __extension__ __PRETTY_FUNCTION__))
12739 "SSE2 rotate lowering only needed for v16i8!")(static_cast <bool> (ByteVT == MVT::v16i8 && "SSE2 rotate lowering only needed for v16i8!"
) ? void (0) : __assert_fail ("ByteVT == MVT::v16i8 && \"SSE2 rotate lowering only needed for v16i8!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12739, __extension__ __PRETTY_FUNCTION__))
;
12740
12741 // Default SSE2 implementation
12742 int LoByteShift = 16 - ByteRotation;
12743 int HiByteShift = ByteRotation;
12744
12745 SDValue LoShift =
12746 DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Lo,
12747 DAG.getTargetConstant(LoByteShift, DL, MVT::i8));
12748 SDValue HiShift =
12749 DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Hi,
12750 DAG.getTargetConstant(HiByteShift, DL, MVT::i8));
12751 return DAG.getBitcast(VT,
12752 DAG.getNode(ISD::OR, DL, MVT::v16i8, LoShift, HiShift));
12753}
12754
12755/// Try to lower a vector shuffle as a dword/qword rotation.
12756///
12757/// AVX512 has a VALIGND/VALIGNQ instructions that will do an arbitrary
12758/// rotation of the concatenation of two vectors; This routine will
12759/// try to generically lower a vector shuffle through such an pattern.
12760///
12761/// Essentially it concatenates V1 and V2, shifts right by some number of
12762/// elements, and takes the low elements as the result. Note that while this is
12763/// specified as a *right shift* because x86 is little-endian, it is a *left
12764/// rotate* of the vector lanes.
12765static SDValue lowerShuffleAsVALIGN(const SDLoc &DL, MVT VT, SDValue V1,
12766 SDValue V2, ArrayRef<int> Mask,
12767 const X86Subtarget &Subtarget,
12768 SelectionDAG &DAG) {
12769 assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&(static_cast <bool> ((VT.getScalarType() == MVT::i32 ||
VT.getScalarType() == MVT::i64) && "Only 32-bit and 64-bit elements are supported!"
) ? void (0) : __assert_fail ("(VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) && \"Only 32-bit and 64-bit elements are supported!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12770, __extension__ __PRETTY_FUNCTION__))
12770 "Only 32-bit and 64-bit elements are supported!")(static_cast <bool> ((VT.getScalarType() == MVT::i32 ||
VT.getScalarType() == MVT::i64) && "Only 32-bit and 64-bit elements are supported!"
) ? void (0) : __assert_fail ("(VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) && \"Only 32-bit and 64-bit elements are supported!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12770, __extension__ __PRETTY_FUNCTION__))
;
12771
12772 // 128/256-bit vectors are only supported with VLX.
12773 assert((Subtarget.hasVLX() || (!VT.is128BitVector() && !VT.is256BitVector()))(static_cast <bool> ((Subtarget.hasVLX() || (!VT.is128BitVector
() && !VT.is256BitVector())) && "VLX required for 128/256-bit vectors"
) ? void (0) : __assert_fail ("(Subtarget.hasVLX() || (!VT.is128BitVector() && !VT.is256BitVector())) && \"VLX required for 128/256-bit vectors\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12774, __extension__ __PRETTY_FUNCTION__))
12774 && "VLX required for 128/256-bit vectors")(static_cast <bool> ((Subtarget.hasVLX() || (!VT.is128BitVector
() && !VT.is256BitVector())) && "VLX required for 128/256-bit vectors"
) ? void (0) : __assert_fail ("(Subtarget.hasVLX() || (!VT.is128BitVector() && !VT.is256BitVector())) && \"VLX required for 128/256-bit vectors\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12774, __extension__ __PRETTY_FUNCTION__))
;
12775
12776 SDValue Lo = V1, Hi = V2;
12777 int Rotation = matchShuffleAsElementRotate(Lo, Hi, Mask);
12778 if (Rotation <= 0)
12779 return SDValue();
12780
12781 return DAG.getNode(X86ISD::VALIGN, DL, VT, Lo, Hi,
12782 DAG.getTargetConstant(Rotation, DL, MVT::i8));
12783}
12784
12785/// Try to lower a vector shuffle as a byte shift sequence.
12786static SDValue lowerShuffleAsByteShiftMask(const SDLoc &DL, MVT VT, SDValue V1,
12787 SDValue V2, ArrayRef<int> Mask,
12788 const APInt &Zeroable,
12789 const X86Subtarget &Subtarget,
12790 SelectionDAG &DAG) {
12791 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!")(static_cast <bool> (!isNoopShuffleMask(Mask) &&
"We shouldn't lower no-op shuffles!") ? void (0) : __assert_fail
("!isNoopShuffleMask(Mask) && \"We shouldn't lower no-op shuffles!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12791, __extension__ __PRETTY_FUNCTION__))
;
12792 assert(VT.is128BitVector() && "Only 128-bit vectors supported")(static_cast <bool> (VT.is128BitVector() && "Only 128-bit vectors supported"
) ? void (0) : __assert_fail ("VT.is128BitVector() && \"Only 128-bit vectors supported\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12792, __extension__ __PRETTY_FUNCTION__))
;
12793
12794 // We need a shuffle that has zeros at one/both ends and a sequential
12795 // shuffle from one source within.
12796 unsigned ZeroLo = Zeroable.countTrailingOnes();
12797 unsigned ZeroHi = Zeroable.countLeadingOnes();
12798 if (!ZeroLo && !ZeroHi)
12799 return SDValue();
12800
12801 unsigned NumElts = Mask.size();
12802 unsigned Len = NumElts - (ZeroLo + ZeroHi);
12803 if (!isSequentialOrUndefInRange(Mask, ZeroLo, Len, Mask[ZeroLo]))
12804 return SDValue();
12805
12806 unsigned Scale = VT.getScalarSizeInBits() / 8;
12807 ArrayRef<int> StubMask = Mask.slice(ZeroLo, Len);
12808 if (!isUndefOrInRange(StubMask, 0, NumElts) &&
12809 !isUndefOrInRange(StubMask, NumElts, 2 * NumElts))
12810 return SDValue();
12811
12812 SDValue Res = Mask[ZeroLo] < (int)NumElts ? V1 : V2;
12813 Res = DAG.getBitcast(MVT::v16i8, Res);
12814
12815 // Use VSHLDQ/VSRLDQ ops to zero the ends of a vector and leave an
12816 // inner sequential set of elements, possibly offset:
12817 // 01234567 --> zzzzzz01 --> 1zzzzzzz
12818 // 01234567 --> 4567zzzz --> zzzzz456
12819 // 01234567 --> z0123456 --> 3456zzzz --> zz3456zz
12820 if (ZeroLo == 0) {
12821 unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
12822 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12823 DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12824 Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
12825 DAG.getTargetConstant(Scale * ZeroHi, DL, MVT::i8));
12826 } else if (ZeroHi == 0) {
12827 unsigned Shift = Mask[ZeroLo] % NumElts;
12828 Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
12829 DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12830 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12831 DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
12832 } else if (!Subtarget.hasSSSE3()) {
12833 // If we don't have PSHUFB then its worth avoiding an AND constant mask
12834 // by performing 3 byte shifts. Shuffle combining can kick in above that.
12835 // TODO: There may be some cases where VSH{LR}DQ+PAND is still better.
12836 unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
12837 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12838 DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12839 Shift += Mask[ZeroLo] % NumElts;
12840 Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
12841 DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12842 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12843 DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
12844 } else
12845 return SDValue();
12846
12847 return DAG.getBitcast(VT, Res);
12848}
12849
12850/// Try to lower a vector shuffle as a bit shift (shifts in zeros).
12851///
12852/// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
12853/// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
12854/// matches elements from one of the input vectors shuffled to the left or
12855/// right with zeroable elements 'shifted in'. It handles both the strictly
12856/// bit-wise element shifts and the byte shift across an entire 128-bit double
12857/// quad word lane.
12858///
12859/// PSHL : (little-endian) left bit shift.
12860/// [ zz, 0, zz, 2 ]
12861/// [ -1, 4, zz, -1 ]
12862/// PSRL : (little-endian) right bit shift.
12863/// [ 1, zz, 3, zz]
12864/// [ -1, -1, 7, zz]
12865/// PSLLDQ : (little-endian) left byte shift
12866/// [ zz, 0, 1, 2, 3, 4, 5, 6]
12867/// [ zz, zz, -1, -1, 2, 3, 4, -1]
12868/// [ zz, zz, zz, zz, zz, zz, -1, 1]
12869/// PSRLDQ : (little-endian) right byte shift
12870/// [ 5, 6, 7, zz, zz, zz, zz, zz]
12871/// [ -1, 5, 6, 7, zz, zz, zz, zz]
12872/// [ 1, 2, -1, -1, -1, -1, zz, zz]
12873static int matchShuffleAsShift(MVT &ShiftVT, unsigned &Opcode,
12874 unsigned ScalarSizeInBits, ArrayRef<int> Mask,
12875 int MaskOffset, const APInt &Zeroable,
12876 const X86Subtarget &Subtarget) {
12877 int Size = Mask.size();
12878 unsigned SizeInBits = Size * ScalarSizeInBits;
12879
12880 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
12881 for (int i = 0; i < Size; i += Scale)
12882 for (int j = 0; j < Shift; ++j)
12883 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
12884 return false;
12885
12886 return true;
12887 };
12888
12889 auto MatchShift = [&](int Shift, int Scale, bool Left) {
12890 for (int i = 0; i != Size; i += Scale) {
12891 unsigned Pos = Left ? i + Shift : i;
12892 unsigned Low = Left ? i : i + Shift;
12893 unsigned Len = Scale - Shift;
12894 if (!isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset))
12895 return -1;
12896 }
12897
12898 int ShiftEltBits = ScalarSizeInBits * Scale;
12899 bool ByteShift = ShiftEltBits > 64;
12900 Opcode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
12901 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
12902 int ShiftAmt = Shift * ScalarSizeInBits / (ByteShift ? 8 : 1);
12903
12904 // Normalize the scale for byte shifts to still produce an i64 element
12905 // type.
12906 Scale = ByteShift ? Scale / 2 : Scale;
12907
12908 // We need to round trip through the appropriate type for the shift.
12909 MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
12910 ShiftVT = ByteShift ? MVT::getVectorVT(MVT::i8, SizeInBits / 8)
12911 : MVT::getVectorVT(ShiftSVT, Size / Scale);
12912 return (int)ShiftAmt;
12913 };
12914
12915 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
12916 // keep doubling the size of the integer elements up to that. We can
12917 // then shift the elements of the integer vector by whole multiples of
12918 // their width within the elements of the larger integer vector. Test each
12919 // multiple to see if we can find a match with the moved element indices
12920 // and that the shifted in elements are all zeroable.
12921 unsigned MaxWidth = ((SizeInBits == 512) && !Subtarget.hasBWI() ? 64 : 128);
12922 for (int Scale = 2; Scale * ScalarSizeInBits <= MaxWidth; Scale *= 2)
12923 for (int Shift = 1; Shift != Scale; ++Shift)
12924 for (bool Left : {true, false})
12925 if (CheckZeros(Shift, Scale, Left)) {
12926 int ShiftAmt = MatchShift(Shift, Scale, Left);
12927 if (0 < ShiftAmt)
12928 return ShiftAmt;
12929 }
12930
12931 // no match
12932 return -1;
12933}
12934
12935static SDValue lowerShuffleAsShift(const SDLoc &DL, MVT VT, SDValue V1,
12936 SDValue V2, ArrayRef<int> Mask,
12937 const APInt &Zeroable,
12938 const X86Subtarget &Subtarget,
12939 SelectionDAG &DAG) {
12940 int Size = Mask.size();
12941 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size")(static_cast <bool> (Size == (int)VT.getVectorNumElements
() && "Unexpected mask size") ? void (0) : __assert_fail
("Size == (int)VT.getVectorNumElements() && \"Unexpected mask size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12941, __extension__ __PRETTY_FUNCTION__))
;
12942
12943 MVT ShiftVT;
12944 SDValue V = V1;
12945 unsigned Opcode;
12946
12947 // Try to match shuffle against V1 shift.
12948 int ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
12949 Mask, 0, Zeroable, Subtarget);
12950
12951 // If V1 failed, try to match shuffle against V2 shift.
12952 if (ShiftAmt < 0) {
12953 ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
12954 Mask, Size, Zeroable, Subtarget);
12955 V = V2;
12956 }
12957
12958 if (ShiftAmt < 0)
12959 return SDValue();
12960
12961 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&(static_cast <bool> (DAG.getTargetLoweringInfo().isTypeLegal
(ShiftVT) && "Illegal integer vector type") ? void (0
) : __assert_fail ("DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) && \"Illegal integer vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12962, __extension__ __PRETTY_FUNCTION__))
12962 "Illegal integer vector type")(static_cast <bool> (DAG.getTargetLoweringInfo().isTypeLegal
(ShiftVT) && "Illegal integer vector type") ? void (0
) : __assert_fail ("DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) && \"Illegal integer vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12962, __extension__ __PRETTY_FUNCTION__))
;
12963 V = DAG.getBitcast(ShiftVT, V);
12964 V = DAG.getNode(Opcode, DL, ShiftVT, V,
12965 DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
12966 return DAG.getBitcast(VT, V);
12967}
12968
12969// EXTRQ: Extract Len elements from lower half of source, starting at Idx.
12970// Remainder of lower half result is zero and upper half is all undef.
12971static bool matchShuffleAsEXTRQ(MVT VT, SDValue &V1, SDValue &V2,
12972 ArrayRef<int> Mask, uint64_t &BitLen,
12973 uint64_t &BitIdx, const APInt &Zeroable) {
12974 int Size = Mask.size();
12975 int HalfSize = Size / 2;
12976 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size")(static_cast <bool> (Size == (int)VT.getVectorNumElements
() && "Unexpected mask size") ? void (0) : __assert_fail
("Size == (int)VT.getVectorNumElements() && \"Unexpected mask size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12976, __extension__ __PRETTY_FUNCTION__))
;
12977 assert(!Zeroable.isAllOnesValue() && "Fully zeroable shuffle mask")(static_cast <bool> (!Zeroable.isAllOnesValue() &&
"Fully zeroable shuffle mask") ? void (0) : __assert_fail ("!Zeroable.isAllOnesValue() && \"Fully zeroable shuffle mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12977, __extension__ __PRETTY_FUNCTION__))
;
12978
12979 // Upper half must be undefined.
12980 if (!isUndefUpperHalf(Mask))
12981 return false;
12982
12983 // Determine the extraction length from the part of the
12984 // lower half that isn't zeroable.
12985 int Len = HalfSize;
12986 for (; Len > 0; --Len)
12987 if (!Zeroable[Len - 1])
12988 break;
12989 assert(Len > 0 && "Zeroable shuffle mask")(static_cast <bool> (Len > 0 && "Zeroable shuffle mask"
) ? void (0) : __assert_fail ("Len > 0 && \"Zeroable shuffle mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 12989, __extension__ __PRETTY_FUNCTION__))
;
12990
12991 // Attempt to match first Len sequential elements from the lower half.
12992 SDValue Src;
12993 int Idx = -1;
12994 for (int i = 0; i != Len; ++i) {
12995 int M = Mask[i];
12996 if (M == SM_SentinelUndef)
12997 continue;
12998 SDValue &V = (M < Size ? V1 : V2);
12999 M = M % Size;
13000
13001 // The extracted elements must start at a valid index and all mask
13002 // elements must be in the lower half.
13003 if (i > M || M >= HalfSize)
13004 return false;
13005
13006 if (Idx < 0 || (Src == V && Idx == (M - i))) {
13007 Src = V;
13008 Idx = M - i;
13009 continue;
13010 }
13011 return false;
13012 }
13013
13014 if (!Src || Idx < 0)
13015 return false;
13016
13017 assert((Idx + Len) <= HalfSize && "Illegal extraction mask")(static_cast <bool> ((Idx + Len) <= HalfSize &&
"Illegal extraction mask") ? void (0) : __assert_fail ("(Idx + Len) <= HalfSize && \"Illegal extraction mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13017, __extension__ __PRETTY_FUNCTION__))
;
13018 BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
13019 BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
13020 V1 = Src;
13021 return true;
13022}
13023
13024// INSERTQ: Extract lowest Len elements from lower half of second source and
13025// insert over first source, starting at Idx.
13026// { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
13027static bool matchShuffleAsINSERTQ(MVT VT, SDValue &V1, SDValue &V2,
13028 ArrayRef<int> Mask, uint64_t &BitLen,
13029 uint64_t &BitIdx) {
13030 int Size = Mask.size();
13031 int HalfSize = Size / 2;
13032 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size")(static_cast <bool> (Size == (int)VT.getVectorNumElements
() && "Unexpected mask size") ? void (0) : __assert_fail
("Size == (int)VT.getVectorNumElements() && \"Unexpected mask size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13032, __extension__ __PRETTY_FUNCTION__))
;
13033
13034 // Upper half must be undefined.
13035 if (!isUndefUpperHalf(Mask))
13036 return false;
13037
13038 for (int Idx = 0; Idx != HalfSize; ++Idx) {
13039 SDValue Base;
13040
13041 // Attempt to match first source from mask before insertion point.
13042 if (isUndefInRange(Mask, 0, Idx)) {
13043 /* EMPTY */
13044 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
13045 Base = V1;
13046 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
13047 Base = V2;
13048 } else {
13049 continue;
13050 }
13051
13052 // Extend the extraction length looking to match both the insertion of
13053 // the second source and the remaining elements of the first.
13054 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
13055 SDValue Insert;
13056 int Len = Hi - Idx;
13057
13058 // Match insertion.
13059 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
13060 Insert = V1;
13061 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
13062 Insert = V2;
13063 } else {
13064 continue;
13065 }
13066
13067 // Match the remaining elements of the lower half.
13068 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
13069 /* EMPTY */
13070 } else if ((!Base || (Base == V1)) &&
13071 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
13072 Base = V1;
13073 } else if ((!Base || (Base == V2)) &&
13074 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
13075 Size + Hi)) {
13076 Base = V2;
13077 } else {
13078 continue;
13079 }
13080
13081 BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
13082 BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
13083 V1 = Base;
13084 V2 = Insert;
13085 return true;
13086 }
13087 }
13088
13089 return false;
13090}
13091
13092/// Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
13093static SDValue lowerShuffleWithSSE4A(const SDLoc &DL, MVT VT, SDValue V1,
13094 SDValue V2, ArrayRef<int> Mask,
13095 const APInt &Zeroable, SelectionDAG &DAG) {
13096 uint64_t BitLen, BitIdx;
13097 if (matchShuffleAsEXTRQ(VT, V1, V2, Mask, BitLen, BitIdx, Zeroable))
13098 return DAG.getNode(X86ISD::EXTRQI, DL, VT, V1,
13099 DAG.getTargetConstant(BitLen, DL, MVT::i8),
13100 DAG.getTargetConstant(BitIdx, DL, MVT::i8));
13101
13102 if (matchShuffleAsINSERTQ(VT, V1, V2, Mask, BitLen, BitIdx))
13103 return DAG.getNode(X86ISD::INSERTQI, DL, VT, V1 ? V1 : DAG.getUNDEF(VT),
13104 V2 ? V2 : DAG.getUNDEF(VT),
13105 DAG.getTargetConstant(BitLen, DL, MVT::i8),
13106 DAG.getTargetConstant(BitIdx, DL, MVT::i8));
13107
13108 return SDValue();
13109}
13110
13111/// Lower a vector shuffle as a zero or any extension.
13112///
13113/// Given a specific number of elements, element bit width, and extension
13114/// stride, produce either a zero or any extension based on the available
13115/// features of the subtarget. The extended elements are consecutive and
13116/// begin and can start from an offsetted element index in the input; to
13117/// avoid excess shuffling the offset must either being in the bottom lane
13118/// or at the start of a higher lane. All extended elements must be from
13119/// the same lane.
13120static SDValue lowerShuffleAsSpecificZeroOrAnyExtend(
13121 const SDLoc &DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
13122 ArrayRef<int> Mask, const X86Subtarget &Subtarget, SelectionDAG &DAG) {
13123 assert(Scale > 1 && "Need a scale to extend.")(static_cast <bool> (Scale > 1 && "Need a scale to extend."
) ? void (0) : __assert_fail ("Scale > 1 && \"Need a scale to extend.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13123, __extension__ __PRETTY_FUNCTION__))
;
13124 int EltBits = VT.getScalarSizeInBits();
13125 int NumElements = VT.getVectorNumElements();
13126 int NumEltsPerLane = 128 / EltBits;
13127 int OffsetLane = Offset / NumEltsPerLane;
13128 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&(static_cast <bool> ((EltBits == 8 || EltBits == 16 || EltBits
== 32) && "Only 8, 16, and 32 bit elements can be extended."
) ? void (0) : __assert_fail ("(EltBits == 8 || EltBits == 16 || EltBits == 32) && \"Only 8, 16, and 32 bit elements can be extended.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13129, __extension__ __PRETTY_FUNCTION__))
13129 "Only 8, 16, and 32 bit elements can be extended.")(static_cast <bool> ((EltBits == 8 || EltBits == 16 || EltBits
== 32) && "Only 8, 16, and 32 bit elements can be extended."
) ? void (0) : __assert_fail ("(EltBits == 8 || EltBits == 16 || EltBits == 32) && \"Only 8, 16, and 32 bit elements can be extended.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13129, __extension__ __PRETTY_FUNCTION__))
;
13130 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.")(static_cast <bool> (Scale * EltBits <= 64 &&
"Cannot zero extend past 64 bits.") ? void (0) : __assert_fail
("Scale * EltBits <= 64 && \"Cannot zero extend past 64 bits.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13130, __extension__ __PRETTY_FUNCTION__))
;
13131 assert(0 <= Offset && "Extension offset must be positive.")(static_cast <bool> (0 <= Offset && "Extension offset must be positive."
) ? void (0) : __assert_fail ("0 <= Offset && \"Extension offset must be positive.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13131, __extension__ __PRETTY_FUNCTION__))
;
13132 assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&(static_cast <bool> ((Offset < NumEltsPerLane || Offset
% NumEltsPerLane == 0) && "Extension offset must be in the first lane or start an upper lane."
) ? void (0) : __assert_fail ("(Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) && \"Extension offset must be in the first lane or start an upper lane.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13133, __extension__ __PRETTY_FUNCTION__))
13133 "Extension offset must be in the first lane or start an upper lane.")(static_cast <bool> ((Offset < NumEltsPerLane || Offset
% NumEltsPerLane == 0) && "Extension offset must be in the first lane or start an upper lane."
) ? void (0) : __assert_fail ("(Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) && \"Extension offset must be in the first lane or start an upper lane.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13133, __extension__ __PRETTY_FUNCTION__))
;
13134
13135 // Check that an index is in same lane as the base offset.
13136 auto SafeOffset = [&](int Idx) {
13137 return OffsetLane == (Idx / NumEltsPerLane);
13138 };
13139
13140 // Shift along an input so that the offset base moves to the first element.
13141 auto ShuffleOffset = [&](SDValue V) {
13142 if (!Offset)
13143 return V;
13144
13145 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
13146 for (int i = 0; i * Scale < NumElements; ++i) {
13147 int SrcIdx = i + Offset;
13148 ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
13149 }
13150 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
13151 };
13152
13153 // Found a valid a/zext mask! Try various lowering strategies based on the
13154 // input type and available ISA extensions.
13155 if (Subtarget.hasSSE41()) {
13156 // Not worth offsetting 128-bit vectors if scale == 2, a pattern using
13157 // PUNPCK will catch this in a later shuffle match.
13158 if (Offset && Scale == 2 && VT.is128BitVector())
13159 return SDValue();
13160 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
13161 NumElements / Scale);
13162 InputV = ShuffleOffset(InputV);
13163 InputV = getEXTEND_VECTOR_INREG(AnyExt ? ISD::ANY_EXTEND : ISD::ZERO_EXTEND,
13164 DL, ExtVT, InputV, DAG);
13165 return DAG.getBitcast(VT, InputV);
13166 }
13167
13168 assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.")(static_cast <bool> (VT.is128BitVector() && "Only 128-bit vectors can be extended."
) ? void (0) : __assert_fail ("VT.is128BitVector() && \"Only 128-bit vectors can be extended.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13168, __extension__ __PRETTY_FUNCTION__))
;
13169
13170 // For any extends we can cheat for larger element sizes and use shuffle
13171 // instructions that can fold with a load and/or copy.
13172 if (AnyExt && EltBits == 32) {
13173 int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
13174 -1};
13175 return DAG.getBitcast(
13176 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
13177 DAG.getBitcast(MVT::v4i32, InputV),
13178 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
13179 }
13180 if (AnyExt && EltBits == 16 && Scale > 2) {
13181 int PSHUFDMask[4] = {Offset / 2, -1,
13182 SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
13183 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
13184 DAG.getBitcast(MVT::v4i32, InputV),
13185 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
13186 int PSHUFWMask[4] = {1, -1, -1, -1};
13187 unsigned OddEvenOp = (Offset & 1) ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
13188 return DAG.getBitcast(
13189 VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
13190 DAG.getBitcast(MVT::v8i16, InputV),
13191 getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
13192 }
13193
13194 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
13195 // to 64-bits.
13196 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget.hasSSE4A()) {
13197 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!")(static_cast <bool> (NumElements == (int)Mask.size() &&
"Unexpected shuffle mask size!") ? void (0) : __assert_fail (
"NumElements == (int)Mask.size() && \"Unexpected shuffle mask size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13197, __extension__ __PRETTY_FUNCTION__))
;
13198 assert(VT.is128BitVector() && "Unexpected vector width!")(static_cast <bool> (VT.is128BitVector() && "Unexpected vector width!"
) ? void (0) : __assert_fail ("VT.is128BitVector() && \"Unexpected vector width!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13198, __extension__ __PRETTY_FUNCTION__))
;
13199
13200 int LoIdx = Offset * EltBits;
13201 SDValue Lo = DAG.getBitcast(
13202 MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
13203 DAG.getTargetConstant(EltBits, DL, MVT::i8),
13204 DAG.getTargetConstant(LoIdx, DL, MVT::i8)));
13205
13206 if (isUndefUpperHalf(Mask) || !SafeOffset(Offset + 1))
13207 return DAG.getBitcast(VT, Lo);
13208
13209 int HiIdx = (Offset + 1) * EltBits;
13210 SDValue Hi = DAG.getBitcast(
13211 MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
13212 DAG.getTargetConstant(EltBits, DL, MVT::i8),
13213 DAG.getTargetConstant(HiIdx, DL, MVT::i8)));
13214 return DAG.getBitcast(VT,
13215 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
13216 }
13217
13218 // If this would require more than 2 unpack instructions to expand, use
13219 // pshufb when available. We can only use more than 2 unpack instructions
13220 // when zero extending i8 elements which also makes it easier to use pshufb.
13221 if (Scale > 4 && EltBits == 8 && Subtarget.hasSSSE3()) {
13222 assert(NumElements == 16 && "Unexpected byte vector width!")(static_cast <bool> (NumElements == 16 && "Unexpected byte vector width!"
) ? void (0) : __assert_fail ("NumElements == 16 && \"Unexpected byte vector width!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13222, __extension__ __PRETTY_FUNCTION__))
;
13223 SDValue PSHUFBMask[16];
13224 for (int i = 0; i < 16; ++i) {
13225 int Idx = Offset + (i / Scale);
13226 if ((i % Scale == 0 && SafeOffset(Idx))) {
13227 PSHUFBMask[i] = DAG.getConstant(Idx, DL, MVT::i8);
13228 continue;
13229 }
13230 PSHUFBMask[i] =
13231 AnyExt ? DAG.getUNDEF(MVT::i8) : DAG.getConstant(0x80, DL, MVT::i8);
13232 }
13233 InputV = DAG.getBitcast(MVT::v16i8, InputV);
13234 return DAG.getBitcast(
13235 VT, DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
13236 DAG.getBuildVector(MVT::v16i8, DL, PSHUFBMask)));
13237 }
13238
13239 // If we are extending from an offset, ensure we start on a boundary that
13240 // we can unpack from.
13241 int AlignToUnpack = Offset % (NumElements / Scale);
13242 if (AlignToUnpack) {
13243 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
13244 for (int i = AlignToUnpack; i < NumElements; ++i)
13245 ShMask[i - AlignToUnpack] = i;
13246 InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
13247 Offset -= AlignToUnpack;
13248 }
13249
13250 // Otherwise emit a sequence of unpacks.
13251 do {
13252 unsigned UnpackLoHi = X86ISD::UNPCKL;
13253 if (Offset >= (NumElements / 2)) {
13254 UnpackLoHi = X86ISD::UNPCKH;
13255 Offset -= (NumElements / 2);
13256 }
13257
13258 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
13259 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
13260 : getZeroVector(InputVT, Subtarget, DAG, DL);
13261 InputV = DAG.getBitcast(InputVT, InputV);
13262 InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
13263 Scale /= 2;
13264 EltBits *= 2;
13265 NumElements /= 2;
13266 } while (Scale > 1);
13267 return DAG.getBitcast(VT, InputV);
13268}
13269
13270/// Try to lower a vector shuffle as a zero extension on any microarch.
13271///
13272/// This routine will try to do everything in its power to cleverly lower
13273/// a shuffle which happens to match the pattern of a zero extend. It doesn't
13274/// check for the profitability of this lowering, it tries to aggressively
13275/// match this pattern. It will use all of the micro-architectural details it
13276/// can to emit an efficient lowering. It handles both blends with all-zero
13277/// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
13278/// masking out later).
13279///
13280/// The reason we have dedicated lowering for zext-style shuffles is that they
13281/// are both incredibly common and often quite performance sensitive.
13282static SDValue lowerShuffleAsZeroOrAnyExtend(
13283 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13284 const APInt &Zeroable, const X86Subtarget &Subtarget,
13285 SelectionDAG &DAG) {
13286 int Bits = VT.getSizeInBits();
13287 int NumLanes = Bits / 128;
13288 int NumElements = VT.getVectorNumElements();
13289 int NumEltsPerLane = NumElements / NumLanes;
13290 assert(VT.getScalarSizeInBits() <= 32 &&(static_cast <bool> (VT.getScalarSizeInBits() <= 32 &&
"Exceeds 32-bit integer zero extension limit") ? void (0) : __assert_fail
("VT.getScalarSizeInBits() <= 32 && \"Exceeds 32-bit integer zero extension limit\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13291, __extension__ __PRETTY_FUNCTION__))
13291 "Exceeds 32-bit integer zero extension limit")(static_cast <bool> (VT.getScalarSizeInBits() <= 32 &&
"Exceeds 32-bit integer zero extension limit") ? void (0) : __assert_fail
("VT.getScalarSizeInBits() <= 32 && \"Exceeds 32-bit integer zero extension limit\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13291, __extension__ __PRETTY_FUNCTION__))
;
13292 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size")(static_cast <bool> ((int)Mask.size() == NumElements &&
"Unexpected shuffle mask size") ? void (0) : __assert_fail (
"(int)Mask.size() == NumElements && \"Unexpected shuffle mask size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13292, __extension__ __PRETTY_FUNCTION__))
;
13293
13294 // Define a helper function to check a particular ext-scale and lower to it if
13295 // valid.
13296 auto Lower = [&](int Scale) -> SDValue {
13297 SDValue InputV;
13298 bool AnyExt = true;
13299 int Offset = 0;
13300 int Matches = 0;
13301 for (int i = 0; i < NumElements; ++i) {
13302 int M = Mask[i];
13303 if (M < 0)
13304 continue; // Valid anywhere but doesn't tell us anything.
13305 if (i % Scale != 0) {
13306 // Each of the extended elements need to be zeroable.
13307 if (!Zeroable[i])
13308 return SDValue();
13309
13310 // We no longer are in the anyext case.
13311 AnyExt = false;
13312 continue;
13313 }
13314
13315 // Each of the base elements needs to be consecutive indices into the
13316 // same input vector.
13317 SDValue V = M < NumElements ? V1 : V2;
13318 M = M % NumElements;
13319 if (!InputV) {
13320 InputV = V;
13321 Offset = M - (i / Scale);
13322 } else if (InputV != V)
13323 return SDValue(); // Flip-flopping inputs.
13324
13325 // Offset must start in the lowest 128-bit lane or at the start of an
13326 // upper lane.
13327 // FIXME: Is it ever worth allowing a negative base offset?
13328 if (!((0 <= Offset && Offset < NumEltsPerLane) ||
13329 (Offset % NumEltsPerLane) == 0))
13330 return SDValue();
13331
13332 // If we are offsetting, all referenced entries must come from the same
13333 // lane.
13334 if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
13335 return SDValue();
13336
13337 if ((M % NumElements) != (Offset + (i / Scale)))
13338 return SDValue(); // Non-consecutive strided elements.
13339 Matches++;
13340 }
13341
13342 // If we fail to find an input, we have a zero-shuffle which should always
13343 // have already been handled.
13344 // FIXME: Maybe handle this here in case during blending we end up with one?
13345 if (!InputV)
13346 return SDValue();
13347
13348 // If we are offsetting, don't extend if we only match a single input, we
13349 // can always do better by using a basic PSHUF or PUNPCK.
13350 if (Offset != 0 && Matches < 2)
13351 return SDValue();
13352
13353 return lowerShuffleAsSpecificZeroOrAnyExtend(DL, VT, Scale, Offset, AnyExt,
13354 InputV, Mask, Subtarget, DAG);
13355 };
13356
13357 // The widest scale possible for extending is to a 64-bit integer.
13358 assert(Bits % 64 == 0 &&(static_cast <bool> (Bits % 64 == 0 && "The number of bits in a vector must be divisible by 64 on x86!"
) ? void (0) : __assert_fail ("Bits % 64 == 0 && \"The number of bits in a vector must be divisible by 64 on x86!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13359, __extension__ __PRETTY_FUNCTION__))
13359 "The number of bits in a vector must be divisible by 64 on x86!")(static_cast <bool> (Bits % 64 == 0 && "The number of bits in a vector must be divisible by 64 on x86!"
) ? void (0) : __assert_fail ("Bits % 64 == 0 && \"The number of bits in a vector must be divisible by 64 on x86!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13359, __extension__ __PRETTY_FUNCTION__))
;
13360 int NumExtElements = Bits / 64;
13361
13362 // Each iteration, try extending the elements half as much, but into twice as
13363 // many elements.
13364 for (; NumExtElements < NumElements; NumExtElements *= 2) {
13365 assert(NumElements % NumExtElements == 0 &&(static_cast <bool> (NumElements % NumExtElements == 0 &&
"The input vector size must be divisible by the extended size."
) ? void (0) : __assert_fail ("NumElements % NumExtElements == 0 && \"The input vector size must be divisible by the extended size.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13366, __extension__ __PRETTY_FUNCTION__))
13366 "The input vector size must be divisible by the extended size.")(static_cast <bool> (NumElements % NumExtElements == 0 &&
"The input vector size must be divisible by the extended size."
) ? void (0) : __assert_fail ("NumElements % NumExtElements == 0 && \"The input vector size must be divisible by the extended size.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13366, __extension__ __PRETTY_FUNCTION__))
;
13367 if (SDValue V = Lower(NumElements / NumExtElements))
13368 return V;
13369 }
13370
13371 // General extends failed, but 128-bit vectors may be able to use MOVQ.
13372 if (Bits != 128)
13373 return SDValue();
13374
13375 // Returns one of the source operands if the shuffle can be reduced to a
13376 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
13377 auto CanZExtLowHalf = [&]() {
13378 for (int i = NumElements / 2; i != NumElements; ++i)
13379 if (!Zeroable[i])
13380 return SDValue();
13381 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
13382 return V1;
13383 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
13384 return V2;
13385 return SDValue();
13386 };
13387
13388 if (SDValue V = CanZExtLowHalf()) {
13389 V = DAG.getBitcast(MVT::v2i64, V);
13390 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
13391 return DAG.getBitcast(VT, V);
13392 }
13393
13394 // No viable ext lowering found.
13395 return SDValue();
13396}
13397
13398/// Try to get a scalar value for a specific element of a vector.
13399///
13400/// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
13401static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
13402 SelectionDAG &DAG) {
13403 MVT VT = V.getSimpleValueType();
13404 MVT EltVT = VT.getVectorElementType();
13405 V = peekThroughBitcasts(V);
13406
13407 // If the bitcasts shift the element size, we can't extract an equivalent
13408 // element from it.
13409 MVT NewVT = V.getSimpleValueType();
13410 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
13411 return SDValue();
13412
13413 if (V.getOpcode() == ISD::BUILD_VECTOR ||
13414 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
13415 // Ensure the scalar operand is the same size as the destination.
13416 // FIXME: Add support for scalar truncation where possible.
13417 SDValue S = V.getOperand(Idx);
13418 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
13419 return DAG.getBitcast(EltVT, S);
13420 }
13421
13422 return SDValue();
13423}
13424
13425/// Helper to test for a load that can be folded with x86 shuffles.
13426///
13427/// This is particularly important because the set of instructions varies
13428/// significantly based on whether the operand is a load or not.
13429static bool isShuffleFoldableLoad(SDValue V) {
13430 V = peekThroughBitcasts(V);
13431 return ISD::isNON_EXTLoad(V.getNode());
13432}
13433
13434/// Try to lower insertion of a single element into a zero vector.
13435///
13436/// This is a common pattern that we have especially efficient patterns to lower
13437/// across all subtarget feature sets.
13438static SDValue lowerShuffleAsElementInsertion(
13439 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13440 const APInt &Zeroable, const X86Subtarget &Subtarget,
13441 SelectionDAG &DAG) {
13442 MVT ExtVT = VT;
13443 MVT EltVT = VT.getVectorElementType();
13444
13445 int V2Index =
13446 find_if(Mask, [&Mask](int M) { return M >= (int)Mask.size(); }) -
13447 Mask.begin();
13448 bool IsV1Zeroable = true;
13449 for (int i = 0, Size = Mask.size(); i < Size; ++i)
13450 if (i != V2Index && !Zeroable[i]) {
13451 IsV1Zeroable = false;
13452 break;
13453 }
13454
13455 // Check for a single input from a SCALAR_TO_VECTOR node.
13456 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
13457 // all the smarts here sunk into that routine. However, the current
13458 // lowering of BUILD_VECTOR makes that nearly impossible until the old
13459 // vector shuffle lowering is dead.
13460 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
13461 DAG);
13462 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
13463 // We need to zext the scalar if it is smaller than an i32.
13464 V2S = DAG.getBitcast(EltVT, V2S);
13465 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
13466 // Using zext to expand a narrow element won't work for non-zero
13467 // insertions.
13468 if (!IsV1Zeroable)
13469 return SDValue();
13470
13471 // Zero-extend directly to i32.
13472 ExtVT = MVT::getVectorVT(MVT::i32, ExtVT.getSizeInBits() / 32);
13473 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
13474 }
13475 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
13476 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
13477 EltVT == MVT::i16) {
13478 // Either not inserting from the low element of the input or the input
13479 // element size is too small to use VZEXT_MOVL to clear the high bits.
13480 return SDValue();
13481 }
13482
13483 if (!IsV1Zeroable) {
13484 // If V1 can't be treated as a zero vector we have fewer options to lower
13485 // this. We can't support integer vectors or non-zero targets cheaply, and
13486 // the V1 elements can't be permuted in any way.
13487 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!")(static_cast <bool> (VT == ExtVT && "Cannot change extended type when non-zeroable!"
) ? void (0) : __assert_fail ("VT == ExtVT && \"Cannot change extended type when non-zeroable!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13487, __extension__ __PRETTY_FUNCTION__))
;
13488 if (!VT.isFloatingPoint() || V2Index != 0)
13489 return SDValue();
13490 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
13491 V1Mask[V2Index] = -1;
13492 if (!isNoopShuffleMask(V1Mask))
13493 return SDValue();
13494 if (!VT.is128BitVector())
13495 return SDValue();
13496
13497 // Otherwise, use MOVSD or MOVSS.
13498 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&(static_cast <bool> ((EltVT == MVT::f32 || EltVT == MVT
::f64) && "Only two types of floating point element types to handle!"
) ? void (0) : __assert_fail ("(EltVT == MVT::f32 || EltVT == MVT::f64) && \"Only two types of floating point element types to handle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13499, __extension__ __PRETTY_FUNCTION__))
13499 "Only two types of floating point element types to handle!")(static_cast <bool> ((EltVT == MVT::f32 || EltVT == MVT
::f64) && "Only two types of floating point element types to handle!"
) ? void (0) : __assert_fail ("(EltVT == MVT::f32 || EltVT == MVT::f64) && \"Only two types of floating point element types to handle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13499, __extension__ __PRETTY_FUNCTION__))
;
13500 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
13501 ExtVT, V1, V2);
13502 }
13503
13504 // This lowering only works for the low element with floating point vectors.
13505 if (VT.isFloatingPoint() && V2Index != 0)
13506 return SDValue();
13507
13508 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
13509 if (ExtVT != VT)
13510 V2 = DAG.getBitcast(VT, V2);
13511
13512 if (V2Index != 0) {
13513 // If we have 4 or fewer lanes we can cheaply shuffle the element into
13514 // the desired position. Otherwise it is more efficient to do a vector
13515 // shift left. We know that we can do a vector shift left because all
13516 // the inputs are zero.
13517 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
13518 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
13519 V2Shuffle[V2Index] = 0;
13520 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
13521 } else {
13522 V2 = DAG.getBitcast(MVT::v16i8, V2);
13523 V2 = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, V2,
13524 DAG.getTargetConstant(
13525 V2Index * EltVT.getSizeInBits() / 8, DL, MVT::i8));
13526 V2 = DAG.getBitcast(VT, V2);
13527 }
13528 }
13529 return V2;
13530}
13531
13532/// Try to lower broadcast of a single - truncated - integer element,
13533/// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
13534///
13535/// This assumes we have AVX2.
13536static SDValue lowerShuffleAsTruncBroadcast(const SDLoc &DL, MVT VT, SDValue V0,
13537 int BroadcastIdx,
13538 const X86Subtarget &Subtarget,
13539 SelectionDAG &DAG) {
13540 assert(Subtarget.hasAVX2() &&(static_cast <bool> (Subtarget.hasAVX2() && "We can only lower integer broadcasts with AVX2!"
) ? void (0) : __assert_fail ("Subtarget.hasAVX2() && \"We can only lower integer broadcasts with AVX2!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13541, __extension__ __PRETTY_FUNCTION__))
13541 "We can only lower integer broadcasts with AVX2!")(static_cast <bool> (Subtarget.hasAVX2() && "We can only lower integer broadcasts with AVX2!"
) ? void (0) : __assert_fail ("Subtarget.hasAVX2() && \"We can only lower integer broadcasts with AVX2!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13541, __extension__ __PRETTY_FUNCTION__))
;
13542
13543 MVT EltVT = VT.getVectorElementType();
13544 MVT V0VT = V0.getSimpleValueType();
13545
13546 assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!")(static_cast <bool> (VT.isInteger() && "Unexpected non-integer trunc broadcast!"
) ? void (0) : __assert_fail ("VT.isInteger() && \"Unexpected non-integer trunc broadcast!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13546, __extension__ __PRETTY_FUNCTION__))
;
13547 assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!")(static_cast <bool> (V0VT.isVector() && "Unexpected non-vector vector-sized value!"
) ? void (0) : __assert_fail ("V0VT.isVector() && \"Unexpected non-vector vector-sized value!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13547, __extension__ __PRETTY_FUNCTION__))
;
13548
13549 MVT V0EltVT = V0VT.getVectorElementType();
13550 if (!V0EltVT.isInteger())
13551 return SDValue();
13552
13553 const unsigned EltSize = EltVT.getSizeInBits();
13554 const unsigned V0EltSize = V0EltVT.getSizeInBits();
13555
13556 // This is only a truncation if the original element type is larger.
13557 if (V0EltSize <= EltSize)
13558 return SDValue();
13559
13560 assert(((V0EltSize % EltSize) == 0) &&(static_cast <bool> (((V0EltSize % EltSize) == 0) &&
"Scalar type sizes must all be powers of 2 on x86!") ? void (
0) : __assert_fail ("((V0EltSize % EltSize) == 0) && \"Scalar type sizes must all be powers of 2 on x86!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13561, __extension__ __PRETTY_FUNCTION__))
13561 "Scalar type sizes must all be powers of 2 on x86!")(static_cast <bool> (((V0EltSize % EltSize) == 0) &&
"Scalar type sizes must all be powers of 2 on x86!") ? void (
0) : __assert_fail ("((V0EltSize % EltSize) == 0) && \"Scalar type sizes must all be powers of 2 on x86!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13561, __extension__ __PRETTY_FUNCTION__))
;
13562
13563 const unsigned V0Opc = V0.getOpcode();
13564 const unsigned Scale = V0EltSize / EltSize;
13565 const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
13566
13567 if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
13568 V0Opc != ISD::BUILD_VECTOR)
13569 return SDValue();
13570
13571 SDValue Scalar = V0.getOperand(V0BroadcastIdx);
13572
13573 // If we're extracting non-least-significant bits, shift so we can truncate.
13574 // Hopefully, we can fold away the trunc/srl/load into the broadcast.
13575 // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
13576 // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
13577 if (const int OffsetIdx = BroadcastIdx % Scale)
13578 Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
13579 DAG.getConstant(OffsetIdx * EltSize, DL, MVT::i8));
13580
13581 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
13582 DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
13583}
13584
13585/// Test whether this can be lowered with a single SHUFPS instruction.
13586///
13587/// This is used to disable more specialized lowerings when the shufps lowering
13588/// will happen to be efficient.
13589static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
13590 // This routine only handles 128-bit shufps.
13591 assert(Mask.size() == 4 && "Unsupported mask size!")(static_cast <bool> (Mask.size() == 4 && "Unsupported mask size!"
) ? void (0) : __assert_fail ("Mask.size() == 4 && \"Unsupported mask size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13591, __extension__ __PRETTY_FUNCTION__))
;
13592 assert(Mask[0] >= -1 && Mask[0] < 8 && "Out of bound mask element!")(static_cast <bool> (Mask[0] >= -1 && Mask[0
] < 8 && "Out of bound mask element!") ? void (0) :
__assert_fail ("Mask[0] >= -1 && Mask[0] < 8 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13592, __extension__ __PRETTY_FUNCTION__))
;
13593 assert(Mask[1] >= -1 && Mask[1] < 8 && "Out of bound mask element!")(static_cast <bool> (Mask[1] >= -1 && Mask[1
] < 8 && "Out of bound mask element!") ? void (0) :
__assert_fail ("Mask[1] >= -1 && Mask[1] < 8 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13593, __extension__ __PRETTY_FUNCTION__))
;
13594 assert(Mask[2] >= -1 && Mask[2] < 8 && "Out of bound mask element!")(static_cast <bool> (Mask[2] >= -1 && Mask[2
] < 8 && "Out of bound mask element!") ? void (0) :
__assert_fail ("Mask[2] >= -1 && Mask[2] < 8 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13594, __extension__ __PRETTY_FUNCTION__))
;
13595 assert(Mask[3] >= -1 && Mask[3] < 8 && "Out of bound mask element!")(static_cast <bool> (Mask[3] >= -1 && Mask[3
] < 8 && "Out of bound mask element!") ? void (0) :
__assert_fail ("Mask[3] >= -1 && Mask[3] < 8 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13595, __extension__ __PRETTY_FUNCTION__))
;
13596
13597 // To lower with a single SHUFPS we need to have the low half and high half
13598 // each requiring a single input.
13599 if (Mask[0] >= 0 && Mask[1] >= 0 && (Mask[0] < 4) != (Mask[1] < 4))
13600 return false;
13601 if (Mask[2] >= 0 && Mask[3] >= 0 && (Mask[2] < 4) != (Mask[3] < 4))
13602 return false;
13603
13604 return true;
13605}
13606
13607/// If we are extracting two 128-bit halves of a vector and shuffling the
13608/// result, match that to a 256-bit AVX2 vperm* instruction to avoid a
13609/// multi-shuffle lowering.
13610static SDValue lowerShuffleOfExtractsAsVperm(const SDLoc &DL, SDValue N0,
13611 SDValue N1, ArrayRef<int> Mask,
13612 SelectionDAG &DAG) {
13613 MVT VT = N0.getSimpleValueType();
13614 assert((VT.is128BitVector() &&(static_cast <bool> ((VT.is128BitVector() && (VT
.getScalarSizeInBits() == 32 || VT.getScalarSizeInBits() == 64
)) && "VPERM* family of shuffles requires 32-bit or 64-bit elements"
) ? void (0) : __assert_fail ("(VT.is128BitVector() && (VT.getScalarSizeInBits() == 32 || VT.getScalarSizeInBits() == 64)) && \"VPERM* family of shuffles requires 32-bit or 64-bit elements\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13616, __extension__ __PRETTY_FUNCTION__))
13615 (VT.getScalarSizeInBits() == 32 || VT.getScalarSizeInBits() == 64)) &&(static_cast <bool> ((VT.is128BitVector() && (VT
.getScalarSizeInBits() == 32 || VT.getScalarSizeInBits() == 64
)) && "VPERM* family of shuffles requires 32-bit or 64-bit elements"
) ? void (0) : __assert_fail ("(VT.is128BitVector() && (VT.getScalarSizeInBits() == 32 || VT.getScalarSizeInBits() == 64)) && \"VPERM* family of shuffles requires 32-bit or 64-bit elements\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13616, __extension__ __PRETTY_FUNCTION__))
13616 "VPERM* family of shuffles requires 32-bit or 64-bit elements")(static_cast <bool> ((VT.is128BitVector() && (VT
.getScalarSizeInBits() == 32 || VT.getScalarSizeInBits() == 64
)) && "VPERM* family of shuffles requires 32-bit or 64-bit elements"
) ? void (0) : __assert_fail ("(VT.is128BitVector() && (VT.getScalarSizeInBits() == 32 || VT.getScalarSizeInBits() == 64)) && \"VPERM* family of shuffles requires 32-bit or 64-bit elements\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13616, __extension__ __PRETTY_FUNCTION__))
;
13617
13618 // Check that both sources are extracts of the same source vector.
13619 if (!N0.hasOneUse() || !N1.hasOneUse() ||
13620 N0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
13621 N1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
13622 N0.getOperand(0) != N1.getOperand(0))
13623 return SDValue();
13624
13625 SDValue WideVec = N0.getOperand(0);
13626 MVT WideVT = WideVec.getSimpleValueType();
13627 if (!WideVT.is256BitVector())
13628 return SDValue();
13629
13630 // Match extracts of each half of the wide source vector. Commute the shuffle
13631 // if the extract of the low half is N1.
13632 unsigned NumElts = VT.getVectorNumElements();
13633 SmallVector<int, 4> NewMask(Mask.begin(), Mask.end());
13634 const APInt &ExtIndex0 = N0.getConstantOperandAPInt(1);
13635 const APInt &ExtIndex1 = N1.getConstantOperandAPInt(1);
13636 if (ExtIndex1 == 0 && ExtIndex0 == NumElts)
13637 ShuffleVectorSDNode::commuteMask(NewMask);
13638 else if (ExtIndex0 != 0 || ExtIndex1 != NumElts)
13639 return SDValue();
13640
13641 // Final bailout: if the mask is simple, we are better off using an extract
13642 // and a simple narrow shuffle. Prefer extract+unpack(h/l)ps to vpermps
13643 // because that avoids a constant load from memory.
13644 if (NumElts == 4 &&
13645 (isSingleSHUFPSMask(NewMask) || is128BitUnpackShuffleMask(NewMask)))
13646 return SDValue();
13647
13648 // Extend the shuffle mask with undef elements.
13649 NewMask.append(NumElts, -1);
13650
13651 // shuf (extract X, 0), (extract X, 4), M --> extract (shuf X, undef, M'), 0
13652 SDValue Shuf = DAG.getVectorShuffle(WideVT, DL, WideVec, DAG.getUNDEF(WideVT),
13653 NewMask);
13654 // This is free: ymm -> xmm.
13655 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuf,
13656 DAG.getIntPtrConstant(0, DL));
13657}
13658
13659/// Try to lower broadcast of a single element.
13660///
13661/// For convenience, this code also bundles all of the subtarget feature set
13662/// filtering. While a little annoying to re-dispatch on type here, there isn't
13663/// a convenient way to factor it out.
13664static SDValue lowerShuffleAsBroadcast(const SDLoc &DL, MVT VT, SDValue V1,
13665 SDValue V2, ArrayRef<int> Mask,
13666 const X86Subtarget &Subtarget,
13667 SelectionDAG &DAG) {
13668 if (!((Subtarget.hasSSE3() && VT == MVT::v2f64) ||
13669 (Subtarget.hasAVX() && VT.isFloatingPoint()) ||
13670 (Subtarget.hasAVX2() && VT.isInteger())))
13671 return SDValue();
13672
13673 // With MOVDDUP (v2f64) we can broadcast from a register or a load, otherwise
13674 // we can only broadcast from a register with AVX2.
13675 unsigned NumEltBits = VT.getScalarSizeInBits();
13676 unsigned Opcode = (VT == MVT::v2f64 && !Subtarget.hasAVX2())
13677 ? X86ISD::MOVDDUP
13678 : X86ISD::VBROADCAST;
13679 bool BroadcastFromReg = (Opcode == X86ISD::MOVDDUP) || Subtarget.hasAVX2();
13680
13681 // Check that the mask is a broadcast.
13682 int BroadcastIdx = getSplatIndex(Mask);
13683 if (BroadcastIdx < 0)
13684 return SDValue();
13685 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "(static_cast <bool> (BroadcastIdx < (int)Mask.size()
&& "We only expect to be called with " "a sorted mask where the broadcast "
"comes from V1.") ? void (0) : __assert_fail ("BroadcastIdx < (int)Mask.size() && \"We only expect to be called with \" \"a sorted mask where the broadcast \" \"comes from V1.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13687, __extension__ __PRETTY_FUNCTION__))
13686 "a sorted mask where the broadcast "(static_cast <bool> (BroadcastIdx < (int)Mask.size()
&& "We only expect to be called with " "a sorted mask where the broadcast "
"comes from V1.") ? void (0) : __assert_fail ("BroadcastIdx < (int)Mask.size() && \"We only expect to be called with \" \"a sorted mask where the broadcast \" \"comes from V1.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13687, __extension__ __PRETTY_FUNCTION__))
13687 "comes from V1.")(static_cast <bool> (BroadcastIdx < (int)Mask.size()
&& "We only expect to be called with " "a sorted mask where the broadcast "
"comes from V1.") ? void (0) : __assert_fail ("BroadcastIdx < (int)Mask.size() && \"We only expect to be called with \" \"a sorted mask where the broadcast \" \"comes from V1.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13687, __extension__ __PRETTY_FUNCTION__))
;
13688
13689 // Go up the chain of (vector) values to find a scalar load that we can
13690 // combine with the broadcast.
13691 // TODO: Combine this logic with findEltLoadSrc() used by
13692 // EltsFromConsecutiveLoads().
13693 int BitOffset = BroadcastIdx * NumEltBits;
13694 SDValue V = V1;
13695 for (;;) {
13696 switch (V.getOpcode()) {
13697 case ISD::BITCAST: {
13698 V = V.getOperand(0);
13699 continue;
13700 }
13701 case ISD::CONCAT_VECTORS: {
13702 int OpBitWidth = V.getOperand(0).getValueSizeInBits();
13703 int OpIdx = BitOffset / OpBitWidth;
13704 V = V.getOperand(OpIdx);
13705 BitOffset %= OpBitWidth;
13706 continue;
13707 }
13708 case ISD::EXTRACT_SUBVECTOR: {
13709 // The extraction index adds to the existing offset.
13710 unsigned EltBitWidth = V.getScalarValueSizeInBits();
13711 unsigned Idx = V.getConstantOperandVal(1);
13712 unsigned BeginOffset = Idx * EltBitWidth;
13713 BitOffset += BeginOffset;
13714 V = V.getOperand(0);
13715 continue;
13716 }
13717 case ISD::INSERT_SUBVECTOR: {
13718 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
13719 int EltBitWidth = VOuter.getScalarValueSizeInBits();
13720 int Idx = (int)V.getConstantOperandVal(2);
13721 int NumSubElts = (int)VInner.getSimpleValueType().getVectorNumElements();
13722 int BeginOffset = Idx * EltBitWidth;
13723 int EndOffset = BeginOffset + NumSubElts * EltBitWidth;
13724 if (BeginOffset <= BitOffset && BitOffset < EndOffset) {
13725 BitOffset -= BeginOffset;
13726 V = VInner;
13727 } else {
13728 V = VOuter;
13729 }
13730 continue;
13731 }
13732 }
13733 break;
13734 }
13735 assert((BitOffset % NumEltBits) == 0 && "Illegal bit-offset")(static_cast <bool> ((BitOffset % NumEltBits) == 0 &&
"Illegal bit-offset") ? void (0) : __assert_fail ("(BitOffset % NumEltBits) == 0 && \"Illegal bit-offset\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13735, __extension__ __PRETTY_FUNCTION__))
;
13736 BroadcastIdx = BitOffset / NumEltBits;
13737
13738 // Do we need to bitcast the source to retrieve the original broadcast index?
13739 bool BitCastSrc = V.getScalarValueSizeInBits() != NumEltBits;
13740
13741 // Check if this is a broadcast of a scalar. We special case lowering
13742 // for scalars so that we can more effectively fold with loads.
13743 // If the original value has a larger element type than the shuffle, the
13744 // broadcast element is in essence truncated. Make that explicit to ease
13745 // folding.
13746 if (BitCastSrc && VT.isInteger())
13747 if (SDValue TruncBroadcast = lowerShuffleAsTruncBroadcast(
13748 DL, VT, V, BroadcastIdx, Subtarget, DAG))
13749 return TruncBroadcast;
13750
13751 // Also check the simpler case, where we can directly reuse the scalar.
13752 if (!BitCastSrc &&
13753 ((V.getOpcode() == ISD::BUILD_VECTOR && V.hasOneUse()) ||
13754 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0))) {
13755 V = V.getOperand(BroadcastIdx);
13756
13757 // If we can't broadcast from a register, check that the input is a load.
13758 if (!BroadcastFromReg && !isShuffleFoldableLoad(V))
13759 return SDValue();
13760 } else if (ISD::isNormalLoad(V.getNode()) &&
13761 cast<LoadSDNode>(V)->isSimple()) {
13762 // We do not check for one-use of the vector load because a broadcast load
13763 // is expected to be a win for code size, register pressure, and possibly
13764 // uops even if the original vector load is not eliminated.
13765
13766 // Reduce the vector load and shuffle to a broadcasted scalar load.
13767 LoadSDNode *Ld = cast<LoadSDNode>(V);
13768 SDValue BaseAddr = Ld->getOperand(1);
13769 MVT SVT = VT.getScalarType();
13770 unsigned Offset = BroadcastIdx * SVT.getStoreSize();
13771 assert((int)(Offset * 8) == BitOffset && "Unexpected bit-offset")(static_cast <bool> ((int)(Offset * 8) == BitOffset &&
"Unexpected bit-offset") ? void (0) : __assert_fail ("(int)(Offset * 8) == BitOffset && \"Unexpected bit-offset\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13771, __extension__ __PRETTY_FUNCTION__))
;
13772 SDValue NewAddr =
13773 DAG.getMemBasePlusOffset(BaseAddr, TypeSize::Fixed(Offset), DL);
13774
13775 // Directly form VBROADCAST_LOAD if we're using VBROADCAST opcode rather
13776 // than MOVDDUP.
13777 // FIXME: Should we add VBROADCAST_LOAD isel patterns for pre-AVX?
13778 if (Opcode == X86ISD::VBROADCAST) {
13779 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
13780 SDValue Ops[] = {Ld->getChain(), NewAddr};
13781 V = DAG.getMemIntrinsicNode(
13782 X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, SVT,
13783 DAG.getMachineFunction().getMachineMemOperand(
13784 Ld->getMemOperand(), Offset, SVT.getStoreSize()));
13785 DAG.makeEquivalentMemoryOrdering(Ld, V);
13786 return DAG.getBitcast(VT, V);
13787 }
13788 assert(SVT == MVT::f64 && "Unexpected VT!")(static_cast <bool> (SVT == MVT::f64 && "Unexpected VT!"
) ? void (0) : __assert_fail ("SVT == MVT::f64 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13788, __extension__ __PRETTY_FUNCTION__))
;
13789 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
13790 DAG.getMachineFunction().getMachineMemOperand(
13791 Ld->getMemOperand(), Offset, SVT.getStoreSize()));
13792 DAG.makeEquivalentMemoryOrdering(Ld, V);
13793 } else if (!BroadcastFromReg) {
13794 // We can't broadcast from a vector register.
13795 return SDValue();
13796 } else if (BitOffset != 0) {
13797 // We can only broadcast from the zero-element of a vector register,
13798 // but it can be advantageous to broadcast from the zero-element of a
13799 // subvector.
13800 if (!VT.is256BitVector() && !VT.is512BitVector())
13801 return SDValue();
13802
13803 // VPERMQ/VPERMPD can perform the cross-lane shuffle directly.
13804 if (VT == MVT::v4f64 || VT == MVT::v4i64)
13805 return SDValue();
13806
13807 // Only broadcast the zero-element of a 128-bit subvector.
13808 if ((BitOffset % 128) != 0)
13809 return SDValue();
13810
13811 assert((BitOffset % V.getScalarValueSizeInBits()) == 0 &&(static_cast <bool> ((BitOffset % V.getScalarValueSizeInBits
()) == 0 && "Unexpected bit-offset") ? void (0) : __assert_fail
("(BitOffset % V.getScalarValueSizeInBits()) == 0 && \"Unexpected bit-offset\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13812, __extension__ __PRETTY_FUNCTION__))
13812 "Unexpected bit-offset")(static_cast <bool> ((BitOffset % V.getScalarValueSizeInBits
()) == 0 && "Unexpected bit-offset") ? void (0) : __assert_fail
("(BitOffset % V.getScalarValueSizeInBits()) == 0 && \"Unexpected bit-offset\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13812, __extension__ __PRETTY_FUNCTION__))
;
13813 assert((V.getValueSizeInBits() == 256 || V.getValueSizeInBits() == 512) &&(static_cast <bool> ((V.getValueSizeInBits() == 256 || V
.getValueSizeInBits() == 512) && "Unexpected vector size"
) ? void (0) : __assert_fail ("(V.getValueSizeInBits() == 256 || V.getValueSizeInBits() == 512) && \"Unexpected vector size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13814, __extension__ __PRETTY_FUNCTION__))
13814 "Unexpected vector size")(static_cast <bool> ((V.getValueSizeInBits() == 256 || V
.getValueSizeInBits() == 512) && "Unexpected vector size"
) ? void (0) : __assert_fail ("(V.getValueSizeInBits() == 256 || V.getValueSizeInBits() == 512) && \"Unexpected vector size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13814, __extension__ __PRETTY_FUNCTION__))
;
13815 unsigned ExtractIdx = BitOffset / V.getScalarValueSizeInBits();
13816 V = extract128BitVector(V, ExtractIdx, DAG, DL);
13817 }
13818
13819 // On AVX we can use VBROADCAST directly for scalar sources.
13820 if (Opcode == X86ISD::MOVDDUP && !V.getValueType().isVector()) {
13821 V = DAG.getBitcast(MVT::f64, V);
13822 if (Subtarget.hasAVX()) {
13823 V = DAG.getNode(X86ISD::VBROADCAST, DL, MVT::v2f64, V);
13824 return DAG.getBitcast(VT, V);
13825 }
13826 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V);
13827 }
13828
13829 // If this is a scalar, do the broadcast on this type and bitcast.
13830 if (!V.getValueType().isVector()) {
13831 assert(V.getScalarValueSizeInBits() == NumEltBits &&(static_cast <bool> (V.getScalarValueSizeInBits() == NumEltBits
&& "Unexpected scalar size") ? void (0) : __assert_fail
("V.getScalarValueSizeInBits() == NumEltBits && \"Unexpected scalar size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13832, __extension__ __PRETTY_FUNCTION__))
13832 "Unexpected scalar size")(static_cast <bool> (V.getScalarValueSizeInBits() == NumEltBits
&& "Unexpected scalar size") ? void (0) : __assert_fail
("V.getScalarValueSizeInBits() == NumEltBits && \"Unexpected scalar size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13832, __extension__ __PRETTY_FUNCTION__))
;
13833 MVT BroadcastVT = MVT::getVectorVT(V.getSimpleValueType(),
13834 VT.getVectorNumElements());
13835 return DAG.getBitcast(VT, DAG.getNode(Opcode, DL, BroadcastVT, V));
13836 }
13837
13838 // We only support broadcasting from 128-bit vectors to minimize the
13839 // number of patterns we need to deal with in isel. So extract down to
13840 // 128-bits, removing as many bitcasts as possible.
13841 if (V.getValueSizeInBits() > 128)
13842 V = extract128BitVector(peekThroughBitcasts(V), 0, DAG, DL);
13843
13844 // Otherwise cast V to a vector with the same element type as VT, but
13845 // possibly narrower than VT. Then perform the broadcast.
13846 unsigned NumSrcElts = V.getValueSizeInBits() / NumEltBits;
13847 MVT CastVT = MVT::getVectorVT(VT.getVectorElementType(), NumSrcElts);
13848 return DAG.getNode(Opcode, DL, VT, DAG.getBitcast(CastVT, V));
13849}
13850
13851// Check for whether we can use INSERTPS to perform the shuffle. We only use
13852// INSERTPS when the V1 elements are already in the correct locations
13853// because otherwise we can just always use two SHUFPS instructions which
13854// are much smaller to encode than a SHUFPS and an INSERTPS. We can also
13855// perform INSERTPS if a single V1 element is out of place and all V2
13856// elements are zeroable.
13857static bool matchShuffleAsInsertPS(SDValue &V1, SDValue &V2,
13858 unsigned &InsertPSMask,
13859 const APInt &Zeroable,
13860 ArrayRef<int> Mask, SelectionDAG &DAG) {
13861 assert(V1.getSimpleValueType().is128BitVector() && "Bad operand type!")(static_cast <bool> (V1.getSimpleValueType().is128BitVector
() && "Bad operand type!") ? void (0) : __assert_fail
("V1.getSimpleValueType().is128BitVector() && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13861, __extension__ __PRETTY_FUNCTION__))
;
13862 assert(V2.getSimpleValueType().is128BitVector() && "Bad operand type!")(static_cast <bool> (V2.getSimpleValueType().is128BitVector
() && "Bad operand type!") ? void (0) : __assert_fail
("V2.getSimpleValueType().is128BitVector() && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13862, __extension__ __PRETTY_FUNCTION__))
;
13863 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!")(static_cast <bool> (Mask.size() == 4 && "Unexpected mask size for v4 shuffle!"
) ? void (0) : __assert_fail ("Mask.size() == 4 && \"Unexpected mask size for v4 shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13863, __extension__ __PRETTY_FUNCTION__))
;
13864
13865 // Attempt to match INSERTPS with one element from VA or VB being
13866 // inserted into VA (or undef). If successful, V1, V2 and InsertPSMask
13867 // are updated.
13868 auto matchAsInsertPS = [&](SDValue VA, SDValue VB,
13869 ArrayRef<int> CandidateMask) {
13870 unsigned ZMask = 0;
13871 int VADstIndex = -1;
13872 int VBDstIndex = -1;
13873 bool VAUsedInPlace = false;
13874
13875 for (int i = 0; i < 4; ++i) {
13876 // Synthesize a zero mask from the zeroable elements (includes undefs).
13877 if (Zeroable[i]) {
13878 ZMask |= 1 << i;
13879 continue;
13880 }
13881
13882 // Flag if we use any VA inputs in place.
13883 if (i == CandidateMask[i]) {
13884 VAUsedInPlace = true;
13885 continue;
13886 }
13887
13888 // We can only insert a single non-zeroable element.
13889 if (VADstIndex >= 0 || VBDstIndex >= 0)
13890 return false;
13891
13892 if (CandidateMask[i] < 4) {
13893 // VA input out of place for insertion.
13894 VADstIndex = i;
13895 } else {
13896 // VB input for insertion.
13897 VBDstIndex = i;
13898 }
13899 }
13900
13901 // Don't bother if we have no (non-zeroable) element for insertion.
13902 if (VADstIndex < 0 && VBDstIndex < 0)
13903 return false;
13904
13905 // Determine element insertion src/dst indices. The src index is from the
13906 // start of the inserted vector, not the start of the concatenated vector.
13907 unsigned VBSrcIndex = 0;
13908 if (VADstIndex >= 0) {
13909 // If we have a VA input out of place, we use VA as the V2 element
13910 // insertion and don't use the original V2 at all.
13911 VBSrcIndex = CandidateMask[VADstIndex];
13912 VBDstIndex = VADstIndex;
13913 VB = VA;
13914 } else {
13915 VBSrcIndex = CandidateMask[VBDstIndex] - 4;
13916 }
13917
13918 // If no V1 inputs are used in place, then the result is created only from
13919 // the zero mask and the V2 insertion - so remove V1 dependency.
13920 if (!VAUsedInPlace)
13921 VA = DAG.getUNDEF(MVT::v4f32);
13922
13923 // Update V1, V2 and InsertPSMask accordingly.
13924 V1 = VA;
13925 V2 = VB;
13926
13927 // Insert the V2 element into the desired position.
13928 InsertPSMask = VBSrcIndex << 6 | VBDstIndex << 4 | ZMask;
13929 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!")(static_cast <bool> ((InsertPSMask & ~0xFFu) == 0 &&
"Invalid mask!") ? void (0) : __assert_fail ("(InsertPSMask & ~0xFFu) == 0 && \"Invalid mask!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13929, __extension__ __PRETTY_FUNCTION__))
;
13930 return true;
13931 };
13932
13933 if (matchAsInsertPS(V1, V2, Mask))
13934 return true;
13935
13936 // Commute and try again.
13937 SmallVector<int, 4> CommutedMask(Mask.begin(), Mask.end());
13938 ShuffleVectorSDNode::commuteMask(CommutedMask);
13939 if (matchAsInsertPS(V2, V1, CommutedMask))
13940 return true;
13941
13942 return false;
13943}
13944
13945static SDValue lowerShuffleAsInsertPS(const SDLoc &DL, SDValue V1, SDValue V2,
13946 ArrayRef<int> Mask, const APInt &Zeroable,
13947 SelectionDAG &DAG) {
13948 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!")(static_cast <bool> (V1.getSimpleValueType() == MVT::v4f32
&& "Bad operand type!") ? void (0) : __assert_fail (
"V1.getSimpleValueType() == MVT::v4f32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13948, __extension__ __PRETTY_FUNCTION__))
;
13949 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!")(static_cast <bool> (V2.getSimpleValueType() == MVT::v4f32
&& "Bad operand type!") ? void (0) : __assert_fail (
"V2.getSimpleValueType() == MVT::v4f32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13949, __extension__ __PRETTY_FUNCTION__))
;
13950
13951 // Attempt to match the insertps pattern.
13952 unsigned InsertPSMask = 0;
13953 if (!matchShuffleAsInsertPS(V1, V2, InsertPSMask, Zeroable, Mask, DAG))
13954 return SDValue();
13955
13956 // Insert the V2 element into the desired position.
13957 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
13958 DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
13959}
13960
13961/// Try to lower a shuffle as a permute of the inputs followed by an
13962/// UNPCK instruction.
13963///
13964/// This specifically targets cases where we end up with alternating between
13965/// the two inputs, and so can permute them into something that feeds a single
13966/// UNPCK instruction. Note that this routine only targets integer vectors
13967/// because for floating point vectors we have a generalized SHUFPS lowering
13968/// strategy that handles everything that doesn't *exactly* match an unpack,
13969/// making this clever lowering unnecessary.
13970static SDValue lowerShuffleAsPermuteAndUnpack(
13971 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13972 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
13973 assert(!VT.isFloatingPoint() &&(static_cast <bool> (!VT.isFloatingPoint() && "This routine only supports integer vectors."
) ? void (0) : __assert_fail ("!VT.isFloatingPoint() && \"This routine only supports integer vectors.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13974, __extension__ __PRETTY_FUNCTION__))
13974 "This routine only supports integer vectors.")(static_cast <bool> (!VT.isFloatingPoint() && "This routine only supports integer vectors."
) ? void (0) : __assert_fail ("!VT.isFloatingPoint() && \"This routine only supports integer vectors.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13974, __extension__ __PRETTY_FUNCTION__))
;
13975 assert(VT.is128BitVector() &&(static_cast <bool> (VT.is128BitVector() && "This routine only works on 128-bit vectors."
) ? void (0) : __assert_fail ("VT.is128BitVector() && \"This routine only works on 128-bit vectors.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13976, __extension__ __PRETTY_FUNCTION__))
13976 "This routine only works on 128-bit vectors.")(static_cast <bool> (VT.is128BitVector() && "This routine only works on 128-bit vectors."
) ? void (0) : __assert_fail ("VT.is128BitVector() && \"This routine only works on 128-bit vectors.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13976, __extension__ __PRETTY_FUNCTION__))
;
13977 assert(!V2.isUndef() &&(static_cast <bool> (!V2.isUndef() && "This routine should only be used when blending two inputs."
) ? void (0) : __assert_fail ("!V2.isUndef() && \"This routine should only be used when blending two inputs.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13978, __extension__ __PRETTY_FUNCTION__))
13978 "This routine should only be used when blending two inputs.")(static_cast <bool> (!V2.isUndef() && "This routine should only be used when blending two inputs."
) ? void (0) : __assert_fail ("!V2.isUndef() && \"This routine should only be used when blending two inputs.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13978, __extension__ __PRETTY_FUNCTION__))
;
13979 assert(Mask.size() >= 2 && "Single element masks are invalid.")(static_cast <bool> (Mask.size() >= 2 && "Single element masks are invalid."
) ? void (0) : __assert_fail ("Mask.size() >= 2 && \"Single element masks are invalid.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 13979, __extension__ __PRETTY_FUNCTION__))
;
13980
13981 int Size = Mask.size();
13982
13983 int NumLoInputs =
13984 count_if(Mask, [Size](int M) { return M >= 0 && M % Size < Size / 2; });
13985 int NumHiInputs =
13986 count_if(Mask, [Size](int M) { return M % Size >= Size / 2; });
13987
13988 bool UnpackLo = NumLoInputs >= NumHiInputs;
13989
13990 auto TryUnpack = [&](int ScalarSize, int Scale) {
13991 SmallVector<int, 16> V1Mask((unsigned)Size, -1);
13992 SmallVector<int, 16> V2Mask((unsigned)Size, -1);
13993
13994 for (int i = 0; i < Size; ++i) {
13995 if (Mask[i] < 0)
13996 continue;
13997
13998 // Each element of the unpack contains Scale elements from this mask.
13999 int UnpackIdx = i / Scale;
14000
14001 // We only handle the case where V1 feeds the first slots of the unpack.
14002 // We rely on canonicalization to ensure this is the case.
14003 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
14004 return SDValue();
14005
14006 // Setup the mask for this input. The indexing is tricky as we have to
14007 // handle the unpack stride.
14008 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
14009 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
14010 Mask[i] % Size;
14011 }
14012
14013 // If we will have to shuffle both inputs to use the unpack, check whether
14014 // we can just unpack first and shuffle the result. If so, skip this unpack.
14015 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
14016 !isNoopShuffleMask(V2Mask))
14017 return SDValue();
14018
14019 // Shuffle the inputs into place.
14020 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
14021 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
14022
14023 // Cast the inputs to the type we will use to unpack them.
14024 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), Size / Scale);
14025 V1 = DAG.getBitcast(UnpackVT, V1);
14026 V2 = DAG.getBitcast(UnpackVT, V2);
14027
14028 // Unpack the inputs and cast the result back to the desired type.
14029 return DAG.getBitcast(
14030 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
14031 UnpackVT, V1, V2));
14032 };
14033
14034 // We try each unpack from the largest to the smallest to try and find one
14035 // that fits this mask.
14036 int OrigScalarSize = VT.getScalarSizeInBits();
14037 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2)
14038 if (SDValue Unpack = TryUnpack(ScalarSize, ScalarSize / OrigScalarSize))
14039 return Unpack;
14040
14041 // If we're shuffling with a zero vector then we're better off not doing
14042 // VECTOR_SHUFFLE(UNPCK()) as we lose track of those zero elements.
14043 if (ISD::isBuildVectorAllZeros(V1.getNode()) ||
14044 ISD::isBuildVectorAllZeros(V2.getNode()))
14045 return SDValue();
14046
14047 // If none of the unpack-rooted lowerings worked (or were profitable) try an
14048 // initial unpack.
14049 if (NumLoInputs == 0 || NumHiInputs == 0) {
14050 assert((NumLoInputs > 0 || NumHiInputs > 0) &&(static_cast <bool> ((NumLoInputs > 0 || NumHiInputs
> 0) && "We have to have *some* inputs!") ? void (
0) : __assert_fail ("(NumLoInputs > 0 || NumHiInputs > 0) && \"We have to have *some* inputs!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14051, __extension__ __PRETTY_FUNCTION__))
14051 "We have to have *some* inputs!")(static_cast <bool> ((NumLoInputs > 0 || NumHiInputs
> 0) && "We have to have *some* inputs!") ? void (
0) : __assert_fail ("(NumLoInputs > 0 || NumHiInputs > 0) && \"We have to have *some* inputs!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14051, __extension__ __PRETTY_FUNCTION__))
;
14052 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
14053
14054 // FIXME: We could consider the total complexity of the permute of each
14055 // possible unpacking. Or at the least we should consider how many
14056 // half-crossings are created.
14057 // FIXME: We could consider commuting the unpacks.
14058
14059 SmallVector<int, 32> PermMask((unsigned)Size, -1);
14060 for (int i = 0; i < Size; ++i) {
14061 if (Mask[i] < 0)
14062 continue;
14063
14064 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!")(static_cast <bool> (Mask[i] % Size >= HalfOffset &&
"Found input from wrong half!") ? void (0) : __assert_fail (
"Mask[i] % Size >= HalfOffset && \"Found input from wrong half!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14064, __extension__ __PRETTY_FUNCTION__))
;
14065
14066 PermMask[i] =
14067 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
14068 }
14069 return DAG.getVectorShuffle(
14070 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
14071 DL, VT, V1, V2),
14072 DAG.getUNDEF(VT), PermMask);
14073 }
14074
14075 return SDValue();
14076}
14077
14078/// Handle lowering of 2-lane 64-bit floating point shuffles.
14079///
14080/// This is the basis function for the 2-lane 64-bit shuffles as we have full
14081/// support for floating point shuffles but not integer shuffles. These
14082/// instructions will incur a domain crossing penalty on some chips though so
14083/// it is better to avoid lowering through this for integer vectors where
14084/// possible.
14085static SDValue lowerV2F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
14086 const APInt &Zeroable, SDValue V1, SDValue V2,
14087 const X86Subtarget &Subtarget,
14088 SelectionDAG &DAG) {
14089 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!")(static_cast <bool> (V1.getSimpleValueType() == MVT::v2f64
&& "Bad operand type!") ? void (0) : __assert_fail (
"V1.getSimpleValueType() == MVT::v2f64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14089, __extension__ __PRETTY_FUNCTION__))
;
14090 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!")(static_cast <bool> (V2.getSimpleValueType() == MVT::v2f64
&& "Bad operand type!") ? void (0) : __assert_fail (
"V2.getSimpleValueType() == MVT::v2f64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14090, __extension__ __PRETTY_FUNCTION__))
;
14091 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!")(static_cast <bool> (Mask.size() == 2 && "Unexpected mask size for v2 shuffle!"
) ? void (0) : __assert_fail ("Mask.size() == 2 && \"Unexpected mask size for v2 shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14091, __extension__ __PRETTY_FUNCTION__))
;
14092
14093 if (V2.isUndef()) {
14094 // Check for being able to broadcast a single element.
14095 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2f64, V1, V2,
14096 Mask, Subtarget, DAG))
14097 return Broadcast;
14098
14099 // Straight shuffle of a single input vector. Simulate this by using the
14100 // single input as both of the "inputs" to this instruction..
14101 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
14102
14103 if (Subtarget.hasAVX()) {
14104 // If we have AVX, we can use VPERMILPS which will allow folding a load
14105 // into the shuffle.
14106 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
14107 DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
14108 }
14109
14110 return DAG.getNode(
14111 X86ISD::SHUFP, DL, MVT::v2f64,
14112 Mask[0] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
14113 Mask[1] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
14114 DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
14115 }
14116 assert(Mask[0] >= 0 && "No undef lanes in multi-input v2 shuffles!")(static_cast <bool> (Mask[0] >= 0 && "No undef lanes in multi-input v2 shuffles!"
) ? void (0) : __assert_fail ("Mask[0] >= 0 && \"No undef lanes in multi-input v2 shuffles!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14116, __extension__ __PRETTY_FUNCTION__))
;
14117 assert(Mask[1] >= 0 && "No undef lanes in multi-input v2 shuffles!")(static_cast <bool> (Mask[1] >= 0 && "No undef lanes in multi-input v2 shuffles!"
) ? void (0) : __assert_fail ("Mask[1] >= 0 && \"No undef lanes in multi-input v2 shuffles!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14117, __extension__ __PRETTY_FUNCTION__))
;
14118 assert(Mask[0] < 2 && "We sort V1 to be the first input.")(static_cast <bool> (Mask[0] < 2 && "We sort V1 to be the first input."
) ? void (0) : __assert_fail ("Mask[0] < 2 && \"We sort V1 to be the first input.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14118, __extension__ __PRETTY_FUNCTION__))
;
14119 assert(Mask[1] >= 2 && "We sort V2 to be the second input.")(static_cast <bool> (Mask[1] >= 2 && "We sort V2 to be the second input."
) ? void (0) : __assert_fail ("Mask[1] >= 2 && \"We sort V2 to be the second input.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14119, __extension__ __PRETTY_FUNCTION__))
;
14120
14121 if (Subtarget.hasAVX2())
14122 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
14123 return Extract;
14124
14125 // When loading a scalar and then shuffling it into a vector we can often do
14126 // the insertion cheaply.
14127 if (SDValue Insertion = lowerShuffleAsElementInsertion(
14128 DL, MVT::v2f64, V1, V2, Mask, Zeroable, Subtarget, DAG))
14129 return Insertion;
14130 // Try inverting the insertion since for v2 masks it is easy to do and we
14131 // can't reliably sort the mask one way or the other.
14132 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
14133 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
14134 if (SDValue Insertion = lowerShuffleAsElementInsertion(
14135 DL, MVT::v2f64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
14136 return Insertion;
14137
14138 // Try to use one of the special instruction patterns to handle two common
14139 // blend patterns if a zero-blend above didn't work.
14140 if (isShuffleEquivalent(Mask, {0, 3}, V1, V2) ||
14141 isShuffleEquivalent(Mask, {1, 3}, V1, V2))
14142 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
14143 // We can either use a special instruction to load over the low double or
14144 // to move just the low double.
14145 return DAG.getNode(
14146 X86ISD::MOVSD, DL, MVT::v2f64, V2,
14147 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
14148
14149 if (Subtarget.hasSSE41())
14150 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
14151 Zeroable, Subtarget, DAG))
14152 return Blend;
14153
14154 // Use dedicated unpack instructions for masks that match their pattern.
14155 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
14156 return V;
14157
14158 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
14159 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
14160 DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
14161}
14162
14163/// Handle lowering of 2-lane 64-bit integer shuffles.
14164///
14165/// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
14166/// the integer unit to minimize domain crossing penalties. However, for blends
14167/// it falls back to the floating point shuffle operation with appropriate bit
14168/// casting.
14169static SDValue lowerV2I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
14170 const APInt &Zeroable, SDValue V1, SDValue V2,
14171 const X86Subtarget &Subtarget,
14172 SelectionDAG &DAG) {
14173 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!")(static_cast <bool> (V1.getSimpleValueType() == MVT::v2i64
&& "Bad operand type!") ? void (0) : __assert_fail (
"V1.getSimpleValueType() == MVT::v2i64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14173, __extension__ __PRETTY_FUNCTION__))
;
14174 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!")(static_cast <bool> (V2.getSimpleValueType() == MVT::v2i64
&& "Bad operand type!") ? void (0) : __assert_fail (
"V2.getSimpleValueType() == MVT::v2i64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14174, __extension__ __PRETTY_FUNCTION__))
;
14175 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!")(static_cast <bool> (Mask.size() == 2 && "Unexpected mask size for v2 shuffle!"
) ? void (0) : __assert_fail ("Mask.size() == 2 && \"Unexpected mask size for v2 shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14175, __extension__ __PRETTY_FUNCTION__))
;
14176
14177 if (V2.isUndef()) {
14178 // Check for being able to broadcast a single element.
14179 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2i64, V1, V2,
14180 Mask, Subtarget, DAG))
14181 return Broadcast;
14182
14183 // Straight shuffle of a single input vector. For everything from SSE2
14184 // onward this has a single fast instruction with no scary immediates.
14185 // We have to map the mask as it is actually a v4i32 shuffle instruction.
14186 V1 = DAG.getBitcast(MVT::v4i32, V1);
14187 int WidenedMask[4] = {Mask[0] < 0 ? -1 : (Mask[0] * 2),
14188 Mask[0] < 0 ? -1 : ((Mask[0] * 2) + 1),
14189 Mask[1] < 0 ? -1 : (Mask[1] * 2),
14190 Mask[1] < 0 ? -1 : ((Mask[1] * 2) + 1)};
14191 return DAG.getBitcast(
14192 MVT::v2i64,
14193 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
14194 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
14195 }
14196 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!")(static_cast <bool> (Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!"
) ? void (0) : __assert_fail ("Mask[0] != -1 && \"No undef lanes in multi-input v2 shuffles!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14196, __extension__ __PRETTY_FUNCTION__))
;
14197 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!")(static_cast <bool> (Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!"
) ? void (0) : __assert_fail ("Mask[1] != -1 && \"No undef lanes in multi-input v2 shuffles!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14197, __extension__ __PRETTY_FUNCTION__))
;
14198 assert(Mask[0] < 2 && "We sort V1 to be the first input.")(static_cast <bool> (Mask[0] < 2 && "We sort V1 to be the first input."
) ? void (0) : __assert_fail ("Mask[0] < 2 && \"We sort V1 to be the first input.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14198, __extension__ __PRETTY_FUNCTION__))
;
14199 assert(Mask[1] >= 2 && "We sort V2 to be the second input.")(static_cast <bool> (Mask[1] >= 2 && "We sort V2 to be the second input."
) ? void (0) : __assert_fail ("Mask[1] >= 2 && \"We sort V2 to be the second input.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14199, __extension__ __PRETTY_FUNCTION__))
;
14200
14201 if (Subtarget.hasAVX2())
14202 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
14203 return Extract;
14204
14205 // Try to use shift instructions.
14206 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask,
14207 Zeroable, Subtarget, DAG))
14208 return Shift;
14209
14210 // When loading a scalar and then shuffling it into a vector we can often do
14211 // the insertion cheaply.
14212 if (SDValue Insertion = lowerShuffleAsElementInsertion(
14213 DL, MVT::v2i64, V1, V2, Mask, Zeroable, Subtarget, DAG))
14214 return Insertion;
14215 // Try inverting the insertion since for v2 masks it is easy to do and we
14216 // can't reliably sort the mask one way or the other.
14217 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
14218 if (SDValue Insertion = lowerShuffleAsElementInsertion(
14219 DL, MVT::v2i64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
14220 return Insertion;
14221
14222 // We have different paths for blend lowering, but they all must use the
14223 // *exact* same predicate.
14224 bool IsBlendSupported = Subtarget.hasSSE41();
14225 if (IsBlendSupported)
14226 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
14227 Zeroable, Subtarget, DAG))
14228 return Blend;
14229
14230 // Use dedicated unpack instructions for masks that match their pattern.
14231 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
14232 return V;
14233
14234 // Try to use byte rotation instructions.
14235 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
14236 if (Subtarget.hasSSSE3()) {
14237 if (Subtarget.hasVLX())
14238 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v2i64, V1, V2, Mask,
14239 Subtarget, DAG))
14240 return Rotate;
14241
14242 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v2i64, V1, V2, Mask,
14243 Subtarget, DAG))
14244 return Rotate;
14245 }
14246
14247 // If we have direct support for blends, we should lower by decomposing into
14248 // a permute. That will be faster than the domain cross.
14249 if (IsBlendSupported)
14250 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v2i64, V1, V2, Mask,
14251 Subtarget, DAG);
14252
14253 // We implement this with SHUFPD which is pretty lame because it will likely
14254 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
14255 // However, all the alternatives are still more cycles and newer chips don't
14256 // have this problem. It would be really nice if x86 had better shuffles here.
14257 V1 = DAG.getBitcast(MVT::v2f64, V1);
14258 V2 = DAG.getBitcast(MVT::v2f64, V2);
14259 return DAG.getBitcast(MVT::v2i64,
14260 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
14261}
14262
14263/// Lower a vector shuffle using the SHUFPS instruction.
14264///
14265/// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
14266/// It makes no assumptions about whether this is the *best* lowering, it simply
14267/// uses it.
14268static SDValue lowerShuffleWithSHUFPS(const SDLoc &DL, MVT VT,
14269 ArrayRef<int> Mask, SDValue V1,
14270 SDValue V2, SelectionDAG &DAG) {
14271 SDValue LowV = V1, HighV = V2;
14272 SmallVector<int, 4> NewMask(Mask.begin(), Mask.end());
14273 int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
14274
14275 if (NumV2Elements == 1) {
14276 int V2Index = find_if(Mask, [](int M) { return M >= 4; }) - Mask.begin();
14277
14278 // Compute the index adjacent to V2Index and in the same half by toggling
14279 // the low bit.
14280 int V2AdjIndex = V2Index ^ 1;
14281
14282 if (Mask[V2AdjIndex] < 0) {
14283 // Handles all the cases where we have a single V2 element and an undef.
14284 // This will only ever happen in the high lanes because we commute the
14285 // vector otherwise.
14286 if (V2Index < 2)
14287 std::swap(LowV, HighV);
14288 NewMask[V2Index] -= 4;
14289 } else {
14290 // Handle the case where the V2 element ends up adjacent to a V1 element.
14291 // To make this work, blend them together as the first step.
14292 int V1Index = V2AdjIndex;
14293 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
14294 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
14295 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
14296
14297 // Now proceed to reconstruct the final blend as we have the necessary
14298 // high or low half formed.
14299 if (V2Index < 2) {
14300 LowV = V2;
14301 HighV = V1;
14302 } else {
14303 HighV = V2;
14304 }
14305 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
14306 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
14307 }
14308 } else if (NumV2Elements == 2) {
14309 if (Mask[0] < 4 && Mask[1] < 4) {
14310 // Handle the easy case where we have V1 in the low lanes and V2 in the
14311 // high lanes.
14312 NewMask[2] -= 4;
14313 NewMask[3] -= 4;
14314 } else if (Mask[2] < 4 && Mask[3] < 4) {
14315 // We also handle the reversed case because this utility may get called
14316 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
14317 // arrange things in the right direction.
14318 NewMask[0] -= 4;
14319 NewMask[1] -= 4;
14320 HighV = V1;
14321 LowV = V2;
14322 } else {
14323 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
14324 // trying to place elements directly, just blend them and set up the final
14325 // shuffle to place them.
14326
14327 // The first two blend mask elements are for V1, the second two are for
14328 // V2.
14329 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
14330 Mask[2] < 4 ? Mask[2] : Mask[3],
14331 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
14332 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
14333 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
14334 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
14335
14336 // Now we do a normal shuffle of V1 by giving V1 as both operands to
14337 // a blend.
14338 LowV = HighV = V1;
14339 NewMask[0] = Mask[0] < 4 ? 0 : 2;
14340 NewMask[1] = Mask[0] < 4 ? 2 : 0;
14341 NewMask[2] = Mask[2] < 4 ? 1 : 3;
14342 NewMask[3] = Mask[2] < 4 ? 3 : 1;
14343 }
14344 } else if (NumV2Elements == 3) {
14345 // Ideally canonicalizeShuffleMaskWithCommute should have caught this, but
14346 // we can get here due to other paths (e.g repeated mask matching) that we
14347 // don't want to do another round of lowerVECTOR_SHUFFLE.
14348 ShuffleVectorSDNode::commuteMask(NewMask);
14349 return lowerShuffleWithSHUFPS(DL, VT, NewMask, V2, V1, DAG);
14350 }
14351 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
14352 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
14353}
14354
14355/// Lower 4-lane 32-bit floating point shuffles.
14356///
14357/// Uses instructions exclusively from the floating point unit to minimize
14358/// domain crossing penalties, as these are sufficient to implement all v4f32
14359/// shuffles.
14360static SDValue lowerV4F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
14361 const APInt &Zeroable, SDValue V1, SDValue V2,
14362 const X86Subtarget &Subtarget,
14363 SelectionDAG &DAG) {
14364 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!")(static_cast <bool> (V1.getSimpleValueType() == MVT::v4f32
&& "Bad operand type!") ? void (0) : __assert_fail (
"V1.getSimpleValueType() == MVT::v4f32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14364, __extension__ __PRETTY_FUNCTION__))
;
14365 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!")(static_cast <bool> (V2.getSimpleValueType() == MVT::v4f32
&& "Bad operand type!") ? void (0) : __assert_fail (
"V2.getSimpleValueType() == MVT::v4f32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14365, __extension__ __PRETTY_FUNCTION__))
;
14366 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!")(static_cast <bool> (Mask.size() == 4 && "Unexpected mask size for v4 shuffle!"
) ? void (0) : __assert_fail ("Mask.size() == 4 && \"Unexpected mask size for v4 shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14366, __extension__ __PRETTY_FUNCTION__))
;
14367
14368 int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
14369
14370 if (NumV2Elements == 0) {
14371 // Check for being able to broadcast a single element.
14372 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f32, V1, V2,
14373 Mask, Subtarget, DAG))
14374 return Broadcast;
14375
14376 // Use even/odd duplicate instructions for masks that match their pattern.
14377 if (Subtarget.hasSSE3()) {
14378 if (isShuffleEquivalent(Mask, {0, 0, 2, 2}, V1, V2))
14379 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
14380 if (isShuffleEquivalent(Mask, {1, 1, 3, 3}, V1, V2))
14381 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
14382 }
14383
14384 if (Subtarget.hasAVX()) {
14385 // If we have AVX, we can use VPERMILPS which will allow folding a load
14386 // into the shuffle.
14387 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
14388 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
14389 }
14390
14391 // Use MOVLHPS/MOVHLPS to simulate unary shuffles. These are only valid
14392 // in SSE1 because otherwise they are widened to v2f64 and never get here.
14393 if (!Subtarget.hasSSE2()) {
14394 if (isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1, V2))
14395 return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V1);
14396 if (isShuffleEquivalent(Mask, {2, 3, 2, 3}, V1, V2))
14397 return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V1, V1);
14398 }
14399
14400 // Otherwise, use a straight shuffle of a single input vector. We pass the
14401 // input vector to both operands to simulate this with a SHUFPS.
14402 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
14403 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
14404 }
14405
14406 if (Subtarget.hasAVX2())
14407 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
14408 return Extract;
14409
14410 // There are special ways we can lower some single-element blends. However, we
14411 // have custom ways we can lower more complex single-element blends below that
14412 // we defer to if both this and BLENDPS fail to match, so restrict this to
14413 // when the V2 input is targeting element 0 of the mask -- that is the fast
14414 // case here.
14415 if (NumV2Elements == 1 && Mask[0] >= 4)
14416 if (SDValue V = lowerShuffleAsElementInsertion(
14417 DL, MVT::v4f32, V1, V2, Mask, Zeroable, Subtarget, DAG))
14418 return V;
14419
14420 if (Subtarget.hasSSE41()) {
14421 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
14422 Zeroable, Subtarget, DAG))
14423 return Blend;
14424
14425 // Use INSERTPS if we can complete the shuffle efficiently.
14426 if (SDValue V = lowerShuffleAsInsertPS(DL, V1, V2, Mask, Zeroable, DAG))
14427 return V;
14428
14429 if (!isSingleSHUFPSMask(Mask))
14430 if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, MVT::v4f32, V1,
14431 V2, Mask, DAG))
14432 return BlendPerm;
14433 }
14434
14435 // Use low/high mov instructions. These are only valid in SSE1 because
14436 // otherwise they are widened to v2f64 and never get here.
14437 if (!Subtarget.hasSSE2()) {
14438 if (isShuffleEquivalent(Mask, {0, 1, 4, 5}, V1, V2))
14439 return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V2);
14440 if (isShuffleEquivalent(Mask, {2, 3, 6, 7}, V1, V2))
14441 return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V2, V1);
14442 }
14443
14444 // Use dedicated unpack instructions for masks that match their pattern.
14445 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
14446 return V;
14447
14448 // Otherwise fall back to a SHUFPS lowering strategy.
14449 return lowerShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
14450}
14451
14452/// Lower 4-lane i32 vector shuffles.
14453///
14454/// We try to handle these with integer-domain shuffles where we can, but for
14455/// blends we use the floating point domain blend instructions.
14456static SDValue lowerV4I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
14457 const APInt &Zeroable, SDValue V1, SDValue V2,
14458 const X86Subtarget &Subtarget,
14459 SelectionDAG &DAG) {
14460 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!")(static_cast <bool> (V1.getSimpleValueType() == MVT::v4i32
&& "Bad operand type!") ? void (0) : __assert_fail (
"V1.getSimpleValueType() == MVT::v4i32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14460, __extension__ __PRETTY_FUNCTION__))
;
14461 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!")(static_cast <bool> (V2.getSimpleValueType() == MVT::v4i32
&& "Bad operand type!") ? void (0) : __assert_fail (
"V2.getSimpleValueType() == MVT::v4i32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14461, __extension__ __PRETTY_FUNCTION__))
;
14462 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!")(static_cast <bool> (Mask.size() == 4 && "Unexpected mask size for v4 shuffle!"
) ? void (0) : __assert_fail ("Mask.size() == 4 && \"Unexpected mask size for v4 shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14462, __extension__ __PRETTY_FUNCTION__))
;
14463
14464 // Whenever we can lower this as a zext, that instruction is strictly faster
14465 // than any alternative. It also allows us to fold memory operands into the
14466 // shuffle in many cases.
14467 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2, Mask,
14468 Zeroable, Subtarget, DAG))
14469 return ZExt;
14470
14471 int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
14472
14473 if (NumV2Elements == 0) {
14474 // Try to use broadcast unless the mask only has one non-undef element.
14475 if (count_if(Mask, [](int M) { return M >= 0 && M < 4; }) > 1) {
14476 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i32, V1, V2,
14477 Mask, Subtarget, DAG))
14478 return Broadcast;
14479 }
14480
14481 // Straight shuffle of a single input vector. For everything from SSE2
14482 // onward this has a single fast instruction with no scary immediates.
14483 // We coerce the shuffle pattern to be compatible with UNPCK instructions
14484 // but we aren't actually going to use the UNPCK instruction because doing
14485 // so prevents folding a load into this instruction or making a copy.
14486 const int UnpackLoMask[] = {0, 0, 1, 1};
14487 const int UnpackHiMask[] = {2, 2, 3, 3};
14488 if (isShuffleEquivalent(Mask, {0, 0, 1, 1}, V1, V2))
14489 Mask = UnpackLoMask;
14490 else if (isShuffleEquivalent(Mask, {2, 2, 3, 3}, V1, V2))
14491 Mask = UnpackHiMask;
14492
14493 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
14494 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
14495 }
14496
14497 if (Subtarget.hasAVX2())
14498 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
14499 return Extract;
14500
14501 // Try to use shift instructions.
14502 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask,
14503 Zeroable, Subtarget, DAG))
14504 return Shift;
14505
14506 // There are special ways we can lower some single-element blends.
14507 if (NumV2Elements == 1)
14508 if (SDValue V = lowerShuffleAsElementInsertion(
14509 DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
14510 return V;
14511
14512 // We have different paths for blend lowering, but they all must use the
14513 // *exact* same predicate.
14514 bool IsBlendSupported = Subtarget.hasSSE41();
14515 if (IsBlendSupported)
14516 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
14517 Zeroable, Subtarget, DAG))
14518 return Blend;
14519
14520 if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask,
14521 Zeroable, Subtarget, DAG))
14522 return Masked;
14523
14524 // Use dedicated unpack instructions for masks that match their pattern.
14525 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
14526 return V;
14527
14528 // Try to use byte rotation instructions.
14529 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
14530 if (Subtarget.hasSSSE3()) {
14531 if (Subtarget.hasVLX())
14532 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i32, V1, V2, Mask,
14533 Subtarget, DAG))
14534 return Rotate;
14535
14536 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i32, V1, V2, Mask,
14537 Subtarget, DAG))
14538 return Rotate;
14539 }
14540
14541 // Assume that a single SHUFPS is faster than an alternative sequence of
14542 // multiple instructions (even if the CPU has a domain penalty).
14543 // If some CPU is harmed by the domain switch, we can fix it in a later pass.
14544 if (!isSingleSHUFPSMask(Mask)) {
14545 // If we have direct support for blends, we should lower by decomposing into
14546 // a permute. That will be faster than the domain cross.
14547 if (IsBlendSupported)
14548 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i32, V1, V2, Mask,
14549 Subtarget, DAG);
14550
14551 // Try to lower by permuting the inputs into an unpack instruction.
14552 if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1, V2,
14553 Mask, Subtarget, DAG))
14554 return Unpack;
14555 }
14556
14557 // We implement this with SHUFPS because it can blend from two vectors.
14558 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
14559 // up the inputs, bypassing domain shift penalties that we would incur if we
14560 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
14561 // relevant.
14562 SDValue CastV1 = DAG.getBitcast(MVT::v4f32, V1);
14563 SDValue CastV2 = DAG.getBitcast(MVT::v4f32, V2);
14564 SDValue ShufPS = DAG.getVectorShuffle(MVT::v4f32, DL, CastV1, CastV2, Mask);
14565 return DAG.getBitcast(MVT::v4i32, ShufPS);
14566}
14567
14568/// Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
14569/// shuffle lowering, and the most complex part.
14570///
14571/// The lowering strategy is to try to form pairs of input lanes which are
14572/// targeted at the same half of the final vector, and then use a dword shuffle
14573/// to place them onto the right half, and finally unpack the paired lanes into
14574/// their final position.
14575///
14576/// The exact breakdown of how to form these dword pairs and align them on the
14577/// correct sides is really tricky. See the comments within the function for
14578/// more of the details.
14579///
14580/// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
14581/// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
14582/// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
14583/// vector, form the analogous 128-bit 8-element Mask.
14584static SDValue lowerV8I16GeneralSingleInputShuffle(
14585 const SDLoc &DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
14586 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
14587 assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!")(static_cast <bool> (VT.getVectorElementType() == MVT::
i16 && "Bad input type!") ? void (0) : __assert_fail (
"VT.getVectorElementType() == MVT::i16 && \"Bad input type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14587, __extension__ __PRETTY_FUNCTION__))
;
14588 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
14589
14590 assert(Mask.size() == 8 && "Shuffle mask length doesn't match!")(static_cast <bool> (Mask.size() == 8 && "Shuffle mask length doesn't match!"
) ? void (0) : __assert_fail ("Mask.size() == 8 && \"Shuffle mask length doesn't match!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14590, __extension__ __PRETTY_FUNCTION__))
;
14591 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
14592 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
14593
14594 // Attempt to directly match PSHUFLW or PSHUFHW.
14595 if (isUndefOrInRange(LoMask, 0, 4) &&
14596 isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
14597 return DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
14598 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
14599 }
14600 if (isUndefOrInRange(HiMask, 4, 8) &&
14601 isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
14602 for (int i = 0; i != 4; ++i)
14603 HiMask[i] = (HiMask[i] < 0 ? HiMask[i] : (HiMask[i] - 4));
14604 return DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
14605 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
14606 }
14607
14608 SmallVector<int, 4> LoInputs;
14609 copy_if(LoMask, std::back_inserter(LoInputs), [](int M) { return M >= 0; });
14610 array_pod_sort(LoInputs.begin(), LoInputs.end());
14611 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
14612 SmallVector<int, 4> HiInputs;
14613 copy_if(HiMask, std::back_inserter(HiInputs), [](int M) { return M >= 0; });
14614 array_pod_sort(HiInputs.begin(), HiInputs.end());
14615 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
14616 int NumLToL = llvm::lower_bound(LoInputs, 4) - LoInputs.begin();
14617 int NumHToL = LoInputs.size() - NumLToL;
14618 int NumLToH = llvm::lower_bound(HiInputs, 4) - HiInputs.begin();
14619 int NumHToH = HiInputs.size() - NumLToH;
14620 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
14621 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
14622 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
14623 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
14624
14625 // If we are shuffling values from one half - check how many different DWORD
14626 // pairs we need to create. If only 1 or 2 then we can perform this as a
14627 // PSHUFLW/PSHUFHW + PSHUFD instead of the PSHUFD+PSHUFLW+PSHUFHW chain below.
14628 auto ShuffleDWordPairs = [&](ArrayRef<int> PSHUFHalfMask,
14629 ArrayRef<int> PSHUFDMask, unsigned ShufWOp) {
14630 V = DAG.getNode(ShufWOp, DL, VT, V,
14631 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
14632 V = DAG.getBitcast(PSHUFDVT, V);
14633 V = DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, V,
14634 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
14635 return DAG.getBitcast(VT, V);
14636 };
14637
14638 if ((NumHToL + NumHToH) == 0 || (NumLToL + NumLToH) == 0) {
14639 int PSHUFDMask[4] = { -1, -1, -1, -1 };
14640 SmallVector<std::pair<int, int>, 4> DWordPairs;
14641 int DOffset = ((NumHToL + NumHToH) == 0 ? 0 : 2);
14642
14643 // Collect the different DWORD pairs.
14644 for (int DWord = 0; DWord != 4; ++DWord) {
14645 int M0 = Mask[2 * DWord + 0];
14646 int M1 = Mask[2 * DWord + 1];
14647 M0 = (M0 >= 0 ? M0 % 4 : M0);
14648 M1 = (M1 >= 0 ? M1 % 4 : M1);
14649 if (M0 < 0 && M1 < 0)
14650 continue;
14651
14652 bool Match = false;
14653 for (int j = 0, e = DWordPairs.size(); j < e; ++j) {
14654 auto &DWordPair = DWordPairs[j];
14655 if ((M0 < 0 || isUndefOrEqual(DWordPair.first, M0)) &&
14656 (M1 < 0 || isUndefOrEqual(DWordPair.second, M1))) {
14657 DWordPair.first = (M0 >= 0 ? M0 : DWordPair.first);
14658 DWordPair.second = (M1 >= 0 ? M1 : DWordPair.second);
14659 PSHUFDMask[DWord] = DOffset + j;
14660 Match = true;
14661 break;
14662 }
14663 }
14664 if (!Match) {
14665 PSHUFDMask[DWord] = DOffset + DWordPairs.size();
14666 DWordPairs.push_back(std::make_pair(M0, M1));
14667 }
14668 }
14669
14670 if (DWordPairs.size() <= 2) {
14671 DWordPairs.resize(2, std::make_pair(-1, -1));
14672 int PSHUFHalfMask[4] = {DWordPairs[0].first, DWordPairs[0].second,
14673 DWordPairs[1].first, DWordPairs[1].second};
14674 if ((NumHToL + NumHToH) == 0)
14675 return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFLW);
14676 if ((NumLToL + NumLToH) == 0)
14677 return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFHW);
14678 }
14679 }
14680
14681 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
14682 // such inputs we can swap two of the dwords across the half mark and end up
14683 // with <=2 inputs to each half in each half. Once there, we can fall through
14684 // to the generic code below. For example:
14685 //
14686 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
14687 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
14688 //
14689 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
14690 // and an existing 2-into-2 on the other half. In this case we may have to
14691 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
14692 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
14693 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
14694 // because any other situation (including a 3-into-1 or 1-into-3 in the other
14695 // half than the one we target for fixing) will be fixed when we re-enter this
14696 // path. We will also combine away any sequence of PSHUFD instructions that
14697 // result into a single instruction. Here is an example of the tricky case:
14698 //
14699 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
14700 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
14701 //
14702 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
14703 //
14704 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
14705 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
14706 //
14707 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
14708 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
14709 //
14710 // The result is fine to be handled by the generic logic.
14711 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
14712 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
14713 int AOffset, int BOffset) {
14714 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&(static_cast <bool> ((AToAInputs.size() == 3 || AToAInputs
.size() == 1) && "Must call this with A having 3 or 1 inputs from the A half."
) ? void (0) : __assert_fail ("(AToAInputs.size() == 3 || AToAInputs.size() == 1) && \"Must call this with A having 3 or 1 inputs from the A half.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14715, __extension__ __PRETTY_FUNCTION__))
14715 "Must call this with A having 3 or 1 inputs from the A half.")(static_cast <bool> ((AToAInputs.size() == 3 || AToAInputs
.size() == 1) && "Must call this with A having 3 or 1 inputs from the A half."
) ? void (0) : __assert_fail ("(AToAInputs.size() == 3 || AToAInputs.size() == 1) && \"Must call this with A having 3 or 1 inputs from the A half.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14715, __extension__ __PRETTY_FUNCTION__))
;
14716 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&(static_cast <bool> ((BToAInputs.size() == 1 || BToAInputs
.size() == 3) && "Must call this with B having 1 or 3 inputs from the B half."
) ? void (0) : __assert_fail ("(BToAInputs.size() == 1 || BToAInputs.size() == 3) && \"Must call this with B having 1 or 3 inputs from the B half.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14717, __extension__ __PRETTY_FUNCTION__))
14717 "Must call this with B having 1 or 3 inputs from the B half.")(static_cast <bool> ((BToAInputs.size() == 1 || BToAInputs
.size() == 3) && "Must call this with B having 1 or 3 inputs from the B half."
) ? void (0) : __assert_fail ("(BToAInputs.size() == 1 || BToAInputs.size() == 3) && \"Must call this with B having 1 or 3 inputs from the B half.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14717, __extension__ __PRETTY_FUNCTION__))
;
14718 assert(AToAInputs.size() + BToAInputs.size() == 4 &&(static_cast <bool> (AToAInputs.size() + BToAInputs.size
() == 4 && "Must call this with either 3:1 or 1:3 inputs (summing to 4)."
) ? void (0) : __assert_fail ("AToAInputs.size() + BToAInputs.size() == 4 && \"Must call this with either 3:1 or 1:3 inputs (summing to 4).\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14719, __extension__ __PRETTY_FUNCTION__))
14719 "Must call this with either 3:1 or 1:3 inputs (summing to 4).")(static_cast <bool> (AToAInputs.size() + BToAInputs.size
() == 4 && "Must call this with either 3:1 or 1:3 inputs (summing to 4)."
) ? void (0) : __assert_fail ("AToAInputs.size() + BToAInputs.size() == 4 && \"Must call this with either 3:1 or 1:3 inputs (summing to 4).\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14719, __extension__ __PRETTY_FUNCTION__))
;
14720
14721 bool ThreeAInputs = AToAInputs.size() == 3;
14722
14723 // Compute the index of dword with only one word among the three inputs in
14724 // a half by taking the sum of the half with three inputs and subtracting
14725 // the sum of the actual three inputs. The difference is the remaining
14726 // slot.
14727 int ADWord = 0, BDWord = 0;
14728 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
14729 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
14730 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
14731 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
14732 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
14733 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
14734 int TripleNonInputIdx =
14735 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
14736 TripleDWord = TripleNonInputIdx / 2;
14737
14738 // We use xor with one to compute the adjacent DWord to whichever one the
14739 // OneInput is in.
14740 OneInputDWord = (OneInput / 2) ^ 1;
14741
14742 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
14743 // and BToA inputs. If there is also such a problem with the BToB and AToB
14744 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
14745 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
14746 // is essential that we don't *create* a 3<-1 as then we might oscillate.
14747 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
14748 // Compute how many inputs will be flipped by swapping these DWords. We
14749 // need
14750 // to balance this to ensure we don't form a 3-1 shuffle in the other
14751 // half.
14752 int NumFlippedAToBInputs =
14753 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
14754 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
14755 int NumFlippedBToBInputs =
14756 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
14757 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
14758 if ((NumFlippedAToBInputs == 1 &&
14759 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
14760 (NumFlippedBToBInputs == 1 &&
14761 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
14762 // We choose whether to fix the A half or B half based on whether that
14763 // half has zero flipped inputs. At zero, we may not be able to fix it
14764 // with that half. We also bias towards fixing the B half because that
14765 // will more commonly be the high half, and we have to bias one way.
14766 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
14767 ArrayRef<int> Inputs) {
14768 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
14769 bool IsFixIdxInput = is_contained(Inputs, PinnedIdx ^ 1);
14770 // Determine whether the free index is in the flipped dword or the
14771 // unflipped dword based on where the pinned index is. We use this bit
14772 // in an xor to conditionally select the adjacent dword.
14773 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
14774 bool IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
14775 if (IsFixIdxInput == IsFixFreeIdxInput)
14776 FixFreeIdx += 1;
14777 IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
14778 assert(IsFixIdxInput != IsFixFreeIdxInput &&(static_cast <bool> (IsFixIdxInput != IsFixFreeIdxInput
&& "We need to be changing the number of flipped inputs!"
) ? void (0) : __assert_fail ("IsFixIdxInput != IsFixFreeIdxInput && \"We need to be changing the number of flipped inputs!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14779, __extension__ __PRETTY_FUNCTION__))
14779 "We need to be changing the number of flipped inputs!")(static_cast <bool> (IsFixIdxInput != IsFixFreeIdxInput
&& "We need to be changing the number of flipped inputs!"
) ? void (0) : __assert_fail ("IsFixIdxInput != IsFixFreeIdxInput && \"We need to be changing the number of flipped inputs!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14779, __extension__ __PRETTY_FUNCTION__))
;
14780 int PSHUFHalfMask[] = {0, 1, 2, 3};
14781 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
14782 V = DAG.getNode(
14783 FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
14784 MVT::getVectorVT(MVT::i16, V.getValueSizeInBits() / 16), V,
14785 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
14786
14787 for (int &M : Mask)
14788 if (M >= 0 && M == FixIdx)
14789 M = FixFreeIdx;
14790 else if (M >= 0 && M == FixFreeIdx)
14791 M = FixIdx;
14792 };
14793 if (NumFlippedBToBInputs != 0) {
14794 int BPinnedIdx =
14795 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
14796 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
14797 } else {
14798 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!")(static_cast <bool> (NumFlippedAToBInputs != 0 &&
"Impossible given predicates!") ? void (0) : __assert_fail (
"NumFlippedAToBInputs != 0 && \"Impossible given predicates!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14798, __extension__ __PRETTY_FUNCTION__))
;
14799 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
14800 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
14801 }
14802 }
14803 }
14804
14805 int PSHUFDMask[] = {0, 1, 2, 3};
14806 PSHUFDMask[ADWord] = BDWord;
14807 PSHUFDMask[BDWord] = ADWord;
14808 V = DAG.getBitcast(
14809 VT,
14810 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
14811 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
14812
14813 // Adjust the mask to match the new locations of A and B.
14814 for (int &M : Mask)
14815 if (M >= 0 && M/2 == ADWord)
14816 M = 2 * BDWord + M % 2;
14817 else if (M >= 0 && M/2 == BDWord)
14818 M = 2 * ADWord + M % 2;
14819
14820 // Recurse back into this routine to re-compute state now that this isn't
14821 // a 3 and 1 problem.
14822 return lowerV8I16GeneralSingleInputShuffle(DL, VT, V, Mask, Subtarget, DAG);
14823 };
14824 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
14825 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
14826 if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
14827 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
14828
14829 // At this point there are at most two inputs to the low and high halves from
14830 // each half. That means the inputs can always be grouped into dwords and
14831 // those dwords can then be moved to the correct half with a dword shuffle.
14832 // We use at most one low and one high word shuffle to collect these paired
14833 // inputs into dwords, and finally a dword shuffle to place them.
14834 int PSHUFLMask[4] = {-1, -1, -1, -1};
14835 int PSHUFHMask[4] = {-1, -1, -1, -1};
14836 int PSHUFDMask[4] = {-1, -1, -1, -1};
14837
14838 // First fix the masks for all the inputs that are staying in their
14839 // original halves. This will then dictate the targets of the cross-half
14840 // shuffles.
14841 auto fixInPlaceInputs =
14842 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
14843 MutableArrayRef<int> SourceHalfMask,
14844 MutableArrayRef<int> HalfMask, int HalfOffset) {
14845 if (InPlaceInputs.empty())
14846 return;
14847 if (InPlaceInputs.size() == 1) {
14848 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
14849 InPlaceInputs[0] - HalfOffset;
14850 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
14851 return;
14852 }
14853 if (IncomingInputs.empty()) {
14854 // Just fix all of the in place inputs.
14855 for (int Input : InPlaceInputs) {
14856 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
14857 PSHUFDMask[Input / 2] = Input / 2;
14858 }
14859 return;
14860 }
14861
14862 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!")(static_cast <bool> (InPlaceInputs.size() == 2 &&
"Cannot handle 3 or 4 inputs!") ? void (0) : __assert_fail (
"InPlaceInputs.size() == 2 && \"Cannot handle 3 or 4 inputs!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14862, __extension__ __PRETTY_FUNCTION__))
;
14863 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
14864 InPlaceInputs[0] - HalfOffset;
14865 // Put the second input next to the first so that they are packed into
14866 // a dword. We find the adjacent index by toggling the low bit.
14867 int AdjIndex = InPlaceInputs[0] ^ 1;
14868 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
14869 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
14870 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
14871 };
14872 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
14873 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
14874
14875 // Now gather the cross-half inputs and place them into a free dword of
14876 // their target half.
14877 // FIXME: This operation could almost certainly be simplified dramatically to
14878 // look more like the 3-1 fixing operation.
14879 auto moveInputsToRightHalf = [&PSHUFDMask](
14880 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
14881 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
14882 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
14883 int DestOffset) {
14884 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
14885 return SourceHalfMask[Word] >= 0 && SourceHalfMask[Word] != Word;
14886 };
14887 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
14888 int Word) {
14889 int LowWord = Word & ~1;
14890 int HighWord = Word | 1;
14891 return isWordClobbered(SourceHalfMask, LowWord) ||
14892 isWordClobbered(SourceHalfMask, HighWord);
14893 };
14894
14895 if (IncomingInputs.empty())
14896 return;
14897
14898 if (ExistingInputs.empty()) {
14899 // Map any dwords with inputs from them into the right half.
14900 for (int Input : IncomingInputs) {
14901 // If the source half mask maps over the inputs, turn those into
14902 // swaps and use the swapped lane.
14903 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
14904 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] < 0) {
14905 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
14906 Input - SourceOffset;
14907 // We have to swap the uses in our half mask in one sweep.
14908 for (int &M : HalfMask)
14909 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
14910 M = Input;
14911 else if (M == Input)
14912 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
14913 } else {
14914 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==(static_cast <bool> (SourceHalfMask[SourceHalfMask[Input
- SourceOffset]] == Input - SourceOffset && "Previous placement doesn't match!"
) ? void (0) : __assert_fail ("SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == Input - SourceOffset && \"Previous placement doesn't match!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14916, __extension__ __PRETTY_FUNCTION__))
14915 Input - SourceOffset &&(static_cast <bool> (SourceHalfMask[SourceHalfMask[Input
- SourceOffset]] == Input - SourceOffset && "Previous placement doesn't match!"
) ? void (0) : __assert_fail ("SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == Input - SourceOffset && \"Previous placement doesn't match!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14916, __extension__ __PRETTY_FUNCTION__))
14916 "Previous placement doesn't match!")(static_cast <bool> (SourceHalfMask[SourceHalfMask[Input
- SourceOffset]] == Input - SourceOffset && "Previous placement doesn't match!"
) ? void (0) : __assert_fail ("SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == Input - SourceOffset && \"Previous placement doesn't match!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14916, __extension__ __PRETTY_FUNCTION__))
;
14917 }
14918 // Note that this correctly re-maps both when we do a swap and when
14919 // we observe the other side of the swap above. We rely on that to
14920 // avoid swapping the members of the input list directly.
14921 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
14922 }
14923
14924 // Map the input's dword into the correct half.
14925 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] < 0)
14926 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
14927 else
14928 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==(static_cast <bool> (PSHUFDMask[(Input - SourceOffset +
DestOffset) / 2] == Input / 2 && "Previous placement doesn't match!"
) ? void (0) : __assert_fail ("PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == Input / 2 && \"Previous placement doesn't match!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14930, __extension__ __PRETTY_FUNCTION__))
14929 Input / 2 &&(static_cast <bool> (PSHUFDMask[(Input - SourceOffset +
DestOffset) / 2] == Input / 2 && "Previous placement doesn't match!"
) ? void (0) : __assert_fail ("PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == Input / 2 && \"Previous placement doesn't match!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14930, __extension__ __PRETTY_FUNCTION__))
14930 "Previous placement doesn't match!")(static_cast <bool> (PSHUFDMask[(Input - SourceOffset +
DestOffset) / 2] == Input / 2 && "Previous placement doesn't match!"
) ? void (0) : __assert_fail ("PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == Input / 2 && \"Previous placement doesn't match!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14930, __extension__ __PRETTY_FUNCTION__))
;
14931 }
14932
14933 // And just directly shift any other-half mask elements to be same-half
14934 // as we will have mirrored the dword containing the element into the
14935 // same position within that half.
14936 for (int &M : HalfMask)
14937 if (M >= SourceOffset && M < SourceOffset + 4) {
14938 M = M - SourceOffset + DestOffset;
14939 assert(M >= 0 && "This should never wrap below zero!")(static_cast <bool> (M >= 0 && "This should never wrap below zero!"
) ? void (0) : __assert_fail ("M >= 0 && \"This should never wrap below zero!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14939, __extension__ __PRETTY_FUNCTION__))
;
14940 }
14941 return;
14942 }
14943
14944 // Ensure we have the input in a viable dword of its current half. This
14945 // is particularly tricky because the original position may be clobbered
14946 // by inputs being moved and *staying* in that half.
14947 if (IncomingInputs.size() == 1) {
14948 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
14949 int InputFixed = find(SourceHalfMask, -1) - std::begin(SourceHalfMask) +
14950 SourceOffset;
14951 SourceHalfMask[InputFixed - SourceOffset] =
14952 IncomingInputs[0] - SourceOffset;
14953 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
14954 InputFixed);
14955 IncomingInputs[0] = InputFixed;
14956 }
14957 } else if (IncomingInputs.size() == 2) {
14958 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
14959 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
14960 // We have two non-adjacent or clobbered inputs we need to extract from
14961 // the source half. To do this, we need to map them into some adjacent
14962 // dword slot in the source mask.
14963 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
14964 IncomingInputs[1] - SourceOffset};
14965
14966 // If there is a free slot in the source half mask adjacent to one of
14967 // the inputs, place the other input in it. We use (Index XOR 1) to
14968 // compute an adjacent index.
14969 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
14970 SourceHalfMask[InputsFixed[0] ^ 1] < 0) {
14971 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
14972 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
14973 InputsFixed[1] = InputsFixed[0] ^ 1;
14974 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
14975 SourceHalfMask[InputsFixed[1] ^ 1] < 0) {
14976 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
14977 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
14978 InputsFixed[0] = InputsFixed[1] ^ 1;
14979 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] < 0 &&
14980 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] < 0) {
14981 // The two inputs are in the same DWord but it is clobbered and the
14982 // adjacent DWord isn't used at all. Move both inputs to the free
14983 // slot.
14984 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
14985 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
14986 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
14987 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
14988 } else {
14989 // The only way we hit this point is if there is no clobbering
14990 // (because there are no off-half inputs to this half) and there is no
14991 // free slot adjacent to one of the inputs. In this case, we have to
14992 // swap an input with a non-input.
14993 for (int i = 0; i < 4; ++i)
14994 assert((SourceHalfMask[i] < 0 || SourceHalfMask[i] == i) &&(static_cast <bool> ((SourceHalfMask[i] < 0 || SourceHalfMask
[i] == i) && "We can't handle any clobbers here!") ? void
(0) : __assert_fail ("(SourceHalfMask[i] < 0 || SourceHalfMask[i] == i) && \"We can't handle any clobbers here!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14995, __extension__ __PRETTY_FUNCTION__))
14995 "We can't handle any clobbers here!")(static_cast <bool> ((SourceHalfMask[i] < 0 || SourceHalfMask
[i] == i) && "We can't handle any clobbers here!") ? void
(0) : __assert_fail ("(SourceHalfMask[i] < 0 || SourceHalfMask[i] == i) && \"We can't handle any clobbers here!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14995, __extension__ __PRETTY_FUNCTION__))
;
14996 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&(static_cast <bool> (InputsFixed[1] != (InputsFixed[0] ^
1) && "Cannot have adjacent inputs here!") ? void (0
) : __assert_fail ("InputsFixed[1] != (InputsFixed[0] ^ 1) && \"Cannot have adjacent inputs here!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14997, __extension__ __PRETTY_FUNCTION__))
14997 "Cannot have adjacent inputs here!")(static_cast <bool> (InputsFixed[1] != (InputsFixed[0] ^
1) && "Cannot have adjacent inputs here!") ? void (0
) : __assert_fail ("InputsFixed[1] != (InputsFixed[0] ^ 1) && \"Cannot have adjacent inputs here!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 14997, __extension__ __PRETTY_FUNCTION__))
;
14998
14999 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
15000 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
15001
15002 // We also have to update the final source mask in this case because
15003 // it may need to undo the above swap.
15004 for (int &M : FinalSourceHalfMask)
15005 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
15006 M = InputsFixed[1] + SourceOffset;
15007 else if (M == InputsFixed[1] + SourceOffset)
15008 M = (InputsFixed[0] ^ 1) + SourceOffset;
15009
15010 InputsFixed[1] = InputsFixed[0] ^ 1;
15011 }
15012
15013 // Point everything at the fixed inputs.
15014 for (int &M : HalfMask)
15015 if (M == IncomingInputs[0])
15016 M = InputsFixed[0] + SourceOffset;
15017 else if (M == IncomingInputs[1])
15018 M = InputsFixed[1] + SourceOffset;
15019
15020 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
15021 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
15022 }
15023 } else {
15024 llvm_unreachable("Unhandled input size!")::llvm::llvm_unreachable_internal("Unhandled input size!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15024)
;
15025 }
15026
15027 // Now hoist the DWord down to the right half.
15028 int FreeDWord = (PSHUFDMask[DestOffset / 2] < 0 ? 0 : 1) + DestOffset / 2;
15029 assert(PSHUFDMask[FreeDWord] < 0 && "DWord not free")(static_cast <bool> (PSHUFDMask[FreeDWord] < 0 &&
"DWord not free") ? void (0) : __assert_fail ("PSHUFDMask[FreeDWord] < 0 && \"DWord not free\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15029, __extension__ __PRETTY_FUNCTION__))
;
15030 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
15031 for (int &M : HalfMask)
15032 for (int Input : IncomingInputs)
15033 if (M == Input)
15034 M = FreeDWord * 2 + Input % 2;
15035 };
15036 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
15037 /*SourceOffset*/ 4, /*DestOffset*/ 0);
15038 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
15039 /*SourceOffset*/ 0, /*DestOffset*/ 4);
15040
15041 // Now enact all the shuffles we've computed to move the inputs into their
15042 // target half.
15043 if (!isNoopShuffleMask(PSHUFLMask))
15044 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
15045 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
15046 if (!isNoopShuffleMask(PSHUFHMask))
15047 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
15048 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
15049 if (!isNoopShuffleMask(PSHUFDMask))
15050 V = DAG.getBitcast(
15051 VT,
15052 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
15053 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
15054
15055 // At this point, each half should contain all its inputs, and we can then
15056 // just shuffle them into their final position.
15057 assert(count_if(LoMask, [](int M) { return M >= 4; }) == 0 &&(static_cast <bool> (count_if(LoMask, [](int M) { return
M >= 4; }) == 0 && "Failed to lift all the high half inputs to the low mask!"
) ? void (0) : __assert_fail ("count_if(LoMask, [](int M) { return M >= 4; }) == 0 && \"Failed to lift all the high half inputs to the low mask!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15058, __extension__ __PRETTY_FUNCTION__))
15058 "Failed to lift all the high half inputs to the low mask!")(static_cast <bool> (count_if(LoMask, [](int M) { return
M >= 4; }) == 0 && "Failed to lift all the high half inputs to the low mask!"
) ? void (0) : __assert_fail ("count_if(LoMask, [](int M) { return M >= 4; }) == 0 && \"Failed to lift all the high half inputs to the low mask!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15058, __extension__ __PRETTY_FUNCTION__))
;
15059 assert(count_if(HiMask, [](int M) { return M >= 0 && M < 4; }) == 0 &&(static_cast <bool> (count_if(HiMask, [](int M) { return
M >= 0 && M < 4; }) == 0 && "Failed to lift all the low half inputs to the high mask!"
) ? void (0) : __assert_fail ("count_if(HiMask, [](int M) { return M >= 0 && M < 4; }) == 0 && \"Failed to lift all the low half inputs to the high mask!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15060, __extension__ __PRETTY_FUNCTION__))
15060 "Failed to lift all the low half inputs to the high mask!")(static_cast <bool> (count_if(HiMask, [](int M) { return
M >= 0 && M < 4; }) == 0 && "Failed to lift all the low half inputs to the high mask!"
) ? void (0) : __assert_fail ("count_if(HiMask, [](int M) { return M >= 0 && M < 4; }) == 0 && \"Failed to lift all the low half inputs to the high mask!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15060, __extension__ __PRETTY_FUNCTION__))
;
15061
15062 // Do a half shuffle for the low mask.
15063 if (!isNoopShuffleMask(LoMask))
15064 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
15065 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
15066
15067 // Do a half shuffle with the high mask after shifting its values down.
15068 for (int &M : HiMask)
15069 if (M >= 0)
15070 M -= 4;
15071 if (!isNoopShuffleMask(HiMask))
15072 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
15073 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
15074
15075 return V;
15076}
15077
15078/// Helper to form a PSHUFB-based shuffle+blend, opportunistically avoiding the
15079/// blend if only one input is used.
15080static SDValue lowerShuffleAsBlendOfPSHUFBs(
15081 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
15082 const APInt &Zeroable, SelectionDAG &DAG, bool &V1InUse, bool &V2InUse) {
15083 assert(!is128BitLaneCrossingShuffleMask(VT, Mask) &&(static_cast <bool> (!is128BitLaneCrossingShuffleMask(VT
, Mask) && "Lane crossing shuffle masks not supported"
) ? void (0) : __assert_fail ("!is128BitLaneCrossingShuffleMask(VT, Mask) && \"Lane crossing shuffle masks not supported\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15084, __extension__ __PRETTY_FUNCTION__))
15084 "Lane crossing shuffle masks not supported")(static_cast <bool> (!is128BitLaneCrossingShuffleMask(VT
, Mask) && "Lane crossing shuffle masks not supported"
) ? void (0) : __assert_fail ("!is128BitLaneCrossingShuffleMask(VT, Mask) && \"Lane crossing shuffle masks not supported\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15084, __extension__ __PRETTY_FUNCTION__))
;
15085
15086 int NumBytes = VT.getSizeInBits() / 8;
15087 int Size = Mask.size();
15088 int Scale = NumBytes / Size;
15089
15090 SmallVector<SDValue, 64> V1Mask(NumBytes, DAG.getUNDEF(MVT::i8));
15091 SmallVector<SDValue, 64> V2Mask(NumBytes, DAG.getUNDEF(MVT::i8));
15092 V1InUse = false;
15093 V2InUse = false;
15094
15095 for (int i = 0; i < NumBytes; ++i) {
15096 int M = Mask[i / Scale];
15097 if (M < 0)
15098 continue;
15099
15100 const int ZeroMask = 0x80;
15101 int V1Idx = M < Size ? M * Scale + i % Scale : ZeroMask;
15102 int V2Idx = M < Size ? ZeroMask : (M - Size) * Scale + i % Scale;
15103 if (Zeroable[i / Scale])
15104 V1Idx = V2Idx = ZeroMask;
15105
15106 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
15107 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
15108 V1InUse |= (ZeroMask != V1Idx);
15109 V2InUse |= (ZeroMask != V2Idx);
15110 }
15111
15112 MVT ShufVT = MVT::getVectorVT(MVT::i8, NumBytes);
15113 if (V1InUse)
15114 V1 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V1),
15115 DAG.getBuildVector(ShufVT, DL, V1Mask));
15116 if (V2InUse)
15117 V2 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V2),
15118 DAG.getBuildVector(ShufVT, DL, V2Mask));
15119
15120 // If we need shuffled inputs from both, blend the two.
15121 SDValue V;
15122 if (V1InUse && V2InUse)
15123 V = DAG.getNode(ISD::OR, DL, ShufVT, V1, V2);
15124 else
15125 V = V1InUse ? V1 : V2;
15126
15127 // Cast the result back to the correct type.
15128 return DAG.getBitcast(VT, V);
15129}
15130
15131/// Generic lowering of 8-lane i16 shuffles.
15132///
15133/// This handles both single-input shuffles and combined shuffle/blends with
15134/// two inputs. The single input shuffles are immediately delegated to
15135/// a dedicated lowering routine.
15136///
15137/// The blends are lowered in one of three fundamental ways. If there are few
15138/// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
15139/// of the input is significantly cheaper when lowered as an interleaving of
15140/// the two inputs, try to interleave them. Otherwise, blend the low and high
15141/// halves of the inputs separately (making them have relatively few inputs)
15142/// and then concatenate them.
15143static SDValue lowerV8I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15144 const APInt &Zeroable, SDValue V1, SDValue V2,
15145 const X86Subtarget &Subtarget,
15146 SelectionDAG &DAG) {
15147 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!")(static_cast <bool> (V1.getSimpleValueType() == MVT::v8i16
&& "Bad operand type!") ? void (0) : __assert_fail (
"V1.getSimpleValueType() == MVT::v8i16 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15147, __extension__ __PRETTY_FUNCTION__))
;
15148 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!")(static_cast <bool> (V2.getSimpleValueType() == MVT::v8i16
&& "Bad operand type!") ? void (0) : __assert_fail (
"V2.getSimpleValueType() == MVT::v8i16 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15148, __extension__ __PRETTY_FUNCTION__))
;
15149 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!")(static_cast <bool> (Mask.size() == 8 && "Unexpected mask size for v8 shuffle!"
) ? void (0) : __assert_fail ("Mask.size() == 8 && \"Unexpected mask size for v8 shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15149, __extension__ __PRETTY_FUNCTION__))
;
15150
15151 // Whenever we can lower this as a zext, that instruction is strictly faster
15152 // than any alternative.
15153 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i16, V1, V2, Mask,
15154 Zeroable, Subtarget, DAG))
15155 return ZExt;
15156
15157 // Try to use lower using a truncation.
15158 if (SDValue V = lowerShuffleWithVPMOV(DL, MVT::v8i16, V1, V2, Mask, Zeroable,
15159 Subtarget, DAG))
15160 return V;
15161
15162 int NumV2Inputs = count_if(Mask, [](int M) { return M >= 8; });
15163
15164 if (NumV2Inputs == 0) {
15165 // Try to use shift instructions.
15166 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask,
15167 Zeroable, Subtarget, DAG))
15168 return Shift;
15169
15170 // Check for being able to broadcast a single element.
15171 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i16, V1, V2,
15172 Mask, Subtarget, DAG))
15173 return Broadcast;
15174
15175 // Try to use bit rotation instructions.
15176 if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v8i16, V1, Mask,
15177 Subtarget, DAG))
15178 return Rotate;
15179
15180 // Use dedicated unpack instructions for masks that match their pattern.
15181 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
15182 return V;
15183
15184 // Use dedicated pack instructions for masks that match their pattern.
15185 if (SDValue V = lowerShuffleWithPACK(DL, MVT::v8i16, Mask, V1, V2, DAG,
15186 Subtarget))
15187 return V;
15188
15189 // Try to use byte rotation instructions.
15190 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V1, Mask,
15191 Subtarget, DAG))
15192 return Rotate;
15193
15194 // Make a copy of the mask so it can be modified.
15195 SmallVector<int, 8> MutableMask(Mask.begin(), Mask.end());
15196 return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v8i16, V1, MutableMask,
15197 Subtarget, DAG);
15198 }
15199
15200 assert(llvm::any_of(Mask, [](int M) { return M >= 0 && M < 8; }) &&(static_cast <bool> (llvm::any_of(Mask, [](int M) { return
M >= 0 && M < 8; }) && "All single-input shuffles should be canonicalized to be V1-input "
"shuffles.") ? void (0) : __assert_fail ("llvm::any_of(Mask, [](int M) { return M >= 0 && M < 8; }) && \"All single-input shuffles should be canonicalized to be V1-input \" \"shuffles.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15202, __extension__ __PRETTY_FUNCTION__))
15201 "All single-input shuffles should be canonicalized to be V1-input "(static_cast <bool> (llvm::any_of(Mask, [](int M) { return
M >= 0 && M < 8; }) && "All single-input shuffles should be canonicalized to be V1-input "
"shuffles.") ? void (0) : __assert_fail ("llvm::any_of(Mask, [](int M) { return M >= 0 && M < 8; }) && \"All single-input shuffles should be canonicalized to be V1-input \" \"shuffles.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15202, __extension__ __PRETTY_FUNCTION__))
15202 "shuffles.")(static_cast <bool> (llvm::any_of(Mask, [](int M) { return
M >= 0 && M < 8; }) && "All single-input shuffles should be canonicalized to be V1-input "
"shuffles.") ? void (0) : __assert_fail ("llvm::any_of(Mask, [](int M) { return M >= 0 && M < 8; }) && \"All single-input shuffles should be canonicalized to be V1-input \" \"shuffles.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15202, __extension__ __PRETTY_FUNCTION__))
;
15203
15204 // Try to use shift instructions.
15205 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask,
15206 Zeroable, Subtarget, DAG))
15207 return Shift;
15208
15209 // See if we can use SSE4A Extraction / Insertion.
15210 if (Subtarget.hasSSE4A())
15211 if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask,
15212 Zeroable, DAG))
15213 return V;
15214
15215 // There are special ways we can lower some single-element blends.
15216 if (NumV2Inputs == 1)
15217 if (SDValue V = lowerShuffleAsElementInsertion(
15218 DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
15219 return V;
15220
15221 // We have different paths for blend lowering, but they all must use the
15222 // *exact* same predicate.
15223 bool IsBlendSupported = Subtarget.hasSSE41();
15224 if (IsBlendSupported)
15225 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
15226 Zeroable, Subtarget, DAG))
15227 return Blend;
15228
15229 if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask,
15230 Zeroable, Subtarget, DAG))
15231 return Masked;
15232
15233 // Use dedicated unpack instructions for masks that match their pattern.
15234 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
15235 return V;
15236
15237 // Use dedicated pack instructions for masks that match their pattern.
15238 if (SDValue V = lowerShuffleWithPACK(DL, MVT::v8i16, Mask, V1, V2, DAG,
15239 Subtarget))
15240 return V;
15241
15242 // Try to use lower using a truncation.
15243 if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v8i16, V1, V2, Mask, Zeroable,
15244 Subtarget, DAG))
15245 return V;
15246
15247 // Try to use byte rotation instructions.
15248 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V2, Mask,
15249 Subtarget, DAG))
15250 return Rotate;
15251
15252 if (SDValue BitBlend =
15253 lowerShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
15254 return BitBlend;
15255
15256 // Try to use byte shift instructions to mask.
15257 if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v8i16, V1, V2, Mask,
15258 Zeroable, Subtarget, DAG))
15259 return V;
15260
15261 // Attempt to lower using compaction, SSE41 is necessary for PACKUSDW.
15262 // We could use SIGN_EXTEND_INREG+PACKSSDW for older targets but this seems to
15263 // be slower than a PSHUFLW+PSHUFHW+PSHUFD chain.
15264 int NumEvenDrops = canLowerByDroppingEvenElements(Mask, false);
15265 if ((NumEvenDrops == 1 || NumEvenDrops == 2) && Subtarget.hasSSE41() &&
15266 !Subtarget.hasVLX()) {
15267 SmallVector<SDValue, 8> DWordClearOps(4, DAG.getConstant(0, DL, MVT::i32));
15268 for (unsigned i = 0; i != 4; i += 1 << (NumEvenDrops - 1))
15269 DWordClearOps[i] = DAG.getConstant(0xFFFF, DL, MVT::i32);
15270 SDValue DWordClearMask = DAG.getBuildVector(MVT::v4i32, DL, DWordClearOps);
15271 V1 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V1),
15272 DWordClearMask);
15273 V2 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V2),
15274 DWordClearMask);
15275 // Now pack things back together.
15276 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v8i16, V1, V2);
15277 if (NumEvenDrops == 2) {
15278 Result = DAG.getBitcast(MVT::v4i32, Result);
15279 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v8i16, Result, Result);
15280 }
15281 return Result;
15282 }
15283
15284 // Try to lower by permuting the inputs into an unpack instruction.
15285 if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1, V2,
15286 Mask, Subtarget, DAG))
15287 return Unpack;
15288
15289 // If we can't directly blend but can use PSHUFB, that will be better as it
15290 // can both shuffle and set up the inefficient blend.
15291 if (!IsBlendSupported && Subtarget.hasSSSE3()) {
15292 bool V1InUse, V2InUse;
15293 return lowerShuffleAsBlendOfPSHUFBs(DL, MVT::v8i16, V1, V2, Mask,
15294 Zeroable, DAG, V1InUse, V2InUse);
15295 }
15296
15297 // We can always bit-blend if we have to so the fallback strategy is to
15298 // decompose into single-input permutes and blends/unpacks.
15299 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8i16, V1, V2,
15300 Mask, Subtarget, DAG);
15301}
15302
15303// Lowers unary/binary shuffle as VPERMV/VPERMV3, for non-VLX targets,
15304// sub-512-bit shuffles are padded to 512-bits for the shuffle and then
15305// the active subvector is extracted.
15306static SDValue lowerShuffleWithPERMV(const SDLoc &DL, MVT VT,
15307 ArrayRef<int> Mask, SDValue V1, SDValue V2,
15308 const X86Subtarget &Subtarget,
15309 SelectionDAG &DAG) {
15310 MVT MaskVT = VT.changeTypeToInteger();
15311 SDValue MaskNode;
15312 MVT ShuffleVT = VT;
15313 if (!VT.is512BitVector() && !Subtarget.hasVLX()) {
15314 V1 = widenSubVector(V1, false, Subtarget, DAG, DL, 512);
15315 V2 = widenSubVector(V2, false, Subtarget, DAG, DL, 512);
15316 ShuffleVT = V1.getSimpleValueType();
15317
15318 // Adjust mask to correct indices for the second input.
15319 int NumElts = VT.getVectorNumElements();
15320 unsigned Scale = 512 / VT.getSizeInBits();
15321 SmallVector<int, 32> AdjustedMask(Mask.begin(), Mask.end());
15322 for (int &M : AdjustedMask)
15323 if (NumElts <= M)
15324 M += (Scale - 1) * NumElts;
15325 MaskNode = getConstVector(AdjustedMask, MaskVT, DAG, DL, true);
15326 MaskNode = widenSubVector(MaskNode, false, Subtarget, DAG, DL, 512);
15327 } else {
15328 MaskNode = getConstVector(Mask, MaskVT, DAG, DL, true);
15329 }
15330
15331 SDValue Result;
15332 if (V2.isUndef())
15333 Result = DAG.getNode(X86ISD::VPERMV, DL, ShuffleVT, MaskNode, V1);
15334 else
15335 Result = DAG.getNode(X86ISD::VPERMV3, DL, ShuffleVT, V1, MaskNode, V2);
15336
15337 if (VT != ShuffleVT)
15338 Result = extractSubVector(Result, 0, DAG, DL, VT.getSizeInBits());
15339
15340 return Result;
15341}
15342
15343/// Generic lowering of v16i8 shuffles.
15344///
15345/// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
15346/// detect any complexity reducing interleaving. If that doesn't help, it uses
15347/// UNPCK to spread the i8 elements across two i16-element vectors, and uses
15348/// the existing lowering for v8i16 blends on each half, finally PACK-ing them
15349/// back together.
15350static SDValue lowerV16I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15351 const APInt &Zeroable, SDValue V1, SDValue V2,
15352 const X86Subtarget &Subtarget,
15353 SelectionDAG &DAG) {
15354 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!")(static_cast <bool> (V1.getSimpleValueType() == MVT::v16i8
&& "Bad operand type!") ? void (0) : __assert_fail (
"V1.getSimpleValueType() == MVT::v16i8 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15354, __extension__ __PRETTY_FUNCTION__))
;
15355 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!")(static_cast <bool> (V2.getSimpleValueType() == MVT::v16i8
&& "Bad operand type!") ? void (0) : __assert_fail (
"V2.getSimpleValueType() == MVT::v16i8 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15355, __extension__ __PRETTY_FUNCTION__))
;
15356 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!")(static_cast <bool> (Mask.size() == 16 && "Unexpected mask size for v16 shuffle!"
) ? void (0) : __assert_fail ("Mask.size() == 16 && \"Unexpected mask size for v16 shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15356, __extension__ __PRETTY_FUNCTION__))
;
15357
15358 // Try to use shift instructions.
15359 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask,
15360 Zeroable, Subtarget, DAG))
15361 return Shift;
15362
15363 // Try to use byte rotation instructions.
15364 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i8, V1, V2, Mask,
15365 Subtarget, DAG))
15366 return Rotate;
15367
15368 // Use dedicated pack instructions for masks that match their pattern.
15369 if (SDValue V = lowerShuffleWithPACK(DL, MVT::v16i8, Mask, V1, V2, DAG,
15370 Subtarget))
15371 return V;
15372
15373 // Try to use a zext lowering.
15374 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v16i8, V1, V2, Mask,
15375 Zeroable, Subtarget, DAG))
15376 return ZExt;
15377
15378 // Try to use lower using a truncation.
15379 if (SDValue V = lowerShuffleWithVPMOV(DL, MVT::v16i8, V1, V2, Mask, Zeroable,
15380 Subtarget, DAG))
15381 return V;
15382
15383 if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v16i8, V1, V2, Mask, Zeroable,
15384 Subtarget, DAG))
15385 return V;
15386
15387 // See if we can use SSE4A Extraction / Insertion.
15388 if (Subtarget.hasSSE4A())
15389 if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask,
15390 Zeroable, DAG))
15391 return V;
15392
15393 int NumV2Elements = count_if(Mask, [](int M) { return M >= 16; });
15394
15395 // For single-input shuffles, there are some nicer lowering tricks we can use.
15396 if (NumV2Elements == 0) {
15397 // Check for being able to broadcast a single element.
15398 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i8, V1, V2,
15399 Mask, Subtarget, DAG))
15400 return Broadcast;
15401
15402 // Try to use bit rotation instructions.
15403 if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v16i8, V1, Mask,
15404 Subtarget, DAG))
15405 return Rotate;
15406
15407 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
15408 return V;
15409
15410 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
15411 // Notably, this handles splat and partial-splat shuffles more efficiently.
15412 // However, it only makes sense if the pre-duplication shuffle simplifies
15413 // things significantly. Currently, this means we need to be able to
15414 // express the pre-duplication shuffle as an i16 shuffle.
15415 //
15416 // FIXME: We should check for other patterns which can be widened into an
15417 // i16 shuffle as well.
15418 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
15419 for (int i = 0; i < 16; i += 2)
15420 if (Mask[i] >= 0 && Mask[i + 1] >= 0 && Mask[i] != Mask[i + 1])
15421 return false;
15422
15423 return true;
15424 };
15425 auto tryToWidenViaDuplication = [&]() -> SDValue {
15426 if (!canWidenViaDuplication(Mask))
15427 return SDValue();
15428 SmallVector<int, 4> LoInputs;
15429 copy_if(Mask, std::back_inserter(LoInputs),
15430 [](int M) { return M >= 0 && M < 8; });
15431 array_pod_sort(LoInputs.begin(), LoInputs.end());
15432 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
15433 LoInputs.end());
15434 SmallVector<int, 4> HiInputs;
15435 copy_if(Mask, std::back_inserter(HiInputs), [](int M) { return M >= 8; });
15436 array_pod_sort(HiInputs.begin(), HiInputs.end());
15437 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
15438 HiInputs.end());
15439
15440 bool TargetLo = LoInputs.size() >= HiInputs.size();
15441 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
15442 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
15443
15444 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
15445 SmallDenseMap<int, int, 8> LaneMap;
15446 for (int I : InPlaceInputs) {
15447 PreDupI16Shuffle[I/2] = I/2;
15448 LaneMap[I] = I;
15449 }
15450 int j = TargetLo ? 0 : 4, je = j + 4;
15451 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
15452 // Check if j is already a shuffle of this input. This happens when
15453 // there are two adjacent bytes after we move the low one.
15454 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
15455 // If we haven't yet mapped the input, search for a slot into which
15456 // we can map it.
15457 while (j < je && PreDupI16Shuffle[j] >= 0)
15458 ++j;
15459
15460 if (j == je)
15461 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
15462 return SDValue();
15463
15464 // Map this input with the i16 shuffle.
15465 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
15466 }
15467
15468 // Update the lane map based on the mapping we ended up with.
15469 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
15470 }
15471 V1 = DAG.getBitcast(
15472 MVT::v16i8,
15473 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
15474 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
15475
15476 // Unpack the bytes to form the i16s that will be shuffled into place.
15477 bool EvenInUse = false, OddInUse = false;
15478 for (int i = 0; i < 16; i += 2) {
15479 EvenInUse |= (Mask[i + 0] >= 0);
15480 OddInUse |= (Mask[i + 1] >= 0);
15481 if (EvenInUse && OddInUse)
15482 break;
15483 }
15484 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
15485 MVT::v16i8, EvenInUse ? V1 : DAG.getUNDEF(MVT::v16i8),
15486 OddInUse ? V1 : DAG.getUNDEF(MVT::v16i8));
15487
15488 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
15489 for (int i = 0; i < 16; ++i)
15490 if (Mask[i] >= 0) {
15491 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
15492 assert(MappedMask < 8 && "Invalid v8 shuffle mask!")(static_cast <bool> (MappedMask < 8 && "Invalid v8 shuffle mask!"
) ? void (0) : __assert_fail ("MappedMask < 8 && \"Invalid v8 shuffle mask!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15492, __extension__ __PRETTY_FUNCTION__))
;
15493 if (PostDupI16Shuffle[i / 2] < 0)
15494 PostDupI16Shuffle[i / 2] = MappedMask;
15495 else
15496 assert(PostDupI16Shuffle[i / 2] == MappedMask &&(static_cast <bool> (PostDupI16Shuffle[i / 2] == MappedMask
&& "Conflicting entries in the original shuffle!") ?
void (0) : __assert_fail ("PostDupI16Shuffle[i / 2] == MappedMask && \"Conflicting entries in the original shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15497, __extension__ __PRETTY_FUNCTION__))
15497 "Conflicting entries in the original shuffle!")(static_cast <bool> (PostDupI16Shuffle[i / 2] == MappedMask
&& "Conflicting entries in the original shuffle!") ?
void (0) : __assert_fail ("PostDupI16Shuffle[i / 2] == MappedMask && \"Conflicting entries in the original shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15497, __extension__ __PRETTY_FUNCTION__))
;
15498 }
15499 return DAG.getBitcast(
15500 MVT::v16i8,
15501 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
15502 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
15503 };
15504 if (SDValue V = tryToWidenViaDuplication())
15505 return V;
15506 }
15507
15508 if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask,
15509 Zeroable, Subtarget, DAG))
15510 return Masked;
15511
15512 // Use dedicated unpack instructions for masks that match their pattern.
15513 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
15514 return V;
15515
15516 // Try to use byte shift instructions to mask.
15517 if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v16i8, V1, V2, Mask,
15518 Zeroable, Subtarget, DAG))
15519 return V;
15520
15521 // Check for compaction patterns.
15522 bool IsSingleInput = V2.isUndef();
15523 int NumEvenDrops = canLowerByDroppingEvenElements(Mask, IsSingleInput);
15524
15525 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
15526 // with PSHUFB. It is important to do this before we attempt to generate any
15527 // blends but after all of the single-input lowerings. If the single input
15528 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
15529 // want to preserve that and we can DAG combine any longer sequences into
15530 // a PSHUFB in the end. But once we start blending from multiple inputs,
15531 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
15532 // and there are *very* few patterns that would actually be faster than the
15533 // PSHUFB approach because of its ability to zero lanes.
15534 //
15535 // If the mask is a binary compaction, we can more efficiently perform this
15536 // as a PACKUS(AND(),AND()) - which is quicker than UNPACK(PSHUFB(),PSHUFB()).
15537 //
15538 // FIXME: The only exceptions to the above are blends which are exact
15539 // interleavings with direct instructions supporting them. We currently don't
15540 // handle those well here.
15541 if (Subtarget.hasSSSE3() && (IsSingleInput || NumEvenDrops != 1)) {
15542 bool V1InUse = false;
15543 bool V2InUse = false;
15544
15545 SDValue PSHUFB = lowerShuffleAsBlendOfPSHUFBs(
15546 DL, MVT::v16i8, V1, V2, Mask, Zeroable, DAG, V1InUse, V2InUse);
15547
15548 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
15549 // do so. This avoids using them to handle blends-with-zero which is
15550 // important as a single pshufb is significantly faster for that.
15551 if (V1InUse && V2InUse) {
15552 if (Subtarget.hasSSE41())
15553 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i8, V1, V2, Mask,
15554 Zeroable, Subtarget, DAG))
15555 return Blend;
15556
15557 // We can use an unpack to do the blending rather than an or in some
15558 // cases. Even though the or may be (very minorly) more efficient, we
15559 // preference this lowering because there are common cases where part of
15560 // the complexity of the shuffles goes away when we do the final blend as
15561 // an unpack.
15562 // FIXME: It might be worth trying to detect if the unpack-feeding
15563 // shuffles will both be pshufb, in which case we shouldn't bother with
15564 // this.
15565 if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(
15566 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
15567 return Unpack;
15568
15569 // AVX512VBMI can lower to VPERMB (non-VLX will pad to v64i8).
15570 if (Subtarget.hasVBMI())
15571 return lowerShuffleWithPERMV(DL, MVT::v16i8, Mask, V1, V2, Subtarget,
15572 DAG);
15573
15574 // If we have XOP we can use one VPPERM instead of multiple PSHUFBs.
15575 if (Subtarget.hasXOP()) {
15576 SDValue MaskNode = getConstVector(Mask, MVT::v16i8, DAG, DL, true);
15577 return DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, V1, V2, MaskNode);
15578 }
15579
15580 // Use PALIGNR+Permute if possible - permute might become PSHUFB but the
15581 // PALIGNR will be cheaper than the second PSHUFB+OR.
15582 if (SDValue V = lowerShuffleAsByteRotateAndPermute(
15583 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
15584 return V;
15585 }
15586
15587 return PSHUFB;
15588 }
15589
15590 // There are special ways we can lower some single-element blends.
15591 if (NumV2Elements == 1)
15592 if (SDValue V = lowerShuffleAsElementInsertion(
15593 DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
15594 return V;
15595
15596 if (SDValue Blend = lowerShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
15597 return Blend;
15598
15599 // Check whether a compaction lowering can be done. This handles shuffles
15600 // which take every Nth element for some even N. See the helper function for
15601 // details.
15602 //
15603 // We special case these as they can be particularly efficiently handled with
15604 // the PACKUSB instruction on x86 and they show up in common patterns of
15605 // rearranging bytes to truncate wide elements.
15606 if (NumEvenDrops) {
15607 // NumEvenDrops is the power of two stride of the elements. Another way of
15608 // thinking about it is that we need to drop the even elements this many
15609 // times to get the original input.
15610
15611 // First we need to zero all the dropped bytes.
15612 assert(NumEvenDrops <= 3 &&(static_cast <bool> (NumEvenDrops <= 3 && "No support for dropping even elements more than 3 times."
) ? void (0) : __assert_fail ("NumEvenDrops <= 3 && \"No support for dropping even elements more than 3 times.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15613, __extension__ __PRETTY_FUNCTION__))
15613 "No support for dropping even elements more than 3 times.")(static_cast <bool> (NumEvenDrops <= 3 && "No support for dropping even elements more than 3 times."
) ? void (0) : __assert_fail ("NumEvenDrops <= 3 && \"No support for dropping even elements more than 3 times.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15613, __extension__ __PRETTY_FUNCTION__))
;
15614 SmallVector<SDValue, 8> WordClearOps(8, DAG.getConstant(0, DL, MVT::i16));
15615 for (unsigned i = 0; i != 8; i += 1 << (NumEvenDrops - 1))
15616 WordClearOps[i] = DAG.getConstant(0xFF, DL, MVT::i16);
15617 SDValue WordClearMask = DAG.getBuildVector(MVT::v8i16, DL, WordClearOps);
15618 V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V1),
15619 WordClearMask);
15620 if (!IsSingleInput)
15621 V2 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V2),
15622 WordClearMask);
15623
15624 // Now pack things back together.
15625 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1,
15626 IsSingleInput ? V1 : V2);
15627 for (int i = 1; i < NumEvenDrops; ++i) {
15628 Result = DAG.getBitcast(MVT::v8i16, Result);
15629 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
15630 }
15631 return Result;
15632 }
15633
15634 // Handle multi-input cases by blending/unpacking single-input shuffles.
15635 if (NumV2Elements > 0)
15636 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v16i8, V1, V2, Mask,
15637 Subtarget, DAG);
15638
15639 // The fallback path for single-input shuffles widens this into two v8i16
15640 // vectors with unpacks, shuffles those, and then pulls them back together
15641 // with a pack.
15642 SDValue V = V1;
15643
15644 std::array<int, 8> LoBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
15645 std::array<int, 8> HiBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
15646 for (int i = 0; i < 16; ++i)
15647 if (Mask[i] >= 0)
15648 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
15649
15650 SDValue VLoHalf, VHiHalf;
15651 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
15652 // them out and avoid using UNPCK{L,H} to extract the elements of V as
15653 // i16s.
15654 if (none_of(LoBlendMask, [](int M) { return M >= 0 && M % 2 == 1; }) &&
15655 none_of(HiBlendMask, [](int M) { return M >= 0 && M % 2 == 1; })) {
15656 // Use a mask to drop the high bytes.
15657 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
15658 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
15659 DAG.getConstant(0x00FF, DL, MVT::v8i16));
15660
15661 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
15662 VHiHalf = DAG.getUNDEF(MVT::v8i16);
15663
15664 // Squash the masks to point directly into VLoHalf.
15665 for (int &M : LoBlendMask)
15666 if (M >= 0)
15667 M /= 2;
15668 for (int &M : HiBlendMask)
15669 if (M >= 0)
15670 M /= 2;
15671 } else {
15672 // Otherwise just unpack the low half of V into VLoHalf and the high half into
15673 // VHiHalf so that we can blend them as i16s.
15674 SDValue Zero = getZeroVector(MVT::v16i8, Subtarget, DAG, DL);
15675
15676 VLoHalf = DAG.getBitcast(
15677 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
15678 VHiHalf = DAG.getBitcast(
15679 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
15680 }
15681
15682 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
15683 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
15684
15685 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
15686}
15687
15688/// Dispatching routine to lower various 128-bit x86 vector shuffles.
15689///
15690/// This routine breaks down the specific type of 128-bit shuffle and
15691/// dispatches to the lowering routines accordingly.
15692static SDValue lower128BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
15693 MVT VT, SDValue V1, SDValue V2,
15694 const APInt &Zeroable,
15695 const X86Subtarget &Subtarget,
15696 SelectionDAG &DAG) {
15697 switch (VT.SimpleTy) {
15698 case MVT::v2i64:
15699 return lowerV2I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15700 case MVT::v2f64:
15701 return lowerV2F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15702 case MVT::v4i32:
15703 return lowerV4I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15704 case MVT::v4f32:
15705 return lowerV4F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15706 case MVT::v8i16:
15707 return lowerV8I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15708 case MVT::v16i8:
15709 return lowerV16I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15710
15711 default:
15712 llvm_unreachable("Unimplemented!")::llvm::llvm_unreachable_internal("Unimplemented!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15712)
;
15713 }
15714}
15715
15716/// Generic routine to split vector shuffle into half-sized shuffles.
15717///
15718/// This routine just extracts two subvectors, shuffles them independently, and
15719/// then concatenates them back together. This should work effectively with all
15720/// AVX vector shuffle types.
15721static SDValue splitAndLowerShuffle(const SDLoc &DL, MVT VT, SDValue V1,
15722 SDValue V2, ArrayRef<int> Mask,
15723 SelectionDAG &DAG) {
15724 assert(VT.getSizeInBits() >= 256 &&(static_cast <bool> (VT.getSizeInBits() >= 256 &&
"Only for 256-bit or wider vector shuffles!") ? void (0) : __assert_fail
("VT.getSizeInBits() >= 256 && \"Only for 256-bit or wider vector shuffles!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15725, __extension__ __PRETTY_FUNCTION__))
15725 "Only for 256-bit or wider vector shuffles!")(static_cast <bool> (VT.getSizeInBits() >= 256 &&
"Only for 256-bit or wider vector shuffles!") ? void (0) : __assert_fail
("VT.getSizeInBits() >= 256 && \"Only for 256-bit or wider vector shuffles!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15725, __extension__ __PRETTY_FUNCTION__))
;
15726 assert(V1.getSimpleValueType() == VT && "Bad operand type!")(static_cast <bool> (V1.getSimpleValueType() == VT &&
"Bad operand type!") ? void (0) : __assert_fail ("V1.getSimpleValueType() == VT && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15726, __extension__ __PRETTY_FUNCTION__))
;
15727 assert(V2.getSimpleValueType() == VT && "Bad operand type!")(static_cast <bool> (V2.getSimpleValueType() == VT &&
"Bad operand type!") ? void (0) : __assert_fail ("V2.getSimpleValueType() == VT && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15727, __extension__ __PRETTY_FUNCTION__))
;
15728
15729 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
15730 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
15731
15732 int NumElements = VT.getVectorNumElements();
15733 int SplitNumElements = NumElements / 2;
15734 MVT ScalarVT = VT.getVectorElementType();
15735 MVT SplitVT = MVT::getVectorVT(ScalarVT, SplitNumElements);
15736
15737 // Use splitVector/extractSubVector so that split build-vectors just build two
15738 // narrower build vectors. This helps shuffling with splats and zeros.
15739 auto SplitVector = [&](SDValue V) {
15740 SDValue LoV, HiV;
15741 std::tie(LoV, HiV) = splitVector(peekThroughBitcasts(V), DAG, DL);
15742 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
15743 DAG.getBitcast(SplitVT, HiV));
15744 };
15745
15746 SDValue LoV1, HiV1, LoV2, HiV2;
15747 std::tie(LoV1, HiV1) = SplitVector(V1);
15748 std::tie(LoV2, HiV2) = SplitVector(V2);
15749
15750 // Now create two 4-way blends of these half-width vectors.
15751 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
15752 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
15753 SmallVector<int, 32> V1BlendMask((unsigned)SplitNumElements, -1);
15754 SmallVector<int, 32> V2BlendMask((unsigned)SplitNumElements, -1);
15755 SmallVector<int, 32> BlendMask((unsigned)SplitNumElements, -1);
15756 for (int i = 0; i < SplitNumElements; ++i) {
15757 int M = HalfMask[i];
15758 if (M >= NumElements) {
15759 if (M >= NumElements + SplitNumElements)
15760 UseHiV2 = true;
15761 else
15762 UseLoV2 = true;
15763 V2BlendMask[i] = M - NumElements;
15764 BlendMask[i] = SplitNumElements + i;
15765 } else if (M >= 0) {
15766 if (M >= SplitNumElements)
15767 UseHiV1 = true;
15768 else
15769 UseLoV1 = true;
15770 V1BlendMask[i] = M;
15771 BlendMask[i] = i;
15772 }
15773 }
15774
15775 // Because the lowering happens after all combining takes place, we need to
15776 // manually combine these blend masks as much as possible so that we create
15777 // a minimal number of high-level vector shuffle nodes.
15778
15779 // First try just blending the halves of V1 or V2.
15780 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
15781 return DAG.getUNDEF(SplitVT);
15782 if (!UseLoV2 && !UseHiV2)
15783 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
15784 if (!UseLoV1 && !UseHiV1)
15785 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
15786
15787 SDValue V1Blend, V2Blend;
15788 if (UseLoV1 && UseHiV1) {
15789 V1Blend =
15790 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
15791 } else {
15792 // We only use half of V1 so map the usage down into the final blend mask.
15793 V1Blend = UseLoV1 ? LoV1 : HiV1;
15794 for (int i = 0; i < SplitNumElements; ++i)
15795 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
15796 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
15797 }
15798 if (UseLoV2 && UseHiV2) {
15799 V2Blend =
15800 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
15801 } else {
15802 // We only use half of V2 so map the usage down into the final blend mask.
15803 V2Blend = UseLoV2 ? LoV2 : HiV2;
15804 for (int i = 0; i < SplitNumElements; ++i)
15805 if (BlendMask[i] >= SplitNumElements)
15806 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
15807 }
15808 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
15809 };
15810 SDValue Lo = HalfBlend(LoMask);
15811 SDValue Hi = HalfBlend(HiMask);
15812 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
15813}
15814
15815/// Either split a vector in halves or decompose the shuffles and the
15816/// blend/unpack.
15817///
15818/// This is provided as a good fallback for many lowerings of non-single-input
15819/// shuffles with more than one 128-bit lane. In those cases, we want to select
15820/// between splitting the shuffle into 128-bit components and stitching those
15821/// back together vs. extracting the single-input shuffles and blending those
15822/// results.
15823static SDValue lowerShuffleAsSplitOrBlend(const SDLoc &DL, MVT VT, SDValue V1,
15824 SDValue V2, ArrayRef<int> Mask,
15825 const X86Subtarget &Subtarget,
15826 SelectionDAG &DAG) {
15827 assert(!V2.isUndef() && "This routine must not be used to lower single-input "(static_cast <bool> (!V2.isUndef() && "This routine must not be used to lower single-input "
"shuffles as it could then recurse on itself.") ? void (0) :
__assert_fail ("!V2.isUndef() && \"This routine must not be used to lower single-input \" \"shuffles as it could then recurse on itself.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15828, __extension__ __PRETTY_FUNCTION__))
15828 "shuffles as it could then recurse on itself.")(static_cast <bool> (!V2.isUndef() && "This routine must not be used to lower single-input "
"shuffles as it could then recurse on itself.") ? void (0) :
__assert_fail ("!V2.isUndef() && \"This routine must not be used to lower single-input \" \"shuffles as it could then recurse on itself.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15828, __extension__ __PRETTY_FUNCTION__))
;
15829 int Size = Mask.size();
15830
15831 // If this can be modeled as a broadcast of two elements followed by a blend,
15832 // prefer that lowering. This is especially important because broadcasts can
15833 // often fold with memory operands.
15834 auto DoBothBroadcast = [&] {
15835 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
15836 for (int M : Mask)
15837 if (M >= Size) {
15838 if (V2BroadcastIdx < 0)
15839 V2BroadcastIdx = M - Size;
15840 else if (M - Size != V2BroadcastIdx)
15841 return false;
15842 } else if (M >= 0) {
15843 if (V1BroadcastIdx < 0)
15844 V1BroadcastIdx = M;
15845 else if (M != V1BroadcastIdx)
15846 return false;
15847 }
15848 return true;
15849 };
15850 if (DoBothBroadcast())
15851 return lowerShuffleAsDecomposedShuffleMerge(DL, VT, V1, V2, Mask, Subtarget,
15852 DAG);
15853
15854 // If the inputs all stem from a single 128-bit lane of each input, then we
15855 // split them rather than blending because the split will decompose to
15856 // unusually few instructions.
15857 int LaneCount = VT.getSizeInBits() / 128;
15858 int LaneSize = Size / LaneCount;
15859 SmallBitVector LaneInputs[2];
15860 LaneInputs[0].resize(LaneCount, false);
15861 LaneInputs[1].resize(LaneCount, false);
15862 for (int i = 0; i < Size; ++i)
15863 if (Mask[i] >= 0)
15864 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
15865 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
15866 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
15867
15868 // Otherwise, just fall back to decomposed shuffles and a blend/unpack. This
15869 // requires that the decomposed single-input shuffles don't end up here.
15870 return lowerShuffleAsDecomposedShuffleMerge(DL, VT, V1, V2, Mask, Subtarget,
15871 DAG);
15872}
15873
15874// Lower as SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
15875// TODO: Extend to support v8f32 (+ 512-bit shuffles).
15876static SDValue lowerShuffleAsLanePermuteAndSHUFP(const SDLoc &DL, MVT VT,
15877 SDValue V1, SDValue V2,
15878 ArrayRef<int> Mask,
15879 SelectionDAG &DAG) {
15880 assert(VT == MVT::v4f64 && "Only for v4f64 shuffles")(static_cast <bool> (VT == MVT::v4f64 && "Only for v4f64 shuffles"
) ? void (0) : __assert_fail ("VT == MVT::v4f64 && \"Only for v4f64 shuffles\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 15880, __extension__ __PRETTY_FUNCTION__))
;
15881
15882 int LHSMask[4] = {-1, -1, -1, -1};
15883 int RHSMask[4] = {-1, -1, -1, -1};
15884 unsigned SHUFPMask = 0;
15885
15886 // As SHUFPD uses a single LHS/RHS element per lane, we can always
15887 // perform the shuffle once the lanes have been shuffled in place.
15888 for (int i = 0; i != 4; ++i) {
15889 int M = Mask[i];
15890 if (M < 0)
15891 continue;
15892 int LaneBase = i & ~1;
15893 auto &LaneMask = (i & 1) ? RHSMask : LHSMask;
15894 LaneMask[LaneBase + (M & 1)] = M;
15895 SHUFPMask |= (M & 1) << i;
15896 }
15897
15898 SDValue LHS = DAG.getVectorShuffle(VT, DL, V1, V2, LHSMask);
15899 SDValue RHS = DAG.getVectorShuffle(VT, DL, V1, V2, RHSMask);
15900 return DAG.getNode(X86ISD::SHUFP, DL, VT, LHS, RHS,
15901 DAG.getTargetConstant(SHUFPMask, DL, MVT::i8));
15902}
15903
15904/// Lower a vector shuffle crossing multiple 128-bit lanes as
15905/// a lane permutation followed by a per-lane permutation.
15906///
15907/// This is mainly for cases where we can have non-repeating permutes
15908/// in each lane.
15909///
15910/// TODO: This is very similar to lowerShuffleAsLanePermuteAndRepeatedMask,
15911/// we should investigate merging them.
15912static SDValue lowerShuffleAsLanePermuteAndPermute(
15913 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
15914 SelectionDAG &DAG, const X86Subtarget &Subtarget) {
15915 int NumElts = VT.getVectorNumElements();
15916 int NumLanes = VT.getSizeInBits() / 128;
15917 int NumEltsPerLane = NumElts / NumLanes;
15918 bool CanUseSublanes = Subtarget.hasAVX2() && V2.isUndef();
15919
15920 /// Attempts to find a sublane permute with the given size
15921 /// that gets all elements into their target lanes.
15922 ///
15923 /// If successful, fills CrossLaneMask and InLaneMask and returns true.
15924 /// If unsuccessful, returns false and may overwrite InLaneMask.
15925 auto getSublanePermute = [&](int NumSublanes) -> SDValue {
15926 int NumSublanesPerLane = NumSublanes / NumLanes;
15927 int NumEltsPerSublane = NumElts / NumSublanes;
15928
15929 SmallVector<int, 16> CrossLaneMask;
15930 SmallVector<int, 16> InLaneMask(NumElts, SM_SentinelUndef);
15931 // CrossLaneMask but one entry == one sublane.
15932 SmallVector<int, 16> CrossLaneMaskLarge(NumSublanes, SM_SentinelUndef);
15933
15934 for (int i = 0; i != NumElts; ++i) {
15935 int M = Mask[i];
15936 if (M < 0)
15937 continue;
15938
15939 int SrcSublane = M / NumEltsPerSublane;
15940 int DstLane = i / NumEltsPerLane;
15941
15942 // We only need to get the elements into the right lane, not sublane.
15943 // So search all sublanes that make up the destination lane.
15944 bool Found = false;
15945 int DstSubStart = DstLane * NumSublanesPerLane;
15946 int DstSubEnd = DstSubStart + NumSublanesPerLane;
15947 for (int DstSublane = DstSubStart; DstSublane < DstSubEnd; ++DstSublane) {
15948 if (!isUndefOrEqual(CrossLaneMaskLarge[DstSublane], SrcSublane))
15949 continue;
15950
15951 Found = true;
15952 CrossLaneMaskLarge[DstSublane] = SrcSublane;
15953 int DstSublaneOffset = DstSublane * NumEltsPerSublane;
15954 InLaneMask[i] = DstSublaneOffset + M % NumEltsPerSublane;
15955 break;
15956 }
15957 if (!Found)
15958 return SDValue();
15959 }
15960
15961 // Fill CrossLaneMask using CrossLaneMaskLarge.
15962 narrowShuffleMaskElts(NumEltsPerSublane, CrossLaneMaskLarge, CrossLaneMask);
15963
15964 if (!CanUseSublanes) {
15965 // If we're only shuffling a single lowest lane and the rest are identity
15966 // then don't bother.
15967 // TODO - isShuffleMaskInputInPlace could be extended to something like
15968 // this.
15969 int NumIdentityLanes = 0;
15970 bool OnlyShuffleLowestLane = true;
15971 for (int i = 0; i != NumLanes; ++i) {
15972 int LaneOffset = i * NumEltsPerLane;
15973 if (isSequentialOrUndefInRange(InLaneMask, LaneOffset, NumEltsPerLane,
15974 i * NumEltsPerLane))
15975 NumIdentityLanes++;
15976 else if (CrossLaneMask[LaneOffset] != 0)
15977 OnlyShuffleLowestLane = false;
15978 }
15979 if (OnlyShuffleLowestLane && NumIdentityLanes == (NumLanes - 1))
15980 return SDValue();
15981 }
15982
15983 SDValue CrossLane = DAG.getVectorShuffle(VT, DL, V1, V2, CrossLaneMask);
15984 return DAG.getVectorShuffle(VT, DL, CrossLane, DAG.getUNDEF(VT),
15985 InLaneMask);
15986 };
15987
15988 // First attempt a solution with full lanes.
15989 if (SDValue V = getSublanePermute(/*NumSublanes=*/NumLanes))
15990 return V;
15991
15992 // The rest of the solutions use sublanes.
15993 if (!CanUseSublanes)
15994 return SDValue();
15995
15996 // Then attempt a solution with 64-bit sublanes (vpermq).
15997 if (SDValue V = getSublanePermute(/*NumSublanes=*/NumLanes * 2))
15998 return V;
15999
16000 // If that doesn't work and we have fast variable cross-lane shuffle,
16001 // attempt 32-bit sublanes (vpermd).
16002 if (!Subtarget.hasFastVariableCrossLaneShuffle())
16003 return SDValue();
16004
16005 return getSublanePermute(/*NumSublanes=*/NumLanes * 4);
16006}
16007
16008/// Lower a vector shuffle crossing multiple 128-bit lanes by shuffling one
16009/// source with a lane permutation.
16010///
16011/// This lowering strategy results in four instructions in the worst case for a
16012/// single-input cross lane shuffle which is lower than any other fully general
16013/// cross-lane shuffle strategy I'm aware of. Special cases for each particular
16014/// shuffle pattern should be handled prior to trying this lowering.
16015static SDValue lowerShuffleAsLanePermuteAndShuffle(
16016 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
16017 SelectionDAG &DAG, const X86Subtarget &Subtarget) {
16018 // FIXME: This should probably be generalized for 512-bit vectors as well.
16019 assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!")(static_cast <bool> (VT.is256BitVector() && "Only for 256-bit vector shuffles!"
) ? void (0) : __assert_fail ("VT.is256BitVector() && \"Only for 256-bit vector shuffles!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16019, __extension__ __PRETTY_FUNCTION__))
;
16020 int Size = Mask.size();
16021 int LaneSize = Size / 2;
16022
16023 // Fold to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
16024 // Only do this if the elements aren't all from the lower lane,
16025 // otherwise we're (probably) better off doing a split.
16026 if (VT == MVT::v4f64 &&
16027 !all_of(Mask, [LaneSize](int M) { return M < LaneSize; }))
16028 if (SDValue V =
16029 lowerShuffleAsLanePermuteAndSHUFP(DL, VT, V1, V2, Mask, DAG))
16030 return V;
16031
16032 // If there are only inputs from one 128-bit lane, splitting will in fact be
16033 // less expensive. The flags track whether the given lane contains an element
16034 // that crosses to another lane.
16035 if (!Subtarget.hasAVX2()) {
16036 bool LaneCrossing[2] = {false, false};
16037 for (int i = 0; i < Size; ++i)
16038 if (Mask[i] >= 0 && ((Mask[i] % Size) / LaneSize) != (i / LaneSize))
16039 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
16040 if (!LaneCrossing[0] || !LaneCrossing[1])
16041 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
16042 } else {
16043 bool LaneUsed[2] = {false, false};
16044 for (int i = 0; i < Size; ++i)
16045 if (Mask[i] >= 0)
16046 LaneUsed[(Mask[i] % Size) / LaneSize] = true;
16047 if (!LaneUsed[0] || !LaneUsed[1])
16048 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
16049 }
16050
16051 // TODO - we could support shuffling V2 in the Flipped input.
16052 assert(V2.isUndef() &&(static_cast <bool> (V2.isUndef() && "This last part of this routine only works on single input shuffles"
) ? void (0) : __assert_fail ("V2.isUndef() && \"This last part of this routine only works on single input shuffles\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16053, __extension__ __PRETTY_FUNCTION__))
16053 "This last part of this routine only works on single input shuffles")(static_cast <bool> (V2.isUndef() && "This last part of this routine only works on single input shuffles"
) ? void (0) : __assert_fail ("V2.isUndef() && \"This last part of this routine only works on single input shuffles\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16053, __extension__ __PRETTY_FUNCTION__))
;
16054
16055 SmallVector<int, 32> InLaneMask(Mask.begin(), Mask.end());
16056 for (int i = 0; i < Size; ++i) {
16057 int &M = InLaneMask[i];
16058 if (M < 0)
16059 continue;
16060 if (((M % Size) / LaneSize) != (i / LaneSize))
16061 M = (M % LaneSize) + ((i / LaneSize) * LaneSize) + Size;
16062 }
16063 assert(!is128BitLaneCrossingShuffleMask(VT, InLaneMask) &&(static_cast <bool> (!is128BitLaneCrossingShuffleMask(VT
, InLaneMask) && "In-lane shuffle mask expected") ? void
(0) : __assert_fail ("!is128BitLaneCrossingShuffleMask(VT, InLaneMask) && \"In-lane shuffle mask expected\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16064, __extension__ __PRETTY_FUNCTION__))
16064 "In-lane shuffle mask expected")(static_cast <bool> (!is128BitLaneCrossingShuffleMask(VT
, InLaneMask) && "In-lane shuffle mask expected") ? void
(0) : __assert_fail ("!is128BitLaneCrossingShuffleMask(VT, InLaneMask) && \"In-lane shuffle mask expected\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16064, __extension__ __PRETTY_FUNCTION__))
;
16065
16066 // Flip the lanes, and shuffle the results which should now be in-lane.
16067 MVT PVT = VT.isFloatingPoint() ? MVT::v4f64 : MVT::v4i64;
16068 SDValue Flipped = DAG.getBitcast(PVT, V1);
16069 Flipped =
16070 DAG.getVectorShuffle(PVT, DL, Flipped, DAG.getUNDEF(PVT), {2, 3, 0, 1});
16071 Flipped = DAG.getBitcast(VT, Flipped);
16072 return DAG.getVectorShuffle(VT, DL, V1, Flipped, InLaneMask);
16073}
16074
16075/// Handle lowering 2-lane 128-bit shuffles.
16076static SDValue lowerV2X128Shuffle(const SDLoc &DL, MVT VT, SDValue V1,
16077 SDValue V2, ArrayRef<int> Mask,
16078 const APInt &Zeroable,
16079 const X86Subtarget &Subtarget,
16080 SelectionDAG &DAG) {
16081 if (V2.isUndef()) {
16082 // Attempt to match VBROADCAST*128 subvector broadcast load.
16083 bool SplatLo = isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1);
16084 bool SplatHi = isShuffleEquivalent(Mask, {2, 3, 2, 3}, V1);
16085 if ((SplatLo || SplatHi) && !Subtarget.hasAVX512() && V1.hasOneUse() &&
16086 MayFoldLoad(peekThroughOneUseBitcasts(V1))) {
16087 MVT MemVT = VT.getHalfNumVectorElementsVT();
16088 unsigned Ofs = SplatLo ? 0 : MemVT.getStoreSize();
16089 auto *Ld = cast<LoadSDNode>(peekThroughOneUseBitcasts(V1));
16090 if (SDValue BcstLd = getBROADCAST_LOAD(X86ISD::SUBV_BROADCAST_LOAD, DL,
16091 VT, MemVT, Ld, Ofs, DAG))
16092 return BcstLd;
16093 }
16094
16095 // With AVX2, use VPERMQ/VPERMPD for unary shuffles to allow memory folding.
16096 if (Subtarget.hasAVX2())
16097 return SDValue();
16098 }
16099
16100 bool V2IsZero = !V2.isUndef() && ISD::isBuildVectorAllZeros(V2.getNode());
16101
16102 SmallVector<int, 4> WidenedMask;
16103 if (!canWidenShuffleElements(Mask, Zeroable, V2IsZero, WidenedMask))
16104 return SDValue();
16105
16106 bool IsLowZero = (Zeroable & 0x3) == 0x3;
16107 bool IsHighZero = (Zeroable & 0xc) == 0xc;
16108
16109 // Try to use an insert into a zero vector.
16110 if (WidenedMask[0] == 0 && IsHighZero) {
16111 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
16112 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
16113 DAG.getIntPtrConstant(0, DL));
16114 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
16115 getZeroVector(VT, Subtarget, DAG, DL), LoV,
16116 DAG.getIntPtrConstant(0, DL));
16117 }
16118
16119 // TODO: If minimizing size and one of the inputs is a zero vector and the
16120 // the zero vector has only one use, we could use a VPERM2X128 to save the
16121 // instruction bytes needed to explicitly generate the zero vector.
16122
16123 // Blends are faster and handle all the non-lane-crossing cases.
16124 if (SDValue Blend = lowerShuffleAsBlend(DL, VT, V1, V2, Mask, Zeroable,
16125 Subtarget, DAG))
16126 return Blend;
16127
16128 // If either input operand is a zero vector, use VPERM2X128 because its mask
16129 // allows us to replace the zero input with an implicit zero.
16130 if (!IsLowZero && !IsHighZero) {
16131 // Check for patterns which can be matched with a single insert of a 128-bit
16132 // subvector.
16133 bool OnlyUsesV1 = isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1, V2);
16134 if (OnlyUsesV1 || isShuffleEquivalent(Mask, {0, 1, 4, 5}, V1, V2)) {
16135
16136 // With AVX1, use vperm2f128 (below) to allow load folding. Otherwise,
16137 // this will likely become vinsertf128 which can't fold a 256-bit memop.
16138 if (!isa<LoadSDNode>(peekThroughBitcasts(V1))) {
16139 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
16140 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
16141 OnlyUsesV1 ? V1 : V2,
16142 DAG.getIntPtrConstant(0, DL));
16143 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
16144 DAG.getIntPtrConstant(2, DL));
16145 }
16146 }
16147
16148 // Try to use SHUF128 if possible.
16149 if (Subtarget.hasVLX()) {
16150 if (WidenedMask[0] < 2 && WidenedMask[1] >= 2) {
16151 unsigned PermMask = ((WidenedMask[0] % 2) << 0) |
16152 ((WidenedMask[1] % 2) << 1);
16153 return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
16154 DAG.getTargetConstant(PermMask, DL, MVT::i8));
16155 }
16156 }
16157 }
16158
16159 // Otherwise form a 128-bit permutation. After accounting for undefs,
16160 // convert the 64-bit shuffle mask selection values into 128-bit
16161 // selection bits by dividing the indexes by 2 and shifting into positions
16162 // defined by a vperm2*128 instruction's immediate control byte.
16163
16164 // The immediate permute control byte looks like this:
16165 // [1:0] - select 128 bits from sources for low half of destination
16166 // [2] - ignore
16167 // [3] - zero low half of destination
16168 // [5:4] - select 128 bits from sources for high half of destination
16169 // [6] - ignore
16170 // [7] - zero high half of destination
16171
16172 assert((WidenedMask[0] >= 0 || IsLowZero) &&(static_cast <bool> ((WidenedMask[0] >= 0 || IsLowZero
) && (WidenedMask[1] >= 0 || IsHighZero) &&
"Undef half?") ? void (0) : __assert_fail ("(WidenedMask[0] >= 0 || IsLowZero) && (WidenedMask[1] >= 0 || IsHighZero) && \"Undef half?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16173, __extension__ __PRETTY_FUNCTION__))
16173 (WidenedMask[1] >= 0 || IsHighZero) && "Undef half?")(static_cast <bool> ((WidenedMask[0] >= 0 || IsLowZero
) && (WidenedMask[1] >= 0 || IsHighZero) &&
"Undef half?") ? void (0) : __assert_fail ("(WidenedMask[0] >= 0 || IsLowZero) && (WidenedMask[1] >= 0 || IsHighZero) && \"Undef half?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16173, __extension__ __PRETTY_FUNCTION__))
;
16174
16175 unsigned PermMask = 0;
16176 PermMask |= IsLowZero ? 0x08 : (WidenedMask[0] << 0);
16177 PermMask |= IsHighZero ? 0x80 : (WidenedMask[1] << 4);
16178
16179 // Check the immediate mask and replace unused sources with undef.
16180 if ((PermMask & 0x0a) != 0x00 && (PermMask & 0xa0) != 0x00)
16181 V1 = DAG.getUNDEF(VT);
16182 if ((PermMask & 0x0a) != 0x02 && (PermMask & 0xa0) != 0x20)
16183 V2 = DAG.getUNDEF(VT);
16184
16185 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
16186 DAG.getTargetConstant(PermMask, DL, MVT::i8));
16187}
16188
16189/// Lower a vector shuffle by first fixing the 128-bit lanes and then
16190/// shuffling each lane.
16191///
16192/// This attempts to create a repeated lane shuffle where each lane uses one
16193/// or two of the lanes of the inputs. The lanes of the input vectors are
16194/// shuffled in one or two independent shuffles to get the lanes into the
16195/// position needed by the final shuffle.
16196static SDValue lowerShuffleAsLanePermuteAndRepeatedMask(
16197 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
16198 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
16199 assert(!V2.isUndef() && "This is only useful with multiple inputs.")(static_cast <bool> (!V2.isUndef() && "This is only useful with multiple inputs."
) ? void (0) : __assert_fail ("!V2.isUndef() && \"This is only useful with multiple inputs.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16199, __extension__ __PRETTY_FUNCTION__))
;
16200
16201 if (is128BitLaneRepeatedShuffleMask(VT, Mask))
16202 return SDValue();
16203
16204 int NumElts = Mask.size();
16205 int NumLanes = VT.getSizeInBits() / 128;
16206 int NumLaneElts = 128 / VT.getScalarSizeInBits();
16207 SmallVector<int, 16> RepeatMask(NumLaneElts, -1);
16208 SmallVector<std::array<int, 2>, 2> LaneSrcs(NumLanes, {{-1, -1}});
16209
16210 // First pass will try to fill in the RepeatMask from lanes that need two
16211 // sources.
16212 for (int Lane = 0; Lane != NumLanes; ++Lane) {
16213 int Srcs[2] = {-1, -1};
16214 SmallVector<int, 16> InLaneMask(NumLaneElts, -1);
16215 for (int i = 0; i != NumLaneElts; ++i) {
16216 int M = Mask[(Lane * NumLaneElts) + i];
16217 if (M < 0)
16218 continue;
16219 // Determine which of the possible input lanes (NumLanes from each source)
16220 // this element comes from. Assign that as one of the sources for this
16221 // lane. We can assign up to 2 sources for this lane. If we run out
16222 // sources we can't do anything.
16223 int LaneSrc = M / NumLaneElts;
16224 int Src;
16225 if (Srcs[0] < 0 || Srcs[0] == LaneSrc)
16226 Src = 0;
16227 else if (Srcs[1] < 0 || Srcs[1] == LaneSrc)
16228 Src = 1;
16229 else
16230 return SDValue();
16231
16232 Srcs[Src] = LaneSrc;
16233 InLaneMask[i] = (M % NumLaneElts) + Src * NumElts;
16234 }
16235
16236 // If this lane has two sources, see if it fits with the repeat mask so far.
16237 if (Srcs[1] < 0)
16238 continue;
16239
16240 LaneSrcs[Lane][0] = Srcs[0];
16241 LaneSrcs[Lane][1] = Srcs[1];
16242
16243 auto MatchMasks = [](ArrayRef<int> M1, ArrayRef<int> M2) {
16244 assert(M1.size() == M2.size() && "Unexpected mask size")(static_cast <bool> (M1.size() == M2.size() && "Unexpected mask size"
) ? void (0) : __assert_fail ("M1.size() == M2.size() && \"Unexpected mask size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16244, __extension__ __PRETTY_FUNCTION__))
;
16245 for (int i = 0, e = M1.size(); i != e; ++i)
16246 if (M1[i] >= 0 && M2[i] >= 0 && M1[i] != M2[i])
16247 return false;
16248 return true;
16249 };
16250
16251 auto MergeMasks = [](ArrayRef<int> Mask, MutableArrayRef<int> MergedMask) {
16252 assert(Mask.size() == MergedMask.size() && "Unexpected mask size")(static_cast <bool> (Mask.size() == MergedMask.size() &&
"Unexpected mask size") ? void (0) : __assert_fail ("Mask.size() == MergedMask.size() && \"Unexpected mask size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16252, __extension__ __PRETTY_FUNCTION__))
;
16253 for (int i = 0, e = MergedMask.size(); i != e; ++i) {
16254 int M = Mask[i];
16255 if (M < 0)
16256 continue;
16257 assert((MergedMask[i] < 0 || MergedMask[i] == M) &&(static_cast <bool> ((MergedMask[i] < 0 || MergedMask
[i] == M) && "Unexpected mask element") ? void (0) : __assert_fail
("(MergedMask[i] < 0 || MergedMask[i] == M) && \"Unexpected mask element\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16258, __extension__ __PRETTY_FUNCTION__))
16258 "Unexpected mask element")(static_cast <bool> ((MergedMask[i] < 0 || MergedMask
[i] == M) && "Unexpected mask element") ? void (0) : __assert_fail
("(MergedMask[i] < 0 || MergedMask[i] == M) && \"Unexpected mask element\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16258, __extension__ __PRETTY_FUNCTION__))
;
16259 MergedMask[i] = M;
16260 }
16261 };
16262
16263 if (MatchMasks(InLaneMask, RepeatMask)) {
16264 // Merge this lane mask into the final repeat mask.
16265 MergeMasks(InLaneMask, RepeatMask);
16266 continue;
16267 }
16268
16269 // Didn't find a match. Swap the operands and try again.
16270 std::swap(LaneSrcs[Lane][0], LaneSrcs[Lane][1]);
16271 ShuffleVectorSDNode::commuteMask(InLaneMask);
16272
16273 if (MatchMasks(InLaneMask, RepeatMask)) {
16274 // Merge this lane mask into the final repeat mask.
16275 MergeMasks(InLaneMask, RepeatMask);
16276 continue;
16277 }
16278
16279 // Couldn't find a match with the operands in either order.
16280 return SDValue();
16281 }
16282
16283 // Now handle any lanes with only one source.
16284 for (int Lane = 0; Lane != NumLanes; ++Lane) {
16285 // If this lane has already been processed, skip it.
16286 if (LaneSrcs[Lane][0] >= 0)
16287 continue;
16288
16289 for (int i = 0; i != NumLaneElts; ++i) {
16290 int M = Mask[(Lane * NumLaneElts) + i];
16291 if (M < 0)
16292 continue;
16293
16294 // If RepeatMask isn't defined yet we can define it ourself.
16295 if (RepeatMask[i] < 0)
16296 RepeatMask[i] = M % NumLaneElts;
16297
16298 if (RepeatMask[i] < NumElts) {
16299 if (RepeatMask[i] != M % NumLaneElts)
16300 return SDValue();
16301 LaneSrcs[Lane][0] = M / NumLaneElts;
16302 } else {
16303 if (RepeatMask[i] != ((M % NumLaneElts) + NumElts))
16304 return SDValue();
16305 LaneSrcs[Lane][1] = M / NumLaneElts;
16306 }
16307 }
16308
16309 if (LaneSrcs[Lane][0] < 0 && LaneSrcs[Lane][1] < 0)
16310 return SDValue();
16311 }
16312
16313 SmallVector<int, 16> NewMask(NumElts, -1);
16314 for (int Lane = 0; Lane != NumLanes; ++Lane) {
16315 int Src = LaneSrcs[Lane][0];
16316 for (int i = 0; i != NumLaneElts; ++i) {
16317 int M = -1;
16318 if (Src >= 0)
16319 M = Src * NumLaneElts + i;
16320 NewMask[Lane * NumLaneElts + i] = M;
16321 }
16322 }
16323 SDValue NewV1 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
16324 // Ensure we didn't get back the shuffle we started with.
16325 // FIXME: This is a hack to make up for some splat handling code in
16326 // getVectorShuffle.
16327 if (isa<ShuffleVectorSDNode>(NewV1) &&
16328 cast<ShuffleVectorSDNode>(NewV1)->getMask() == Mask)
16329 return SDValue();
16330
16331 for (int Lane = 0; Lane != NumLanes; ++Lane) {
16332 int Src = LaneSrcs[Lane][1];
16333 for (int i = 0; i != NumLaneElts; ++i) {
16334 int M = -1;
16335 if (Src >= 0)
16336 M = Src * NumLaneElts + i;
16337 NewMask[Lane * NumLaneElts + i] = M;
16338 }
16339 }
16340 SDValue NewV2 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
16341 // Ensure we didn't get back the shuffle we started with.
16342 // FIXME: This is a hack to make up for some splat handling code in
16343 // getVectorShuffle.
16344 if (isa<ShuffleVectorSDNode>(NewV2) &&
16345 cast<ShuffleVectorSDNode>(NewV2)->getMask() == Mask)
16346 return SDValue();
16347
16348 for (int i = 0; i != NumElts; ++i) {
16349 NewMask[i] = RepeatMask[i % NumLaneElts];
16350 if (NewMask[i] < 0)
16351 continue;
16352
16353 NewMask[i] += (i / NumLaneElts) * NumLaneElts;
16354 }
16355 return DAG.getVectorShuffle(VT, DL, NewV1, NewV2, NewMask);
16356}
16357
16358/// If the input shuffle mask results in a vector that is undefined in all upper
16359/// or lower half elements and that mask accesses only 2 halves of the
16360/// shuffle's operands, return true. A mask of half the width with mask indexes
16361/// adjusted to access the extracted halves of the original shuffle operands is
16362/// returned in HalfMask. HalfIdx1 and HalfIdx2 return whether the upper or
16363/// lower half of each input operand is accessed.
16364static bool
16365getHalfShuffleMask(ArrayRef<int> Mask, MutableArrayRef<int> HalfMask,
16366 int &HalfIdx1, int &HalfIdx2) {
16367 assert((Mask.size() == HalfMask.size() * 2) &&(static_cast <bool> ((Mask.size() == HalfMask.size() * 2
) && "Expected input mask to be twice as long as output"
) ? void (0) : __assert_fail ("(Mask.size() == HalfMask.size() * 2) && \"Expected input mask to be twice as long as output\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16368, __extension__ __PRETTY_FUNCTION__))
16368 "Expected input mask to be twice as long as output")(static_cast <bool> ((Mask.size() == HalfMask.size() * 2
) && "Expected input mask to be twice as long as output"
) ? void (0) : __assert_fail ("(Mask.size() == HalfMask.size() * 2) && \"Expected input mask to be twice as long as output\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16368, __extension__ __PRETTY_FUNCTION__))
;
16369
16370 // Exactly one half of the result must be undef to allow narrowing.
16371 bool UndefLower = isUndefLowerHalf(Mask);
16372 bool UndefUpper = isUndefUpperHalf(Mask);
16373 if (UndefLower == UndefUpper)
16374 return false;
16375
16376 unsigned HalfNumElts = HalfMask.size();
16377 unsigned MaskIndexOffset = UndefLower ? HalfNumElts : 0;
16378 HalfIdx1 = -1;
16379 HalfIdx2 = -1;
16380 for (unsigned i = 0; i != HalfNumElts; ++i) {
16381 int M = Mask[i + MaskIndexOffset];
16382 if (M < 0) {
16383 HalfMask[i] = M;
16384 continue;
16385 }
16386
16387 // Determine which of the 4 half vectors this element is from.
16388 // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
16389 int HalfIdx = M / HalfNumElts;
16390
16391 // Determine the element index into its half vector source.
16392 int HalfElt = M % HalfNumElts;
16393
16394 // We can shuffle with up to 2 half vectors, set the new 'half'
16395 // shuffle mask accordingly.
16396 if (HalfIdx1 < 0 || HalfIdx1 == HalfIdx) {
16397 HalfMask[i] = HalfElt;
16398 HalfIdx1 = HalfIdx;
16399 continue;
16400 }
16401 if (HalfIdx2 < 0 || HalfIdx2 == HalfIdx) {
16402 HalfMask[i] = HalfElt + HalfNumElts;
16403 HalfIdx2 = HalfIdx;
16404 continue;
16405 }
16406
16407 // Too many half vectors referenced.
16408 return false;
16409 }
16410
16411 return true;
16412}
16413
16414/// Given the output values from getHalfShuffleMask(), create a half width
16415/// shuffle of extracted vectors followed by an insert back to full width.
16416static SDValue getShuffleHalfVectors(const SDLoc &DL, SDValue V1, SDValue V2,
16417 ArrayRef<int> HalfMask, int HalfIdx1,
16418 int HalfIdx2, bool UndefLower,
16419 SelectionDAG &DAG, bool UseConcat = false) {
16420 assert(V1.getValueType() == V2.getValueType() && "Different sized vectors?")(static_cast <bool> (V1.getValueType() == V2.getValueType
() && "Different sized vectors?") ? void (0) : __assert_fail
("V1.getValueType() == V2.getValueType() && \"Different sized vectors?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16420, __extension__ __PRETTY_FUNCTION__))
;
16421 assert(V1.getValueType().isSimple() && "Expecting only simple types")(static_cast <bool> (V1.getValueType().isSimple() &&
"Expecting only simple types") ? void (0) : __assert_fail ("V1.getValueType().isSimple() && \"Expecting only simple types\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16421, __extension__ __PRETTY_FUNCTION__))
;
16422
16423 MVT VT = V1.getSimpleValueType();
16424 MVT HalfVT = VT.getHalfNumVectorElementsVT();
16425 unsigned HalfNumElts = HalfVT.getVectorNumElements();
16426
16427 auto getHalfVector = [&](int HalfIdx) {
16428 if (HalfIdx < 0)
16429 return DAG.getUNDEF(HalfVT);
16430 SDValue V = (HalfIdx < 2 ? V1 : V2);
16431 HalfIdx = (HalfIdx % 2) * HalfNumElts;
16432 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
16433 DAG.getIntPtrConstant(HalfIdx, DL));
16434 };
16435
16436 // ins undef, (shuf (ext V1, HalfIdx1), (ext V2, HalfIdx2), HalfMask), Offset
16437 SDValue Half1 = getHalfVector(HalfIdx1);
16438 SDValue Half2 = getHalfVector(HalfIdx2);
16439 SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
16440 if (UseConcat) {
16441 SDValue Op0 = V;
16442 SDValue Op1 = DAG.getUNDEF(HalfVT);
16443 if (UndefLower)
16444 std::swap(Op0, Op1);
16445 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Op0, Op1);
16446 }
16447
16448 unsigned Offset = UndefLower ? HalfNumElts : 0;
16449 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
16450 DAG.getIntPtrConstant(Offset, DL));
16451}
16452
16453/// Lower shuffles where an entire half of a 256 or 512-bit vector is UNDEF.
16454/// This allows for fast cases such as subvector extraction/insertion
16455/// or shuffling smaller vector types which can lower more efficiently.
16456static SDValue lowerShuffleWithUndefHalf(const SDLoc &DL, MVT VT, SDValue V1,
16457 SDValue V2, ArrayRef<int> Mask,
16458 const X86Subtarget &Subtarget,
16459 SelectionDAG &DAG) {
16460 assert((VT.is256BitVector() || VT.is512BitVector()) &&(static_cast <bool> ((VT.is256BitVector() || VT.is512BitVector
()) && "Expected 256-bit or 512-bit vector") ? void (
0) : __assert_fail ("(VT.is256BitVector() || VT.is512BitVector()) && \"Expected 256-bit or 512-bit vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16461, __extension__ __PRETTY_FUNCTION__))
16461 "Expected 256-bit or 512-bit vector")(static_cast <bool> ((VT.is256BitVector() || VT.is512BitVector
()) && "Expected 256-bit or 512-bit vector") ? void (
0) : __assert_fail ("(VT.is256BitVector() || VT.is512BitVector()) && \"Expected 256-bit or 512-bit vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16461, __extension__ __PRETTY_FUNCTION__))
;
16462
16463 bool UndefLower = isUndefLowerHalf(Mask);
16464 if (!UndefLower && !isUndefUpperHalf(Mask))
16465 return SDValue();
16466
16467 assert((!UndefLower || !isUndefUpperHalf(Mask)) &&(static_cast <bool> ((!UndefLower || !isUndefUpperHalf(
Mask)) && "Completely undef shuffle mask should have been simplified already"
) ? void (0) : __assert_fail ("(!UndefLower || !isUndefUpperHalf(Mask)) && \"Completely undef shuffle mask should have been simplified already\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16468, __extension__ __PRETTY_FUNCTION__))
16468 "Completely undef shuffle mask should have been simplified already")(static_cast <bool> ((!UndefLower || !isUndefUpperHalf(
Mask)) && "Completely undef shuffle mask should have been simplified already"
) ? void (0) : __assert_fail ("(!UndefLower || !isUndefUpperHalf(Mask)) && \"Completely undef shuffle mask should have been simplified already\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16468, __extension__ __PRETTY_FUNCTION__))
;
16469
16470 // Upper half is undef and lower half is whole upper subvector.
16471 // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16472 MVT HalfVT = VT.getHalfNumVectorElementsVT();
16473 unsigned HalfNumElts = HalfVT.getVectorNumElements();
16474 if (!UndefLower &&
16475 isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
16476 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
16477 DAG.getIntPtrConstant(HalfNumElts, DL));
16478 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
16479 DAG.getIntPtrConstant(0, DL));
16480 }
16481
16482 // Lower half is undef and upper half is whole lower subvector.
16483 // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16484 if (UndefLower &&
16485 isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
16486 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
16487 DAG.getIntPtrConstant(0, DL));
16488 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
16489 DAG.getIntPtrConstant(HalfNumElts, DL));
16490 }
16491
16492 int HalfIdx1, HalfIdx2;
16493 SmallVector<int, 8> HalfMask(HalfNumElts);
16494 if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2))
16495 return SDValue();
16496
16497 assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length")(static_cast <bool> (HalfMask.size() == HalfNumElts &&
"Unexpected shuffle mask length") ? void (0) : __assert_fail
("HalfMask.size() == HalfNumElts && \"Unexpected shuffle mask length\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16497, __extension__ __PRETTY_FUNCTION__))
;
16498
16499 // Only shuffle the halves of the inputs when useful.
16500 unsigned NumLowerHalves =
16501 (HalfIdx1 == 0 || HalfIdx1 == 2) + (HalfIdx2 == 0 || HalfIdx2 == 2);
16502 unsigned NumUpperHalves =
16503 (HalfIdx1 == 1 || HalfIdx1 == 3) + (HalfIdx2 == 1 || HalfIdx2 == 3);
16504 assert(NumLowerHalves + NumUpperHalves <= 2 && "Only 1 or 2 halves allowed")(static_cast <bool> (NumLowerHalves + NumUpperHalves <=
2 && "Only 1 or 2 halves allowed") ? void (0) : __assert_fail
("NumLowerHalves + NumUpperHalves <= 2 && \"Only 1 or 2 halves allowed\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16504, __extension__ __PRETTY_FUNCTION__))
;
16505
16506 // Determine the larger pattern of undef/halves, then decide if it's worth
16507 // splitting the shuffle based on subtarget capabilities and types.
16508 unsigned EltWidth = VT.getVectorElementType().getSizeInBits();
16509 if (!UndefLower) {
16510 // XXXXuuuu: no insert is needed.
16511 // Always extract lowers when setting lower - these are all free subreg ops.
16512 if (NumUpperHalves == 0)
16513 return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
16514 UndefLower, DAG);
16515
16516 if (NumUpperHalves == 1) {
16517 // AVX2 has efficient 32/64-bit element cross-lane shuffles.
16518 if (Subtarget.hasAVX2()) {
16519 // extract128 + vunpckhps/vshufps, is better than vblend + vpermps.
16520 if (EltWidth == 32 && NumLowerHalves && HalfVT.is128BitVector() &&
16521 !is128BitUnpackShuffleMask(HalfMask) &&
16522 (!isSingleSHUFPSMask(HalfMask) ||
16523 Subtarget.hasFastVariableCrossLaneShuffle()))
16524 return SDValue();
16525 // If this is a unary shuffle (assume that the 2nd operand is
16526 // canonicalized to undef), then we can use vpermpd. Otherwise, we
16527 // are better off extracting the upper half of 1 operand and using a
16528 // narrow shuffle.
16529 if (EltWidth == 64 && V2.isUndef())
16530 return SDValue();
16531 }
16532 // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
16533 if (Subtarget.hasAVX512() && VT.is512BitVector())
16534 return SDValue();
16535 // Extract + narrow shuffle is better than the wide alternative.
16536 return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
16537 UndefLower, DAG);
16538 }
16539
16540 // Don't extract both uppers, instead shuffle and then extract.
16541 assert(NumUpperHalves == 2 && "Half vector count went wrong")(static_cast <bool> (NumUpperHalves == 2 && "Half vector count went wrong"
) ? void (0) : __assert_fail ("NumUpperHalves == 2 && \"Half vector count went wrong\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16541, __extension__ __PRETTY_FUNCTION__))
;
16542 return SDValue();
16543 }
16544
16545 // UndefLower - uuuuXXXX: an insert to high half is required if we split this.
16546 if (NumUpperHalves == 0) {
16547 // AVX2 has efficient 64-bit element cross-lane shuffles.
16548 // TODO: Refine to account for unary shuffle, splat, and other masks?
16549 if (Subtarget.hasAVX2() && EltWidth == 64)
16550 return SDValue();
16551 // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
16552 if (Subtarget.hasAVX512() && VT.is512BitVector())
16553 return SDValue();
16554 // Narrow shuffle + insert is better than the wide alternative.
16555 return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
16556 UndefLower, DAG);
16557 }
16558
16559 // NumUpperHalves != 0: don't bother with extract, shuffle, and then insert.
16560 return SDValue();
16561}
16562
16563/// Test whether the specified input (0 or 1) is in-place blended by the
16564/// given mask.
16565///
16566/// This returns true if the elements from a particular input are already in the
16567/// slot required by the given mask and require no permutation.
16568static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
16569 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.")(static_cast <bool> ((Input == 0 || Input == 1) &&
"Only two inputs to shuffles.") ? void (0) : __assert_fail (
"(Input == 0 || Input == 1) && \"Only two inputs to shuffles.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16569, __extension__ __PRETTY_FUNCTION__))
;
16570 int Size = Mask.size();
16571 for (int i = 0; i < Size; ++i)
16572 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
16573 return false;
16574
16575 return true;
16576}
16577
16578/// Handle case where shuffle sources are coming from the same 128-bit lane and
16579/// every lane can be represented as the same repeating mask - allowing us to
16580/// shuffle the sources with the repeating shuffle and then permute the result
16581/// to the destination lanes.
16582static SDValue lowerShuffleAsRepeatedMaskAndLanePermute(
16583 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
16584 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
16585 int NumElts = VT.getVectorNumElements();
16586 int NumLanes = VT.getSizeInBits() / 128;
16587 int NumLaneElts = NumElts / NumLanes;
16588
16589 // On AVX2 we may be able to just shuffle the lowest elements and then
16590 // broadcast the result.
16591 if (Subtarget.hasAVX2()) {
16592 for (unsigned BroadcastSize : {16, 32, 64}) {
16593 if (BroadcastSize <= VT.getScalarSizeInBits())
16594 continue;
16595 int NumBroadcastElts = BroadcastSize / VT.getScalarSizeInBits();
16596
16597 // Attempt to match a repeating pattern every NumBroadcastElts,
16598 // accounting for UNDEFs but only references the lowest 128-bit
16599 // lane of the inputs.
16600 auto FindRepeatingBroadcastMask = [&](SmallVectorImpl<int> &RepeatMask) {
16601 for (int i = 0; i != NumElts; i += NumBroadcastElts)
16602 for (int j = 0; j != NumBroadcastElts; ++j) {
16603 int M = Mask[i + j];
16604 if (M < 0)
16605 continue;
16606 int &R = RepeatMask[j];
16607 if (0 != ((M % NumElts) / NumLaneElts))
16608 return false;
16609 if (0 <= R && R != M)
16610 return false;
16611 R = M;
16612 }
16613 return true;
16614 };
16615
16616 SmallVector<int, 8> RepeatMask((unsigned)NumElts, -1);
16617 if (!FindRepeatingBroadcastMask(RepeatMask))
16618 continue;
16619
16620 // Shuffle the (lowest) repeated elements in place for broadcast.
16621 SDValue RepeatShuf = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatMask);
16622
16623 // Shuffle the actual broadcast.
16624 SmallVector<int, 8> BroadcastMask((unsigned)NumElts, -1);
16625 for (int i = 0; i != NumElts; i += NumBroadcastElts)
16626 for (int j = 0; j != NumBroadcastElts; ++j)
16627 BroadcastMask[i + j] = j;
16628 return DAG.getVectorShuffle(VT, DL, RepeatShuf, DAG.getUNDEF(VT),
16629 BroadcastMask);
16630 }
16631 }
16632
16633 // Bail if the shuffle mask doesn't cross 128-bit lanes.
16634 if (!is128BitLaneCrossingShuffleMask(VT, Mask))
16635 return SDValue();
16636
16637 // Bail if we already have a repeated lane shuffle mask.
16638 SmallVector<int, 8> RepeatedShuffleMask;
16639 if (is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedShuffleMask))
16640 return SDValue();
16641
16642 // On AVX2 targets we can permute 256-bit vectors as 64-bit sub-lanes
16643 // (with PERMQ/PERMPD), otherwise we can only permute whole 128-bit lanes.
16644 int SubLaneScale = Subtarget.hasAVX2() && VT.is256BitVector() ? 2 : 1;
16645 int NumSubLanes = NumLanes * SubLaneScale;
16646 int NumSubLaneElts = NumLaneElts / SubLaneScale;
16647
16648 // Check that all the sources are coming from the same lane and see if we can
16649 // form a repeating shuffle mask (local to each sub-lane). At the same time,
16650 // determine the source sub-lane for each destination sub-lane.
16651 int TopSrcSubLane = -1;
16652 SmallVector<int, 8> Dst2SrcSubLanes((unsigned)NumSubLanes, -1);
16653 SmallVector<int, 8> RepeatedSubLaneMasks[2] = {
16654 SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef),
16655 SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef)};
16656
16657 for (int DstSubLane = 0; DstSubLane != NumSubLanes; ++DstSubLane) {
16658 // Extract the sub-lane mask, check that it all comes from the same lane
16659 // and normalize the mask entries to come from the first lane.
16660 int SrcLane = -1;
16661 SmallVector<int, 8> SubLaneMask((unsigned)NumSubLaneElts, -1);
16662 for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
16663 int M = Mask[(DstSubLane * NumSubLaneElts) + Elt];
16664 if (M < 0)
16665 continue;
16666 int Lane = (M % NumElts) / NumLaneElts;
16667 if ((0 <= SrcLane) && (SrcLane != Lane))
16668 return SDValue();
16669 SrcLane = Lane;
16670 int LocalM = (M % NumLaneElts) + (M < NumElts ? 0 : NumElts);
16671 SubLaneMask[Elt] = LocalM;
16672 }
16673
16674 // Whole sub-lane is UNDEF.
16675 if (SrcLane < 0)
16676 continue;
16677
16678 // Attempt to match against the candidate repeated sub-lane masks.
16679 for (int SubLane = 0; SubLane != SubLaneScale; ++SubLane) {
16680 auto MatchMasks = [NumSubLaneElts](ArrayRef<int> M1, ArrayRef<int> M2) {
16681 for (int i = 0; i != NumSubLaneElts; ++i) {
16682 if (M1[i] < 0 || M2[i] < 0)
16683 continue;
16684 if (M1[i] != M2[i])
16685 return false;
16686 }
16687 return true;
16688 };
16689
16690 auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane];
16691 if (!MatchMasks(SubLaneMask, RepeatedSubLaneMask))
16692 continue;
16693
16694 // Merge the sub-lane mask into the matching repeated sub-lane mask.
16695 for (int i = 0; i != NumSubLaneElts; ++i) {
16696 int M = SubLaneMask[i];
16697 if (M < 0)
16698 continue;
16699 assert((RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask[i] == M) &&(static_cast <bool> ((RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask
[i] == M) && "Unexpected mask element") ? void (0) : __assert_fail
("(RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask[i] == M) && \"Unexpected mask element\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16700, __extension__ __PRETTY_FUNCTION__))
16700 "Unexpected mask element")(static_cast <bool> ((RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask
[i] == M) && "Unexpected mask element") ? void (0) : __assert_fail
("(RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask[i] == M) && \"Unexpected mask element\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16700, __extension__ __PRETTY_FUNCTION__))
;
16701 RepeatedSubLaneMask[i] = M;
16702 }
16703
16704 // Track the top most source sub-lane - by setting the remaining to UNDEF
16705 // we can greatly simplify shuffle matching.
16706 int SrcSubLane = (SrcLane * SubLaneScale) + SubLane;
16707 TopSrcSubLane = std::max(TopSrcSubLane, SrcSubLane);
16708 Dst2SrcSubLanes[DstSubLane] = SrcSubLane;
16709 break;
16710 }
16711
16712 // Bail if we failed to find a matching repeated sub-lane mask.
16713 if (Dst2SrcSubLanes[DstSubLane] < 0)
16714 return SDValue();
16715 }
16716 assert(0 <= TopSrcSubLane && TopSrcSubLane < NumSubLanes &&(static_cast <bool> (0 <= TopSrcSubLane && TopSrcSubLane
< NumSubLanes && "Unexpected source lane") ? void
(0) : __assert_fail ("0 <= TopSrcSubLane && TopSrcSubLane < NumSubLanes && \"Unexpected source lane\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16717, __extension__ __PRETTY_FUNCTION__))
16717 "Unexpected source lane")(static_cast <bool> (0 <= TopSrcSubLane && TopSrcSubLane
< NumSubLanes && "Unexpected source lane") ? void
(0) : __assert_fail ("0 <= TopSrcSubLane && TopSrcSubLane < NumSubLanes && \"Unexpected source lane\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16717, __extension__ __PRETTY_FUNCTION__))
;
16718
16719 // Create a repeating shuffle mask for the entire vector.
16720 SmallVector<int, 8> RepeatedMask((unsigned)NumElts, -1);
16721 for (int SubLane = 0; SubLane <= TopSrcSubLane; ++SubLane) {
16722 int Lane = SubLane / SubLaneScale;
16723 auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane % SubLaneScale];
16724 for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
16725 int M = RepeatedSubLaneMask[Elt];
16726 if (M < 0)
16727 continue;
16728 int Idx = (SubLane * NumSubLaneElts) + Elt;
16729 RepeatedMask[Idx] = M + (Lane * NumLaneElts);
16730 }
16731 }
16732 SDValue RepeatedShuffle = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatedMask);
16733
16734 // Shuffle each source sub-lane to its destination.
16735 SmallVector<int, 8> SubLaneMask((unsigned)NumElts, -1);
16736 for (int i = 0; i != NumElts; i += NumSubLaneElts) {
16737 int SrcSubLane = Dst2SrcSubLanes[i / NumSubLaneElts];
16738 if (SrcSubLane < 0)
16739 continue;
16740 for (int j = 0; j != NumSubLaneElts; ++j)
16741 SubLaneMask[i + j] = j + (SrcSubLane * NumSubLaneElts);
16742 }
16743
16744 return DAG.getVectorShuffle(VT, DL, RepeatedShuffle, DAG.getUNDEF(VT),
16745 SubLaneMask);
16746}
16747
16748static bool matchShuffleWithSHUFPD(MVT VT, SDValue &V1, SDValue &V2,
16749 bool &ForceV1Zero, bool &ForceV2Zero,
16750 unsigned &ShuffleImm, ArrayRef<int> Mask,
16751 const APInt &Zeroable) {
16752 int NumElts = VT.getVectorNumElements();
16753 assert(VT.getScalarSizeInBits() == 64 &&(static_cast <bool> (VT.getScalarSizeInBits() == 64 &&
(NumElts == 2 || NumElts == 4 || NumElts == 8) && "Unexpected data type for VSHUFPD"
) ? void (0) : __assert_fail ("VT.getScalarSizeInBits() == 64 && (NumElts == 2 || NumElts == 4 || NumElts == 8) && \"Unexpected data type for VSHUFPD\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16755, __extension__ __PRETTY_FUNCTION__))
16754 (NumElts == 2 || NumElts == 4 || NumElts == 8) &&(static_cast <bool> (VT.getScalarSizeInBits() == 64 &&
(NumElts == 2 || NumElts == 4 || NumElts == 8) && "Unexpected data type for VSHUFPD"
) ? void (0) : __assert_fail ("VT.getScalarSizeInBits() == 64 && (NumElts == 2 || NumElts == 4 || NumElts == 8) && \"Unexpected data type for VSHUFPD\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16755, __extension__ __PRETTY_FUNCTION__))
16755 "Unexpected data type for VSHUFPD")(static_cast <bool> (VT.getScalarSizeInBits() == 64 &&
(NumElts == 2 || NumElts == 4 || NumElts == 8) && "Unexpected data type for VSHUFPD"
) ? void (0) : __assert_fail ("VT.getScalarSizeInBits() == 64 && (NumElts == 2 || NumElts == 4 || NumElts == 8) && \"Unexpected data type for VSHUFPD\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16755, __extension__ __PRETTY_FUNCTION__))
;
16756 assert(isUndefOrZeroOrInRange(Mask, 0, 2 * NumElts) &&(static_cast <bool> (isUndefOrZeroOrInRange(Mask, 0, 2 *
NumElts) && "Illegal shuffle mask") ? void (0) : __assert_fail
("isUndefOrZeroOrInRange(Mask, 0, 2 * NumElts) && \"Illegal shuffle mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16757, __extension__ __PRETTY_FUNCTION__))
16757 "Illegal shuffle mask")(static_cast <bool> (isUndefOrZeroOrInRange(Mask, 0, 2 *
NumElts) && "Illegal shuffle mask") ? void (0) : __assert_fail
("isUndefOrZeroOrInRange(Mask, 0, 2 * NumElts) && \"Illegal shuffle mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16757, __extension__ __PRETTY_FUNCTION__))
;
16758
16759 bool ZeroLane[2] = { true, true };
16760 for (int i = 0; i < NumElts; ++i)
16761 ZeroLane[i & 1] &= Zeroable[i];
16762
16763 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
16764 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
16765 ShuffleImm = 0;
16766 bool ShufpdMask = true;
16767 bool CommutableMask = true;
16768 for (int i = 0; i < NumElts; ++i) {
16769 if (Mask[i] == SM_SentinelUndef || ZeroLane[i & 1])
16770 continue;
16771 if (Mask[i] < 0)
16772 return false;
16773 int Val = (i & 6) + NumElts * (i & 1);
16774 int CommutVal = (i & 0xe) + NumElts * ((i & 1) ^ 1);
16775 if (Mask[i] < Val || Mask[i] > Val + 1)
16776 ShufpdMask = false;
16777 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
16778 CommutableMask = false;
16779 ShuffleImm |= (Mask[i] % 2) << i;
16780 }
16781
16782 if (!ShufpdMask && !CommutableMask)
16783 return false;
16784
16785 if (!ShufpdMask && CommutableMask)
16786 std::swap(V1, V2);
16787
16788 ForceV1Zero = ZeroLane[0];
16789 ForceV2Zero = ZeroLane[1];
16790 return true;
16791}
16792
16793static SDValue lowerShuffleWithSHUFPD(const SDLoc &DL, MVT VT, SDValue V1,
16794 SDValue V2, ArrayRef<int> Mask,
16795 const APInt &Zeroable,
16796 const X86Subtarget &Subtarget,
16797 SelectionDAG &DAG) {
16798 assert((VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v8f64) &&(static_cast <bool> ((VT == MVT::v2f64 || VT == MVT::v4f64
|| VT == MVT::v8f64) && "Unexpected data type for VSHUFPD"
) ? void (0) : __assert_fail ("(VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v8f64) && \"Unexpected data type for VSHUFPD\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16799, __extension__ __PRETTY_FUNCTION__))
16799 "Unexpected data type for VSHUFPD")(static_cast <bool> ((VT == MVT::v2f64 || VT == MVT::v4f64
|| VT == MVT::v8f64) && "Unexpected data type for VSHUFPD"
) ? void (0) : __assert_fail ("(VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v8f64) && \"Unexpected data type for VSHUFPD\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16799, __extension__ __PRETTY_FUNCTION__))
;
16800
16801 unsigned Immediate = 0;
16802 bool ForceV1Zero = false, ForceV2Zero = false;
16803 if (!matchShuffleWithSHUFPD(VT, V1, V2, ForceV1Zero, ForceV2Zero, Immediate,
16804 Mask, Zeroable))
16805 return SDValue();
16806
16807 // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
16808 if (ForceV1Zero)
16809 V1 = getZeroVector(VT, Subtarget, DAG, DL);
16810 if (ForceV2Zero)
16811 V2 = getZeroVector(VT, Subtarget, DAG, DL);
16812
16813 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
16814 DAG.getTargetConstant(Immediate, DL, MVT::i8));
16815}
16816
16817// Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
16818// by zeroable elements in the remaining 24 elements. Turn this into two
16819// vmovqb instructions shuffled together.
16820static SDValue lowerShuffleAsVTRUNCAndUnpack(const SDLoc &DL, MVT VT,
16821 SDValue V1, SDValue V2,
16822 ArrayRef<int> Mask,
16823 const APInt &Zeroable,
16824 SelectionDAG &DAG) {
16825 assert(VT == MVT::v32i8 && "Unexpected type!")(static_cast <bool> (VT == MVT::v32i8 && "Unexpected type!"
) ? void (0) : __assert_fail ("VT == MVT::v32i8 && \"Unexpected type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16825, __extension__ __PRETTY_FUNCTION__))
;
16826
16827 // The first 8 indices should be every 8th element.
16828 if (!isSequentialOrUndefInRange(Mask, 0, 8, 0, 8))
16829 return SDValue();
16830
16831 // Remaining elements need to be zeroable.
16832 if (Zeroable.countLeadingOnes() < (Mask.size() - 8))
16833 return SDValue();
16834
16835 V1 = DAG.getBitcast(MVT::v4i64, V1);
16836 V2 = DAG.getBitcast(MVT::v4i64, V2);
16837
16838 V1 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V1);
16839 V2 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V2);
16840
16841 // The VTRUNCs will put 0s in the upper 12 bytes. Use them to put zeroes in
16842 // the upper bits of the result using an unpckldq.
16843 SDValue Unpack = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2,
16844 { 0, 1, 2, 3, 16, 17, 18, 19,
16845 4, 5, 6, 7, 20, 21, 22, 23 });
16846 // Insert the unpckldq into a zero vector to widen to v32i8.
16847 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v32i8,
16848 DAG.getConstant(0, DL, MVT::v32i8), Unpack,
16849 DAG.getIntPtrConstant(0, DL));
16850}
16851
16852
16853/// Handle lowering of 4-lane 64-bit floating point shuffles.
16854///
16855/// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
16856/// isn't available.
16857static SDValue lowerV4F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16858 const APInt &Zeroable, SDValue V1, SDValue V2,
16859 const X86Subtarget &Subtarget,
16860 SelectionDAG &DAG) {
16861 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!")(static_cast <bool> (V1.getSimpleValueType() == MVT::v4f64
&& "Bad operand type!") ? void (0) : __assert_fail (
"V1.getSimpleValueType() == MVT::v4f64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16861, __extension__ __PRETTY_FUNCTION__))
;
16862 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!")(static_cast <bool> (V2.getSimpleValueType() == MVT::v4f64
&& "Bad operand type!") ? void (0) : __assert_fail (
"V2.getSimpleValueType() == MVT::v4f64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16862, __extension__ __PRETTY_FUNCTION__))
;
16863 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!")(static_cast <bool> (Mask.size() == 4 && "Unexpected mask size for v4 shuffle!"
) ? void (0) : __assert_fail ("Mask.size() == 4 && \"Unexpected mask size for v4 shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16863, __extension__ __PRETTY_FUNCTION__))
;
16864
16865 if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4f64, V1, V2, Mask, Zeroable,
16866 Subtarget, DAG))
16867 return V;
16868
16869 if (V2.isUndef()) {
16870 // Check for being able to broadcast a single element.
16871 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f64, V1, V2,
16872 Mask, Subtarget, DAG))
16873 return Broadcast;
16874
16875 // Use low duplicate instructions for masks that match their pattern.
16876 if (isShuffleEquivalent(Mask, {0, 0, 2, 2}, V1, V2))
16877 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
16878
16879 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
16880 // Non-half-crossing single input shuffles can be lowered with an
16881 // interleaved permutation.
16882 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
16883 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
16884 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
16885 DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
16886 }
16887
16888 // With AVX2 we have direct support for this permutation.
16889 if (Subtarget.hasAVX2())
16890 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
16891 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
16892
16893 // Try to create an in-lane repeating shuffle mask and then shuffle the
16894 // results into the target lanes.
16895 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16896 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
16897 return V;
16898
16899 // Try to permute the lanes and then use a per-lane permute.
16900 if (SDValue V = lowerShuffleAsLanePermuteAndPermute(DL, MVT::v4f64, V1, V2,
16901 Mask, DAG, Subtarget))
16902 return V;
16903
16904 // Otherwise, fall back.
16905 return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v4f64, V1, V2, Mask,
16906 DAG, Subtarget);
16907 }
16908
16909 // Use dedicated unpack instructions for masks that match their pattern.
16910 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
16911 return V;
16912
16913 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
16914 Zeroable, Subtarget, DAG))
16915 return Blend;
16916
16917 // Check if the blend happens to exactly fit that of SHUFPD.
16918 if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v4f64, V1, V2, Mask,
16919 Zeroable, Subtarget, DAG))
16920 return Op;
16921
16922 // If we have lane crossing shuffles AND they don't all come from the lower
16923 // lane elements, lower to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
16924 // TODO: Handle BUILD_VECTOR sources which getVectorShuffle currently
16925 // canonicalize to a blend of splat which isn't necessary for this combine.
16926 if (is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask) &&
16927 !all_of(Mask, [](int M) { return M < 2 || (4 <= M && M < 6); }) &&
16928 (V1.getOpcode() != ISD::BUILD_VECTOR) &&
16929 (V2.getOpcode() != ISD::BUILD_VECTOR))
16930 if (SDValue Op = lowerShuffleAsLanePermuteAndSHUFP(DL, MVT::v4f64, V1, V2,
16931 Mask, DAG))
16932 return Op;
16933
16934 // If we have one input in place, then we can permute the other input and
16935 // blend the result.
16936 if (isShuffleMaskInputInPlace(0, Mask) || isShuffleMaskInputInPlace(1, Mask))
16937 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4f64, V1, V2, Mask,
16938 Subtarget, DAG);
16939
16940 // Try to create an in-lane repeating shuffle mask and then shuffle the
16941 // results into the target lanes.
16942 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16943 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
16944 return V;
16945
16946 // Try to simplify this by merging 128-bit lanes to enable a lane-based
16947 // shuffle. However, if we have AVX2 and either inputs are already in place,
16948 // we will be able to shuffle even across lanes the other input in a single
16949 // instruction so skip this pattern.
16950 if (!(Subtarget.hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
16951 isShuffleMaskInputInPlace(1, Mask))))
16952 if (SDValue V = lowerShuffleAsLanePermuteAndRepeatedMask(
16953 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
16954 return V;
16955
16956 // If we have VLX support, we can use VEXPAND.
16957 if (Subtarget.hasVLX())
16958 if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v4f64, Zeroable, Mask, V1, V2,
16959 DAG, Subtarget))
16960 return V;
16961
16962 // If we have AVX2 then we always want to lower with a blend because an v4 we
16963 // can fully permute the elements.
16964 if (Subtarget.hasAVX2())
16965 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4f64, V1, V2, Mask,
16966 Subtarget, DAG);
16967
16968 // Otherwise fall back on generic lowering.
16969 return lowerShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask,
16970 Subtarget, DAG);
16971}
16972
16973/// Handle lowering of 4-lane 64-bit integer shuffles.
16974///
16975/// This routine is only called when we have AVX2 and thus a reasonable
16976/// instruction set for v4i64 shuffling..
16977static SDValue lowerV4I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16978 const APInt &Zeroable, SDValue V1, SDValue V2,
16979 const X86Subtarget &Subtarget,
16980 SelectionDAG &DAG) {
16981 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!")(static_cast <bool> (V1.getSimpleValueType() == MVT::v4i64
&& "Bad operand type!") ? void (0) : __assert_fail (
"V1.getSimpleValueType() == MVT::v4i64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16981, __extension__ __PRETTY_FUNCTION__))
;
16982 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!")(static_cast <bool> (V2.getSimpleValueType() == MVT::v4i64
&& "Bad operand type!") ? void (0) : __assert_fail (
"V2.getSimpleValueType() == MVT::v4i64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16982, __extension__ __PRETTY_FUNCTION__))
;
16983 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!")(static_cast <bool> (Mask.size() == 4 && "Unexpected mask size for v4 shuffle!"
) ? void (0) : __assert_fail ("Mask.size() == 4 && \"Unexpected mask size for v4 shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16983, __extension__ __PRETTY_FUNCTION__))
;
16984 assert(Subtarget.hasAVX2() && "We can only lower v4i64 with AVX2!")(static_cast <bool> (Subtarget.hasAVX2() && "We can only lower v4i64 with AVX2!"
) ? void (0) : __assert_fail ("Subtarget.hasAVX2() && \"We can only lower v4i64 with AVX2!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 16984, __extension__ __PRETTY_FUNCTION__))
;
16985
16986 if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4i64, V1, V2, Mask, Zeroable,
16987 Subtarget, DAG))
16988 return V;
16989
16990 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
16991 Zeroable, Subtarget, DAG))
16992 return Blend;
16993
16994 // Check for being able to broadcast a single element.
16995 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i64, V1, V2, Mask,
16996 Subtarget, DAG))
16997 return Broadcast;
16998
16999 if (V2.isUndef()) {
17000 // When the shuffle is mirrored between the 128-bit lanes of the unit, we
17001 // can use lower latency instructions that will operate on both lanes.
17002 SmallVector<int, 2> RepeatedMask;
17003 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
17004 SmallVector<int, 4> PSHUFDMask;
17005 narrowShuffleMaskElts(2, RepeatedMask, PSHUFDMask);
17006 return DAG.getBitcast(
17007 MVT::v4i64,
17008 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
17009 DAG.getBitcast(MVT::v8i32, V1),
17010 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
17011 }
17012
17013 // AVX2 provides a direct instruction for permuting a single input across
17014 // lanes.
17015 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
17016 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
17017 }
17018
17019 // Try to use shift instructions.
17020 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask,
17021 Zeroable, Subtarget, DAG))
17022 return Shift;
17023
17024 // If we have VLX support, we can use VALIGN or VEXPAND.
17025 if (Subtarget.hasVLX()) {
17026 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i64, V1, V2, Mask,
17027 Subtarget, DAG))
17028 return Rotate;
17029
17030 if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v4i64, Zeroable, Mask, V1, V2,
17031 DAG, Subtarget))
17032 return V;
17033 }
17034
17035 // Try to use PALIGNR.
17036 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i64, V1, V2, Mask,
17037 Subtarget, DAG))
17038 return Rotate;
17039
17040 // Use dedicated unpack instructions for masks that match their pattern.
17041 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
17042 return V;
17043
17044 // If we have one input in place, then we can permute the other input and
17045 // blend the result.
17046 if (isShuffleMaskInputInPlace(0, Mask) || isShuffleMaskInputInPlace(1, Mask))
17047 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i64, V1, V2, Mask,
17048 Subtarget, DAG);
17049
17050 // Try to create an in-lane repeating shuffle mask and then shuffle the
17051 // results into the target lanes.
17052 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17053 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
17054 return V;
17055
17056 // Try to simplify this by merging 128-bit lanes to enable a lane-based
17057 // shuffle. However, if we have AVX2 and either inputs are already in place,
17058 // we will be able to shuffle even across lanes the other input in a single
17059 // instruction so skip this pattern.
17060 if (!isShuffleMaskInputInPlace(0, Mask) &&
17061 !isShuffleMaskInputInPlace(1, Mask))
17062 if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
17063 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
17064 return Result;
17065
17066 // Otherwise fall back on generic blend lowering.
17067 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i64, V1, V2, Mask,
17068 Subtarget, DAG);
17069}
17070
17071/// Handle lowering of 8-lane 32-bit floating point shuffles.
17072///
17073/// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
17074/// isn't available.
17075static SDValue lowerV8F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17076 const APInt &Zeroable, SDValue V1, SDValue V2,
17077 const X86Subtarget &Subtarget,
17078 SelectionDAG &DAG) {
17079 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!")(static_cast <bool> (V1.getSimpleValueType() == MVT::v8f32
&& "Bad operand type!") ? void (0) : __assert_fail (
"V1.getSimpleValueType() == MVT::v8f32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17079, __extension__ __PRETTY_FUNCTION__))
;
17080 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!")(static_cast <bool> (V2.getSimpleValueType() == MVT::v8f32
&& "Bad operand type!") ? void (0) : __assert_fail (
"V2.getSimpleValueType() == MVT::v8f32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17080, __extension__ __PRETTY_FUNCTION__))
;
17081 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!")(static_cast <bool> (Mask.size() == 8 && "Unexpected mask size for v8 shuffle!"
) ? void (0) : __assert_fail ("Mask.size() == 8 && \"Unexpected mask size for v8 shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17081, __extension__ __PRETTY_FUNCTION__))
;
17082
17083 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
17084 Zeroable, Subtarget, DAG))
17085 return Blend;
17086
17087 // Check for being able to broadcast a single element.
17088 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8f32, V1, V2, Mask,
17089 Subtarget, DAG))
17090 return Broadcast;
17091
17092 // If the shuffle mask is repeated in each 128-bit lane, we have many more
17093 // options to efficiently lower the shuffle.
17094 SmallVector<int, 4> RepeatedMask;
17095 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
17096 assert(RepeatedMask.size() == 4 &&(static_cast <bool> (RepeatedMask.size() == 4 &&
"Repeated masks must be half the mask width!") ? void (0) : __assert_fail
("RepeatedMask.size() == 4 && \"Repeated masks must be half the mask width!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17097, __extension__ __PRETTY_FUNCTION__))
17097 "Repeated masks must be half the mask width!")(static_cast <bool> (RepeatedMask.size() == 4 &&
"Repeated masks must be half the mask width!") ? void (0) : __assert_fail
("RepeatedMask.size() == 4 && \"Repeated masks must be half the mask width!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17097, __extension__ __PRETTY_FUNCTION__))
;
17098
17099 // Use even/odd duplicate instructions for masks that match their pattern.
17100 if (isShuffleEquivalent(RepeatedMask, {0, 0, 2, 2}, V1, V2))
17101 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
17102 if (isShuffleEquivalent(RepeatedMask, {1, 1, 3, 3}, V1, V2))
17103 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
17104
17105 if (V2.isUndef())
17106 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
17107 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17108
17109 // Use dedicated unpack instructions for masks that match their pattern.
17110 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
17111 return V;
17112
17113 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
17114 // have already handled any direct blends.
17115 return lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
17116 }
17117
17118 // Try to create an in-lane repeating shuffle mask and then shuffle the
17119 // results into the target lanes.
17120 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17121 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
17122 return V;
17123
17124 // If we have a single input shuffle with different shuffle patterns in the
17125 // two 128-bit lanes use the variable mask to VPERMILPS.
17126 if (V2.isUndef()) {
17127 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask)) {
17128 SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
17129 return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, V1, VPermMask);
17130 }
17131 if (Subtarget.hasAVX2()) {
17132 SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
17133 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32, VPermMask, V1);
17134 }
17135 // Otherwise, fall back.
17136 return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v8f32, V1, V2, Mask,
17137 DAG, Subtarget);
17138 }
17139
17140 // Try to simplify this by merging 128-bit lanes to enable a lane-based
17141 // shuffle.
17142 if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
17143 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
17144 return Result;
17145
17146 // If we have VLX support, we can use VEXPAND.
17147 if (Subtarget.hasVLX())
17148 if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8f32, Zeroable, Mask, V1, V2,
17149 DAG, Subtarget))
17150 return V;
17151
17152 // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
17153 // since after split we get a more efficient code using vpunpcklwd and
17154 // vpunpckhwd instrs than vblend.
17155 if (!Subtarget.hasAVX512() && isUnpackWdShuffleMask(Mask, MVT::v8f32))
17156 return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, Subtarget,
17157 DAG);
17158
17159 // If we have AVX2 then we always want to lower with a blend because at v8 we
17160 // can fully permute the elements.
17161 if (Subtarget.hasAVX2())
17162 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8f32, V1, V2, Mask,
17163 Subtarget, DAG);
17164
17165 // Otherwise fall back on generic lowering.
17166 return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask,
17167 Subtarget, DAG);
17168}
17169
17170/// Handle lowering of 8-lane 32-bit integer shuffles.
17171///
17172/// This routine is only called when we have AVX2 and thus a reasonable
17173/// instruction set for v8i32 shuffling..
17174static SDValue lowerV8I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17175 const APInt &Zeroable, SDValue V1, SDValue V2,
17176 const X86Subtarget &Subtarget,
17177 SelectionDAG &DAG) {
17178 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!")(static_cast <bool> (V1.getSimpleValueType() == MVT::v8i32
&& "Bad operand type!") ? void (0) : __assert_fail (
"V1.getSimpleValueType() == MVT::v8i32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17178, __extension__ __PRETTY_FUNCTION__))
;
17179 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!")(static_cast <bool> (V2.getSimpleValueType() == MVT::v8i32
&& "Bad operand type!") ? void (0) : __assert_fail (
"V2.getSimpleValueType() == MVT::v8i32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17179, __extension__ __PRETTY_FUNCTION__))
;
17180 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!")(static_cast <bool> (Mask.size() == 8 && "Unexpected mask size for v8 shuffle!"
) ? void (0) : __assert_fail ("Mask.size() == 8 && \"Unexpected mask size for v8 shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17180, __extension__ __PRETTY_FUNCTION__))
;
17181 assert(Subtarget.hasAVX2() && "We can only lower v8i32 with AVX2!")(static_cast <bool> (Subtarget.hasAVX2() && "We can only lower v8i32 with AVX2!"
) ? void (0) : __assert_fail ("Subtarget.hasAVX2() && \"We can only lower v8i32 with AVX2!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17181, __extension__ __PRETTY_FUNCTION__))
;
17182
17183 // Whenever we can lower this as a zext, that instruction is strictly faster
17184 // than any alternative. It also allows us to fold memory operands into the
17185 // shuffle in many cases.
17186 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2, Mask,
17187 Zeroable, Subtarget, DAG))
17188 return ZExt;
17189
17190 // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
17191 // since after split we get a more efficient code than vblend by using
17192 // vpunpcklwd and vpunpckhwd instrs.
17193 if (isUnpackWdShuffleMask(Mask, MVT::v8i32) && !V2.isUndef() &&
17194 !Subtarget.hasAVX512())
17195 return lowerShuffleAsSplitOrBlend(DL, MVT::v8i32, V1, V2, Mask, Subtarget,
17196 DAG);
17197
17198 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
17199 Zeroable, Subtarget, DAG))
17200 return Blend;
17201
17202 // Check for being able to broadcast a single element.
17203 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i32, V1, V2, Mask,
17204 Subtarget, DAG))
17205 return Broadcast;
17206
17207 // If the shuffle mask is repeated in each 128-bit lane we can use more
17208 // efficient instructions that mirror the shuffles across the two 128-bit
17209 // lanes.
17210 SmallVector<int, 4> RepeatedMask;
17211 bool Is128BitLaneRepeatedShuffle =
17212 is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask);
17213 if (Is128BitLaneRepeatedShuffle) {
17214 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!")(static_cast <bool> (RepeatedMask.size() == 4 &&
"Unexpected repeated mask size!") ? void (0) : __assert_fail
("RepeatedMask.size() == 4 && \"Unexpected repeated mask size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17214, __extension__ __PRETTY_FUNCTION__))
;
17215 if (V2.isUndef())
17216 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
17217 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17218
17219 // Use dedicated unpack instructions for masks that match their pattern.
17220 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
17221 return V;
17222 }
17223
17224 // Try to use shift instructions.
17225 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask,
17226 Zeroable, Subtarget, DAG))
17227 return Shift;
17228
17229 // If we have VLX support, we can use VALIGN or EXPAND.
17230 if (Subtarget.hasVLX()) {
17231 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i32, V1, V2, Mask,
17232 Subtarget, DAG))
17233 return Rotate;
17234
17235 if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8i32, Zeroable, Mask, V1, V2,
17236 DAG, Subtarget))
17237 return V;
17238 }
17239
17240 // Try to use byte rotation instructions.
17241 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i32, V1, V2, Mask,
17242 Subtarget, DAG))
17243 return Rotate;
17244
17245 // Try to create an in-lane repeating shuffle mask and then shuffle the
17246 // results into the target lanes.
17247 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17248 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
17249 return V;
17250
17251 if (V2.isUndef()) {
17252 // Try to produce a fixed cross-128-bit lane permute followed by unpack
17253 // because that should be faster than the variable permute alternatives.
17254 if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v8i32, Mask, V1, V2, DAG))
17255 return V;
17256
17257 // If the shuffle patterns aren't repeated but it's a single input, directly
17258 // generate a cross-lane VPERMD instruction.
17259 SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
17260 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8i32, VPermMask, V1);
17261 }
17262
17263 // Assume that a single SHUFPS is faster than an alternative sequence of
17264 // multiple instructions (even if the CPU has a domain penalty).
17265 // If some CPU is harmed by the domain switch, we can fix it in a later pass.
17266 if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
17267 SDValue CastV1 = DAG.getBitcast(MVT::v8f32, V1);
17268 SDValue CastV2 = DAG.getBitcast(MVT::v8f32, V2);
17269 SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask,
17270 CastV1, CastV2, DAG);
17271 return DAG.getBitcast(MVT::v8i32, ShufPS);
17272 }
17273
17274 // Try to simplify this by merging 128-bit lanes to enable a lane-based
17275 // shuffle.
17276 if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
17277 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
17278 return Result;
17279
17280 // Otherwise fall back on generic blend lowering.
17281 return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8i32, V1, V2, Mask,
17282 Subtarget, DAG);
17283}
17284
17285/// Handle lowering of 16-lane 16-bit integer shuffles.
17286///
17287/// This routine is only called when we have AVX2 and thus a reasonable
17288/// instruction set for v16i16 shuffling..
17289static SDValue lowerV16I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17290 const APInt &Zeroable, SDValue V1, SDValue V2,
17291 const X86Subtarget &Subtarget,
17292 SelectionDAG &DAG) {
17293 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!")(static_cast <bool> (V1.getSimpleValueType() == MVT::v16i16
&& "Bad operand type!") ? void (0) : __assert_fail (
"V1.getSimpleValueType() == MVT::v16i16 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17293, __extension__ __PRETTY_FUNCTION__))
;
17294 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!")(static_cast <bool> (V2.getSimpleValueType() == MVT::v16i16
&& "Bad operand type!") ? void (0) : __assert_fail (
"V2.getSimpleValueType() == MVT::v16i16 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17294, __extension__ __PRETTY_FUNCTION__))
;
17295 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!")(static_cast <bool> (Mask.size() == 16 && "Unexpected mask size for v16 shuffle!"
) ? void (0) : __assert_fail ("Mask.size() == 16 && \"Unexpected mask size for v16 shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17295, __extension__ __PRETTY_FUNCTION__))
;
17296 assert(Subtarget.hasAVX2() && "We can only lower v16i16 with AVX2!")(static_cast <bool> (Subtarget.hasAVX2() && "We can only lower v16i16 with AVX2!"
) ? void (0) : __assert_fail ("Subtarget.hasAVX2() && \"We can only lower v16i16 with AVX2!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17296, __extension__ __PRETTY_FUNCTION__))
;
17297
17298 // Whenever we can lower this as a zext, that instruction is strictly faster
17299 // than any alternative. It also allows us to fold memory operands into the
17300 // shuffle in many cases.
17301 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
17302 DL, MVT::v16i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
17303 return ZExt;
17304
17305 // Check for being able to broadcast a single element.
17306 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i16, V1, V2, Mask,
17307 Subtarget, DAG))
17308 return Broadcast;
17309
17310 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
17311 Zeroable, Subtarget, DAG))
17312 return Blend;
17313
17314 // Use dedicated unpack instructions for masks that match their pattern.
17315 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
17316 return V;
17317
17318 // Use dedicated pack instructions for masks that match their pattern.
17319 if (SDValue V = lowerShuffleWithPACK(DL, MVT::v16i16, Mask, V1, V2, DAG,
17320 Subtarget))
17321 return V;
17322
17323 // Try to use lower using a truncation.
17324 if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v16i16, V1, V2, Mask, Zeroable,
17325 Subtarget, DAG))
17326 return V;
17327
17328 // Try to use shift instructions.
17329 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask,
17330 Zeroable, Subtarget, DAG))
17331 return Shift;
17332
17333 // Try to use byte rotation instructions.
17334 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i16, V1, V2, Mask,
17335 Subtarget, DAG))
17336 return Rotate;
17337
17338 // Try to create an in-lane repeating shuffle mask and then shuffle the
17339 // results into the target lanes.
17340 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17341 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
17342 return V;
17343
17344 if (V2.isUndef()) {
17345 // Try to use bit rotation instructions.
17346 if (SDValue Rotate =
17347 lowerShuffleAsBitRotate(DL, MVT::v16i16, V1, Mask, Subtarget, DAG))
17348 return Rotate;
17349
17350 // Try to produce a fixed cross-128-bit lane permute followed by unpack
17351 // because that should be faster than the variable permute alternatives.
17352 if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v16i16, Mask, V1, V2, DAG))
17353 return V;
17354
17355 // There are no generalized cross-lane shuffle operations available on i16
17356 // element types.
17357 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask)) {
17358 if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
17359 DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
17360 return V;
17361
17362 return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v16i16, V1, V2, Mask,
17363 DAG, Subtarget);
17364 }
17365
17366 SmallVector<int, 8> RepeatedMask;
17367 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
17368 // As this is a single-input shuffle, the repeated mask should be
17369 // a strictly valid v8i16 mask that we can pass through to the v8i16
17370 // lowering to handle even the v16 case.
17371 return lowerV8I16GeneralSingleInputShuffle(
17372 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
17373 }
17374 }
17375
17376 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v16i16, Mask, V1, V2,
17377 Zeroable, Subtarget, DAG))
17378 return PSHUFB;
17379
17380 // AVX512BW can lower to VPERMW (non-VLX will pad to v32i16).
17381 if (Subtarget.hasBWI())
17382 return lowerShuffleWithPERMV(DL, MVT::v16i16, Mask, V1, V2, Subtarget, DAG);
17383
17384 // Try to simplify this by merging 128-bit lanes to enable a lane-based
17385 // shuffle.
17386 if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
17387 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
17388 return Result;
17389
17390 // Try to permute the lanes and then use a per-lane permute.
17391 if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
17392 DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
17393 return V;
17394
17395 // Otherwise fall back on generic lowering.
17396 return lowerShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask,
17397 Subtarget, DAG);
17398}
17399
17400/// Handle lowering of 32-lane 8-bit integer shuffles.
17401///
17402/// This routine is only called when we have AVX2 and thus a reasonable
17403/// instruction set for v32i8 shuffling..
17404static SDValue lowerV32I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17405 const APInt &Zeroable, SDValue V1, SDValue V2,
17406 const X86Subtarget &Subtarget,
17407 SelectionDAG &DAG) {
17408 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!")(static_cast <bool> (V1.getSimpleValueType() == MVT::v32i8
&& "Bad operand type!") ? void (0) : __assert_fail (
"V1.getSimpleValueType() == MVT::v32i8 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17408, __extension__ __PRETTY_FUNCTION__))
;
17409 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!")(static_cast <bool> (V2.getSimpleValueType() == MVT::v32i8
&& "Bad operand type!") ? void (0) : __assert_fail (
"V2.getSimpleValueType() == MVT::v32i8 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17409, __extension__ __PRETTY_FUNCTION__))
;
17410 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!")(static_cast <bool> (Mask.size() == 32 && "Unexpected mask size for v32 shuffle!"
) ? void (0) : __assert_fail ("Mask.size() == 32 && \"Unexpected mask size for v32 shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17410, __extension__ __PRETTY_FUNCTION__))
;
17411 assert(Subtarget.hasAVX2() && "We can only lower v32i8 with AVX2!")(static_cast <bool> (Subtarget.hasAVX2() && "We can only lower v32i8 with AVX2!"
) ? void (0) : __assert_fail ("Subtarget.hasAVX2() && \"We can only lower v32i8 with AVX2!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17411, __extension__ __PRETTY_FUNCTION__))
;
17412
17413 // Whenever we can lower this as a zext, that instruction is strictly faster
17414 // than any alternative. It also allows us to fold memory operands into the
17415 // shuffle in many cases.
17416 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2, Mask,
17417 Zeroable, Subtarget, DAG))
17418 return ZExt;
17419
17420 // Check for being able to broadcast a single element.
17421 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v32i8, V1, V2, Mask,
17422 Subtarget, DAG))
17423 return Broadcast;
17424
17425 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
17426 Zeroable, Subtarget, DAG))
17427 return Blend;
17428
17429 // Use dedicated unpack instructions for masks that match their pattern.
17430 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
17431 return V;
17432
17433 // Use dedicated pack instructions for masks that match their pattern.
17434 if (SDValue V = lowerShuffleWithPACK(DL, MVT::v32i8, Mask, V1, V2, DAG,
17435 Subtarget))
17436 return V;
17437
17438 // Try to use lower using a truncation.
17439 if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v32i8, V1, V2, Mask, Zeroable,
17440 Subtarget, DAG))
17441 return V;
17442
17443 // Try to use shift instructions.
17444 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask,
17445 Zeroable, Subtarget, DAG))
17446 return Shift;
17447
17448 // Try to use byte rotation instructions.
17449 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i8, V1, V2, Mask,
17450 Subtarget, DAG))
17451 return Rotate;
17452
17453 // Try to use bit rotation instructions.
17454 if (V2.isUndef())
17455 if (SDValue Rotate =
17456 lowerShuffleAsBitRotate(DL, MVT::v32i8, V1, Mask, Subtarget, DAG))
17457 return Rotate;
17458
17459 // Try to create an in-lane repeating shuffle mask and then shuffle the
17460 // results into the target lanes.
17461 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17462 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
17463 return V;
17464
17465 // There are no generalized cross-lane shuffle operations available on i8
17466 // element types.
17467 if (V2.isUndef() && is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask)) {
17468 // Try to produce a fixed cross-128-bit lane permute followed by unpack
17469 // because that should be faster than the variable permute alternatives.
17470 if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v32i8, Mask, V1, V2, DAG))
17471 return V;
17472
17473 if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
17474 DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
17475 return V;
17476
17477 return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v32i8, V1, V2, Mask,
17478 DAG, Subtarget);
17479 }
17480
17481 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i8, Mask, V1, V2,
17482 Zeroable, Subtarget, DAG))
17483 return PSHUFB;
17484
17485 // AVX512VBMI can lower to VPERMB (non-VLX will pad to v64i8).
17486 if (Subtarget.hasVBMI())
17487 return lowerShuffleWithPERMV(DL, MVT::v32i8, Mask, V1, V2, Subtarget, DAG);
17488
17489 // Try to simplify this by merging 128-bit lanes to enable a lane-based
17490 // shuffle.
17491 if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
17492 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
17493 return Result;
17494
17495 // Try to permute the lanes and then use a per-lane permute.
17496 if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
17497 DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
17498 return V;
17499
17500 // Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
17501 // by zeroable elements in the remaining 24 elements. Turn this into two
17502 // vmovqb instructions shuffled together.
17503 if (Subtarget.hasVLX())
17504 if (SDValue V = lowerShuffleAsVTRUNCAndUnpack(DL, MVT::v32i8, V1, V2,
17505 Mask, Zeroable, DAG))
17506 return V;
17507
17508 // Otherwise fall back on generic lowering.
17509 return lowerShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask,
17510 Subtarget, DAG);
17511}
17512
17513/// High-level routine to lower various 256-bit x86 vector shuffles.
17514///
17515/// This routine either breaks down the specific type of a 256-bit x86 vector
17516/// shuffle or splits it into two 128-bit shuffles and fuses the results back
17517/// together based on the available instructions.
17518static SDValue lower256BitShuffle(const SDLoc &DL, ArrayRef<int> Mask, MVT VT,
17519 SDValue V1, SDValue V2, const APInt &Zeroable,
17520 const X86Subtarget &Subtarget,
17521 SelectionDAG &DAG) {
17522 // If we have a single input to the zero element, insert that into V1 if we
17523 // can do so cheaply.
17524 int NumElts = VT.getVectorNumElements();
17525 int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
17526
17527 if (NumV2Elements == 1 && Mask[0] >= NumElts)
17528 if (SDValue Insertion = lowerShuffleAsElementInsertion(
17529 DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
17530 return Insertion;
17531
17532 // Handle special cases where the lower or upper half is UNDEF.
17533 if (SDValue V =
17534 lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
17535 return V;
17536
17537 // There is a really nice hard cut-over between AVX1 and AVX2 that means we
17538 // can check for those subtargets here and avoid much of the subtarget
17539 // querying in the per-vector-type lowering routines. With AVX1 we have
17540 // essentially *zero* ability to manipulate a 256-bit vector with integer
17541 // types. Since we'll use floating point types there eventually, just
17542 // immediately cast everything to a float and operate entirely in that domain.
17543 if (VT.isInteger() && !Subtarget.hasAVX2()) {
17544 int ElementBits = VT.getScalarSizeInBits();
17545 if (ElementBits < 32) {
17546 // No floating point type available, if we can't use the bit operations
17547 // for masking/blending then decompose into 128-bit vectors.
17548 if (SDValue V = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
17549 Subtarget, DAG))
17550 return V;
17551 if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
17552 return V;
17553 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
17554 }
17555
17556 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
17557 VT.getVectorNumElements());
17558 V1 = DAG.getBitcast(FpVT, V1);
17559 V2 = DAG.getBitcast(FpVT, V2);
17560 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
17561 }
17562
17563 switch (VT.SimpleTy) {
17564 case MVT::v4f64:
17565 return lowerV4F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17566 case MVT::v4i64:
17567 return lowerV4I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17568 case MVT::v8f32:
17569 return lowerV8F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17570 case MVT::v8i32:
17571 return lowerV8I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17572 case MVT::v16i16:
17573 return lowerV16I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17574 case MVT::v32i8:
17575 return lowerV32I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17576
17577 default:
17578 llvm_unreachable("Not a valid 256-bit x86 vector type!")::llvm::llvm_unreachable_internal("Not a valid 256-bit x86 vector type!"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17578)
;
17579 }
17580}
17581
17582/// Try to lower a vector shuffle as a 128-bit shuffles.
17583static SDValue lowerV4X128Shuffle(const SDLoc &DL, MVT VT, ArrayRef<int> Mask,
17584 const APInt &Zeroable, SDValue V1, SDValue V2,
17585 const X86Subtarget &Subtarget,
17586 SelectionDAG &DAG) {
17587 assert(VT.getScalarSizeInBits() == 64 &&(static_cast <bool> (VT.getScalarSizeInBits() == 64 &&
"Unexpected element type size for 128bit shuffle.") ? void (
0) : __assert_fail ("VT.getScalarSizeInBits() == 64 && \"Unexpected element type size for 128bit shuffle.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17588, __extension__ __PRETTY_FUNCTION__))
17588 "Unexpected element type size for 128bit shuffle.")(static_cast <bool> (VT.getScalarSizeInBits() == 64 &&
"Unexpected element type size for 128bit shuffle.") ? void (
0) : __assert_fail ("VT.getScalarSizeInBits() == 64 && \"Unexpected element type size for 128bit shuffle.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17588, __extension__ __PRETTY_FUNCTION__))
;
17589
17590 // To handle 256 bit vector requires VLX and most probably
17591 // function lowerV2X128VectorShuffle() is better solution.
17592 assert(VT.is512BitVector() && "Unexpected vector size for 512bit shuffle.")(static_cast <bool> (VT.is512BitVector() && "Unexpected vector size for 512bit shuffle."
) ? void (0) : __assert_fail ("VT.is512BitVector() && \"Unexpected vector size for 512bit shuffle.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17592, __extension__ __PRETTY_FUNCTION__))
;
17593
17594 // TODO - use Zeroable like we do for lowerV2X128VectorShuffle?
17595 SmallVector<int, 4> Widened128Mask;
17596 if (!canWidenShuffleElements(Mask, Widened128Mask))
17597 return SDValue();
17598 assert(Widened128Mask.size() == 4 && "Shuffle widening mismatch")(static_cast <bool> (Widened128Mask.size() == 4 &&
"Shuffle widening mismatch") ? void (0) : __assert_fail ("Widened128Mask.size() == 4 && \"Shuffle widening mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17598, __extension__ __PRETTY_FUNCTION__))
;
17599
17600 // Try to use an insert into a zero vector.
17601 if (Widened128Mask[0] == 0 && (Zeroable & 0xf0) == 0xf0 &&
17602 (Widened128Mask[1] == 1 || (Zeroable & 0x0c) == 0x0c)) {
17603 unsigned NumElts = ((Zeroable & 0x0c) == 0x0c) ? 2 : 4;
17604 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
17605 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
17606 DAG.getIntPtrConstant(0, DL));
17607 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
17608 getZeroVector(VT, Subtarget, DAG, DL), LoV,
17609 DAG.getIntPtrConstant(0, DL));
17610 }
17611
17612 // Check for patterns which can be matched with a single insert of a 256-bit
17613 // subvector.
17614 bool OnlyUsesV1 = isShuffleEquivalent(Mask, {0, 1, 2, 3, 0, 1, 2, 3}, V1, V2);
17615 if (OnlyUsesV1 ||
17616 isShuffleEquivalent(Mask, {0, 1, 2, 3, 8, 9, 10, 11}, V1, V2)) {
17617 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 4);
17618 SDValue SubVec =
17619 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, OnlyUsesV1 ? V1 : V2,
17620 DAG.getIntPtrConstant(0, DL));
17621 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
17622 DAG.getIntPtrConstant(4, DL));
17623 }
17624
17625 // See if this is an insertion of the lower 128-bits of V2 into V1.
17626 bool IsInsert = true;
17627 int V2Index = -1;
17628 for (int i = 0; i < 4; ++i) {
17629 assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value")(static_cast <bool> (Widened128Mask[i] >= -1 &&
"Illegal shuffle sentinel value") ? void (0) : __assert_fail
("Widened128Mask[i] >= -1 && \"Illegal shuffle sentinel value\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17629, __extension__ __PRETTY_FUNCTION__))
;
17630 if (Widened128Mask[i] < 0)
17631 continue;
17632
17633 // Make sure all V1 subvectors are in place.
17634 if (Widened128Mask[i] < 4) {
17635 if (Widened128Mask[i] != i) {
17636 IsInsert = false;
17637 break;
17638 }
17639 } else {
17640 // Make sure we only have a single V2 index and its the lowest 128-bits.
17641 if (V2Index >= 0 || Widened128Mask[i] != 4) {
17642 IsInsert = false;
17643 break;
17644 }
17645 V2Index = i;
17646 }
17647 }
17648 if (IsInsert && V2Index >= 0) {
17649 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
17650 SDValue Subvec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
17651 DAG.getIntPtrConstant(0, DL));
17652 return insert128BitVector(V1, Subvec, V2Index * 2, DAG, DL);
17653 }
17654
17655 // See if we can widen to a 256-bit lane shuffle, we're going to lose 128-lane
17656 // UNDEF info by lowering to X86ISD::SHUF128 anyway, so by widening where
17657 // possible we at least ensure the lanes stay sequential to help later
17658 // combines.
17659 SmallVector<int, 2> Widened256Mask;
17660 if (canWidenShuffleElements(Widened128Mask, Widened256Mask)) {
17661 Widened128Mask.clear();
17662 narrowShuffleMaskElts(2, Widened256Mask, Widened128Mask);
17663 }
17664
17665 // Try to lower to vshuf64x2/vshuf32x4.
17666 SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
17667 unsigned PermMask = 0;
17668 // Insure elements came from the same Op.
17669 for (int i = 0; i < 4; ++i) {
17670 assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value")(static_cast <bool> (Widened128Mask[i] >= -1 &&
"Illegal shuffle sentinel value") ? void (0) : __assert_fail
("Widened128Mask[i] >= -1 && \"Illegal shuffle sentinel value\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17670, __extension__ __PRETTY_FUNCTION__))
;
17671 if (Widened128Mask[i] < 0)
17672 continue;
17673
17674 SDValue Op = Widened128Mask[i] >= 4 ? V2 : V1;
17675 unsigned OpIndex = i / 2;
17676 if (Ops[OpIndex].isUndef())
17677 Ops[OpIndex] = Op;
17678 else if (Ops[OpIndex] != Op)
17679 return SDValue();
17680
17681 // Convert the 128-bit shuffle mask selection values into 128-bit selection
17682 // bits defined by a vshuf64x2 instruction's immediate control byte.
17683 PermMask |= (Widened128Mask[i] % 4) << (i * 2);
17684 }
17685
17686 return DAG.getNode(X86ISD::SHUF128, DL, VT, Ops[0], Ops[1],
17687 DAG.getTargetConstant(PermMask, DL, MVT::i8));
17688}
17689
17690/// Handle lowering of 8-lane 64-bit floating point shuffles.
17691static SDValue lowerV8F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17692 const APInt &Zeroable, SDValue V1, SDValue V2,
17693 const X86Subtarget &Subtarget,
17694 SelectionDAG &DAG) {
17695 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!")(static_cast <bool> (V1.getSimpleValueType() == MVT::v8f64
&& "Bad operand type!") ? void (0) : __assert_fail (
"V1.getSimpleValueType() == MVT::v8f64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17695, __extension__ __PRETTY_FUNCTION__))
;
17696 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!")(static_cast <bool> (V2.getSimpleValueType() == MVT::v8f64
&& "Bad operand type!") ? void (0) : __assert_fail (
"V2.getSimpleValueType() == MVT::v8f64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17696, __extension__ __PRETTY_FUNCTION__))
;
17697 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!")(static_cast <bool> (Mask.size() == 8 && "Unexpected mask size for v8 shuffle!"
) ? void (0) : __assert_fail ("Mask.size() == 8 && \"Unexpected mask size for v8 shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17697, __extension__ __PRETTY_FUNCTION__))
;
17698
17699 if (V2.isUndef()) {
17700 // Use low duplicate instructions for masks that match their pattern.
17701 if (isShuffleEquivalent(Mask, {0, 0, 2, 2, 4, 4, 6, 6}, V1, V2))
17702 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v8f64, V1);
17703
17704 if (!is128BitLaneCrossingShuffleMask(MVT::v8f64, Mask)) {
17705 // Non-half-crossing single input shuffles can be lowered with an
17706 // interleaved permutation.
17707 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
17708 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3) |
17709 ((Mask[4] == 5) << 4) | ((Mask[5] == 5) << 5) |
17710 ((Mask[6] == 7) << 6) | ((Mask[7] == 7) << 7);
17711 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f64, V1,
17712 DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
17713 }
17714
17715 SmallVector<int, 4> RepeatedMask;
17716 if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask))
17717 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8f64, V1,
17718 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17719 }
17720
17721 if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8f64, Mask, Zeroable, V1,
17722 V2, Subtarget, DAG))
17723 return Shuf128;
17724
17725 if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
17726 return Unpck;
17727
17728 // Check if the blend happens to exactly fit that of SHUFPD.
17729 if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v8f64, V1, V2, Mask,
17730 Zeroable, Subtarget, DAG))
17731 return Op;
17732
17733 if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8f64, Zeroable, Mask, V1, V2,
17734 DAG, Subtarget))
17735 return V;
17736
17737 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f64, V1, V2, Mask,
17738 Zeroable, Subtarget, DAG))
17739 return Blend;
17740
17741 return lowerShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, Subtarget, DAG);
17742}
17743
17744/// Handle lowering of 16-lane 32-bit floating point shuffles.
17745static SDValue lowerV16F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17746 const APInt &Zeroable, SDValue V1, SDValue V2,
17747 const X86Subtarget &Subtarget,
17748 SelectionDAG &DAG) {
17749 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!")(static_cast <bool> (V1.getSimpleValueType() == MVT::v16f32
&& "Bad operand type!") ? void (0) : __assert_fail (
"V1.getSimpleValueType() == MVT::v16f32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17749, __extension__ __PRETTY_FUNCTION__))
;
17750 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!")(static_cast <bool> (V2.getSimpleValueType() == MVT::v16f32
&& "Bad operand type!") ? void (0) : __assert_fail (
"V2.getSimpleValueType() == MVT::v16f32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17750, __extension__ __PRETTY_FUNCTION__))
;
17751 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!")(static_cast <bool> (Mask.size() == 16 && "Unexpected mask size for v16 shuffle!"
) ? void (0) : __assert_fail ("Mask.size() == 16 && \"Unexpected mask size for v16 shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17751, __extension__ __PRETTY_FUNCTION__))
;
17752
17753 // If the shuffle mask is repeated in each 128-bit lane, we have many more
17754 // options to efficiently lower the shuffle.
17755 SmallVector<int, 4> RepeatedMask;
17756 if (is128BitLaneRepeatedShuffleMask(MVT::v16f32, Mask, RepeatedMask)) {
17757 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!")(static_cast <bool> (RepeatedMask.size() == 4 &&
"Unexpected repeated mask size!") ? void (0) : __assert_fail
("RepeatedMask.size() == 4 && \"Unexpected repeated mask size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17757, __extension__ __PRETTY_FUNCTION__))
;
17758
17759 // Use even/odd duplicate instructions for masks that match their pattern.
17760 if (isShuffleEquivalent(RepeatedMask, {0, 0, 2, 2}, V1, V2))
17761 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v16f32, V1);
17762 if (isShuffleEquivalent(RepeatedMask, {1, 1, 3, 3}, V1, V2))
17763 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v16f32, V1);
17764
17765 if (V2.isUndef())
17766 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v16f32, V1,
17767 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17768
17769 // Use dedicated unpack instructions for masks that match their pattern.
17770 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
17771 return V;
17772
17773 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16f32, V1, V2, Mask,
17774 Zeroable, Subtarget, DAG))
17775 return Blend;
17776
17777 // Otherwise, fall back to a SHUFPS sequence.
17778 return lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask, V1, V2, DAG);
17779 }
17780
17781 // Try to create an in-lane repeating shuffle mask and then shuffle the
17782 // results into the target lanes.
17783 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17784 DL, MVT::v16f32, V1, V2, Mask, Subtarget, DAG))
17785 return V;
17786
17787 // If we have a single input shuffle with different shuffle patterns in the
17788 // 128-bit lanes and don't lane cross, use variable mask VPERMILPS.
17789 if (V2.isUndef() &&
17790 !is128BitLaneCrossingShuffleMask(MVT::v16f32, Mask)) {
17791 SDValue VPermMask = getConstVector(Mask, MVT::v16i32, DAG, DL, true);
17792 return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v16f32, V1, VPermMask);
17793 }
17794
17795 // If we have AVX512F support, we can use VEXPAND.
17796 if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v16f32, Zeroable, Mask,
17797 V1, V2, DAG, Subtarget))
17798 return V;
17799
17800 return lowerShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, Subtarget, DAG);
17801}
17802
17803/// Handle lowering of 8-lane 64-bit integer shuffles.
17804static SDValue lowerV8I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17805 const APInt &Zeroable, SDValue V1, SDValue V2,
17806 const X86Subtarget &Subtarget,
17807 SelectionDAG &DAG) {
17808 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!")(static_cast <bool> (V1.getSimpleValueType() == MVT::v8i64
&& "Bad operand type!") ? void (0) : __assert_fail (
"V1.getSimpleValueType() == MVT::v8i64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17808, __extension__ __PRETTY_FUNCTION__))
;
17809 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!")(static_cast <bool> (V2.getSimpleValueType() == MVT::v8i64
&& "Bad operand type!") ? void (0) : __assert_fail (
"V2.getSimpleValueType() == MVT::v8i64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17809, __extension__ __PRETTY_FUNCTION__))
;
17810 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!")(static_cast <bool> (Mask.size() == 8 && "Unexpected mask size for v8 shuffle!"
) ? void (0) : __assert_fail ("Mask.size() == 8 && \"Unexpected mask size for v8 shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17810, __extension__ __PRETTY_FUNCTION__))
;
17811
17812 if (V2.isUndef()) {
17813 // When the shuffle is mirrored between the 128-bit lanes of the unit, we
17814 // can use lower latency instructions that will operate on all four
17815 // 128-bit lanes.
17816 SmallVector<int, 2> Repeated128Mask;
17817 if (is128BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated128Mask)) {
17818 SmallVector<int, 4> PSHUFDMask;
17819 narrowShuffleMaskElts(2, Repeated128Mask, PSHUFDMask);
17820 return DAG.getBitcast(
17821 MVT::v8i64,
17822 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32,
17823 DAG.getBitcast(MVT::v16i32, V1),
17824 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
17825 }
17826
17827 SmallVector<int, 4> Repeated256Mask;
17828 if (is256BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated256Mask))
17829 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8i64, V1,
17830 getV4X86ShuffleImm8ForMask(Repeated256Mask, DL, DAG));
17831 }
17832
17833 if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8i64, Mask, Zeroable, V1,
17834 V2, Subtarget, DAG))
17835 return Shuf128;
17836
17837 // Try to use shift instructions.
17838 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i64, V1, V2, Mask,
17839 Zeroable, Subtarget, DAG))
17840 return Shift;
17841
17842 // Try to use VALIGN.
17843 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i64, V1, V2, Mask,
17844 Subtarget, DAG))
17845 return Rotate;
17846
17847 // Try to use PALIGNR.
17848 if (Subtarget.hasBWI())
17849 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i64, V1, V2, Mask,
17850 Subtarget, DAG))
17851 return Rotate;
17852
17853 if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
17854 return Unpck;
17855
17856 // If we have AVX512F support, we can use VEXPAND.
17857 if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8i64, Zeroable, Mask, V1, V2,
17858 DAG, Subtarget))
17859 return V;
17860
17861 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i64, V1, V2, Mask,
17862 Zeroable, Subtarget, DAG))
17863 return Blend;
17864
17865 return lowerShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, Subtarget, DAG);
17866}
17867
17868/// Handle lowering of 16-lane 32-bit integer shuffles.
17869static SDValue lowerV16I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17870 const APInt &Zeroable, SDValue V1, SDValue V2,
17871 const X86Subtarget &Subtarget,
17872 SelectionDAG &DAG) {
17873 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!")(static_cast <bool> (V1.getSimpleValueType() == MVT::v16i32
&& "Bad operand type!") ? void (0) : __assert_fail (
"V1.getSimpleValueType() == MVT::v16i32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17873, __extension__ __PRETTY_FUNCTION__))
;
17874 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!")(static_cast <bool> (V2.getSimpleValueType() == MVT::v16i32
&& "Bad operand type!") ? void (0) : __assert_fail (
"V2.getSimpleValueType() == MVT::v16i32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17874, __extension__ __PRETTY_FUNCTION__))
;
17875 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!")(static_cast <bool> (Mask.size() == 16 && "Unexpected mask size for v16 shuffle!"
) ? void (0) : __assert_fail ("Mask.size() == 16 && \"Unexpected mask size for v16 shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17875, __extension__ __PRETTY_FUNCTION__))
;
17876
17877 // Whenever we can lower this as a zext, that instruction is strictly faster
17878 // than any alternative. It also allows us to fold memory operands into the
17879 // shuffle in many cases.
17880 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
17881 DL, MVT::v16i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
17882 return ZExt;
17883
17884 // If the shuffle mask is repeated in each 128-bit lane we can use more
17885 // efficient instructions that mirror the shuffles across the four 128-bit
17886 // lanes.
17887 SmallVector<int, 4> RepeatedMask;
17888 bool Is128BitLaneRepeatedShuffle =
17889 is128BitLaneRepeatedShuffleMask(MVT::v16i32, Mask, RepeatedMask);
17890 if (Is128BitLaneRepeatedShuffle) {
17891 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!")(static_cast <bool> (RepeatedMask.size() == 4 &&
"Unexpected repeated mask size!") ? void (0) : __assert_fail
("RepeatedMask.size() == 4 && \"Unexpected repeated mask size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17891, __extension__ __PRETTY_FUNCTION__))
;
17892 if (V2.isUndef())
17893 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32, V1,
17894 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17895
17896 // Use dedicated unpack instructions for masks that match their pattern.
17897 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
17898 return V;
17899 }
17900
17901 // Try to use shift instructions.
17902 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v16i32, V1, V2, Mask,
17903 Zeroable, Subtarget, DAG))
17904 return Shift;
17905
17906 // Try to use VALIGN.
17907 if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v16i32, V1, V2, Mask,
17908 Subtarget, DAG))
17909 return Rotate;
17910
17911 // Try to use byte rotation instructions.
17912 if (Subtarget.hasBWI())
17913 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i32, V1, V2, Mask,
17914 Subtarget, DAG))
17915 return Rotate;
17916
17917 // Assume that a single SHUFPS is faster than using a permv shuffle.
17918 // If some CPU is harmed by the domain switch, we can fix it in a later pass.
17919 if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
17920 SDValue CastV1 = DAG.getBitcast(MVT::v16f32, V1);
17921 SDValue CastV2 = DAG.getBitcast(MVT::v16f32, V2);
17922 SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask,
17923 CastV1, CastV2, DAG);
17924 return DAG.getBitcast(MVT::v16i32, ShufPS);
17925 }
17926
17927 // Try to create an in-lane repeating shuffle mask and then shuffle the
17928 // results into the target lanes.
17929 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17930 DL, MVT::v16i32, V1, V2, Mask, Subtarget, DAG))
17931 return V;
17932
17933 // If we have AVX512F support, we can use VEXPAND.
17934 if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v16i32, Zeroable, Mask, V1, V2,
17935 DAG, Subtarget))
17936 return V;
17937
17938 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i32, V1, V2, Mask,
17939 Zeroable, Subtarget, DAG))
17940 return Blend;
17941
17942 return lowerShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, Subtarget, DAG);
17943}
17944
17945/// Handle lowering of 32-lane 16-bit integer shuffles.
17946static SDValue lowerV32I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17947 const APInt &Zeroable, SDValue V1, SDValue V2,
17948 const X86Subtarget &Subtarget,
17949 SelectionDAG &DAG) {
17950 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!")(static_cast <bool> (V1.getSimpleValueType() == MVT::v32i16
&& "Bad operand type!") ? void (0) : __assert_fail (
"V1.getSimpleValueType() == MVT::v32i16 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17950, __extension__ __PRETTY_FUNCTION__))
;
17951 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!")(static_cast <bool> (V2.getSimpleValueType() == MVT::v32i16
&& "Bad operand type!") ? void (0) : __assert_fail (
"V2.getSimpleValueType() == MVT::v32i16 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17951, __extension__ __PRETTY_FUNCTION__))
;
17952 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!")(static_cast <bool> (Mask.size() == 32 && "Unexpected mask size for v32 shuffle!"
) ? void (0) : __assert_fail ("Mask.size() == 32 && \"Unexpected mask size for v32 shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17952, __extension__ __PRETTY_FUNCTION__))
;
17953 assert(Subtarget.hasBWI() && "We can only lower v32i16 with AVX-512-BWI!")(static_cast <bool> (Subtarget.hasBWI() && "We can only lower v32i16 with AVX-512-BWI!"
) ? void (0) : __assert_fail ("Subtarget.hasBWI() && \"We can only lower v32i16 with AVX-512-BWI!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 17953, __extension__ __PRETTY_FUNCTION__))
;
17954
17955 // Whenever we can lower this as a zext, that instruction is strictly faster
17956 // than any alternative. It also allows us to fold memory operands into the
17957 // shuffle in many cases.
17958 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
17959 DL, MVT::v32i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
17960 return ZExt;
17961
17962 // Use dedicated unpack instructions for masks that match their pattern.
17963 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i16, Mask, V1, V2, DAG))
17964 return V;
17965
17966 // Use dedicated pack instructions for masks that match their pattern.
17967 if (SDValue V =
17968 lowerShuffleWithPACK(DL, MVT::v32i16, Mask, V1, V2, DAG, Subtarget))
17969 return V;
17970
17971 // Try to use shift instructions.
17972 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v32i16, V1, V2, Mask,
17973 Zeroable, Subtarget, DAG))
17974 return Shift;
17975
17976 // Try to use byte rotation instructions.
17977 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i16, V1, V2, Mask,
17978 Subtarget, DAG))
17979 return Rotate;
17980
17981 if (V2.isUndef()) {
17982 // Try to use bit rotation instructions.
17983 if (SDValue Rotate =
17984 lowerShuffleAsBitRotate(DL, MVT::v32i16, V1, Mask, Subtarget, DAG))
17985 return Rotate;
17986
17987 SmallVector<int, 8> RepeatedMask;
17988 if (is128BitLaneRepeatedShuffleMask(MVT::v32i16, Mask, RepeatedMask)) {
17989 // As this is a single-input shuffle, the repeated mask should be
17990 // a strictly valid v8i16 mask that we can pass through to the v8i16
17991 // lowering to handle even the v32 case.
17992 return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v32i16, V1,
17993 RepeatedMask, Subtarget, DAG);
17994 }
17995 }
17996
17997 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i16, V1, V2, Mask,
17998 Zeroable, Subtarget, DAG))
17999 return Blend;
18000
18001 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i16, Mask, V1, V2,
18002 Zeroable, Subtarget, DAG))
18003 return PSHUFB;
18004
18005 return lowerShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, Subtarget, DAG);
18006}
18007
18008/// Handle lowering of 64-lane 8-bit integer shuffles.
18009static SDValue lowerV64I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
18010 const APInt &Zeroable, SDValue V1, SDValue V2,
18011 const X86Subtarget &Subtarget,
18012 SelectionDAG &DAG) {
18013 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!")(static_cast <bool> (V1.getSimpleValueType() == MVT::v64i8
&& "Bad operand type!") ? void (0) : __assert_fail (
"V1.getSimpleValueType() == MVT::v64i8 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18013, __extension__ __PRETTY_FUNCTION__))
;
18014 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!")(static_cast <bool> (V2.getSimpleValueType() == MVT::v64i8
&& "Bad operand type!") ? void (0) : __assert_fail (
"V2.getSimpleValueType() == MVT::v64i8 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18014, __extension__ __PRETTY_FUNCTION__))
;
18015 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!")(static_cast <bool> (Mask.size() == 64 && "Unexpected mask size for v64 shuffle!"
) ? void (0) : __assert_fail ("Mask.size() == 64 && \"Unexpected mask size for v64 shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18015, __extension__ __PRETTY_FUNCTION__))
;
18016 assert(Subtarget.hasBWI() && "We can only lower v64i8 with AVX-512-BWI!")(static_cast <bool> (Subtarget.hasBWI() && "We can only lower v64i8 with AVX-512-BWI!"
) ? void (0) : __assert_fail ("Subtarget.hasBWI() && \"We can only lower v64i8 with AVX-512-BWI!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18016, __extension__ __PRETTY_FUNCTION__))
;
18017
18018 // Whenever we can lower this as a zext, that instruction is strictly faster
18019 // than any alternative. It also allows us to fold memory operands into the
18020 // shuffle in many cases.
18021 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
18022 DL, MVT::v64i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
18023 return ZExt;
18024
18025 // Use dedicated unpack instructions for masks that match their pattern.
18026 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v64i8, Mask, V1, V2, DAG))
18027 return V;
18028
18029 // Use dedicated pack instructions for masks that match their pattern.
18030 if (SDValue V = lowerShuffleWithPACK(DL, MVT::v64i8, Mask, V1, V2, DAG,
18031 Subtarget))
18032 return V;
18033
18034 // Try to use shift instructions.
18035 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v64i8, V1, V2, Mask,
18036 Zeroable, Subtarget, DAG))
18037 return Shift;
18038
18039 // Try to use byte rotation instructions.
18040 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v64i8, V1, V2, Mask,
18041 Subtarget, DAG))
18042 return Rotate;
18043
18044 // Try to use bit rotation instructions.
18045 if (V2.isUndef())
18046 if (SDValue Rotate =
18047 lowerShuffleAsBitRotate(DL, MVT::v64i8, V1, Mask, Subtarget, DAG))
18048 return Rotate;
18049
18050 // Lower as AND if possible.
18051 if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v64i8, V1, V2, Mask,
18052 Zeroable, Subtarget, DAG))
18053 return Masked;
18054
18055 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v64i8, Mask, V1, V2,
18056 Zeroable, Subtarget, DAG))
18057 return PSHUFB;
18058
18059 // VBMI can use VPERMV/VPERMV3 byte shuffles.
18060 if (Subtarget.hasVBMI())
18061 return lowerShuffleWithPERMV(DL, MVT::v64i8, Mask, V1, V2, Subtarget, DAG);
18062
18063 // Try to create an in-lane repeating shuffle mask and then shuffle the
18064 // results into the target lanes.
18065 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
18066 DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
18067 return V;
18068
18069 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v64i8, V1, V2, Mask,
18070 Zeroable, Subtarget, DAG))
18071 return Blend;
18072
18073 // Try to simplify this by merging 128-bit lanes to enable a lane-based
18074 // shuffle.
18075 if (!V2.isUndef())
18076 if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
18077 DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
18078 return Result;
18079
18080 // FIXME: Implement direct support for this type!
18081 return splitAndLowerShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
18082}
18083
18084/// High-level routine to lower various 512-bit x86 vector shuffles.
18085///
18086/// This routine either breaks down the specific type of a 512-bit x86 vector
18087/// shuffle or splits it into two 256-bit shuffles and fuses the results back
18088/// together based on the available instructions.
18089static SDValue lower512BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
18090 MVT VT, SDValue V1, SDValue V2,
18091 const APInt &Zeroable,
18092 const X86Subtarget &Subtarget,
18093 SelectionDAG &DAG) {
18094 assert(Subtarget.hasAVX512() &&(static_cast <bool> (Subtarget.hasAVX512() && "Cannot lower 512-bit vectors w/ basic ISA!"
) ? void (0) : __assert_fail ("Subtarget.hasAVX512() && \"Cannot lower 512-bit vectors w/ basic ISA!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18095, __extension__ __PRETTY_FUNCTION__))
18095 "Cannot lower 512-bit vectors w/ basic ISA!")(static_cast <bool> (Subtarget.hasAVX512() && "Cannot lower 512-bit vectors w/ basic ISA!"
) ? void (0) : __assert_fail ("Subtarget.hasAVX512() && \"Cannot lower 512-bit vectors w/ basic ISA!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18095, __extension__ __PRETTY_FUNCTION__))
;
18096
18097 // If we have a single input to the zero element, insert that into V1 if we
18098 // can do so cheaply.
18099 int NumElts = Mask.size();
18100 int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
18101
18102 if (NumV2Elements == 1 && Mask[0] >= NumElts)
18103 if (SDValue Insertion = lowerShuffleAsElementInsertion(
18104 DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
18105 return Insertion;
18106
18107 // Handle special cases where the lower or upper half is UNDEF.
18108 if (SDValue V =
18109 lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
18110 return V;
18111
18112 // Check for being able to broadcast a single element.
18113 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, Mask,
18114 Subtarget, DAG))
18115 return Broadcast;
18116
18117 if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI()) {
18118 // Try using bit ops for masking and blending before falling back to
18119 // splitting.
18120 if (SDValue V = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
18121 Subtarget, DAG))
18122 return V;
18123 if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
18124 return V;
18125
18126 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
18127 }
18128
18129 // Dispatch to each element type for lowering. If we don't have support for
18130 // specific element type shuffles at 512 bits, immediately split them and
18131 // lower them. Each lowering routine of a given type is allowed to assume that
18132 // the requisite ISA extensions for that element type are available.
18133 switch (VT.SimpleTy) {
18134 case MVT::v8f64:
18135 return lowerV8F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18136 case MVT::v16f32:
18137 return lowerV16F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18138 case MVT::v8i64:
18139 return lowerV8I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18140 case MVT::v16i32:
18141 return lowerV16I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18142 case MVT::v32i16:
18143 return lowerV32I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18144 case MVT::v64i8:
18145 return lowerV64I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18146
18147 default:
18148 llvm_unreachable("Not a valid 512-bit x86 vector type!")::llvm::llvm_unreachable_internal("Not a valid 512-bit x86 vector type!"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18148)
;
18149 }
18150}
18151
18152static SDValue lower1BitShuffleAsKSHIFTR(const SDLoc &DL, ArrayRef<int> Mask,
18153 MVT VT, SDValue V1, SDValue V2,
18154 const X86Subtarget &Subtarget,
18155 SelectionDAG &DAG) {
18156 // Shuffle should be unary.
18157 if (!V2.isUndef())
18158 return SDValue();
18159
18160 int ShiftAmt = -1;
18161 int NumElts = Mask.size();
18162 for (int i = 0; i != NumElts; ++i) {
18163 int M = Mask[i];
18164 assert((M == SM_SentinelUndef || (0 <= M && M < NumElts)) &&(static_cast <bool> ((M == SM_SentinelUndef || (0 <=
M && M < NumElts)) && "Unexpected mask index."
) ? void (0) : __assert_fail ("(M == SM_SentinelUndef || (0 <= M && M < NumElts)) && \"Unexpected mask index.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18165, __extension__ __PRETTY_FUNCTION__))
18165 "Unexpected mask index.")(static_cast <bool> ((M == SM_SentinelUndef || (0 <=
M && M < NumElts)) && "Unexpected mask index."
) ? void (0) : __assert_fail ("(M == SM_SentinelUndef || (0 <= M && M < NumElts)) && \"Unexpected mask index.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18165, __extension__ __PRETTY_FUNCTION__))
;
18166 if (M < 0)
18167 continue;
18168
18169 // The first non-undef element determines our shift amount.
18170 if (ShiftAmt < 0) {
18171 ShiftAmt = M - i;
18172 // Need to be shifting right.
18173 if (ShiftAmt <= 0)
18174 return SDValue();
18175 }
18176 // All non-undef elements must shift by the same amount.
18177 if (ShiftAmt != M - i)
18178 return SDValue();
18179 }
18180 assert(ShiftAmt >= 0 && "All undef?")(static_cast <bool> (ShiftAmt >= 0 && "All undef?"
) ? void (0) : __assert_fail ("ShiftAmt >= 0 && \"All undef?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18180, __extension__ __PRETTY_FUNCTION__))
;
18181
18182 // Great we found a shift right.
18183 MVT WideVT = VT;
18184 if ((!Subtarget.hasDQI() && NumElts == 8) || NumElts < 8)
18185 WideVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
18186 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT,
18187 DAG.getUNDEF(WideVT), V1,
18188 DAG.getIntPtrConstant(0, DL));
18189 Res = DAG.getNode(X86ISD::KSHIFTR, DL, WideVT, Res,
18190 DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
18191 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
18192 DAG.getIntPtrConstant(0, DL));
18193}
18194
18195// Determine if this shuffle can be implemented with a KSHIFT instruction.
18196// Returns the shift amount if possible or -1 if not. This is a simplified
18197// version of matchShuffleAsShift.
18198static int match1BitShuffleAsKSHIFT(unsigned &Opcode, ArrayRef<int> Mask,
18199 int MaskOffset, const APInt &Zeroable) {
18200 int Size = Mask.size();
18201
18202 auto CheckZeros = [&](int Shift, bool Left) {
18203 for (int j = 0; j < Shift; ++j)
18204 if (!Zeroable[j + (Left ? 0 : (Size - Shift))])
18205 return false;
18206
18207 return true;
18208 };
18209
18210 auto MatchShift = [&](int Shift, bool Left) {
18211 unsigned Pos = Left ? Shift : 0;
18212 unsigned Low = Left ? 0 : Shift;
18213 unsigned Len = Size - Shift;
18214 return isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset);
18215 };
18216
18217 for (int Shift = 1; Shift != Size; ++Shift)
18218 for (bool Left : {true, false})
18219 if (CheckZeros(Shift, Left) && MatchShift(Shift, Left)) {
18220 Opcode = Left ? X86ISD::KSHIFTL : X86ISD::KSHIFTR;
18221 return Shift;
18222 }
18223
18224 return -1;
18225}
18226
18227
18228// Lower vXi1 vector shuffles.
18229// There is no a dedicated instruction on AVX-512 that shuffles the masks.
18230// The only way to shuffle bits is to sign-extend the mask vector to SIMD
18231// vector, shuffle and then truncate it back.
18232static SDValue lower1BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
18233 MVT VT, SDValue V1, SDValue V2,
18234 const APInt &Zeroable,
18235 const X86Subtarget &Subtarget,
18236 SelectionDAG &DAG) {
18237 assert(Subtarget.hasAVX512() &&(static_cast <bool> (Subtarget.hasAVX512() && "Cannot lower 512-bit vectors w/o basic ISA!"
) ? void (0) : __assert_fail ("Subtarget.hasAVX512() && \"Cannot lower 512-bit vectors w/o basic ISA!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18238, __extension__ __PRETTY_FUNCTION__))
18238 "Cannot lower 512-bit vectors w/o basic ISA!")(static_cast <bool> (Subtarget.hasAVX512() && "Cannot lower 512-bit vectors w/o basic ISA!"
) ? void (0) : __assert_fail ("Subtarget.hasAVX512() && \"Cannot lower 512-bit vectors w/o basic ISA!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18238, __extension__ __PRETTY_FUNCTION__))
;
18239
18240 int NumElts = Mask.size();
18241
18242 // Try to recognize shuffles that are just padding a subvector with zeros.
18243 int SubvecElts = 0;
18244 int Src = -1;
18245 for (int i = 0; i != NumElts; ++i) {
18246 if (Mask[i] >= 0) {
18247 // Grab the source from the first valid mask. All subsequent elements need
18248 // to use this same source.
18249 if (Src < 0)
18250 Src = Mask[i] / NumElts;
18251 if (Src != (Mask[i] / NumElts) || (Mask[i] % NumElts) != i)
18252 break;
18253 }
18254
18255 ++SubvecElts;
18256 }
18257 assert(SubvecElts != NumElts && "Identity shuffle?")(static_cast <bool> (SubvecElts != NumElts && "Identity shuffle?"
) ? void (0) : __assert_fail ("SubvecElts != NumElts && \"Identity shuffle?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18257, __extension__ __PRETTY_FUNCTION__))
;
18258
18259 // Clip to a power 2.
18260 SubvecElts = PowerOf2Floor(SubvecElts);
18261
18262 // Make sure the number of zeroable bits in the top at least covers the bits
18263 // not covered by the subvector.
18264 if ((int)Zeroable.countLeadingOnes() >= (NumElts - SubvecElts)) {
18265 assert(Src >= 0 && "Expected a source!")(static_cast <bool> (Src >= 0 && "Expected a source!"
) ? void (0) : __assert_fail ("Src >= 0 && \"Expected a source!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18265, __extension__ __PRETTY_FUNCTION__))
;
18266 MVT ExtractVT = MVT::getVectorVT(MVT::i1, SubvecElts);
18267 SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT,
18268 Src == 0 ? V1 : V2,
18269 DAG.getIntPtrConstant(0, DL));
18270 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
18271 DAG.getConstant(0, DL, VT),
18272 Extract, DAG.getIntPtrConstant(0, DL));
18273 }
18274
18275 // Try a simple shift right with undef elements. Later we'll try with zeros.
18276 if (SDValue Shift = lower1BitShuffleAsKSHIFTR(DL, Mask, VT, V1, V2, Subtarget,
18277 DAG))
18278 return Shift;
18279
18280 // Try to match KSHIFTs.
18281 unsigned Offset = 0;
18282 for (SDValue V : { V1, V2 }) {
18283 unsigned Opcode;
18284 int ShiftAmt = match1BitShuffleAsKSHIFT(Opcode, Mask, Offset, Zeroable);
18285 if (ShiftAmt >= 0) {
18286 MVT WideVT = VT;
18287 if ((!Subtarget.hasDQI() && NumElts == 8) || NumElts < 8)
18288 WideVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
18289 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT,
18290 DAG.getUNDEF(WideVT), V,
18291 DAG.getIntPtrConstant(0, DL));
18292 // Widened right shifts need two shifts to ensure we shift in zeroes.
18293 if (Opcode == X86ISD::KSHIFTR && WideVT != VT) {
18294 int WideElts = WideVT.getVectorNumElements();
18295 // Shift left to put the original vector in the MSBs of the new size.
18296 Res = DAG.getNode(X86ISD::KSHIFTL, DL, WideVT, Res,
18297 DAG.getTargetConstant(WideElts - NumElts, DL, MVT::i8));
18298 // Increase the shift amount to account for the left shift.
18299 ShiftAmt += WideElts - NumElts;
18300 }
18301
18302 Res = DAG.getNode(Opcode, DL, WideVT, Res,
18303 DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
18304 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
18305 DAG.getIntPtrConstant(0, DL));
18306 }
18307 Offset += NumElts; // Increment for next iteration.
18308 }
18309
18310
18311
18312 MVT ExtVT;
18313 switch (VT.SimpleTy) {
18314 default:
18315 llvm_unreachable("Expected a vector of i1 elements")::llvm::llvm_unreachable_internal("Expected a vector of i1 elements"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18315)
;
18316 case MVT::v2i1:
18317 ExtVT = MVT::v2i64;
18318 break;
18319 case MVT::v4i1:
18320 ExtVT = MVT::v4i32;
18321 break;
18322 case MVT::v8i1:
18323 // Take 512-bit type, more shuffles on KNL. If we have VLX use a 256-bit
18324 // shuffle.
18325 ExtVT = Subtarget.hasVLX() ? MVT::v8i32 : MVT::v8i64;
18326 break;
18327 case MVT::v16i1:
18328 // Take 512-bit type, unless we are avoiding 512-bit types and have the
18329 // 256-bit operation available.
18330 ExtVT = Subtarget.canExtendTo512DQ() ? MVT::v16i32 : MVT::v16i16;
18331 break;
18332 case MVT::v32i1:
18333 // Take 512-bit type, unless we are avoiding 512-bit types and have the
18334 // 256-bit operation available.
18335 assert(Subtarget.hasBWI() && "Expected AVX512BW support")(static_cast <bool> (Subtarget.hasBWI() && "Expected AVX512BW support"
) ? void (0) : __assert_fail ("Subtarget.hasBWI() && \"Expected AVX512BW support\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18335, __extension__ __PRETTY_FUNCTION__))
;
18336 ExtVT = Subtarget.canExtendTo512BW() ? MVT::v32i16 : MVT::v32i8;
18337 break;
18338 case MVT::v64i1:
18339 // Fall back to scalarization. FIXME: We can do better if the shuffle
18340 // can be partitioned cleanly.
18341 if (!Subtarget.useBWIRegs())
18342 return SDValue();
18343 ExtVT = MVT::v64i8;
18344 break;
18345 }
18346
18347 V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
18348 V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
18349
18350 SDValue Shuffle = DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask);
18351 // i1 was sign extended we can use X86ISD::CVT2MASK.
18352 int NumElems = VT.getVectorNumElements();
18353 if ((Subtarget.hasBWI() && (NumElems >= 32)) ||
18354 (Subtarget.hasDQI() && (NumElems < 32)))
18355 return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, ExtVT),
18356 Shuffle, ISD::SETGT);
18357
18358 return DAG.getNode(ISD::TRUNCATE, DL, VT, Shuffle);
18359}
18360
18361/// Helper function that returns true if the shuffle mask should be
18362/// commuted to improve canonicalization.
18363static bool canonicalizeShuffleMaskWithCommute(ArrayRef<int> Mask) {
18364 int NumElements = Mask.size();
18365
18366 int NumV1Elements = 0, NumV2Elements = 0;
18367 for (int M : Mask)
18368 if (M < 0)
18369 continue;
18370 else if (M < NumElements)
18371 ++NumV1Elements;
18372 else
18373 ++NumV2Elements;
18374
18375 // Commute the shuffle as needed such that more elements come from V1 than
18376 // V2. This allows us to match the shuffle pattern strictly on how many
18377 // elements come from V1 without handling the symmetric cases.
18378 if (NumV2Elements > NumV1Elements)
18379 return true;
18380
18381 assert(NumV1Elements > 0 && "No V1 indices")(static_cast <bool> (NumV1Elements > 0 && "No V1 indices"
) ? void (0) : __assert_fail ("NumV1Elements > 0 && \"No V1 indices\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18381, __extension__ __PRETTY_FUNCTION__))
;
18382
18383 if (NumV2Elements == 0)
18384 return false;
18385
18386 // When the number of V1 and V2 elements are the same, try to minimize the
18387 // number of uses of V2 in the low half of the vector. When that is tied,
18388 // ensure that the sum of indices for V1 is equal to or lower than the sum
18389 // indices for V2. When those are equal, try to ensure that the number of odd
18390 // indices for V1 is lower than the number of odd indices for V2.
18391 if (NumV1Elements == NumV2Elements) {
18392 int LowV1Elements = 0, LowV2Elements = 0;
18393 for (int M : Mask.slice(0, NumElements / 2))
18394 if (M >= NumElements)
18395 ++LowV2Elements;
18396 else if (M >= 0)
18397 ++LowV1Elements;
18398 if (LowV2Elements > LowV1Elements)
18399 return true;
18400 if (LowV2Elements == LowV1Elements) {
18401 int SumV1Indices = 0, SumV2Indices = 0;
18402 for (int i = 0, Size = Mask.size(); i < Size; ++i)
18403 if (Mask[i] >= NumElements)
18404 SumV2Indices += i;
18405 else if (Mask[i] >= 0)
18406 SumV1Indices += i;
18407 if (SumV2Indices < SumV1Indices)
18408 return true;
18409 if (SumV2Indices == SumV1Indices) {
18410 int NumV1OddIndices = 0, NumV2OddIndices = 0;
18411 for (int i = 0, Size = Mask.size(); i < Size; ++i)
18412 if (Mask[i] >= NumElements)
18413 NumV2OddIndices += i % 2;
18414 else if (Mask[i] >= 0)
18415 NumV1OddIndices += i % 2;
18416 if (NumV2OddIndices < NumV1OddIndices)
18417 return true;
18418 }
18419 }
18420 }
18421
18422 return false;
18423}
18424
18425/// Top-level lowering for x86 vector shuffles.
18426///
18427/// This handles decomposition, canonicalization, and lowering of all x86
18428/// vector shuffles. Most of the specific lowering strategies are encapsulated
18429/// above in helper routines. The canonicalization attempts to widen shuffles
18430/// to involve fewer lanes of wider elements, consolidate symmetric patterns
18431/// s.t. only one of the two inputs needs to be tested, etc.
18432static SDValue lowerVECTOR_SHUFFLE(SDValue Op, const X86Subtarget &Subtarget,
18433 SelectionDAG &DAG) {
18434 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
18435 ArrayRef<int> OrigMask = SVOp->getMask();
18436 SDValue V1 = Op.getOperand(0);
18437 SDValue V2 = Op.getOperand(1);
18438 MVT VT = Op.getSimpleValueType();
18439 int NumElements = VT.getVectorNumElements();
18440 SDLoc DL(Op);
18441 bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
18442
18443 assert((VT.getSizeInBits() != 64 || Is1BitVector) &&(static_cast <bool> ((VT.getSizeInBits() != 64 || Is1BitVector
) && "Can't lower MMX shuffles") ? void (0) : __assert_fail
("(VT.getSizeInBits() != 64 || Is1BitVector) && \"Can't lower MMX shuffles\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18444, __extension__ __PRETTY_FUNCTION__))
18444 "Can't lower MMX shuffles")(static_cast <bool> ((VT.getSizeInBits() != 64 || Is1BitVector
) && "Can't lower MMX shuffles") ? void (0) : __assert_fail
("(VT.getSizeInBits() != 64 || Is1BitVector) && \"Can't lower MMX shuffles\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18444, __extension__ __PRETTY_FUNCTION__))
;
18445
18446 bool V1IsUndef = V1.isUndef();
18447 bool V2IsUndef = V2.isUndef();
18448 if (V1IsUndef && V2IsUndef)
18449 return DAG.getUNDEF(VT);
18450
18451 // When we create a shuffle node we put the UNDEF node to second operand,
18452 // but in some cases the first operand may be transformed to UNDEF.
18453 // In this case we should just commute the node.
18454 if (V1IsUndef)
18455 return DAG.getCommutedVectorShuffle(*SVOp);
18456
18457 // Check for non-undef masks pointing at an undef vector and make the masks
18458 // undef as well. This makes it easier to match the shuffle based solely on
18459 // the mask.
18460 if (V2IsUndef &&
18461 any_of(OrigMask, [NumElements](int M) { return M >= NumElements; })) {
18462 SmallVector<int, 8> NewMask(OrigMask.begin(), OrigMask.end());
18463 for (int &M : NewMask)
18464 if (M >= NumElements)
18465 M = -1;
18466 return DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
18467 }
18468
18469 // Check for illegal shuffle mask element index values.
18470 int MaskUpperLimit = OrigMask.size() * (V2IsUndef ? 1 : 2);
18471 (void)MaskUpperLimit;
18472 assert(llvm::all_of(OrigMask,(static_cast <bool> (llvm::all_of(OrigMask, [&](int
M) { return -1 <= M && M < MaskUpperLimit; }) &&
"Out of bounds shuffle index") ? void (0) : __assert_fail ("llvm::all_of(OrigMask, [&](int M) { return -1 <= M && M < MaskUpperLimit; }) && \"Out of bounds shuffle index\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18474, __extension__ __PRETTY_FUNCTION__))
18473 [&](int M) { return -1 <= M && M < MaskUpperLimit; }) &&(static_cast <bool> (llvm::all_of(OrigMask, [&](int
M) { return -1 <= M && M < MaskUpperLimit; }) &&
"Out of bounds shuffle index") ? void (0) : __assert_fail ("llvm::all_of(OrigMask, [&](int M) { return -1 <= M && M < MaskUpperLimit; }) && \"Out of bounds shuffle index\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18474, __extension__ __PRETTY_FUNCTION__))
18474 "Out of bounds shuffle index")(static_cast <bool> (llvm::all_of(OrigMask, [&](int
M) { return -1 <= M && M < MaskUpperLimit; }) &&
"Out of bounds shuffle index") ? void (0) : __assert_fail ("llvm::all_of(OrigMask, [&](int M) { return -1 <= M && M < MaskUpperLimit; }) && \"Out of bounds shuffle index\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18474, __extension__ __PRETTY_FUNCTION__))
;
18475
18476 // We actually see shuffles that are entirely re-arrangements of a set of
18477 // zero inputs. This mostly happens while decomposing complex shuffles into
18478 // simple ones. Directly lower these as a buildvector of zeros.
18479 APInt KnownUndef, KnownZero;
18480 computeZeroableShuffleElements(OrigMask, V1, V2, KnownUndef, KnownZero);
18481
18482 APInt Zeroable = KnownUndef | KnownZero;
18483 if (Zeroable.isAllOnesValue())
18484 return getZeroVector(VT, Subtarget, DAG, DL);
18485
18486 bool V2IsZero = !V2IsUndef && ISD::isBuildVectorAllZeros(V2.getNode());
18487
18488 // Try to collapse shuffles into using a vector type with fewer elements but
18489 // wider element types. We cap this to not form integers or floating point
18490 // elements wider than 64 bits. It does not seem beneficial to form i128
18491 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
18492 SmallVector<int, 16> WidenedMask;
18493 if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
18494 canWidenShuffleElements(OrigMask, Zeroable, V2IsZero, WidenedMask)) {
18495 // Shuffle mask widening should not interfere with a broadcast opportunity
18496 // by obfuscating the operands with bitcasts.
18497 // TODO: Avoid lowering directly from this top-level function: make this
18498 // a query (canLowerAsBroadcast) and defer lowering to the type-based calls.
18499 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, OrigMask,
18500 Subtarget, DAG))
18501 return Broadcast;
18502
18503 MVT NewEltVT = VT.isFloatingPoint()
18504 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
18505 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
18506 int NewNumElts = NumElements / 2;
18507 MVT NewVT = MVT::getVectorVT(NewEltVT, NewNumElts);
18508 // Make sure that the new vector type is legal. For example, v2f64 isn't
18509 // legal on SSE1.
18510 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
18511 if (V2IsZero) {
18512 // Modify the new Mask to take all zeros from the all-zero vector.
18513 // Choose indices that are blend-friendly.
18514 bool UsedZeroVector = false;
18515 assert(is_contained(WidenedMask, SM_SentinelZero) &&(static_cast <bool> (is_contained(WidenedMask, SM_SentinelZero
) && "V2's non-undef elements are used?!") ? void (0)
: __assert_fail ("is_contained(WidenedMask, SM_SentinelZero) && \"V2's non-undef elements are used?!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18516, __extension__ __PRETTY_FUNCTION__))
18516 "V2's non-undef elements are used?!")(static_cast <bool> (is_contained(WidenedMask, SM_SentinelZero
) && "V2's non-undef elements are used?!") ? void (0)
: __assert_fail ("is_contained(WidenedMask, SM_SentinelZero) && \"V2's non-undef elements are used?!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18516, __extension__ __PRETTY_FUNCTION__))
;
18517 for (int i = 0; i != NewNumElts; ++i)
18518 if (WidenedMask[i] == SM_SentinelZero) {
18519 WidenedMask[i] = i + NewNumElts;
18520 UsedZeroVector = true;
18521 }
18522 // Ensure all elements of V2 are zero - isBuildVectorAllZeros permits
18523 // some elements to be undef.
18524 if (UsedZeroVector)
18525 V2 = getZeroVector(NewVT, Subtarget, DAG, DL);
18526 }
18527 V1 = DAG.getBitcast(NewVT, V1);
18528 V2 = DAG.getBitcast(NewVT, V2);
18529 return DAG.getBitcast(
18530 VT, DAG.getVectorShuffle(NewVT, DL, V1, V2, WidenedMask));
18531 }
18532 }
18533
18534 // Commute the shuffle if it will improve canonicalization.
18535 SmallVector<int, 64> Mask(OrigMask.begin(), OrigMask.end());
18536 if (canonicalizeShuffleMaskWithCommute(Mask)) {
18537 ShuffleVectorSDNode::commuteMask(Mask);
18538 std::swap(V1, V2);
18539 }
18540
18541 // For each vector width, delegate to a specialized lowering routine.
18542 if (VT.is128BitVector())
18543 return lower128BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
18544
18545 if (VT.is256BitVector())
18546 return lower256BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
18547
18548 if (VT.is512BitVector())
18549 return lower512BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
18550
18551 if (Is1BitVector)
18552 return lower1BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
18553
18554 llvm_unreachable("Unimplemented!")::llvm::llvm_unreachable_internal("Unimplemented!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18554)
;
18555}
18556
18557/// Try to lower a VSELECT instruction to a vector shuffle.
18558static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
18559 const X86Subtarget &Subtarget,
18560 SelectionDAG &DAG) {
18561 SDValue Cond = Op.getOperand(0);
18562 SDValue LHS = Op.getOperand(1);
18563 SDValue RHS = Op.getOperand(2);
18564 MVT VT = Op.getSimpleValueType();
18565
18566 // Only non-legal VSELECTs reach this lowering, convert those into generic
18567 // shuffles and re-use the shuffle lowering path for blends.
18568 if (ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
18569 SmallVector<int, 32> Mask;
18570 if (createShuffleMaskFromVSELECT(Mask, Cond))
18571 return DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, Mask);
18572 }
18573
18574 return SDValue();
18575}
18576
18577SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
18578 SDValue Cond = Op.getOperand(0);
18579 SDValue LHS = Op.getOperand(1);
18580 SDValue RHS = Op.getOperand(2);
18581
18582 // A vselect where all conditions and data are constants can be optimized into
18583 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
18584 if (ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()) &&
18585 ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
18586 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
18587 return SDValue();
18588
18589 // Try to lower this to a blend-style vector shuffle. This can handle all
18590 // constant condition cases.
18591 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
18592 return BlendOp;
18593
18594 // If this VSELECT has a vector if i1 as a mask, it will be directly matched
18595 // with patterns on the mask registers on AVX-512.
18596 MVT CondVT = Cond.getSimpleValueType();
18597 unsigned CondEltSize = Cond.getScalarValueSizeInBits();
18598 if (CondEltSize == 1)
18599 return Op;
18600
18601 // Variable blends are only legal from SSE4.1 onward.
18602 if (!Subtarget.hasSSE41())
18603 return SDValue();
18604
18605 SDLoc dl(Op);
18606 MVT VT = Op.getSimpleValueType();
18607 unsigned EltSize = VT.getScalarSizeInBits();
18608 unsigned NumElts = VT.getVectorNumElements();
18609
18610 // Expand v32i16/v64i8 without BWI.
18611 if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
18612 return SDValue();
18613
18614 // If the VSELECT is on a 512-bit type, we have to convert a non-i1 condition
18615 // into an i1 condition so that we can use the mask-based 512-bit blend
18616 // instructions.
18617 if (VT.getSizeInBits() == 512) {
18618 // Build a mask by testing the condition against zero.
18619 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
18620 SDValue Mask = DAG.getSetCC(dl, MaskVT, Cond,
18621 DAG.getConstant(0, dl, CondVT),
18622 ISD::SETNE);
18623 // Now return a new VSELECT using the mask.
18624 return DAG.getSelect(dl, VT, Mask, LHS, RHS);
18625 }
18626
18627 // SEXT/TRUNC cases where the mask doesn't match the destination size.
18628 if (CondEltSize != EltSize) {
18629 // If we don't have a sign splat, rely on the expansion.
18630 if (CondEltSize != DAG.ComputeNumSignBits(Cond))
18631 return SDValue();
18632
18633 MVT NewCondSVT = MVT::getIntegerVT(EltSize);
18634 MVT NewCondVT = MVT::getVectorVT(NewCondSVT, NumElts);
18635 Cond = DAG.getSExtOrTrunc(Cond, dl, NewCondVT);
18636 return DAG.getNode(ISD::VSELECT, dl, VT, Cond, LHS, RHS);
18637 }
18638
18639 // Only some types will be legal on some subtargets. If we can emit a legal
18640 // VSELECT-matching blend, return Op, and but if we need to expand, return
18641 // a null value.
18642 switch (VT.SimpleTy) {
18643 default:
18644 // Most of the vector types have blends past SSE4.1.
18645 return Op;
18646
18647 case MVT::v32i8:
18648 // The byte blends for AVX vectors were introduced only in AVX2.
18649 if (Subtarget.hasAVX2())
18650 return Op;
18651
18652 return SDValue();
18653
18654 case MVT::v8i16:
18655 case MVT::v16i16: {
18656 // Bitcast everything to the vXi8 type and use a vXi8 vselect.
18657 MVT CastVT = MVT::getVectorVT(MVT::i8, NumElts * 2);
18658 Cond = DAG.getBitcast(CastVT, Cond);
18659 LHS = DAG.getBitcast(CastVT, LHS);
18660 RHS = DAG.getBitcast(CastVT, RHS);
18661 SDValue Select = DAG.getNode(ISD::VSELECT, dl, CastVT, Cond, LHS, RHS);
18662 return DAG.getBitcast(VT, Select);
18663 }
18664 }
18665}
18666
18667static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
18668 MVT VT = Op.getSimpleValueType();
18669 SDValue Vec = Op.getOperand(0);
18670 SDValue Idx = Op.getOperand(1);
18671 assert(isa<ConstantSDNode>(Idx) && "Constant index expected")(static_cast <bool> (isa<ConstantSDNode>(Idx) &&
"Constant index expected") ? void (0) : __assert_fail ("isa<ConstantSDNode>(Idx) && \"Constant index expected\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18671, __extension__ __PRETTY_FUNCTION__))
;
18672 SDLoc dl(Op);
18673
18674 if (!Vec.getSimpleValueType().is128BitVector())
18675 return SDValue();
18676
18677 if (VT.getSizeInBits() == 8) {
18678 // If IdxVal is 0, it's cheaper to do a move instead of a pextrb, unless
18679 // we're going to zero extend the register or fold the store.
18680 if (llvm::isNullConstant(Idx) && !MayFoldIntoZeroExtend(Op) &&
18681 !MayFoldIntoStore(Op))
18682 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i8,
18683 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
18684 DAG.getBitcast(MVT::v4i32, Vec), Idx));
18685
18686 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
18687 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32, Vec,
18688 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
18689 return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
18690 }
18691
18692 if (VT == MVT::f32) {
18693 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
18694 // the result back to FR32 register. It's only worth matching if the
18695 // result has a single use which is a store or a bitcast to i32. And in
18696 // the case of a store, it's not worth it if the index is a constant 0,
18697 // because a MOVSSmr can be used instead, which is smaller and faster.
18698 if (!Op.hasOneUse())
18699 return SDValue();
18700 SDNode *User = *Op.getNode()->use_begin();
18701 if ((User->getOpcode() != ISD::STORE || isNullConstant(Idx)) &&
18702 (User->getOpcode() != ISD::BITCAST ||
18703 User->getValueType(0) != MVT::i32))
18704 return SDValue();
18705 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
18706 DAG.getBitcast(MVT::v4i32, Vec), Idx);
18707 return DAG.getBitcast(MVT::f32, Extract);
18708 }
18709
18710 if (VT == MVT::i32 || VT == MVT::i64)
18711 return Op;
18712
18713 return SDValue();
18714}
18715
18716/// Extract one bit from mask vector, like v16i1 or v8i1.
18717/// AVX-512 feature.
18718static SDValue ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG,
18719 const X86Subtarget &Subtarget) {
18720 SDValue Vec = Op.getOperand(0);
18721 SDLoc dl(Vec);
18722 MVT VecVT = Vec.getSimpleValueType();
18723 SDValue Idx = Op.getOperand(1);
18724 auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
18725 MVT EltVT = Op.getSimpleValueType();
18726
18727 assert((VecVT.getVectorNumElements() <= 16 || Subtarget.hasBWI()) &&(static_cast <bool> ((VecVT.getVectorNumElements() <=
16 || Subtarget.hasBWI()) && "Unexpected vector type in ExtractBitFromMaskVector"
) ? void (0) : __assert_fail ("(VecVT.getVectorNumElements() <= 16 || Subtarget.hasBWI()) && \"Unexpected vector type in ExtractBitFromMaskVector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18728, __extension__ __PRETTY_FUNCTION__))
18728 "Unexpected vector type in ExtractBitFromMaskVector")(static_cast <bool> ((VecVT.getVectorNumElements() <=
16 || Subtarget.hasBWI()) && "Unexpected vector type in ExtractBitFromMaskVector"
) ? void (0) : __assert_fail ("(VecVT.getVectorNumElements() <= 16 || Subtarget.hasBWI()) && \"Unexpected vector type in ExtractBitFromMaskVector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18728, __extension__ __PRETTY_FUNCTION__))
;
18729
18730 // variable index can't be handled in mask registers,
18731 // extend vector to VR512/128
18732 if (!IdxC) {
18733 unsigned NumElts = VecVT.getVectorNumElements();
18734 // Extending v8i1/v16i1 to 512-bit get better performance on KNL
18735 // than extending to 128/256bit.
18736 MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
18737 MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
18738 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec);
18739 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ExtEltVT, Ext, Idx);
18740 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
18741 }
18742
18743 unsigned IdxVal = IdxC->getZExtValue();
18744 if (IdxVal == 0) // the operation is legal
18745 return Op;
18746
18747 // Extend to natively supported kshift.
18748 unsigned NumElems = VecVT.getVectorNumElements();
18749 MVT WideVecVT = VecVT;
18750 if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8) {
18751 WideVecVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
18752 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVecVT,
18753 DAG.getUNDEF(WideVecVT), Vec,
18754 DAG.getIntPtrConstant(0, dl));
18755 }
18756
18757 // Use kshiftr instruction to move to the lower element.
18758 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideVecVT, Vec,
18759 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
18760
18761 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
18762 DAG.getIntPtrConstant(0, dl));
18763}
18764
18765SDValue
18766X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
18767 SelectionDAG &DAG) const {
18768 SDLoc dl(Op);
18769 SDValue Vec = Op.getOperand(0);
18770 MVT VecVT = Vec.getSimpleValueType();
18771 SDValue Idx = Op.getOperand(1);
18772 auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
18773
18774 if (VecVT.getVectorElementType() == MVT::i1)
18775 return ExtractBitFromMaskVector(Op, DAG, Subtarget);
18776
18777 if (!IdxC) {
18778 // Its more profitable to go through memory (1 cycles throughput)
18779 // than using VMOVD + VPERMV/PSHUFB sequence ( 2/3 cycles throughput)
18780 // IACA tool was used to get performance estimation
18781 // (https://software.intel.com/en-us/articles/intel-architecture-code-analyzer)
18782 //
18783 // example : extractelement <16 x i8> %a, i32 %i
18784 //
18785 // Block Throughput: 3.00 Cycles
18786 // Throughput Bottleneck: Port5
18787 //
18788 // | Num Of | Ports pressure in cycles | |
18789 // | Uops | 0 - DV | 5 | 6 | 7 | |
18790 // ---------------------------------------------
18791 // | 1 | | 1.0 | | | CP | vmovd xmm1, edi
18792 // | 1 | | 1.0 | | | CP | vpshufb xmm0, xmm0, xmm1
18793 // | 2 | 1.0 | 1.0 | | | CP | vpextrb eax, xmm0, 0x0
18794 // Total Num Of Uops: 4
18795 //
18796 //
18797 // Block Throughput: 1.00 Cycles
18798 // Throughput Bottleneck: PORT2_AGU, PORT3_AGU, Port4
18799 //
18800 // | | Ports pressure in cycles | |
18801 // |Uops| 1 | 2 - D |3 - D | 4 | 5 | |
18802 // ---------------------------------------------------------
18803 // |2^ | | 0.5 | 0.5 |1.0| |CP| vmovaps xmmword ptr [rsp-0x18], xmm0
18804 // |1 |0.5| | | |0.5| | lea rax, ptr [rsp-0x18]
18805 // |1 | |0.5, 0.5|0.5, 0.5| | |CP| mov al, byte ptr [rdi+rax*1]
18806 // Total Num Of Uops: 4
18807
18808 return SDValue();
18809 }
18810
18811 unsigned IdxVal = IdxC->getZExtValue();
18812
18813 // If this is a 256-bit vector result, first extract the 128-bit vector and
18814 // then extract the element from the 128-bit vector.
18815 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
18816 // Get the 128-bit vector.
18817 Vec = extract128BitVector(Vec, IdxVal, DAG, dl);
18818 MVT EltVT = VecVT.getVectorElementType();
18819
18820 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
18821 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2")(static_cast <bool> (isPowerOf2_32(ElemsPerChunk) &&
"Elements per chunk not power of 2") ? void (0) : __assert_fail
("isPowerOf2_32(ElemsPerChunk) && \"Elements per chunk not power of 2\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18821, __extension__ __PRETTY_FUNCTION__))
;
18822
18823 // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
18824 // this can be done with a mask.
18825 IdxVal &= ElemsPerChunk - 1;
18826 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
18827 DAG.getIntPtrConstant(IdxVal, dl));
18828 }
18829
18830 assert(VecVT.is128BitVector() && "Unexpected vector length")(static_cast <bool> (VecVT.is128BitVector() && "Unexpected vector length"
) ? void (0) : __assert_fail ("VecVT.is128BitVector() && \"Unexpected vector length\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 18830, __extension__ __PRETTY_FUNCTION__))
;
18831
18832 MVT VT = Op.getSimpleValueType();
18833
18834 if (VT.getSizeInBits() == 16) {
18835 // If IdxVal is 0, it's cheaper to do a move instead of a pextrw, unless
18836 // we're going to zero extend the register or fold the store (SSE41 only).
18837 if (IdxVal == 0 && !MayFoldIntoZeroExtend(Op) &&
18838 !(Subtarget.hasSSE41() && MayFoldIntoStore(Op)))
18839 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
18840 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
18841 DAG.getBitcast(MVT::v4i32, Vec), Idx));
18842
18843 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32, Vec,
18844 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
18845 return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
18846 }
18847
18848 if (Subtarget.hasSSE41())
18849 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
18850 return Res;
18851
18852 // TODO: We only extract a single element from v16i8, we can probably afford
18853 // to be more aggressive here before using the default approach of spilling to
18854 // stack.
18855 if (VT.getSizeInBits() == 8 && Op->isOnlyUserOf(Vec.getNode())) {
18856 // Extract either the lowest i32 or any i16, and extract the sub-byte.
18857 int DWordIdx = IdxVal / 4;
18858 if (DWordIdx == 0) {
18859 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
18860 DAG.getBitcast(MVT::v4i32, Vec),
18861 DAG.getIntPtrConstant(DWordIdx, dl));
18862 int ShiftVal = (IdxVal % 4) * 8;
18863 if (ShiftVal != 0)
18864 Res = DAG.getNode(ISD::SRL, dl, MVT::i32, Res,
18865 DAG.getConstant(ShiftVal, dl, MVT::i8));
18866 return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
18867 }
18868
18869 int WordIdx = IdxVal / 2;
18870 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
18871 DAG.getBitcast(MVT::v8i16, Vec),
18872 DAG.getIntPtrConstant(WordIdx, dl));
18873 int ShiftVal = (IdxVal % 2) * 8;
18874 if (ShiftVal != 0)
18875 Res = DAG.getNode(ISD::SRL, dl, MVT::i16, Res,
18876 DAG.getConstant(ShiftVal, dl, MVT::i8));
18877 return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
18878 }
18879
18880 if (VT.getSizeInBits() == 32) {
18881 if (IdxVal == 0)
18882 return Op;
18883
18884 // SHUFPS the element to the lowest double word, then movss.
18885 int Mask[4] = { static_cast<int>(IdxVal), -1, -1, -1 };
18886 Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
18887 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
18888 DAG.getIntPtrConstant(0, dl));
18889 }
18890
18891 if (VT.getSizeInBits() == 64) {
18892 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
18893 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
18894 // to match extract_elt for f64.
18895 if (IdxVal == 0)
18896 return Op;
18897
18898 // UNPCKHPD the element to the lowest double word, then movsd.
18899 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
18900 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
18901 int Mask[2] = { 1, -1 };
18902 Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
18903 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
18904 DAG.getIntPtrConstant(0, dl));
18905 }
18906
18907 return SDValue();
18908}
18909
18910/// Insert one bit to mask vector, like v16i1 or v8i1.
18911/// AVX-512 feature.
18912static SDValue InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG,
18913 const X86Subtarget &Subtarget) {
18914 SDLoc dl(Op);
18915 SDValue Vec = Op.getOperand(0);
18916 SDValue Elt = Op.getOperand(1);
18917 SDValue Idx = Op.getOperand(2);
18918 MVT VecVT = Vec.getSimpleValueType();
18919
18920 if (!isa<ConstantSDNode>(Idx)) {
18921 // Non constant index. Extend source and destination,
18922 // insert element and then truncate the result.
18923 unsigned NumElts = VecVT.getVectorNumElements();
18924 MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
18925 MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
18926 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
18927 DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec),
18928 DAG.getNode(ISD::SIGN_EXTEND, dl, ExtEltVT, Elt), Idx);
18929 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
18930 }
18931
18932 // Copy into a k-register, extract to v1i1 and insert_subvector.
18933 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i1, Elt);
18934 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VecVT, Vec, EltInVec, Idx);
18935}
18936
18937SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
18938 SelectionDAG &DAG) const {
18939 MVT VT = Op.getSimpleValueType();
18940 MVT EltVT = VT.getVectorElementType();
18941 unsigned NumElts = VT.getVectorNumElements();
18942 unsigned EltSizeInBits = EltVT.getScalarSizeInBits();
18943
18944 if (EltVT == MVT::i1)
18945 return InsertBitToMaskVector(Op, DAG, Subtarget);
18946
18947 SDLoc dl(Op);
18948 SDValue N0 = Op.getOperand(0);
18949 SDValue N1 = Op.getOperand(1);
18950 SDValue N2 = Op.getOperand(2);
18951 auto *N2C = dyn_cast<ConstantSDNode>(N2);
18952
18953 if (!N2C) {
18954 // Variable insertion indices, usually we're better off spilling to stack,
18955 // but AVX512 can use a variable compare+select by comparing against all
18956 // possible vector indices, and FP insertion has less gpr->simd traffic.
18957 if (!(Subtarget.hasBWI() ||
18958 (Subtarget.hasAVX512() && EltSizeInBits >= 32) ||
18959 (Subtarget.hasSSE41() && VT.isFloatingPoint())))
18960 return SDValue();
18961
18962 MVT IdxSVT = MVT::getIntegerVT(EltSizeInBits);
18963 MVT IdxVT = MVT::getVectorVT(IdxSVT, NumElts);
18964 SDValue IdxExt = DAG.getZExtOrTrunc(N2, dl, IdxSVT);
18965 SDValue IdxSplat = DAG.getSplatBuildVector(IdxVT, dl, IdxExt);
18966 SDValue EltSplat = DAG.getSplatBuildVector(VT, dl, N1);
18967
18968 SmallVector<SDValue, 16> RawIndices;
18969 for (unsigned I = 0; I != NumElts; ++I)
18970 RawIndices.push_back(DAG.getConstant(I, dl, IdxSVT));
18971 SDValue Indices = DAG.getBuildVector(IdxVT, dl, RawIndices);
18972
18973 // inselt N0, N1, N2 --> select (SplatN2 == {0,1,2...}) ? SplatN1 : N0.
18974 return DAG.getSelectCC(dl, IdxSplat, Indices, EltSplat, N0,
18975 ISD::CondCode::SETEQ);
18976 }
18977
18978 if (N2C->getAPIntValue().uge(NumElts))
18979 return SDValue();
18980 uint64_t IdxVal = N2C->getZExtValue();
18981
18982 bool IsZeroElt = X86::isZeroNode(N1);
18983 bool IsAllOnesElt = VT.isInteger() && llvm::isAllOnesConstant(N1);
18984
18985 // If we are inserting a element, see if we can do this more efficiently with
18986 // a blend shuffle with a rematerializable vector than a costly integer
18987 // insertion.
18988 if ((IsZeroElt || IsAllOnesElt) && Subtarget.hasSSE41() &&
18989 (16 <= EltSizeInBits || (IsZeroElt && !VT.is128BitVector()))) {
18990 SmallVector<int, 8> BlendMask;
18991 for (unsigned i = 0; i != NumElts; ++i)
18992 BlendMask.push_back(i == IdxVal ? i + NumElts : i);
18993 SDValue CstVector = IsZeroElt ? getZeroVector(VT, Subtarget, DAG, dl)
18994 : getOnesVector(VT, DAG, dl);
18995 return DAG.getVectorShuffle(VT, dl, N0, CstVector, BlendMask);
18996 }
18997
18998 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
18999 // into that, and then insert the subvector back into the result.
19000 if (VT.is256BitVector() || VT.is512BitVector()) {
19001 // With a 256-bit vector, we can insert into the zero element efficiently
19002 // using a blend if we have AVX or AVX2 and the right data type.
19003 if (VT.is256BitVector() && IdxVal == 0) {
19004 // TODO: It is worthwhile to cast integer to floating point and back
19005 // and incur a domain crossing penalty if that's what we'll end up
19006 // doing anyway after extracting to a 128-bit vector.
19007 if ((Subtarget.hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
19008 (Subtarget.hasAVX2() && EltVT == MVT::i32)) {
19009 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
19010 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec,
19011 DAG.getTargetConstant(1, dl, MVT::i8));
19012 }
19013 }
19014
19015 // Get the desired 128-bit vector chunk.
19016 SDValue V = extract128BitVector(N0, IdxVal, DAG, dl);
19017
19018 // Insert the element into the desired chunk.
19019 unsigned NumEltsIn128 = 128 / EltSizeInBits;
19020 assert(isPowerOf2_32(NumEltsIn128))(static_cast <bool> (isPowerOf2_32(NumEltsIn128)) ? void
(0) : __assert_fail ("isPowerOf2_32(NumEltsIn128)", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19020, __extension__ __PRETTY_FUNCTION__))
;
19021 // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
19022 unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
19023
19024 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
19025 DAG.getIntPtrConstant(IdxIn128, dl));
19026
19027 // Insert the changed part back into the bigger vector
19028 return insert128BitVector(N0, V, IdxVal, DAG, dl);
19029 }
19030 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!")(static_cast <bool> (VT.is128BitVector() && "Only 128-bit vector types should be left!"
) ? void (0) : __assert_fail ("VT.is128BitVector() && \"Only 128-bit vector types should be left!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19030, __extension__ __PRETTY_FUNCTION__))
;
19031
19032 // This will be just movd/movq/movss/movsd.
19033 if (IdxVal == 0 && ISD::isBuildVectorAllZeros(N0.getNode())) {
19034 if (EltVT == MVT::i32 || EltVT == MVT::f32 || EltVT == MVT::f64 ||
19035 EltVT == MVT::i64) {
19036 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
19037 return getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
19038 }
19039
19040 // We can't directly insert an i8 or i16 into a vector, so zero extend
19041 // it to i32 first.
19042 if (EltVT == MVT::i16 || EltVT == MVT::i8) {
19043 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, N1);
19044 MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
19045 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, N1);
19046 N1 = getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
19047 return DAG.getBitcast(VT, N1);
19048 }
19049 }
19050
19051 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
19052 // argument. SSE41 required for pinsrb.
19053 if (VT == MVT::v8i16 || (VT == MVT::v16i8 && Subtarget.hasSSE41())) {
19054 unsigned Opc;
19055 if (VT == MVT::v8i16) {
19056 assert(Subtarget.hasSSE2() && "SSE2 required for PINSRW")(static_cast <bool> (Subtarget.hasSSE2() && "SSE2 required for PINSRW"
) ? void (0) : __assert_fail ("Subtarget.hasSSE2() && \"SSE2 required for PINSRW\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19056, __extension__ __PRETTY_FUNCTION__))
;
19057 Opc = X86ISD::PINSRW;
19058 } else {
19059 assert(VT == MVT::v16i8 && "PINSRB requires v16i8 vector")(static_cast <bool> (VT == MVT::v16i8 && "PINSRB requires v16i8 vector"
) ? void (0) : __assert_fail ("VT == MVT::v16i8 && \"PINSRB requires v16i8 vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19059, __extension__ __PRETTY_FUNCTION__))
;
19060 assert(Subtarget.hasSSE41() && "SSE41 required for PINSRB")(static_cast <bool> (Subtarget.hasSSE41() && "SSE41 required for PINSRB"
) ? void (0) : __assert_fail ("Subtarget.hasSSE41() && \"SSE41 required for PINSRB\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19060, __extension__ __PRETTY_FUNCTION__))
;
19061 Opc = X86ISD::PINSRB;
19062 }
19063
19064 assert(N1.getValueType() != MVT::i32 && "Unexpected VT")(static_cast <bool> (N1.getValueType() != MVT::i32 &&
"Unexpected VT") ? void (0) : __assert_fail ("N1.getValueType() != MVT::i32 && \"Unexpected VT\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19064, __extension__ __PRETTY_FUNCTION__))
;
19065 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
19066 N2 = DAG.getTargetConstant(IdxVal, dl, MVT::i8);
19067 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
19068 }
19069
19070 if (Subtarget.hasSSE41()) {
19071 if (EltVT == MVT::f32) {
19072 // Bits [7:6] of the constant are the source select. This will always be
19073 // zero here. The DAG Combiner may combine an extract_elt index into
19074 // these bits. For example (insert (extract, 3), 2) could be matched by
19075 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
19076 // Bits [5:4] of the constant are the destination select. This is the
19077 // value of the incoming immediate.
19078 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
19079 // combine either bitwise AND or insert of float 0.0 to set these bits.
19080
19081 bool MinSize = DAG.getMachineFunction().getFunction().hasMinSize();
19082 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
19083 // If this is an insertion of 32-bits into the low 32-bits of
19084 // a vector, we prefer to generate a blend with immediate rather
19085 // than an insertps. Blends are simpler operations in hardware and so
19086 // will always have equal or better performance than insertps.
19087 // But if optimizing for size and there's a load folding opportunity,
19088 // generate insertps because blendps does not have a 32-bit memory
19089 // operand form.
19090 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
19091 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1,
19092 DAG.getTargetConstant(1, dl, MVT::i8));
19093 }
19094 // Create this as a scalar to vector..
19095 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
19096 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1,
19097 DAG.getTargetConstant(IdxVal << 4, dl, MVT::i8));
19098 }
19099
19100 // PINSR* works with constant index.
19101 if (EltVT == MVT::i32 || EltVT == MVT::i64)
19102 return Op;
19103 }
19104
19105 return SDValue();
19106}
19107
19108static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, const X86Subtarget &Subtarget,
19109 SelectionDAG &DAG) {
19110 SDLoc dl(Op);
19111 MVT OpVT = Op.getSimpleValueType();
19112
19113 // It's always cheaper to replace a xor+movd with xorps and simplifies further
19114 // combines.
19115 if (X86::isZeroNode(Op.getOperand(0)))
19116 return getZeroVector(OpVT, Subtarget, DAG, dl);
19117
19118 // If this is a 256-bit vector result, first insert into a 128-bit
19119 // vector and then insert into the 256-bit vector.
19120 if (!OpVT.is128BitVector()) {
19121 // Insert into a 128-bit vector.
19122 unsigned SizeFactor = OpVT.getSizeInBits() / 128;
19123 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
19124 OpVT.getVectorNumElements() / SizeFactor);
19125
19126 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
19127
19128 // Insert the 128-bit vector.
19129 return insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
19130 }
19131 assert(OpVT.is128BitVector() && OpVT.isInteger() && OpVT != MVT::v2i64 &&(static_cast <bool> (OpVT.is128BitVector() && OpVT
.isInteger() && OpVT != MVT::v2i64 && "Expected an SSE type!"
) ? void (0) : __assert_fail ("OpVT.is128BitVector() && OpVT.isInteger() && OpVT != MVT::v2i64 && \"Expected an SSE type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19132, __extension__ __PRETTY_FUNCTION__))
19132 "Expected an SSE type!")(static_cast <bool> (OpVT.is128BitVector() && OpVT
.isInteger() && OpVT != MVT::v2i64 && "Expected an SSE type!"
) ? void (0) : __assert_fail ("OpVT.is128BitVector() && OpVT.isInteger() && OpVT != MVT::v2i64 && \"Expected an SSE type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19132, __extension__ __PRETTY_FUNCTION__))
;
19133
19134 // Pass through a v4i32 SCALAR_TO_VECTOR as that's what we use in tblgen.
19135 if (OpVT == MVT::v4i32)
19136 return Op;
19137
19138 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
19139 return DAG.getBitcast(
19140 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
19141}
19142
19143// Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
19144// simple superregister reference or explicit instructions to insert
19145// the upper bits of a vector.
19146static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
19147 SelectionDAG &DAG) {
19148 assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1)(static_cast <bool> (Op.getSimpleValueType().getVectorElementType
() == MVT::i1) ? void (0) : __assert_fail ("Op.getSimpleValueType().getVectorElementType() == MVT::i1"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19148, __extension__ __PRETTY_FUNCTION__))
;
19149
19150 return insert1BitVector(Op, DAG, Subtarget);
19151}
19152
19153static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
19154 SelectionDAG &DAG) {
19155 assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&(static_cast <bool> (Op.getSimpleValueType().getVectorElementType
() == MVT::i1 && "Only vXi1 extract_subvectors need custom lowering"
) ? void (0) : __assert_fail ("Op.getSimpleValueType().getVectorElementType() == MVT::i1 && \"Only vXi1 extract_subvectors need custom lowering\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19156, __extension__ __PRETTY_FUNCTION__))
19156 "Only vXi1 extract_subvectors need custom lowering")(static_cast <bool> (Op.getSimpleValueType().getVectorElementType
() == MVT::i1 && "Only vXi1 extract_subvectors need custom lowering"
) ? void (0) : __assert_fail ("Op.getSimpleValueType().getVectorElementType() == MVT::i1 && \"Only vXi1 extract_subvectors need custom lowering\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19156, __extension__ __PRETTY_FUNCTION__))
;
19157
19158 SDLoc dl(Op);
19159 SDValue Vec = Op.getOperand(0);
19160 uint64_t IdxVal = Op.getConstantOperandVal(1);
19161
19162 if (IdxVal == 0) // the operation is legal
19163 return Op;
19164
19165 MVT VecVT = Vec.getSimpleValueType();
19166 unsigned NumElems = VecVT.getVectorNumElements();
19167
19168 // Extend to natively supported kshift.
19169 MVT WideVecVT = VecVT;
19170 if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8) {
19171 WideVecVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
19172 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVecVT,
19173 DAG.getUNDEF(WideVecVT), Vec,
19174 DAG.getIntPtrConstant(0, dl));
19175 }
19176
19177 // Shift to the LSB.
19178 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideVecVT, Vec,
19179 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
19180
19181 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, Op.getValueType(), Vec,
19182 DAG.getIntPtrConstant(0, dl));
19183}
19184
19185// Returns the appropriate wrapper opcode for a global reference.
19186unsigned X86TargetLowering::getGlobalWrapperKind(
19187 const GlobalValue *GV, const unsigned char OpFlags) const {
19188 // References to absolute symbols are never PC-relative.
19189 if (GV && GV->isAbsoluteSymbolRef())
19190 return X86ISD::Wrapper;
19191
19192 CodeModel::Model M = getTargetMachine().getCodeModel();
19193 if (Subtarget.isPICStyleRIPRel() &&
19194 (M == CodeModel::Small || M == CodeModel::Kernel))
19195 return X86ISD::WrapperRIP;
19196
19197 // GOTPCREL references must always use RIP.
19198 if (OpFlags == X86II::MO_GOTPCREL)
19199 return X86ISD::WrapperRIP;
19200
19201 return X86ISD::Wrapper;
19202}
19203
19204// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
19205// their target counterpart wrapped in the X86ISD::Wrapper node. Suppose N is
19206// one of the above mentioned nodes. It has to be wrapped because otherwise
19207// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
19208// be used to form addressing mode. These wrapped nodes will be selected
19209// into MOV32ri.
19210SDValue
19211X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
19212 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
19213
19214 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
19215 // global base reg.
19216 unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
19217
19218 auto PtrVT = getPointerTy(DAG.getDataLayout());
19219 SDValue Result = DAG.getTargetConstantPool(
19220 CP->getConstVal(), PtrVT, CP->getAlign(), CP->getOffset(), OpFlag);
19221 SDLoc DL(CP);
19222 Result = DAG.getNode(getGlobalWrapperKind(), DL, PtrVT, Result);
19223 // With PIC, the address is actually $g + Offset.
19224 if (OpFlag) {
19225 Result =
19226 DAG.getNode(ISD::ADD, DL, PtrVT,
19227 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
19228 }
19229
19230 return Result;
19231}
19232
19233SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
19234 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
19235
19236 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
19237 // global base reg.
19238 unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
19239
19240 auto PtrVT = getPointerTy(DAG.getDataLayout());
19241 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
19242 SDLoc DL(JT);
19243 Result = DAG.getNode(getGlobalWrapperKind(), DL, PtrVT, Result);
19244
19245 // With PIC, the address is actually $g + Offset.
19246 if (OpFlag)
19247 Result =
19248 DAG.getNode(ISD::ADD, DL, PtrVT,
19249 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
19250
19251 return Result;
19252}
19253
19254SDValue X86TargetLowering::LowerExternalSymbol(SDValue Op,
19255 SelectionDAG &DAG) const {
19256 return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false);
19257}
19258
19259SDValue
19260X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
19261 // Create the TargetBlockAddressAddress node.
19262 unsigned char OpFlags =
19263 Subtarget.classifyBlockAddressReference();
19264 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
19265 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
19266 SDLoc dl(Op);
19267 auto PtrVT = getPointerTy(DAG.getDataLayout());
19268 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
19269 Result = DAG.getNode(getGlobalWrapperKind(), dl, PtrVT, Result);
19270
19271 // With PIC, the address is actually $g + Offset.
19272 if (isGlobalRelativeToPICBase(OpFlags)) {
19273 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
19274 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
19275 }
19276
19277 return Result;
19278}
19279
19280/// Creates target global address or external symbol nodes for calls or
19281/// other uses.
19282SDValue X86TargetLowering::LowerGlobalOrExternal(SDValue Op, SelectionDAG &DAG,
19283 bool ForCall) const {
19284 // Unpack the global address or external symbol.
19285 const SDLoc &dl = SDLoc(Op);
19286 const GlobalValue *GV = nullptr;
19287 int64_t Offset = 0;
19288 const char *ExternalSym = nullptr;
19289 if (const auto *G = dyn_cast<GlobalAddressSDNode>(Op)) {
19290 GV = G->getGlobal();
19291 Offset = G->getOffset();
19292 } else {
19293 const auto *ES = cast<ExternalSymbolSDNode>(Op);
19294 ExternalSym = ES->getSymbol();
19295 }
19296
19297 // Calculate some flags for address lowering.
19298 const Module &Mod = *DAG.getMachineFunction().getFunction().getParent();
19299 unsigned char OpFlags;
19300 if (ForCall)
19301 OpFlags = Subtarget.classifyGlobalFunctionReference(GV, Mod);
19302 else
19303 OpFlags = Subtarget.classifyGlobalReference(GV, Mod);
19304 bool HasPICReg = isGlobalRelativeToPICBase(OpFlags);
19305 bool NeedsLoad = isGlobalStubReference(OpFlags);
19306
19307 CodeModel::Model M = DAG.getTarget().getCodeModel();
19308 auto PtrVT = getPointerTy(DAG.getDataLayout());
19309 SDValue Result;
19310
19311 if (GV) {
19312 // Create a target global address if this is a global. If possible, fold the
19313 // offset into the global address reference. Otherwise, ADD it on later.
19314 // Suppress the folding if Offset is negative: movl foo-1, %eax is not
19315 // allowed because if the address of foo is 0, the ELF R_X86_64_32
19316 // relocation will compute to a negative value, which is invalid.
19317 int64_t GlobalOffset = 0;
19318 if (OpFlags == X86II::MO_NO_FLAG && Offset >= 0 &&
19319 X86::isOffsetSuitableForCodeModel(Offset, M, true)) {
19320 std::swap(GlobalOffset, Offset);
19321 }
19322 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, GlobalOffset, OpFlags);
19323 } else {
19324 // If this is not a global address, this must be an external symbol.
19325 Result = DAG.getTargetExternalSymbol(ExternalSym, PtrVT, OpFlags);
19326 }
19327
19328 // If this is a direct call, avoid the wrapper if we don't need to do any
19329 // loads or adds. This allows SDAG ISel to match direct calls.
19330 if (ForCall && !NeedsLoad && !HasPICReg && Offset == 0)
19331 return Result;
19332
19333 Result = DAG.getNode(getGlobalWrapperKind(GV, OpFlags), dl, PtrVT, Result);
19334
19335 // With PIC, the address is actually $g + Offset.
19336 if (HasPICReg) {
19337 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
19338 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
19339 }
19340
19341 // For globals that require a load from a stub to get the address, emit the
19342 // load.
19343 if (NeedsLoad)
19344 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
19345 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
19346
19347 // If there was a non-zero offset that we didn't fold, create an explicit
19348 // addition for it.
19349 if (Offset != 0)
19350 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
19351 DAG.getConstant(Offset, dl, PtrVT));
19352
19353 return Result;
19354}
19355
19356SDValue
19357X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
19358 return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false);
19359}
19360
19361static SDValue
19362GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
19363 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
19364 unsigned char OperandFlags, bool LocalDynamic = false) {
19365 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
19366 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
19367 SDLoc dl(GA);
19368 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
19369 GA->getValueType(0),
19370 GA->getOffset(),
19371 OperandFlags);
19372
19373 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
19374 : X86ISD::TLSADDR;
19375
19376 if (InFlag) {
19377 SDValue Ops[] = { Chain, TGA, *InFlag };
19378 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
19379 } else {
19380 SDValue Ops[] = { Chain, TGA };
19381 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
19382 }
19383
19384 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
19385 MFI.setAdjustsStack(true);
19386 MFI.setHasCalls(true);
19387
19388 SDValue Flag = Chain.getValue(1);
19389 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
19390}
19391
19392// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
19393static SDValue
19394LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
19395 const EVT PtrVT) {
19396 SDValue InFlag;
19397 SDLoc dl(GA); // ? function entry point might be better
19398 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
19399 DAG.getNode(X86ISD::GlobalBaseReg,
19400 SDLoc(), PtrVT), InFlag);
19401 InFlag = Chain.getValue(1);
19402
19403 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
19404}
19405
19406// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit LP64
19407static SDValue
19408LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
19409 const EVT PtrVT) {
19410 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
19411 X86::RAX, X86II::MO_TLSGD);
19412}
19413
19414// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit ILP32
19415static SDValue
19416LowerToTLSGeneralDynamicModelX32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
19417 const EVT PtrVT) {
19418 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
19419 X86::EAX, X86II::MO_TLSGD);
19420}
19421
19422static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
19423 SelectionDAG &DAG, const EVT PtrVT,
19424 bool Is64Bit, bool Is64BitLP64) {
19425 SDLoc dl(GA);
19426
19427 // Get the start address of the TLS block for this module.
19428 X86MachineFunctionInfo *MFI = DAG.getMachineFunction()
19429 .getInfo<X86MachineFunctionInfo>();
19430 MFI->incNumLocalDynamicTLSAccesses();
19431
19432 SDValue Base;
19433 if (Is64Bit) {
19434 unsigned ReturnReg = Is64BitLP64 ? X86::RAX : X86::EAX;
19435 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, ReturnReg,
19436 X86II::MO_TLSLD, /*LocalDynamic=*/true);
19437 } else {
19438 SDValue InFlag;
19439 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
19440 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
19441 InFlag = Chain.getValue(1);
19442 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
19443 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
19444 }
19445
19446 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
19447 // of Base.
19448
19449 // Build x@dtpoff.
19450 unsigned char OperandFlags = X86II::MO_DTPOFF;
19451 unsigned WrapperKind = X86ISD::Wrapper;
19452 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
19453 GA->getValueType(0),
19454 GA->getOffset(), OperandFlags);
19455 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
19456
19457 // Add x@dtpoff with the base.
19458 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
19459}
19460
19461// Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
19462static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
19463 const EVT PtrVT, TLSModel::Model model,
19464 bool is64Bit, bool isPIC) {
19465 SDLoc dl(GA);
19466
19467 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
19468 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
19469 is64Bit ? 257 : 256));
19470
19471 SDValue ThreadPointer =
19472 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
19473 MachinePointerInfo(Ptr));
19474
19475 unsigned char OperandFlags = 0;
19476 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
19477 // initialexec.
19478 unsigned WrapperKind = X86ISD::Wrapper;
19479 if (model == TLSModel::LocalExec) {
19480 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
19481 } else if (model == TLSModel::InitialExec) {
19482 if (is64Bit) {
19483 OperandFlags = X86II::MO_GOTTPOFF;
19484 WrapperKind = X86ISD::WrapperRIP;
19485 } else {
19486 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
19487 }
19488 } else {
19489 llvm_unreachable("Unexpected model")::llvm::llvm_unreachable_internal("Unexpected model", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19489)
;
19490 }
19491
19492 // emit "addl x@ntpoff,%eax" (local exec)
19493 // or "addl x@indntpoff,%eax" (initial exec)
19494 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
19495 SDValue TGA =
19496 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
19497 GA->getOffset(), OperandFlags);
19498 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
19499
19500 if (model == TLSModel::InitialExec) {
19501 if (isPIC && !is64Bit) {
19502 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
19503 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
19504 Offset);
19505 }
19506
19507 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
19508 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
19509 }
19510
19511 // The address of the thread local variable is the add of the thread
19512 // pointer with the offset of the variable.
19513 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
19514}
19515
19516SDValue
19517X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
19518
19519 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
19520
19521 if (DAG.getTarget().useEmulatedTLS())
19522 return LowerToTLSEmulatedModel(GA, DAG);
19523
19524 const GlobalValue *GV = GA->getGlobal();
19525 auto PtrVT = getPointerTy(DAG.getDataLayout());
19526 bool PositionIndependent = isPositionIndependent();
19527
19528 if (Subtarget.isTargetELF()) {
19529 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
19530 switch (model) {
19531 case TLSModel::GeneralDynamic:
19532 if (Subtarget.is64Bit()) {
19533 if (Subtarget.isTarget64BitLP64())
19534 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
19535 return LowerToTLSGeneralDynamicModelX32(GA, DAG, PtrVT);
19536 }
19537 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
19538 case TLSModel::LocalDynamic:
19539 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT, Subtarget.is64Bit(),
19540 Subtarget.isTarget64BitLP64());
19541 case TLSModel::InitialExec:
19542 case TLSModel::LocalExec:
19543 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget.is64Bit(),
19544 PositionIndependent);
19545 }
19546 llvm_unreachable("Unknown TLS model.")::llvm::llvm_unreachable_internal("Unknown TLS model.", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19546)
;
19547 }
19548
19549 if (Subtarget.isTargetDarwin()) {
19550 // Darwin only has one model of TLS. Lower to that.
19551 unsigned char OpFlag = 0;
19552 unsigned WrapperKind = Subtarget.isPICStyleRIPRel() ?
19553 X86ISD::WrapperRIP : X86ISD::Wrapper;
19554
19555 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
19556 // global base reg.
19557 bool PIC32 = PositionIndependent && !Subtarget.is64Bit();
19558 if (PIC32)
19559 OpFlag = X86II::MO_TLVP_PIC_BASE;
19560 else
19561 OpFlag = X86II::MO_TLVP;
19562 SDLoc DL(Op);
19563 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
19564 GA->getValueType(0),
19565 GA->getOffset(), OpFlag);
19566 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
19567
19568 // With PIC32, the address is actually $g + Offset.
19569 if (PIC32)
19570 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
19571 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
19572 Offset);
19573
19574 // Lowering the machine isd will make sure everything is in the right
19575 // location.
19576 SDValue Chain = DAG.getEntryNode();
19577 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
19578 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
19579 SDValue Args[] = { Chain, Offset };
19580 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
19581 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
19582 DAG.getIntPtrConstant(0, DL, true),
19583 Chain.getValue(1), DL);
19584
19585 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
19586 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
19587 MFI.setAdjustsStack(true);
19588
19589 // And our return value (tls address) is in the standard call return value
19590 // location.
19591 unsigned Reg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
19592 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
19593 }
19594
19595 if (Subtarget.isOSWindows()) {
19596 // Just use the implicit TLS architecture
19597 // Need to generate something similar to:
19598 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
19599 // ; from TEB
19600 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
19601 // mov rcx, qword [rdx+rcx*8]
19602 // mov eax, .tls$:tlsvar
19603 // [rax+rcx] contains the address
19604 // Windows 64bit: gs:0x58
19605 // Windows 32bit: fs:__tls_array
19606
19607 SDLoc dl(GA);
19608 SDValue Chain = DAG.getEntryNode();
19609
19610 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
19611 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
19612 // use its literal value of 0x2C.
19613 Value *Ptr = Constant::getNullValue(Subtarget.is64Bit()
19614 ? Type::getInt8PtrTy(*DAG.getContext(),
19615 256)
19616 : Type::getInt32PtrTy(*DAG.getContext(),
19617 257));
19618
19619 SDValue TlsArray = Subtarget.is64Bit()
19620 ? DAG.getIntPtrConstant(0x58, dl)
19621 : (Subtarget.isTargetWindowsGNU()
19622 ? DAG.getIntPtrConstant(0x2C, dl)
19623 : DAG.getExternalSymbol("_tls_array", PtrVT));
19624
19625 SDValue ThreadPointer =
19626 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr));
19627
19628 SDValue res;
19629 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
19630 res = ThreadPointer;
19631 } else {
19632 // Load the _tls_index variable
19633 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
19634 if (Subtarget.is64Bit())
19635 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
19636 MachinePointerInfo(), MVT::i32);
19637 else
19638 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo());
19639
19640 const DataLayout &DL = DAG.getDataLayout();
19641 SDValue Scale =
19642 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, MVT::i8);
19643 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
19644
19645 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
19646 }
19647
19648 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo());
19649
19650 // Get the offset of start of .tls section
19651 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
19652 GA->getValueType(0),
19653 GA->getOffset(), X86II::MO_SECREL);
19654 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
19655
19656 // The address of the thread local variable is the add of the thread
19657 // pointer with the offset of the variable.
19658 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
19659 }
19660
19661 llvm_unreachable("TLS not implemented for this target.")::llvm::llvm_unreachable_internal("TLS not implemented for this target."
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19661)
;
19662}
19663
19664/// Lower SRA_PARTS and friends, which return two i32 values
19665/// and take a 2 x i32 value to shift plus a shift amount.
19666/// TODO: Can this be moved to general expansion code?
19667static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
19668 SDValue Lo, Hi;
19669 DAG.getTargetLoweringInfo().expandShiftParts(Op.getNode(), Lo, Hi, DAG);
19670 return DAG.getMergeValues({Lo, Hi}, SDLoc(Op));
19671}
19672
19673static SDValue LowerFunnelShift(SDValue Op, const X86Subtarget &Subtarget,
19674 SelectionDAG &DAG) {
19675 MVT VT = Op.getSimpleValueType();
19676 assert((Op.getOpcode() == ISD::FSHL || Op.getOpcode() == ISD::FSHR) &&(static_cast <bool> ((Op.getOpcode() == ISD::FSHL || Op
.getOpcode() == ISD::FSHR) && "Unexpected funnel shift opcode!"
) ? void (0) : __assert_fail ("(Op.getOpcode() == ISD::FSHL || Op.getOpcode() == ISD::FSHR) && \"Unexpected funnel shift opcode!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19677, __extension__ __PRETTY_FUNCTION__))
19677 "Unexpected funnel shift opcode!")(static_cast <bool> ((Op.getOpcode() == ISD::FSHL || Op
.getOpcode() == ISD::FSHR) && "Unexpected funnel shift opcode!"
) ? void (0) : __assert_fail ("(Op.getOpcode() == ISD::FSHL || Op.getOpcode() == ISD::FSHR) && \"Unexpected funnel shift opcode!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19677, __extension__ __PRETTY_FUNCTION__))
;
19678
19679 SDLoc DL(Op);
19680 SDValue Op0 = Op.getOperand(0);
19681 SDValue Op1 = Op.getOperand(1);
19682 SDValue Amt = Op.getOperand(2);
19683
19684 bool IsFSHR = Op.getOpcode() == ISD::FSHR;
19685
19686 if (VT.isVector()) {
19687 assert(Subtarget.hasVBMI2() && "Expected VBMI2")(static_cast <bool> (Subtarget.hasVBMI2() && "Expected VBMI2"
) ? void (0) : __assert_fail ("Subtarget.hasVBMI2() && \"Expected VBMI2\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19687, __extension__ __PRETTY_FUNCTION__))
;
19688
19689 if (IsFSHR)
19690 std::swap(Op0, Op1);
19691
19692 // With AVX512, but not VLX we need to widen to get a 512-bit result type.
19693 if (!Subtarget.hasVLX() && !VT.is512BitVector()) {
19694 Op0 = widenSubVector(Op0, false, Subtarget, DAG, DL, 512);
19695 Op1 = widenSubVector(Op1, false, Subtarget, DAG, DL, 512);
19696 }
19697
19698 SDValue Funnel;
19699 APInt APIntShiftAmt;
19700 MVT ResultVT = Op0.getSimpleValueType();
19701 if (X86::isConstantSplat(Amt, APIntShiftAmt)) {
19702 uint64_t ShiftAmt = APIntShiftAmt.urem(VT.getScalarSizeInBits());
19703 Funnel =
19704 DAG.getNode(IsFSHR ? X86ISD::VSHRD : X86ISD::VSHLD, DL, ResultVT, Op0,
19705 Op1, DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
19706 } else {
19707 if (!Subtarget.hasVLX() && !VT.is512BitVector())
19708 Amt = widenSubVector(Amt, false, Subtarget, DAG, DL, 512);
19709 Funnel = DAG.getNode(IsFSHR ? X86ISD::VSHRDV : X86ISD::VSHLDV, DL,
19710 ResultVT, Op0, Op1, Amt);
19711 }
19712 if (!Subtarget.hasVLX() && !VT.is512BitVector())
19713 Funnel = extractSubVector(Funnel, 0, DAG, DL, VT.getSizeInBits());
19714 return Funnel;
19715 }
19716 assert((static_cast <bool> ((VT == MVT::i8 || VT == MVT::i16 ||
VT == MVT::i32 || VT == MVT::i64) && "Unexpected funnel shift type!"
) ? void (0) : __assert_fail ("(VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) && \"Unexpected funnel shift type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19718, __extension__ __PRETTY_FUNCTION__))
19717 (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) &&(static_cast <bool> ((VT == MVT::i8 || VT == MVT::i16 ||
VT == MVT::i32 || VT == MVT::i64) && "Unexpected funnel shift type!"
) ? void (0) : __assert_fail ("(VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) && \"Unexpected funnel shift type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19718, __extension__ __PRETTY_FUNCTION__))
19718 "Unexpected funnel shift type!")(static_cast <bool> ((VT == MVT::i8 || VT == MVT::i16 ||
VT == MVT::i32 || VT == MVT::i64) && "Unexpected funnel shift type!"
) ? void (0) : __assert_fail ("(VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) && \"Unexpected funnel shift type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19718, __extension__ __PRETTY_FUNCTION__))
;
19719
19720 // Expand slow SHLD/SHRD cases if we are not optimizing for size.
19721 bool OptForSize = DAG.shouldOptForSize();
19722 bool ExpandFunnel = !OptForSize && Subtarget.isSHLDSlow();
19723
19724 // fshl(x,y,z) -> (((aext(x) << bw) | zext(y)) << (z & (bw-1))) >> bw.
19725 // fshr(x,y,z) -> (((aext(x) << bw) | zext(y)) >> (z & (bw-1))).
19726 if ((VT == MVT::i8 || (ExpandFunnel && VT == MVT::i16)) &&
19727 !isa<ConstantSDNode>(Amt)) {
19728 unsigned EltSizeInBits = VT.getScalarSizeInBits();
19729 SDValue Mask = DAG.getConstant(EltSizeInBits - 1, DL, Amt.getValueType());
19730 SDValue HiShift = DAG.getConstant(EltSizeInBits, DL, Amt.getValueType());
19731 Op0 = DAG.getAnyExtOrTrunc(Op0, DL, MVT::i32);
19732 Op1 = DAG.getZExtOrTrunc(Op1, DL, MVT::i32);
19733 Amt = DAG.getNode(ISD::AND, DL, Amt.getValueType(), Amt, Mask);
19734 SDValue Res = DAG.getNode(ISD::SHL, DL, MVT::i32, Op0, HiShift);
19735 Res = DAG.getNode(ISD::OR, DL, MVT::i32, Res, Op1);
19736 if (IsFSHR) {
19737 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, Res, Amt);
19738 } else {
19739 Res = DAG.getNode(ISD::SHL, DL, MVT::i32, Res, Amt);
19740 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, Res, HiShift);
19741 }
19742 return DAG.getZExtOrTrunc(Res, DL, VT);
19743 }
19744
19745 if (VT == MVT::i8 || ExpandFunnel)
19746 return SDValue();
19747
19748 // i16 needs to modulo the shift amount, but i32/i64 have implicit modulo.
19749 if (VT == MVT::i16) {
19750 Amt = DAG.getNode(ISD::AND, DL, Amt.getValueType(), Amt,
19751 DAG.getConstant(15, DL, Amt.getValueType()));
19752 unsigned FSHOp = (IsFSHR ? X86ISD::FSHR : X86ISD::FSHL);
19753 return DAG.getNode(FSHOp, DL, VT, Op0, Op1, Amt);
19754 }
19755
19756 return Op;
19757}
19758
19759// Try to use a packed vector operation to handle i64 on 32-bit targets when
19760// AVX512DQ is enabled.
19761static SDValue LowerI64IntToFP_AVX512DQ(SDValue Op, SelectionDAG &DAG,
19762 const X86Subtarget &Subtarget) {
19763 assert((Op.getOpcode() == ISD::SINT_TO_FP ||(static_cast <bool> ((Op.getOpcode() == ISD::SINT_TO_FP
|| Op.getOpcode() == ISD::STRICT_SINT_TO_FP || Op.getOpcode(
) == ISD::STRICT_UINT_TO_FP || Op.getOpcode() == ISD::UINT_TO_FP
) && "Unexpected opcode!") ? void (0) : __assert_fail
("(Op.getOpcode() == ISD::SINT_TO_FP || Op.getOpcode() == ISD::STRICT_SINT_TO_FP || Op.getOpcode() == ISD::STRICT_UINT_TO_FP || Op.getOpcode() == ISD::UINT_TO_FP) && \"Unexpected opcode!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19767, __extension__ __PRETTY_FUNCTION__))
19764 Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||(static_cast <bool> ((Op.getOpcode() == ISD::SINT_TO_FP
|| Op.getOpcode() == ISD::STRICT_SINT_TO_FP || Op.getOpcode(
) == ISD::STRICT_UINT_TO_FP || Op.getOpcode() == ISD::UINT_TO_FP
) && "Unexpected opcode!") ? void (0) : __assert_fail
("(Op.getOpcode() == ISD::SINT_TO_FP || Op.getOpcode() == ISD::STRICT_SINT_TO_FP || Op.getOpcode() == ISD::STRICT_UINT_TO_FP || Op.getOpcode() == ISD::UINT_TO_FP) && \"Unexpected opcode!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19767, __extension__ __PRETTY_FUNCTION__))
19765 Op.getOpcode() == ISD::STRICT_UINT_TO_FP ||(static_cast <bool> ((Op.getOpcode() == ISD::SINT_TO_FP
|| Op.getOpcode() == ISD::STRICT_SINT_TO_FP || Op.getOpcode(
) == ISD::STRICT_UINT_TO_FP || Op.getOpcode() == ISD::UINT_TO_FP
) && "Unexpected opcode!") ? void (0) : __assert_fail
("(Op.getOpcode() == ISD::SINT_TO_FP || Op.getOpcode() == ISD::STRICT_SINT_TO_FP || Op.getOpcode() == ISD::STRICT_UINT_TO_FP || Op.getOpcode() == ISD::UINT_TO_FP) && \"Unexpected opcode!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19767, __extension__ __PRETTY_FUNCTION__))
19766 Op.getOpcode() == ISD::UINT_TO_FP) &&(static_cast <bool> ((Op.getOpcode() == ISD::SINT_TO_FP
|| Op.getOpcode() == ISD::STRICT_SINT_TO_FP || Op.getOpcode(
) == ISD::STRICT_UINT_TO_FP || Op.getOpcode() == ISD::UINT_TO_FP
) && "Unexpected opcode!") ? void (0) : __assert_fail
("(Op.getOpcode() == ISD::SINT_TO_FP || Op.getOpcode() == ISD::STRICT_SINT_TO_FP || Op.getOpcode() == ISD::STRICT_UINT_TO_FP || Op.getOpcode() == ISD::UINT_TO_FP) && \"Unexpected opcode!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19767, __extension__ __PRETTY_FUNCTION__))
19767 "Unexpected opcode!")(static_cast <bool> ((Op.getOpcode() == ISD::SINT_TO_FP
|| Op.getOpcode() == ISD::STRICT_SINT_TO_FP || Op.getOpcode(
) == ISD::STRICT_UINT_TO_FP || Op.getOpcode() == ISD::UINT_TO_FP
) && "Unexpected opcode!") ? void (0) : __assert_fail
("(Op.getOpcode() == ISD::SINT_TO_FP || Op.getOpcode() == ISD::STRICT_SINT_TO_FP || Op.getOpcode() == ISD::STRICT_UINT_TO_FP || Op.getOpcode() == ISD::UINT_TO_FP) && \"Unexpected opcode!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19767, __extension__ __PRETTY_FUNCTION__))
;
19768 bool IsStrict = Op->isStrictFPOpcode();
19769 unsigned OpNo = IsStrict ? 1 : 0;
19770 SDValue Src = Op.getOperand(OpNo);
19771 MVT SrcVT = Src.getSimpleValueType();
19772 MVT VT = Op.getSimpleValueType();
19773
19774 if (!Subtarget.hasDQI() || SrcVT != MVT::i64 || Subtarget.is64Bit() ||
19775 (VT != MVT::f32 && VT != MVT::f64))
19776 return SDValue();
19777
19778 // Pack the i64 into a vector, do the operation and extract.
19779
19780 // Using 256-bit to ensure result is 128-bits for f32 case.
19781 unsigned NumElts = Subtarget.hasVLX() ? 4 : 8;
19782 MVT VecInVT = MVT::getVectorVT(MVT::i64, NumElts);
19783 MVT VecVT = MVT::getVectorVT(VT, NumElts);
19784
19785 SDLoc dl(Op);
19786 SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecInVT, Src);
19787 if (IsStrict) {
19788 SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, {VecVT, MVT::Other},
19789 {Op.getOperand(0), InVec});
19790 SDValue Chain = CvtVec.getValue(1);
19791 SDValue Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
19792 DAG.getIntPtrConstant(0, dl));
19793 return DAG.getMergeValues({Value, Chain}, dl);
19794 }
19795
19796 SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, VecVT, InVec);
19797
19798 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
19799 DAG.getIntPtrConstant(0, dl));
19800}
19801
19802static bool useVectorCast(unsigned Opcode, MVT FromVT, MVT ToVT,
19803 const X86Subtarget &Subtarget) {
19804 switch (Opcode) {
19805 case ISD::SINT_TO_FP:
19806 // TODO: Handle wider types with AVX/AVX512.
19807 if (!Subtarget.hasSSE2() || FromVT != MVT::v4i32)
19808 return false;
19809 // CVTDQ2PS or (V)CVTDQ2PD
19810 return ToVT == MVT::v4f32 || (Subtarget.hasAVX() && ToVT == MVT::v4f64);
19811
19812 case ISD::UINT_TO_FP:
19813 // TODO: Handle wider types and i64 elements.
19814 if (!Subtarget.hasAVX512() || FromVT != MVT::v4i32)
19815 return false;
19816 // VCVTUDQ2PS or VCVTUDQ2PD
19817 return ToVT == MVT::v4f32 || ToVT == MVT::v4f64;
19818
19819 default:
19820 return false;
19821 }
19822}
19823
19824/// Given a scalar cast operation that is extracted from a vector, try to
19825/// vectorize the cast op followed by extraction. This will avoid an expensive
19826/// round-trip between XMM and GPR.
19827static SDValue vectorizeExtractedCast(SDValue Cast, SelectionDAG &DAG,
19828 const X86Subtarget &Subtarget) {
19829 // TODO: This could be enhanced to handle smaller integer types by peeking
19830 // through an extend.
19831 SDValue Extract = Cast.getOperand(0);
19832 MVT DestVT = Cast.getSimpleValueType();
19833 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
19834 !isa<ConstantSDNode>(Extract.getOperand(1)))
19835 return SDValue();
19836
19837 // See if we have a 128-bit vector cast op for this type of cast.
19838 SDValue VecOp = Extract.getOperand(0);
19839 MVT FromVT = VecOp.getSimpleValueType();
19840 unsigned NumEltsInXMM = 128 / FromVT.getScalarSizeInBits();
19841 MVT Vec128VT = MVT::getVectorVT(FromVT.getScalarType(), NumEltsInXMM);
19842 MVT ToVT = MVT::getVectorVT(DestVT, NumEltsInXMM);
19843 if (!useVectorCast(Cast.getOpcode(), Vec128VT, ToVT, Subtarget))
19844 return SDValue();
19845
19846 // If we are extracting from a non-zero element, first shuffle the source
19847 // vector to allow extracting from element zero.
19848 SDLoc DL(Cast);
19849 if (!isNullConstant(Extract.getOperand(1))) {
19850 SmallVector<int, 16> Mask(FromVT.getVectorNumElements(), -1);
19851 Mask[0] = Extract.getConstantOperandVal(1);
19852 VecOp = DAG.getVectorShuffle(FromVT, DL, VecOp, DAG.getUNDEF(FromVT), Mask);
19853 }
19854 // If the source vector is wider than 128-bits, extract the low part. Do not
19855 // create an unnecessarily wide vector cast op.
19856 if (FromVT != Vec128VT)
19857 VecOp = extract128BitVector(VecOp, 0, DAG, DL);
19858
19859 // cast (extelt V, 0) --> extelt (cast (extract_subv V)), 0
19860 // cast (extelt V, C) --> extelt (cast (extract_subv (shuffle V, [C...]))), 0
19861 SDValue VCast = DAG.getNode(Cast.getOpcode(), DL, ToVT, VecOp);
19862 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, DestVT, VCast,
19863 DAG.getIntPtrConstant(0, DL));
19864}
19865
19866/// Given a scalar cast to FP with a cast to integer operand (almost an ftrunc),
19867/// try to vectorize the cast ops. This will avoid an expensive round-trip
19868/// between XMM and GPR.
19869static SDValue lowerFPToIntToFP(SDValue CastToFP, SelectionDAG &DAG,
19870 const X86Subtarget &Subtarget) {
19871 // TODO: Allow FP_TO_UINT.
19872 SDValue CastToInt = CastToFP.getOperand(0);
19873 MVT VT = CastToFP.getSimpleValueType();
19874 if (CastToInt.getOpcode() != ISD::FP_TO_SINT || VT.isVector())
19875 return SDValue();
19876
19877 MVT IntVT = CastToInt.getSimpleValueType();
19878 SDValue X = CastToInt.getOperand(0);
19879 MVT SrcVT = X.getSimpleValueType();
19880 if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
19881 return SDValue();
19882
19883 // See if we have 128-bit vector cast instructions for this type of cast.
19884 // We need cvttps2dq/cvttpd2dq and cvtdq2ps/cvtdq2pd.
19885 if (!Subtarget.hasSSE2() || (VT != MVT::f32 && VT != MVT::f64) ||
19886 IntVT != MVT::i32)
19887 return SDValue();
19888
19889 unsigned SrcSize = SrcVT.getSizeInBits();
19890 unsigned IntSize = IntVT.getSizeInBits();
19891 unsigned VTSize = VT.getSizeInBits();
19892 MVT VecSrcVT = MVT::getVectorVT(SrcVT, 128 / SrcSize);
19893 MVT VecIntVT = MVT::getVectorVT(IntVT, 128 / IntSize);
19894 MVT VecVT = MVT::getVectorVT(VT, 128 / VTSize);
19895
19896 // We need target-specific opcodes if this is v2f64 -> v4i32 -> v2f64.
19897 unsigned ToIntOpcode =
19898 SrcSize != IntSize ? X86ISD::CVTTP2SI : (unsigned)ISD::FP_TO_SINT;
19899 unsigned ToFPOpcode =
19900 IntSize != VTSize ? X86ISD::CVTSI2P : (unsigned)ISD::SINT_TO_FP;
19901
19902 // sint_to_fp (fp_to_sint X) --> extelt (sint_to_fp (fp_to_sint (s2v X))), 0
19903 //
19904 // We are not defining the high elements (for example, zero them) because
19905 // that could nullify any performance advantage that we hoped to gain from
19906 // this vector op hack. We do not expect any adverse effects (like denorm
19907 // penalties) with cast ops.
19908 SDLoc DL(CastToFP);
19909 SDValue ZeroIdx = DAG.getIntPtrConstant(0, DL);
19910 SDValue VecX = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecSrcVT, X);
19911 SDValue VCastToInt = DAG.getNode(ToIntOpcode, DL, VecIntVT, VecX);
19912 SDValue VCastToFP = DAG.getNode(ToFPOpcode, DL, VecVT, VCastToInt);
19913 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, VCastToFP, ZeroIdx);
19914}
19915
19916static SDValue lowerINT_TO_FP_vXi64(SDValue Op, SelectionDAG &DAG,
19917 const X86Subtarget &Subtarget) {
19918 SDLoc DL(Op);
19919 bool IsStrict = Op->isStrictFPOpcode();
19920 MVT VT = Op->getSimpleValueType(0);
19921 SDValue Src = Op->getOperand(IsStrict ? 1 : 0);
19922
19923 if (Subtarget.hasDQI()) {
19924 assert(!Subtarget.hasVLX() && "Unexpected features")(static_cast <bool> (!Subtarget.hasVLX() && "Unexpected features"
) ? void (0) : __assert_fail ("!Subtarget.hasVLX() && \"Unexpected features\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19924, __extension__ __PRETTY_FUNCTION__))
;
19925
19926 assert((Src.getSimpleValueType() == MVT::v2i64 ||(static_cast <bool> ((Src.getSimpleValueType() == MVT::
v2i64 || Src.getSimpleValueType() == MVT::v4i64) && "Unsupported custom type"
) ? void (0) : __assert_fail ("(Src.getSimpleValueType() == MVT::v2i64 || Src.getSimpleValueType() == MVT::v4i64) && \"Unsupported custom type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19928, __extension__ __PRETTY_FUNCTION__))
19927 Src.getSimpleValueType() == MVT::v4i64) &&(static_cast <bool> ((Src.getSimpleValueType() == MVT::
v2i64 || Src.getSimpleValueType() == MVT::v4i64) && "Unsupported custom type"
) ? void (0) : __assert_fail ("(Src.getSimpleValueType() == MVT::v2i64 || Src.getSimpleValueType() == MVT::v4i64) && \"Unsupported custom type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19928, __extension__ __PRETTY_FUNCTION__))
19928 "Unsupported custom type")(static_cast <bool> ((Src.getSimpleValueType() == MVT::
v2i64 || Src.getSimpleValueType() == MVT::v4i64) && "Unsupported custom type"
) ? void (0) : __assert_fail ("(Src.getSimpleValueType() == MVT::v2i64 || Src.getSimpleValueType() == MVT::v4i64) && \"Unsupported custom type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19928, __extension__ __PRETTY_FUNCTION__))
;
19929
19930 // With AVX512DQ, but not VLX we need to widen to get a 512-bit result type.
19931 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v4f64) &&(static_cast <bool> ((VT == MVT::v4f32 || VT == MVT::v2f64
|| VT == MVT::v4f64) && "Unexpected VT!") ? void (0)
: __assert_fail ("(VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v4f64) && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19932, __extension__ __PRETTY_FUNCTION__))
19932 "Unexpected VT!")(static_cast <bool> ((VT == MVT::v4f32 || VT == MVT::v2f64
|| VT == MVT::v4f64) && "Unexpected VT!") ? void (0)
: __assert_fail ("(VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v4f64) && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 19932, __extension__ __PRETTY_FUNCTION__))
;
19933 MVT WideVT = VT == MVT::v4f32 ? MVT::v8f32 : MVT::v8f64;
19934
19935 // Need to concat with zero vector for strict fp to avoid spurious
19936 // exceptions.
19937 SDValue Tmp = IsStrict ? DAG.getConstant(0, DL, MVT::v8i64)
19938 : DAG.getUNDEF(MVT::v8i64);
19939 Src = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i64, Tmp, Src,
19940 DAG.getIntPtrConstant(0, DL));
19941 SDValue Res, Chain;
19942 if (IsStrict) {
19943 Res = DAG.getNode(Op.getOpcode(), DL, {WideVT, MVT::Other},
19944 {Op->getOperand(0), Src});
19945 Chain = Res.getValue(1);
19946 } else {
19947 Res = DAG.getNode(Op.getOpcode(), DL, WideVT, Src);
19948 }
19949
19950 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
19951 DAG.getIntPtrConstant(0, DL));
19952
19953 if (IsStrict)
19954 return DAG.getMergeValues({Res, Chain}, DL);
19955 return Res;
19956 }
19957
19958 bool IsSigned = Op->getOpcode() == ISD::SINT_TO_FP ||
19959 Op->getOpcode() == ISD::STRICT_SINT_TO_FP;
19960 if (VT != MVT::v4f32 || IsSigned)
19961 return SDValue();
19962
19963 SDValue Zero = DAG.getConstant(0, DL, MVT::v4i64);
19964 SDValue One = DAG.getConstant(1, DL, MVT::v4i64);
19965 SDValue Sign = DAG.getNode(ISD::OR, DL, MVT::v4i64,
19966 DAG.getNode(ISD::SRL, DL, MVT::v4i64, Src, One),
19967 DAG.getNode(ISD::AND, DL, MVT::v4i64, Src, One));
19968 SDValue IsNeg = DAG.getSetCC(DL, MVT::v4i64, Src, Zero, ISD::SETLT);
19969 SDValue SignSrc = DAG.getSelect(DL, MVT::v4i64, IsNeg, Sign, Src);
19970 SmallVector<SDValue, 4> SignCvts(4);
19971 SmallVector<SDValue, 4> Chains(4);
19972 for (int i = 0; i != 4; ++i) {
19973 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, SignSrc,
19974 DAG.getIntPtrConstant(i, DL));
19975 if (IsStrict) {
19976 SignCvts[i] =
19977 DAG.getNode(ISD::STRICT_SINT_TO_FP, DL, {MVT::f32, MVT::Other},
19978 {Op.getOperand(0), Elt});
19979 Chains[i] = SignCvts[i].getValue(1);
19980 } else {
19981 SignCvts[i] = DAG.getNode(ISD::SINT_TO_FP, DL, MVT::f32, Elt);
19982 }
19983 }
19984 SDValue SignCvt = DAG.getBuildVector(VT, DL, SignCvts);
19985
19986 SDValue Slow, Chain;
19987 if (IsStrict) {
19988 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
19989 Slow = DAG.getNode(ISD::STRICT_FADD, DL, {MVT::v4f32, MVT::Other},
19990 {Chain, SignCvt, SignCvt});
19991 Chain = Slow.getValue(1);
19992 } else {
19993 Slow = DAG.getNode(ISD::FADD, DL, MVT::v4f32, SignCvt, SignCvt);
19994 }
19995
19996 IsNeg = DAG.getNode(ISD::TRUNCATE, DL, MVT::v4i32, IsNeg);
19997 SDValue Cvt = DAG.getSelect(DL, MVT::v4f32, IsNeg, Slow, SignCvt);
19998
19999 if (IsStrict)
20000 return DAG.getMergeValues({Cvt, Chain}, DL);
20001
20002 return Cvt;
20003}
20004
20005SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
20006 SelectionDAG &DAG) const {
20007 bool IsStrict = Op->isStrictFPOpcode();
20008 unsigned OpNo = IsStrict ? 1 : 0;
20009 SDValue Src = Op.getOperand(OpNo);
20010 SDValue Chain = IsStrict ? Op->getOperand(0) : DAG.getEntryNode();
20011 MVT SrcVT = Src.getSimpleValueType();
20012 MVT VT = Op.getSimpleValueType();
20013 SDLoc dl(Op);
20014
20015 if (SDValue Extract = vectorizeExtractedCast(Op, DAG, Subtarget))
20016 return Extract;
20017
20018 if (SDValue R = lowerFPToIntToFP(Op, DAG, Subtarget))
20019 return R;
20020
20021 if (SrcVT.isVector()) {
20022 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
20023 // Note: Since v2f64 is a legal type. We don't need to zero extend the
20024 // source for strict FP.
20025 if (IsStrict)
20026 return DAG.getNode(
20027 X86ISD::STRICT_CVTSI2P, dl, {VT, MVT::Other},
20028 {Chain, DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
20029 DAG.getUNDEF(SrcVT))});
20030 return DAG.getNode(X86ISD::CVTSI2P, dl, VT,
20031 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
20032 DAG.getUNDEF(SrcVT)));
20033 }
20034 if (SrcVT == MVT::v2i64 || SrcVT == MVT::v4i64)
20035 return lowerINT_TO_FP_vXi64(Op, DAG, Subtarget);
20036
20037 return SDValue();
20038 }
20039
20040 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&(static_cast <bool> (SrcVT <= MVT::i64 && SrcVT
>= MVT::i16 && "Unknown SINT_TO_FP to lower!") ? void
(0) : __assert_fail ("SrcVT <= MVT::i64 && SrcVT >= MVT::i16 && \"Unknown SINT_TO_FP to lower!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20041, __extension__ __PRETTY_FUNCTION__))
20041 "Unknown SINT_TO_FP to lower!")(static_cast <bool> (SrcVT <= MVT::i64 && SrcVT
>= MVT::i16 && "Unknown SINT_TO_FP to lower!") ? void
(0) : __assert_fail ("SrcVT <= MVT::i64 && SrcVT >= MVT::i16 && \"Unknown SINT_TO_FP to lower!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20041, __extension__ __PRETTY_FUNCTION__))
;
20042
20043 bool UseSSEReg = isScalarFPTypeInSSEReg(VT);
20044
20045 // These are really Legal; return the operand so the caller accepts it as
20046 // Legal.
20047 if (SrcVT == MVT::i32 && UseSSEReg)
20048 return Op;
20049 if (SrcVT == MVT::i64 && UseSSEReg && Subtarget.is64Bit())
20050 return Op;
20051
20052 if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, DAG, Subtarget))
20053 return V;
20054
20055 // SSE doesn't have an i16 conversion so we need to promote.
20056 if (SrcVT == MVT::i16 && (UseSSEReg || VT == MVT::f128)) {
20057 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, Src);
20058 if (IsStrict)
20059 return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
20060 {Chain, Ext});
20061
20062 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Ext);
20063 }
20064
20065 if (VT == MVT::f128)
20066 return SDValue();
20067
20068 SDValue ValueToStore = Src;
20069 if (SrcVT == MVT::i64 && Subtarget.hasSSE2() && !Subtarget.is64Bit())
20070 // Bitcasting to f64 here allows us to do a single 64-bit store from
20071 // an SSE register, avoiding the store forwarding penalty that would come
20072 // with two 32-bit stores.
20073 ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
20074
20075 unsigned Size = SrcVT.getStoreSize();
20076 Align Alignment(Size);
20077 MachineFunction &MF = DAG.getMachineFunction();
20078 auto PtrVT = getPointerTy(MF.getDataLayout());
20079 int SSFI = MF.getFrameInfo().CreateStackObject(Size, Alignment, false);
20080 MachinePointerInfo MPI =
20081 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI);
20082 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
20083 Chain = DAG.getStore(Chain, dl, ValueToStore, StackSlot, MPI, Alignment);
20084 std::pair<SDValue, SDValue> Tmp =
20085 BuildFILD(VT, SrcVT, dl, Chain, StackSlot, MPI, Alignment, DAG);
20086
20087 if (IsStrict)
20088 return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
20089
20090 return Tmp.first;
20091}
20092
20093std::pair<SDValue, SDValue> X86TargetLowering::BuildFILD(
20094 EVT DstVT, EVT SrcVT, const SDLoc &DL, SDValue Chain, SDValue Pointer,
20095 MachinePointerInfo PtrInfo, Align Alignment, SelectionDAG &DAG) const {
20096 // Build the FILD
20097 SDVTList Tys;
20098 bool useSSE = isScalarFPTypeInSSEReg(DstVT);
20099 if (useSSE)
20100 Tys = DAG.getVTList(MVT::f80, MVT::Other);
20101 else
20102 Tys = DAG.getVTList(DstVT, MVT::Other);
20103
20104 SDValue FILDOps[] = {Chain, Pointer};
20105 SDValue Result =
20106 DAG.getMemIntrinsicNode(X86ISD::FILD, DL, Tys, FILDOps, SrcVT, PtrInfo,
20107 Alignment, MachineMemOperand::MOLoad);
20108 Chain = Result.getValue(1);
20109
20110 if (useSSE) {
20111 MachineFunction &MF = DAG.getMachineFunction();
20112 unsigned SSFISize = DstVT.getStoreSize();
20113 int SSFI =
20114 MF.getFrameInfo().CreateStackObject(SSFISize, Align(SSFISize), false);
20115 auto PtrVT = getPointerTy(MF.getDataLayout());
20116 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
20117 Tys = DAG.getVTList(MVT::Other);
20118 SDValue FSTOps[] = {Chain, Result, StackSlot};
20119 MachineMemOperand *StoreMMO = DAG.getMachineFunction().getMachineMemOperand(
20120 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
20121 MachineMemOperand::MOStore, SSFISize, Align(SSFISize));
20122
20123 Chain =
20124 DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, FSTOps, DstVT, StoreMMO);
20125 Result = DAG.getLoad(
20126 DstVT, DL, Chain, StackSlot,
20127 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI));
20128 Chain = Result.getValue(1);
20129 }
20130
20131 return { Result, Chain };
20132}
20133
20134/// Horizontal vector math instructions may be slower than normal math with
20135/// shuffles. Limit horizontal op codegen based on size/speed trade-offs, uarch
20136/// implementation, and likely shuffle complexity of the alternate sequence.
20137static bool shouldUseHorizontalOp(bool IsSingleSource, SelectionDAG &DAG,
20138 const X86Subtarget &Subtarget) {
20139 bool IsOptimizingSize = DAG.shouldOptForSize();
20140 bool HasFastHOps = Subtarget.hasFastHorizontalOps();
20141 return !IsSingleSource || IsOptimizingSize || HasFastHOps;
20142}
20143
20144/// 64-bit unsigned integer to double expansion.
20145static SDValue LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG,
20146 const X86Subtarget &Subtarget) {
20147 // We can't use this algorithm for strict fp. It produces -0.0 instead of +0.0
20148 // when converting 0 when rounding toward negative infinity. Caller will
20149 // fall back to Expand for when i64 or is legal or use FILD in 32-bit mode.
20150 assert(!Op->isStrictFPOpcode() && "Expected non-strict uint_to_fp!")(static_cast <bool> (!Op->isStrictFPOpcode() &&
"Expected non-strict uint_to_fp!") ? void (0) : __assert_fail
("!Op->isStrictFPOpcode() && \"Expected non-strict uint_to_fp!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20150, __extension__ __PRETTY_FUNCTION__))
;
20151 // This algorithm is not obvious. Here it is what we're trying to output:
20152 /*
20153 movq %rax, %xmm0
20154 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
20155 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
20156 #ifdef __SSE3__
20157 haddpd %xmm0, %xmm0
20158 #else
20159 pshufd $0x4e, %xmm0, %xmm1
20160 addpd %xmm1, %xmm0
20161 #endif
20162 */
20163
20164 SDLoc dl(Op);
20165 LLVMContext *Context = DAG.getContext();
20166
20167 // Build some magic constants.
20168 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
20169 Constant *C0 = ConstantDataVector::get(*Context, CV0);
20170 auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
20171 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, Align(16));
20172
20173 SmallVector<Constant*,2> CV1;
20174 CV1.push_back(
20175 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
20176 APInt(64, 0x4330000000000000ULL))));
20177 CV1.push_back(
20178 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
20179 APInt(64, 0x4530000000000000ULL))));
20180 Constant *C1 = ConstantVector::get(CV1);
20181 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, Align(16));
20182
20183 // Load the 64-bit value into an XMM register.
20184 SDValue XR1 =
20185 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Op.getOperand(0));
20186 SDValue CLod0 = DAG.getLoad(
20187 MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
20188 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(16));
20189 SDValue Unpck1 =
20190 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
20191
20192 SDValue CLod1 = DAG.getLoad(
20193 MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
20194 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(16));
20195 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
20196 // TODO: Are there any fast-math-flags to propagate here?
20197 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
20198 SDValue Result;
20199
20200 if (Subtarget.hasSSE3() &&
20201 shouldUseHorizontalOp(true, DAG, Subtarget)) {
20202 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
20203 } else {
20204 SDValue Shuffle = DAG.getVectorShuffle(MVT::v2f64, dl, Sub, Sub, {1,-1});
20205 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuffle, Sub);
20206 }
20207 Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
20208 DAG.getIntPtrConstant(0, dl));
20209 return Result;
20210}
20211
20212/// 32-bit unsigned integer to float expansion.
20213static SDValue LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG,
20214 const X86Subtarget &Subtarget) {
20215 unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
20216 SDLoc dl(Op);
20217 // FP constant to bias correct the final result.
20218 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
20219 MVT::f64);
20220
20221 // Load the 32-bit value into an XMM register.
20222 SDValue Load =
20223 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Op.getOperand(OpNo));
20224
20225 // Zero out the upper parts of the register.
20226 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
20227
20228 // Or the load with the bias.
20229 SDValue Or = DAG.getNode(
20230 ISD::OR, dl, MVT::v2i64,
20231 DAG.getBitcast(MVT::v2i64, Load),
20232 DAG.getBitcast(MVT::v2i64,
20233 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
20234 Or =
20235 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
20236 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
20237
20238 if (Op.getNode()->isStrictFPOpcode()) {
20239 // Subtract the bias.
20240 // TODO: Are there any fast-math-flags to propagate here?
20241 SDValue Chain = Op.getOperand(0);
20242 SDValue Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::f64, MVT::Other},
20243 {Chain, Or, Bias});
20244
20245 if (Op.getValueType() == Sub.getValueType())
20246 return Sub;
20247
20248 // Handle final rounding.
20249 std::pair<SDValue, SDValue> ResultPair = DAG.getStrictFPExtendOrRound(
20250 Sub, Sub.getValue(1), dl, Op.getSimpleValueType());
20251
20252 return DAG.getMergeValues({ResultPair.first, ResultPair.second}, dl);
20253 }
20254
20255 // Subtract the bias.
20256 // TODO: Are there any fast-math-flags to propagate here?
20257 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
20258
20259 // Handle final rounding.
20260 return DAG.getFPExtendOrRound(Sub, dl, Op.getSimpleValueType());
20261}
20262
20263static SDValue lowerUINT_TO_FP_v2i32(SDValue Op, SelectionDAG &DAG,
20264 const X86Subtarget &Subtarget,
20265 const SDLoc &DL) {
20266 if (Op.getSimpleValueType() != MVT::v2f64)
20267 return SDValue();
20268
20269 bool IsStrict = Op->isStrictFPOpcode();
20270
20271 SDValue N0 = Op.getOperand(IsStrict ? 1 : 0);
20272 assert(N0.getSimpleValueType() == MVT::v2i32 && "Unexpected input type")(static_cast <bool> (N0.getSimpleValueType() == MVT::v2i32
&& "Unexpected input type") ? void (0) : __assert_fail
("N0.getSimpleValueType() == MVT::v2i32 && \"Unexpected input type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20272, __extension__ __PRETTY_FUNCTION__))
;
20273
20274 if (Subtarget.hasAVX512()) {
20275 if (!Subtarget.hasVLX()) {
20276 // Let generic type legalization widen this.
20277 if (!IsStrict)
20278 return SDValue();
20279 // Otherwise pad the integer input with 0s and widen the operation.
20280 N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
20281 DAG.getConstant(0, DL, MVT::v2i32));
20282 SDValue Res = DAG.getNode(Op->getOpcode(), DL, {MVT::v4f64, MVT::Other},
20283 {Op.getOperand(0), N0});
20284 SDValue Chain = Res.getValue(1);
20285 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2f64, Res,
20286 DAG.getIntPtrConstant(0, DL));
20287 return DAG.getMergeValues({Res, Chain}, DL);
20288 }
20289
20290 // Legalize to v4i32 type.
20291 N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
20292 DAG.getUNDEF(MVT::v2i32));
20293 if (IsStrict)
20294 return DAG.getNode(X86ISD::STRICT_CVTUI2P, DL, {MVT::v2f64, MVT::Other},
20295 {Op.getOperand(0), N0});
20296 return DAG.getNode(X86ISD::CVTUI2P, DL, MVT::v2f64, N0);
20297 }
20298
20299 // Zero extend to 2i64, OR with the floating point representation of 2^52.
20300 // This gives us the floating point equivalent of 2^52 + the i32 integer
20301 // since double has 52-bits of mantissa. Then subtract 2^52 in floating
20302 // point leaving just our i32 integers in double format.
20303 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v2i64, N0);
20304 SDValue VBias =
20305 DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), DL, MVT::v2f64);
20306 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v2i64, ZExtIn,
20307 DAG.getBitcast(MVT::v2i64, VBias));
20308 Or = DAG.getBitcast(MVT::v2f64, Or);
20309
20310 if (IsStrict)
20311 return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v2f64, MVT::Other},
20312 {Op.getOperand(0), Or, VBias});
20313 return DAG.getNode(ISD::FSUB, DL, MVT::v2f64, Or, VBias);
20314}
20315
20316static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
20317 const X86Subtarget &Subtarget) {
20318 SDLoc DL(Op);
20319 bool IsStrict = Op->isStrictFPOpcode();
20320 SDValue V = Op->getOperand(IsStrict ? 1 : 0);
20321 MVT VecIntVT = V.getSimpleValueType();
20322 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&(static_cast <bool> ((VecIntVT == MVT::v4i32 || VecIntVT
== MVT::v8i32) && "Unsupported custom type") ? void (
0) : __assert_fail ("(VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) && \"Unsupported custom type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20323, __extension__ __PRETTY_FUNCTION__))
20323 "Unsupported custom type")(static_cast <bool> ((VecIntVT == MVT::v4i32 || VecIntVT
== MVT::v8i32) && "Unsupported custom type") ? void (
0) : __assert_fail ("(VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) && \"Unsupported custom type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20323, __extension__ __PRETTY_FUNCTION__))
;
20324
20325 if (Subtarget.hasAVX512()) {
20326 // With AVX512, but not VLX we need to widen to get a 512-bit result type.
20327 assert(!Subtarget.hasVLX() && "Unexpected features")(static_cast <bool> (!Subtarget.hasVLX() && "Unexpected features"
) ? void (0) : __assert_fail ("!Subtarget.hasVLX() && \"Unexpected features\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20327, __extension__ __PRETTY_FUNCTION__))
;
20328 MVT VT = Op->getSimpleValueType(0);
20329
20330 // v8i32->v8f64 is legal with AVX512 so just return it.
20331 if (VT == MVT::v8f64)
20332 return Op;
20333
20334 assert((VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v4f64) &&(static_cast <bool> ((VT == MVT::v4f32 || VT == MVT::v8f32
|| VT == MVT::v4f64) && "Unexpected VT!") ? void (0)
: __assert_fail ("(VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v4f64) && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20335, __extension__ __PRETTY_FUNCTION__))
20335 "Unexpected VT!")(static_cast <bool> ((VT == MVT::v4f32 || VT == MVT::v8f32
|| VT == MVT::v4f64) && "Unexpected VT!") ? void (0)
: __assert_fail ("(VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v4f64) && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20335, __extension__ __PRETTY_FUNCTION__))
;
20336 MVT WideVT = VT == MVT::v4f64 ? MVT::v8f64 : MVT::v16f32;
20337 MVT WideIntVT = VT == MVT::v4f64 ? MVT::v8i32 : MVT::v16i32;
20338 // Need to concat with zero vector for strict fp to avoid spurious
20339 // exceptions.
20340 SDValue Tmp =
20341 IsStrict ? DAG.getConstant(0, DL, WideIntVT) : DAG.getUNDEF(WideIntVT);
20342 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideIntVT, Tmp, V,
20343 DAG.getIntPtrConstant(0, DL));
20344 SDValue Res, Chain;
20345 if (IsStrict) {
20346 Res = DAG.getNode(ISD::STRICT_UINT_TO_FP, DL, {WideVT, MVT::Other},
20347 {Op->getOperand(0), V});
20348 Chain = Res.getValue(1);
20349 } else {
20350 Res = DAG.getNode(ISD::UINT_TO_FP, DL, WideVT, V);
20351 }
20352
20353 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
20354 DAG.getIntPtrConstant(0, DL));
20355
20356 if (IsStrict)
20357 return DAG.getMergeValues({Res, Chain}, DL);
20358 return Res;
20359 }
20360
20361 if (Subtarget.hasAVX() && VecIntVT == MVT::v4i32 &&
20362 Op->getSimpleValueType(0) == MVT::v4f64) {
20363 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i64, V);
20364 Constant *Bias = ConstantFP::get(
20365 *DAG.getContext(),
20366 APFloat(APFloat::IEEEdouble(), APInt(64, 0x4330000000000000ULL)));
20367 auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
20368 SDValue CPIdx = DAG.getConstantPool(Bias, PtrVT, Align(8));
20369 SDVTList Tys = DAG.getVTList(MVT::v4f64, MVT::Other);
20370 SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
20371 SDValue VBias = DAG.getMemIntrinsicNode(
20372 X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::f64,
20373 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(8),
20374 MachineMemOperand::MOLoad);
20375
20376 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v4i64, ZExtIn,
20377 DAG.getBitcast(MVT::v4i64, VBias));
20378 Or = DAG.getBitcast(MVT::v4f64, Or);
20379
20380 if (IsStrict)
20381 return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v4f64, MVT::Other},
20382 {Op.getOperand(0), Or, VBias});
20383 return DAG.getNode(ISD::FSUB, DL, MVT::v4f64, Or, VBias);
20384 }
20385
20386 // The algorithm is the following:
20387 // #ifdef __SSE4_1__
20388 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
20389 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
20390 // (uint4) 0x53000000, 0xaa);
20391 // #else
20392 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
20393 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
20394 // #endif
20395 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
20396 // return (float4) lo + fhi;
20397
20398 bool Is128 = VecIntVT == MVT::v4i32;
20399 MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
20400 // If we convert to something else than the supported type, e.g., to v4f64,
20401 // abort early.
20402 if (VecFloatVT != Op->getSimpleValueType(0))
20403 return SDValue();
20404
20405 // In the #idef/#else code, we have in common:
20406 // - The vector of constants:
20407 // -- 0x4b000000
20408 // -- 0x53000000
20409 // - A shift:
20410 // -- v >> 16
20411
20412 // Create the splat vector for 0x4b000000.
20413 SDValue VecCstLow = DAG.getConstant(0x4b000000, DL, VecIntVT);
20414 // Create the splat vector for 0x53000000.
20415 SDValue VecCstHigh = DAG.getConstant(0x53000000, DL, VecIntVT);
20416
20417 // Create the right shift.
20418 SDValue VecCstShift = DAG.getConstant(16, DL, VecIntVT);
20419 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
20420
20421 SDValue Low, High;
20422 if (Subtarget.hasSSE41()) {
20423 MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
20424 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
20425 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
20426 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
20427 // Low will be bitcasted right away, so do not bother bitcasting back to its
20428 // original type.
20429 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
20430 VecCstLowBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
20431 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
20432 // (uint4) 0x53000000, 0xaa);
20433 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
20434 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
20435 // High will be bitcasted right away, so do not bother bitcasting back to
20436 // its original type.
20437 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
20438 VecCstHighBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
20439 } else {
20440 SDValue VecCstMask = DAG.getConstant(0xffff, DL, VecIntVT);
20441 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
20442 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
20443 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
20444
20445 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
20446 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
20447 }
20448
20449 // Create the vector constant for (0x1.0p39f + 0x1.0p23f).
20450 SDValue VecCstFSub = DAG.getConstantFP(
20451 APFloat(APFloat::IEEEsingle(), APInt(32, 0x53000080)), DL, VecFloatVT);
20452
20453 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
20454 // NOTE: By using fsub of a positive constant instead of fadd of a negative
20455 // constant, we avoid reassociation in MachineCombiner when unsafe-fp-math is
20456 // enabled. See PR24512.
20457 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
20458 // TODO: Are there any fast-math-flags to propagate here?
20459 // (float4) lo;
20460 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
20461 // return (float4) lo + fhi;
20462 if (IsStrict) {
20463 SDValue FHigh = DAG.getNode(ISD::STRICT_FSUB, DL, {VecFloatVT, MVT::Other},
20464 {Op.getOperand(0), HighBitcast, VecCstFSub});
20465 return DAG.getNode(ISD::STRICT_FADD, DL, {VecFloatVT, MVT::Other},
20466 {FHigh.getValue(1), LowBitcast, FHigh});
20467 }
20468
20469 SDValue FHigh =
20470 DAG.getNode(ISD::FSUB, DL, VecFloatVT, HighBitcast, VecCstFSub);
20471 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
20472}
20473
20474static SDValue lowerUINT_TO_FP_vec(SDValue Op, SelectionDAG &DAG,
20475 const X86Subtarget &Subtarget) {
20476 unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
20477 SDValue N0 = Op.getOperand(OpNo);
20478 MVT SrcVT = N0.getSimpleValueType();
20479 SDLoc dl(Op);
20480
20481 switch (SrcVT.SimpleTy) {
20482 default:
20483 llvm_unreachable("Custom UINT_TO_FP is not supported!")::llvm::llvm_unreachable_internal("Custom UINT_TO_FP is not supported!"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20483)
;
20484 case MVT::v2i32:
20485 return lowerUINT_TO_FP_v2i32(Op, DAG, Subtarget, dl);
20486 case MVT::v4i32:
20487 case MVT::v8i32:
20488 return lowerUINT_TO_FP_vXi32(Op, DAG, Subtarget);
20489 case MVT::v2i64:
20490 case MVT::v4i64:
20491 return lowerINT_TO_FP_vXi64(Op, DAG, Subtarget);
20492 }
20493}
20494
20495SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
20496 SelectionDAG &DAG) const {
20497 bool IsStrict = Op->isStrictFPOpcode();
20498 unsigned OpNo = IsStrict ? 1 : 0;
20499 SDValue Src = Op.getOperand(OpNo);
20500 SDLoc dl(Op);
20501 auto PtrVT = getPointerTy(DAG.getDataLayout());
20502 MVT SrcVT = Src.getSimpleValueType();
20503 MVT DstVT = Op->getSimpleValueType(0);
20504 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
20505
20506 if (DstVT == MVT::f128)
20507 return SDValue();
20508
20509 if (DstVT.isVector())
20510 return lowerUINT_TO_FP_vec(Op, DAG, Subtarget);
20511
20512 if (SDValue Extract = vectorizeExtractedCast(Op, DAG, Subtarget))
20513 return Extract;
20514
20515 if (Subtarget.hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
20516 (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget.is64Bit()))) {
20517 // Conversions from unsigned i32 to f32/f64 are legal,
20518 // using VCVTUSI2SS/SD. Same for i64 in 64-bit mode.
20519 return Op;
20520 }
20521
20522 // Promote i32 to i64 and use a signed conversion on 64-bit targets.
20523 if (SrcVT == MVT::i32 && Subtarget.is64Bit()) {
20524 Src = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Src);
20525 if (IsStrict)
20526 return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {DstVT, MVT::Other},
20527 {Chain, Src});
20528 return DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Src);
20529 }
20530
20531 if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, DAG, Subtarget))
20532 return V;
20533
20534 // The transform for i64->f64 isn't correct for 0 when rounding to negative
20535 // infinity. It produces -0.0, so disable under strictfp.
20536 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64 && !IsStrict)
20537 return LowerUINT_TO_FP_i64(Op, DAG, Subtarget);
20538 if (SrcVT == MVT::i32 && X86ScalarSSEf64 && DstVT != MVT::f80)
20539 return LowerUINT_TO_FP_i32(Op, DAG, Subtarget);
20540 if (Subtarget.is64Bit() && SrcVT == MVT::i64 &&
20541 (DstVT == MVT::f32 || DstVT == MVT::f64))
20542 return SDValue();
20543
20544 // Make a 64-bit buffer, and use it to build an FILD.
20545 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64, 8);
20546 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
20547 Align SlotAlign(8);
20548 MachinePointerInfo MPI =
20549 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI);
20550 if (SrcVT == MVT::i32) {
20551 SDValue OffsetSlot =
20552 DAG.getMemBasePlusOffset(StackSlot, TypeSize::Fixed(4), dl);
20553 SDValue Store1 = DAG.getStore(Chain, dl, Src, StackSlot, MPI, SlotAlign);
20554 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
20555 OffsetSlot, MPI.getWithOffset(4), SlotAlign);
20556 std::pair<SDValue, SDValue> Tmp =
20557 BuildFILD(DstVT, MVT::i64, dl, Store2, StackSlot, MPI, SlotAlign, DAG);
20558 if (IsStrict)
20559 return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
20560
20561 return Tmp.first;
20562 }
20563
20564 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP")(static_cast <bool> (SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP"
) ? void (0) : __assert_fail ("SrcVT == MVT::i64 && \"Unexpected type in UINT_TO_FP\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20564, __extension__ __PRETTY_FUNCTION__))
;
20565 SDValue ValueToStore = Src;
20566 if (isScalarFPTypeInSSEReg(Op.getValueType()) && !Subtarget.is64Bit()) {
20567 // Bitcasting to f64 here allows us to do a single 64-bit store from
20568 // an SSE register, avoiding the store forwarding penalty that would come
20569 // with two 32-bit stores.
20570 ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
20571 }
20572 SDValue Store =
20573 DAG.getStore(Chain, dl, ValueToStore, StackSlot, MPI, SlotAlign);
20574 // For i64 source, we need to add the appropriate power of 2 if the input
20575 // was negative. We must be careful to do the computation in x87 extended
20576 // precision, not in SSE.
20577 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
20578 SDValue Ops[] = { Store, StackSlot };
20579 SDValue Fild =
20580 DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, MVT::i64, MPI,
20581 SlotAlign, MachineMemOperand::MOLoad);
20582 Chain = Fild.getValue(1);
20583
20584
20585 // Check whether the sign bit is set.
20586 SDValue SignSet = DAG.getSetCC(
20587 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
20588 Op.getOperand(OpNo), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
20589
20590 // Build a 64 bit pair (FF, 0) in the constant pool, with FF in the hi bits.
20591 APInt FF(64, 0x5F80000000000000ULL);
20592 SDValue FudgePtr = DAG.getConstantPool(
20593 ConstantInt::get(*DAG.getContext(), FF), PtrVT);
20594 Align CPAlignment = cast<ConstantPoolSDNode>(FudgePtr)->getAlign();
20595
20596 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
20597 SDValue Zero = DAG.getIntPtrConstant(0, dl);
20598 SDValue Four = DAG.getIntPtrConstant(4, dl);
20599 SDValue Offset = DAG.getSelect(dl, Zero.getValueType(), SignSet, Four, Zero);
20600 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
20601
20602 // Load the value out, extending it from f32 to f80.
20603 SDValue Fudge = DAG.getExtLoad(
20604 ISD::EXTLOAD, dl, MVT::f80, Chain, FudgePtr,
20605 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
20606 CPAlignment);
20607 Chain = Fudge.getValue(1);
20608 // Extend everything to 80 bits to force it to be done on x87.
20609 // TODO: Are there any fast-math-flags to propagate here?
20610 if (IsStrict) {
20611 SDValue Add = DAG.getNode(ISD::STRICT_FADD, dl, {MVT::f80, MVT::Other},
20612 {Chain, Fild, Fudge});
20613 // STRICT_FP_ROUND can't handle equal types.
20614 if (DstVT == MVT::f80)
20615 return Add;
20616 return DAG.getNode(ISD::STRICT_FP_ROUND, dl, {DstVT, MVT::Other},
20617 {Add.getValue(1), Add, DAG.getIntPtrConstant(0, dl)});
20618 }
20619 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
20620 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
20621 DAG.getIntPtrConstant(0, dl));
20622}
20623
20624// If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
20625// is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
20626// just return an SDValue().
20627// Otherwise it is assumed to be a conversion from one of f32, f64 or f80
20628// to i16, i32 or i64, and we lower it to a legal sequence and return the
20629// result.
20630SDValue
20631X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
20632 bool IsSigned, SDValue &Chain) const {
20633 bool IsStrict = Op->isStrictFPOpcode();
20634 SDLoc DL(Op);
20635
20636 EVT DstTy = Op.getValueType();
20637 SDValue Value = Op.getOperand(IsStrict ? 1 : 0);
20638 EVT TheVT = Value.getValueType();
20639 auto PtrVT = getPointerTy(DAG.getDataLayout());
20640
20641 if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
20642 // f16 must be promoted before using the lowering in this routine.
20643 // fp128 does not use this lowering.
20644 return SDValue();
20645 }
20646
20647 // If using FIST to compute an unsigned i64, we'll need some fixup
20648 // to handle values above the maximum signed i64. A FIST is always
20649 // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
20650 bool UnsignedFixup = !IsSigned && DstTy == MVT::i64;
20651
20652 // FIXME: This does not generate an invalid exception if the input does not
20653 // fit in i32. PR44019
20654 if (!IsSigned && DstTy != MVT::i64) {
20655 // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
20656 // The low 32 bits of the fist result will have the correct uint32 result.
20657 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT")(static_cast <bool> (DstTy == MVT::i32 && "Unexpected FP_TO_UINT"
) ? void (0) : __assert_fail ("DstTy == MVT::i32 && \"Unexpected FP_TO_UINT\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20657, __extension__ __PRETTY_FUNCTION__))
;
20658 DstTy = MVT::i64;
20659 }
20660
20661 assert(DstTy.getSimpleVT() <= MVT::i64 &&(static_cast <bool> (DstTy.getSimpleVT() <= MVT::i64
&& DstTy.getSimpleVT() >= MVT::i16 && "Unknown FP_TO_INT to lower!"
) ? void (0) : __assert_fail ("DstTy.getSimpleVT() <= MVT::i64 && DstTy.getSimpleVT() >= MVT::i16 && \"Unknown FP_TO_INT to lower!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20663, __extension__ __PRETTY_FUNCTION__))
20662 DstTy.getSimpleVT() >= MVT::i16 &&(static_cast <bool> (DstTy.getSimpleVT() <= MVT::i64
&& DstTy.getSimpleVT() >= MVT::i16 && "Unknown FP_TO_INT to lower!"
) ? void (0) : __assert_fail ("DstTy.getSimpleVT() <= MVT::i64 && DstTy.getSimpleVT() >= MVT::i16 && \"Unknown FP_TO_INT to lower!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20663, __extension__ __PRETTY_FUNCTION__))
20663 "Unknown FP_TO_INT to lower!")(static_cast <bool> (DstTy.getSimpleVT() <= MVT::i64
&& DstTy.getSimpleVT() >= MVT::i16 && "Unknown FP_TO_INT to lower!"
) ? void (0) : __assert_fail ("DstTy.getSimpleVT() <= MVT::i64 && DstTy.getSimpleVT() >= MVT::i16 && \"Unknown FP_TO_INT to lower!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20663, __extension__ __PRETTY_FUNCTION__))
;
20664
20665 // We lower FP->int64 into FISTP64 followed by a load from a temporary
20666 // stack slot.
20667 MachineFunction &MF = DAG.getMachineFunction();
20668 unsigned MemSize = DstTy.getStoreSize();
20669 int SSFI =
20670 MF.getFrameInfo().CreateStackObject(MemSize, Align(MemSize), false);
20671 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
20672
20673 Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
20674
20675 SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
20676
20677 if (UnsignedFixup) {
20678 //
20679 // Conversion to unsigned i64 is implemented with a select,
20680 // depending on whether the source value fits in the range
20681 // of a signed i64. Let Thresh be the FP equivalent of
20682 // 0x8000000000000000ULL.
20683 //
20684 // Adjust = (Value >= Thresh) ? 0x80000000 : 0;
20685 // FltOfs = (Value >= Thresh) ? 0x80000000 : 0;
20686 // FistSrc = (Value - FltOfs);
20687 // Fist-to-mem64 FistSrc
20688 // Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
20689 // to XOR'ing the high 32 bits with Adjust.
20690 //
20691 // Being a power of 2, Thresh is exactly representable in all FP formats.
20692 // For X87 we'd like to use the smallest FP type for this constant, but
20693 // for DAG type consistency we have to match the FP operand type.
20694
20695 APFloat Thresh(APFloat::IEEEsingle(), APInt(32, 0x5f000000));
20696 LLVM_ATTRIBUTE_UNUSED__attribute__((__unused__)) APFloat::opStatus Status = APFloat::opOK;
20697 bool LosesInfo = false;
20698 if (TheVT == MVT::f64)
20699 // The rounding mode is irrelevant as the conversion should be exact.
20700 Status = Thresh.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
20701 &LosesInfo);
20702 else if (TheVT == MVT::f80)
20703 Status = Thresh.convert(APFloat::x87DoubleExtended(),
20704 APFloat::rmNearestTiesToEven, &LosesInfo);
20705
20706 assert(Status == APFloat::opOK && !LosesInfo &&(static_cast <bool> (Status == APFloat::opOK &&
!LosesInfo && "FP conversion should have been exact"
) ? void (0) : __assert_fail ("Status == APFloat::opOK && !LosesInfo && \"FP conversion should have been exact\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20707, __extension__ __PRETTY_FUNCTION__))
20707 "FP conversion should have been exact")(static_cast <bool> (Status == APFloat::opOK &&
!LosesInfo && "FP conversion should have been exact"
) ? void (0) : __assert_fail ("Status == APFloat::opOK && !LosesInfo && \"FP conversion should have been exact\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20707, __extension__ __PRETTY_FUNCTION__))
;
20708
20709 SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
20710
20711 EVT ResVT = getSetCCResultType(DAG.getDataLayout(),
20712 *DAG.getContext(), TheVT);
20713 SDValue Cmp;
20714 if (IsStrict) {
20715 Cmp = DAG.getSetCC(DL, ResVT, Value, ThreshVal, ISD::SETGE, Chain,
20716 /*IsSignaling*/ true);
20717 Chain = Cmp.getValue(1);
20718 } else {
20719 Cmp = DAG.getSetCC(DL, ResVT, Value, ThreshVal, ISD::SETGE);
20720 }
20721
20722 // Our preferred lowering of
20723 //
20724 // (Value >= Thresh) ? 0x8000000000000000ULL : 0
20725 //
20726 // is
20727 //
20728 // (Value >= Thresh) << 63
20729 //
20730 // but since we can get here after LegalOperations, DAGCombine might do the
20731 // wrong thing if we create a select. So, directly create the preferred
20732 // version.
20733 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Cmp);
20734 SDValue Const63 = DAG.getConstant(63, DL, MVT::i8);
20735 Adjust = DAG.getNode(ISD::SHL, DL, MVT::i64, Zext, Const63);
20736
20737 SDValue FltOfs = DAG.getSelect(DL, TheVT, Cmp, ThreshVal,
20738 DAG.getConstantFP(0.0, DL, TheVT));
20739
20740 if (IsStrict) {
20741 Value = DAG.getNode(ISD::STRICT_FSUB, DL, { TheVT, MVT::Other},
20742 { Chain, Value, FltOfs });
20743 Chain = Value.getValue(1);
20744 } else
20745 Value = DAG.getNode(ISD::FSUB, DL, TheVT, Value, FltOfs);
20746 }
20747
20748 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, SSFI);
20749
20750 // FIXME This causes a redundant load/store if the SSE-class value is already
20751 // in memory, such as if it is on the callstack.
20752 if (isScalarFPTypeInSSEReg(TheVT)) {
20753 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!")(static_cast <bool> (DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!"
) ? void (0) : __assert_fail ("DstTy == MVT::i64 && \"Invalid FP_TO_SINT to lower!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20753, __extension__ __PRETTY_FUNCTION__))
;
20754 Chain = DAG.getStore(Chain, DL, Value, StackSlot, MPI);
20755 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
20756 SDValue Ops[] = { Chain, StackSlot };
20757
20758 unsigned FLDSize = TheVT.getStoreSize();
20759 assert(FLDSize <= MemSize && "Stack slot not big enough")(static_cast <bool> (FLDSize <= MemSize && "Stack slot not big enough"
) ? void (0) : __assert_fail ("FLDSize <= MemSize && \"Stack slot not big enough\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20759, __extension__ __PRETTY_FUNCTION__))
;
20760 MachineMemOperand *MMO = MF.getMachineMemOperand(
20761 MPI, MachineMemOperand::MOLoad, FLDSize, Align(FLDSize));
20762 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, TheVT, MMO);
20763 Chain = Value.getValue(1);
20764 }
20765
20766 // Build the FP_TO_INT*_IN_MEM
20767 MachineMemOperand *MMO = MF.getMachineMemOperand(
20768 MPI, MachineMemOperand::MOStore, MemSize, Align(MemSize));
20769 SDValue Ops[] = { Chain, Value, StackSlot };
20770 SDValue FIST = DAG.getMemIntrinsicNode(X86ISD::FP_TO_INT_IN_MEM, DL,
20771 DAG.getVTList(MVT::Other),
20772 Ops, DstTy, MMO);
20773
20774 SDValue Res = DAG.getLoad(Op.getValueType(), SDLoc(Op), FIST, StackSlot, MPI);
20775 Chain = Res.getValue(1);
20776
20777 // If we need an unsigned fixup, XOR the result with adjust.
20778 if (UnsignedFixup)
20779 Res = DAG.getNode(ISD::XOR, DL, MVT::i64, Res, Adjust);
20780
20781 return Res;
20782}
20783
20784static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
20785 const X86Subtarget &Subtarget) {
20786 MVT VT = Op.getSimpleValueType();
20787 SDValue In = Op.getOperand(0);
20788 MVT InVT = In.getSimpleValueType();
20789 SDLoc dl(Op);
20790 unsigned Opc = Op.getOpcode();
20791
20792 assert(VT.isVector() && InVT.isVector() && "Expected vector type")(static_cast <bool> (VT.isVector() && InVT.isVector
() && "Expected vector type") ? void (0) : __assert_fail
("VT.isVector() && InVT.isVector() && \"Expected vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20792, __extension__ __PRETTY_FUNCTION__))
;
20793 assert((Opc == ISD::ANY_EXTEND || Opc == ISD::ZERO_EXTEND) &&(static_cast <bool> ((Opc == ISD::ANY_EXTEND || Opc == ISD
::ZERO_EXTEND) && "Unexpected extension opcode") ? void
(0) : __assert_fail ("(Opc == ISD::ANY_EXTEND || Opc == ISD::ZERO_EXTEND) && \"Unexpected extension opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20794, __extension__ __PRETTY_FUNCTION__))
20794 "Unexpected extension opcode")(static_cast <bool> ((Opc == ISD::ANY_EXTEND || Opc == ISD
::ZERO_EXTEND) && "Unexpected extension opcode") ? void
(0) : __assert_fail ("(Opc == ISD::ANY_EXTEND || Opc == ISD::ZERO_EXTEND) && \"Unexpected extension opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20794, __extension__ __PRETTY_FUNCTION__))
;
20795 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&(static_cast <bool> (VT.getVectorNumElements() == InVT.
getVectorNumElements() && "Expected same number of elements"
) ? void (0) : __assert_fail ("VT.getVectorNumElements() == InVT.getVectorNumElements() && \"Expected same number of elements\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20796, __extension__ __PRETTY_FUNCTION__))
20796 "Expected same number of elements")(static_cast <bool> (VT.getVectorNumElements() == InVT.
getVectorNumElements() && "Expected same number of elements"
) ? void (0) : __assert_fail ("VT.getVectorNumElements() == InVT.getVectorNumElements() && \"Expected same number of elements\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20796, __extension__ __PRETTY_FUNCTION__))
;
20797 assert((VT.getVectorElementType() == MVT::i16 ||(static_cast <bool> ((VT.getVectorElementType() == MVT::
i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType
() == MVT::i64) && "Unexpected element type") ? void (
0) : __assert_fail ("(VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType() == MVT::i64) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20800, __extension__ __PRETTY_FUNCTION__))
20798 VT.getVectorElementType() == MVT::i32 ||(static_cast <bool> ((VT.getVectorElementType() == MVT::
i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType
() == MVT::i64) && "Unexpected element type") ? void (
0) : __assert_fail ("(VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType() == MVT::i64) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20800, __extension__ __PRETTY_FUNCTION__))
20799 VT.getVectorElementType() == MVT::i64) &&(static_cast <bool> ((VT.getVectorElementType() == MVT::
i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType
() == MVT::i64) && "Unexpected element type") ? void (
0) : __assert_fail ("(VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType() == MVT::i64) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20800, __extension__ __PRETTY_FUNCTION__))
20800 "Unexpected element type")(static_cast <bool> ((VT.getVectorElementType() == MVT::
i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType
() == MVT::i64) && "Unexpected element type") ? void (
0) : __assert_fail ("(VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType() == MVT::i64) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20800, __extension__ __PRETTY_FUNCTION__))
;
20801 assert((InVT.getVectorElementType() == MVT::i8 ||(static_cast <bool> ((InVT.getVectorElementType() == MVT
::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType
() == MVT::i32) && "Unexpected element type") ? void (
0) : __assert_fail ("(InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20804, __extension__ __PRETTY_FUNCTION__))
20802 InVT.getVectorElementType() == MVT::i16 ||(static_cast <bool> ((InVT.getVectorElementType() == MVT
::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType
() == MVT::i32) && "Unexpected element type") ? void (
0) : __assert_fail ("(InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20804, __extension__ __PRETTY_FUNCTION__))
20803 InVT.getVectorElementType() == MVT::i32) &&(static_cast <bool> ((InVT.getVectorElementType() == MVT
::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType
() == MVT::i32) && "Unexpected element type") ? void (
0) : __assert_fail ("(InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20804, __extension__ __PRETTY_FUNCTION__))
20804 "Unexpected element type")(static_cast <bool> ((InVT.getVectorElementType() == MVT
::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType
() == MVT::i32) && "Unexpected element type") ? void (
0) : __assert_fail ("(InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20804, __extension__ __PRETTY_FUNCTION__))
;
20805
20806 unsigned ExtendInVecOpc = getOpcode_EXTEND_VECTOR_INREG(Opc);
20807
20808 if (VT == MVT::v32i16 && !Subtarget.hasBWI()) {
20809 assert(InVT == MVT::v32i8 && "Unexpected VT!")(static_cast <bool> (InVT == MVT::v32i8 && "Unexpected VT!"
) ? void (0) : __assert_fail ("InVT == MVT::v32i8 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20809, __extension__ __PRETTY_FUNCTION__))
;
20810 return splitVectorIntUnary(Op, DAG);
20811 }
20812
20813 if (Subtarget.hasInt256())
20814 return Op;
20815
20816 // Optimize vectors in AVX mode:
20817 //
20818 // v8i16 -> v8i32
20819 // Use vpmovzwd for 4 lower elements v8i16 -> v4i32.
20820 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
20821 // Concat upper and lower parts.
20822 //
20823 // v4i32 -> v4i64
20824 // Use vpmovzdq for 4 lower elements v4i32 -> v2i64.
20825 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
20826 // Concat upper and lower parts.
20827 //
20828 MVT HalfVT = VT.getHalfNumVectorElementsVT();
20829 SDValue OpLo = DAG.getNode(ExtendInVecOpc, dl, HalfVT, In);
20830
20831 // Short-circuit if we can determine that each 128-bit half is the same value.
20832 // Otherwise, this is difficult to match and optimize.
20833 if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(In))
20834 if (hasIdenticalHalvesShuffleMask(Shuf->getMask()))
20835 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpLo);
20836
20837 SDValue ZeroVec = DAG.getConstant(0, dl, InVT);
20838 SDValue Undef = DAG.getUNDEF(InVT);
20839 bool NeedZero = Opc == ISD::ZERO_EXTEND;
20840 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
20841 OpHi = DAG.getBitcast(HalfVT, OpHi);
20842
20843 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
20844}
20845
20846// Helper to split and extend a v16i1 mask to v16i8 or v16i16.
20847static SDValue SplitAndExtendv16i1(unsigned ExtOpc, MVT VT, SDValue In,
20848 const SDLoc &dl, SelectionDAG &DAG) {
20849 assert((VT == MVT::v16i8 || VT == MVT::v16i16) && "Unexpected VT.")(static_cast <bool> ((VT == MVT::v16i8 || VT == MVT::v16i16
) && "Unexpected VT.") ? void (0) : __assert_fail ("(VT == MVT::v16i8 || VT == MVT::v16i16) && \"Unexpected VT.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20849, __extension__ __PRETTY_FUNCTION__))
;
20850 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
20851 DAG.getIntPtrConstant(0, dl));
20852 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
20853 DAG.getIntPtrConstant(8, dl));
20854 Lo = DAG.getNode(ExtOpc, dl, MVT::v8i16, Lo);
20855 Hi = DAG.getNode(ExtOpc, dl, MVT::v8i16, Hi);
20856 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i16, Lo, Hi);
20857 return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
20858}
20859
20860static SDValue LowerZERO_EXTEND_Mask(SDValue Op,
20861 const X86Subtarget &Subtarget,
20862 SelectionDAG &DAG) {
20863 MVT VT = Op->getSimpleValueType(0);
20864 SDValue In = Op->getOperand(0);
20865 MVT InVT = In.getSimpleValueType();
20866 assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!")(static_cast <bool> (InVT.getVectorElementType() == MVT
::i1 && "Unexpected input type!") ? void (0) : __assert_fail
("InVT.getVectorElementType() == MVT::i1 && \"Unexpected input type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20866, __extension__ __PRETTY_FUNCTION__))
;
20867 SDLoc DL(Op);
20868 unsigned NumElts = VT.getVectorNumElements();
20869
20870 // For all vectors, but vXi8 we can just emit a sign_extend and a shift. This
20871 // avoids a constant pool load.
20872 if (VT.getVectorElementType() != MVT::i8) {
20873 SDValue Extend = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, In);
20874 return DAG.getNode(ISD::SRL, DL, VT, Extend,
20875 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
20876 }
20877
20878 // Extend VT if BWI is not supported.
20879 MVT ExtVT = VT;
20880 if (!Subtarget.hasBWI()) {
20881 // If v16i32 is to be avoided, we'll need to split and concatenate.
20882 if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
20883 return SplitAndExtendv16i1(ISD::ZERO_EXTEND, VT, In, DL, DAG);
20884
20885 ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
20886 }
20887
20888 // Widen to 512-bits if VLX is not supported.
20889 MVT WideVT = ExtVT;
20890 if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
20891 NumElts *= 512 / ExtVT.getSizeInBits();
20892 InVT = MVT::getVectorVT(MVT::i1, NumElts);
20893 In = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT, DAG.getUNDEF(InVT),
20894 In, DAG.getIntPtrConstant(0, DL));
20895 WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(),
20896 NumElts);
20897 }
20898
20899 SDValue One = DAG.getConstant(1, DL, WideVT);
20900 SDValue Zero = DAG.getConstant(0, DL, WideVT);
20901
20902 SDValue SelectedVal = DAG.getSelect(DL, WideVT, In, One, Zero);
20903
20904 // Truncate if we had to extend above.
20905 if (VT != ExtVT) {
20906 WideVT = MVT::getVectorVT(MVT::i8, NumElts);
20907 SelectedVal = DAG.getNode(ISD::TRUNCATE, DL, WideVT, SelectedVal);
20908 }
20909
20910 // Extract back to 128/256-bit if we widened.
20911 if (WideVT != VT)
20912 SelectedVal = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SelectedVal,
20913 DAG.getIntPtrConstant(0, DL));
20914
20915 return SelectedVal;
20916}
20917
20918static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
20919 SelectionDAG &DAG) {
20920 SDValue In = Op.getOperand(0);
20921 MVT SVT = In.getSimpleValueType();
20922
20923 if (SVT.getVectorElementType() == MVT::i1)
20924 return LowerZERO_EXTEND_Mask(Op, Subtarget, DAG);
20925
20926 assert(Subtarget.hasAVX() && "Expected AVX support")(static_cast <bool> (Subtarget.hasAVX() && "Expected AVX support"
) ? void (0) : __assert_fail ("Subtarget.hasAVX() && \"Expected AVX support\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20926, __extension__ __PRETTY_FUNCTION__))
;
20927 return LowerAVXExtend(Op, DAG, Subtarget);
20928}
20929
20930/// Helper to recursively truncate vector elements in half with PACKSS/PACKUS.
20931/// It makes use of the fact that vectors with enough leading sign/zero bits
20932/// prevent the PACKSS/PACKUS from saturating the results.
20933/// AVX2 (Int256) sub-targets require extra shuffling as the PACK*S operates
20934/// within each 128-bit lane.
20935static SDValue truncateVectorWithPACK(unsigned Opcode, EVT DstVT, SDValue In,
20936 const SDLoc &DL, SelectionDAG &DAG,
20937 const X86Subtarget &Subtarget) {
20938 assert((Opcode == X86ISD::PACKSS || Opcode == X86ISD::PACKUS) &&(static_cast <bool> ((Opcode == X86ISD::PACKSS || Opcode
== X86ISD::PACKUS) && "Unexpected PACK opcode") ? void
(0) : __assert_fail ("(Opcode == X86ISD::PACKSS || Opcode == X86ISD::PACKUS) && \"Unexpected PACK opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20939, __extension__ __PRETTY_FUNCTION__))
20939 "Unexpected PACK opcode")(static_cast <bool> ((Opcode == X86ISD::PACKSS || Opcode
== X86ISD::PACKUS) && "Unexpected PACK opcode") ? void
(0) : __assert_fail ("(Opcode == X86ISD::PACKSS || Opcode == X86ISD::PACKUS) && \"Unexpected PACK opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20939, __extension__ __PRETTY_FUNCTION__))
;
20940 assert(DstVT.isVector() && "VT not a vector?")(static_cast <bool> (DstVT.isVector() && "VT not a vector?"
) ? void (0) : __assert_fail ("DstVT.isVector() && \"VT not a vector?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20940, __extension__ __PRETTY_FUNCTION__))
;
20941
20942 // Requires SSE2 for PACKSS (SSE41 PACKUSDW is handled below).
20943 if (!Subtarget.hasSSE2())
20944 return SDValue();
20945
20946 EVT SrcVT = In.getValueType();
20947
20948 // No truncation required, we might get here due to recursive calls.
20949 if (SrcVT == DstVT)
20950 return In;
20951
20952 // We only support vector truncation to 64bits or greater from a
20953 // 128bits or greater source.
20954 unsigned DstSizeInBits = DstVT.getSizeInBits();
20955 unsigned SrcSizeInBits = SrcVT.getSizeInBits();
20956 if ((DstSizeInBits % 64) != 0 || (SrcSizeInBits % 128) != 0)
20957 return SDValue();
20958
20959 unsigned NumElems = SrcVT.getVectorNumElements();
20960 if (!isPowerOf2_32(NumElems))
20961 return SDValue();
20962
20963 LLVMContext &Ctx = *DAG.getContext();
20964 assert(DstVT.getVectorNumElements() == NumElems && "Illegal truncation")(static_cast <bool> (DstVT.getVectorNumElements() == NumElems
&& "Illegal truncation") ? void (0) : __assert_fail (
"DstVT.getVectorNumElements() == NumElems && \"Illegal truncation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20964, __extension__ __PRETTY_FUNCTION__))
;
20965 assert(SrcSizeInBits > DstSizeInBits && "Illegal truncation")(static_cast <bool> (SrcSizeInBits > DstSizeInBits &&
"Illegal truncation") ? void (0) : __assert_fail ("SrcSizeInBits > DstSizeInBits && \"Illegal truncation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 20965, __extension__ __PRETTY_FUNCTION__))
;
20966
20967 EVT PackedSVT = EVT::getIntegerVT(Ctx, SrcVT.getScalarSizeInBits() / 2);
20968
20969 // Pack to the largest type possible:
20970 // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
20971 EVT InVT = MVT::i16, OutVT = MVT::i8;
20972 if (SrcVT.getScalarSizeInBits() > 16 &&
20973 (Opcode == X86ISD::PACKSS || Subtarget.hasSSE41())) {
20974 InVT = MVT::i32;
20975 OutVT = MVT::i16;
20976 }
20977
20978 // 128bit -> 64bit truncate - PACK 128-bit src in the lower subvector.
20979 if (SrcVT.is128BitVector()) {
20980 InVT = EVT::getVectorVT(Ctx, InVT, 128 / InVT.getSizeInBits());
20981 OutVT = EVT::getVectorVT(Ctx, OutVT, 128 / OutVT.getSizeInBits());
20982 In = DAG.getBitcast(InVT, In);
20983 SDValue Res = DAG.getNode(Opcode, DL, OutVT, In, DAG.getUNDEF(InVT));
20984 Res = extractSubVector(Res, 0, DAG, DL, 64);
20985 return DAG.getBitcast(DstVT, Res);
20986 }
20987
20988 // Split lower/upper subvectors.
20989 SDValue Lo, Hi;
20990 std::tie(Lo, Hi) = splitVector(In, DAG, DL);
20991
20992 unsigned SubSizeInBits = SrcSizeInBits / 2;
20993 InVT = EVT::getVectorVT(Ctx, InVT, SubSizeInBits / InVT.getSizeInBits());
20994 OutVT = EVT::getVectorVT(Ctx, OutVT, SubSizeInBits / OutVT.getSizeInBits());
20995
20996 // 256bit -> 128bit truncate - PACK lower/upper 128-bit subvectors.
20997 if (SrcVT.is256BitVector() && DstVT.is128BitVector()) {
20998 Lo = DAG.getBitcast(InVT, Lo);
20999 Hi = DAG.getBitcast(InVT, Hi);
21000 SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
21001 return DAG.getBitcast(DstVT, Res);
21002 }
21003
21004 // AVX2: 512bit -> 256bit truncate - PACK lower/upper 256-bit subvectors.
21005 // AVX2: 512bit -> 128bit truncate - PACK(PACK, PACK).
21006 if (SrcVT.is512BitVector() && Subtarget.hasInt256()) {
21007 Lo = DAG.getBitcast(InVT, Lo);
21008 Hi = DAG.getBitcast(InVT, Hi);
21009 SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
21010
21011 // 256-bit PACK(ARG0, ARG1) leaves us with ((LO0,LO1),(HI0,HI1)),
21012 // so we need to shuffle to get ((LO0,HI0),(LO1,HI1)).
21013 // Scale shuffle mask to avoid bitcasts and help ComputeNumSignBits.
21014 SmallVector<int, 64> Mask;
21015 int Scale = 64 / OutVT.getScalarSizeInBits();
21016 narrowShuffleMaskElts(Scale, { 0, 2, 1, 3 }, Mask);
21017 Res = DAG.getVectorShuffle(OutVT, DL, Res, Res, Mask);
21018
21019 if (DstVT.is256BitVector())
21020 return DAG.getBitcast(DstVT, Res);
21021
21022 // If 512bit -> 128bit truncate another stage.
21023 EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems);
21024 Res = DAG.getBitcast(PackedVT, Res);
21025 return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
21026 }
21027
21028 // Recursively pack lower/upper subvectors, concat result and pack again.
21029 assert(SrcSizeInBits >= 256 && "Expected 256-bit vector or greater")(static_cast <bool> (SrcSizeInBits >= 256 &&
"Expected 256-bit vector or greater") ? void (0) : __assert_fail
("SrcSizeInBits >= 256 && \"Expected 256-bit vector or greater\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21029, __extension__ __PRETTY_FUNCTION__))
;
21030 EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems / 2);
21031 Lo = truncateVectorWithPACK(Opcode, PackedVT, Lo, DL, DAG, Subtarget);
21032 Hi = truncateVectorWithPACK(Opcode, PackedVT, Hi, DL, DAG, Subtarget);
21033
21034 PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems);
21035 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, PackedVT, Lo, Hi);
21036 return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
21037}
21038
21039static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
21040 const X86Subtarget &Subtarget) {
21041
21042 SDLoc DL(Op);
21043 MVT VT = Op.getSimpleValueType();
21044 SDValue In = Op.getOperand(0);
21045 MVT InVT = In.getSimpleValueType();
21046
21047 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type.")(static_cast <bool> (VT.getVectorElementType() == MVT::
i1 && "Unexpected vector type.") ? void (0) : __assert_fail
("VT.getVectorElementType() == MVT::i1 && \"Unexpected vector type.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21047, __extension__ __PRETTY_FUNCTION__))
;
21048
21049 // Shift LSB to MSB and use VPMOVB/W2M or TESTD/Q.
21050 unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
21051 if (InVT.getScalarSizeInBits() <= 16) {
21052 if (Subtarget.hasBWI()) {
21053 // legal, will go to VPMOVB2M, VPMOVW2M
21054 if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
21055 // We need to shift to get the lsb into sign position.
21056 // Shift packed bytes not supported natively, bitcast to word
21057 MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
21058 In = DAG.getNode(ISD::SHL, DL, ExtVT,
21059 DAG.getBitcast(ExtVT, In),
21060 DAG.getConstant(ShiftInx, DL, ExtVT));
21061 In = DAG.getBitcast(InVT, In);
21062 }
21063 return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT),
21064 In, ISD::SETGT);
21065 }
21066 // Use TESTD/Q, extended vector to packed dword/qword.
21067 assert((InVT.is256BitVector() || InVT.is128BitVector()) &&(static_cast <bool> ((InVT.is256BitVector() || InVT.is128BitVector
()) && "Unexpected vector type.") ? void (0) : __assert_fail
("(InVT.is256BitVector() || InVT.is128BitVector()) && \"Unexpected vector type.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21068, __extension__ __PRETTY_FUNCTION__))
21068 "Unexpected vector type.")(static_cast <bool> ((InVT.is256BitVector() || InVT.is128BitVector
()) && "Unexpected vector type.") ? void (0) : __assert_fail
("(InVT.is256BitVector() || InVT.is128BitVector()) && \"Unexpected vector type.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21068, __extension__ __PRETTY_FUNCTION__))
;
21069 unsigned NumElts = InVT.getVectorNumElements();
21070 assert((NumElts == 8 || NumElts == 16) && "Unexpected number of elements")(static_cast <bool> ((NumElts == 8 || NumElts == 16) &&
"Unexpected number of elements") ? void (0) : __assert_fail (
"(NumElts == 8 || NumElts == 16) && \"Unexpected number of elements\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21070, __extension__ __PRETTY_FUNCTION__))
;
21071 // We need to change to a wider element type that we have support for.
21072 // For 8 element vectors this is easy, we either extend to v8i32 or v8i64.
21073 // For 16 element vectors we extend to v16i32 unless we are explicitly
21074 // trying to avoid 512-bit vectors. If we are avoiding 512-bit vectors
21075 // we need to split into two 8 element vectors which we can extend to v8i32,
21076 // truncate and concat the results. There's an additional complication if
21077 // the original type is v16i8. In that case we can't split the v16i8
21078 // directly, so we need to shuffle high elements to low and use
21079 // sign_extend_vector_inreg.
21080 if (NumElts == 16 && !Subtarget.canExtendTo512DQ()) {
21081 SDValue Lo, Hi;
21082 if (InVT == MVT::v16i8) {
21083 Lo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, MVT::v8i32, In);
21084 Hi = DAG.getVectorShuffle(
21085 InVT, DL, In, In,
21086 {8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1});
21087 Hi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, MVT::v8i32, Hi);
21088 } else {
21089 assert(InVT == MVT::v16i16 && "Unexpected VT!")(static_cast <bool> (InVT == MVT::v16i16 && "Unexpected VT!"
) ? void (0) : __assert_fail ("InVT == MVT::v16i16 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21089, __extension__ __PRETTY_FUNCTION__))
;
21090 Lo = extract128BitVector(In, 0, DAG, DL);
21091 Hi = extract128BitVector(In, 8, DAG, DL);
21092 }
21093 // We're split now, just emit two truncates and a concat. The two
21094 // truncates will trigger legalization to come back to this function.
21095 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Lo);
21096 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Hi);
21097 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
21098 }
21099 // We either have 8 elements or we're allowed to use 512-bit vectors.
21100 // If we have VLX, we want to use the narrowest vector that can get the
21101 // job done so we use vXi32.
21102 MVT EltVT = Subtarget.hasVLX() ? MVT::i32 : MVT::getIntegerVT(512/NumElts);
21103 MVT ExtVT = MVT::getVectorVT(EltVT, NumElts);
21104 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
21105 InVT = ExtVT;
21106 ShiftInx = InVT.getScalarSizeInBits() - 1;
21107 }
21108
21109 if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
21110 // We need to shift to get the lsb into sign position.
21111 In = DAG.getNode(ISD::SHL, DL, InVT, In,
21112 DAG.getConstant(ShiftInx, DL, InVT));
21113 }
21114 // If we have DQI, emit a pattern that will be iseled as vpmovq2m/vpmovd2m.
21115 if (Subtarget.hasDQI())
21116 return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT), In, ISD::SETGT);
21117 return DAG.getSetCC(DL, VT, In, DAG.getConstant(0, DL, InVT), ISD::SETNE);
21118}
21119
21120SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
21121 SDLoc DL(Op);
21122 MVT VT = Op.getSimpleValueType();
21123 SDValue In = Op.getOperand(0);
21124 MVT InVT = In.getSimpleValueType();
21125 unsigned InNumEltBits = InVT.getScalarSizeInBits();
21126
21127 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&(static_cast <bool> (VT.getVectorNumElements() == InVT.
getVectorNumElements() && "Invalid TRUNCATE operation"
) ? void (0) : __assert_fail ("VT.getVectorNumElements() == InVT.getVectorNumElements() && \"Invalid TRUNCATE operation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21128, __extension__ __PRETTY_FUNCTION__))
21128 "Invalid TRUNCATE operation")(static_cast <bool> (VT.getVectorNumElements() == InVT.
getVectorNumElements() && "Invalid TRUNCATE operation"
) ? void (0) : __assert_fail ("VT.getVectorNumElements() == InVT.getVectorNumElements() && \"Invalid TRUNCATE operation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21128, __extension__ __PRETTY_FUNCTION__))
;
21129
21130 // If we're called by the type legalizer, handle a few cases.
21131 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21132 if (!TLI.isTypeLegal(InVT)) {
21133 if ((InVT == MVT::v8i64 || InVT == MVT::v16i32 || InVT == MVT::v16i64) &&
21134 VT.is128BitVector()) {
21135 assert((InVT == MVT::v16i64 || Subtarget.hasVLX()) &&(static_cast <bool> ((InVT == MVT::v16i64 || Subtarget.
hasVLX()) && "Unexpected subtarget!") ? void (0) : __assert_fail
("(InVT == MVT::v16i64 || Subtarget.hasVLX()) && \"Unexpected subtarget!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21136, __extension__ __PRETTY_FUNCTION__))
21136 "Unexpected subtarget!")(static_cast <bool> ((InVT == MVT::v16i64 || Subtarget.
hasVLX()) && "Unexpected subtarget!") ? void (0) : __assert_fail
("(InVT == MVT::v16i64 || Subtarget.hasVLX()) && \"Unexpected subtarget!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21136, __extension__ __PRETTY_FUNCTION__))
;
21137 // The default behavior is to truncate one step, concatenate, and then
21138 // truncate the remainder. We'd rather produce two 64-bit results and
21139 // concatenate those.
21140 SDValue Lo, Hi;
21141 std::tie(Lo, Hi) = DAG.SplitVector(In, DL);
21142
21143 EVT LoVT, HiVT;
21144 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
21145
21146 Lo = DAG.getNode(ISD::TRUNCATE, DL, LoVT, Lo);
21147 Hi = DAG.getNode(ISD::TRUNCATE, DL, HiVT, Hi);
21148 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
21149 }
21150
21151 // Otherwise let default legalization handle it.
21152 return SDValue();
21153 }
21154
21155 if (VT.getVectorElementType() == MVT::i1)
21156 return LowerTruncateVecI1(Op, DAG, Subtarget);
21157
21158 // vpmovqb/w/d, vpmovdb/w, vpmovwb
21159 if (Subtarget.hasAVX512()) {
21160 if (InVT == MVT::v32i16 && !Subtarget.hasBWI()) {
21161 assert(VT == MVT::v32i8 && "Unexpected VT!")(static_cast <bool> (VT == MVT::v32i8 && "Unexpected VT!"
) ? void (0) : __assert_fail ("VT == MVT::v32i8 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21161, __extension__ __PRETTY_FUNCTION__))
;
21162 return splitVectorIntUnary(Op, DAG);
21163 }
21164
21165 // word to byte only under BWI. Otherwise we have to promoted to v16i32
21166 // and then truncate that. But we should only do that if we haven't been
21167 // asked to avoid 512-bit vectors. The actual promotion to v16i32 will be
21168 // handled by isel patterns.
21169 if (InVT != MVT::v16i16 || Subtarget.hasBWI() ||
21170 Subtarget.canExtendTo512DQ())
21171 return Op;
21172 }
21173
21174 unsigned NumPackedSignBits = std::min<unsigned>(VT.getScalarSizeInBits(), 16);
21175 unsigned NumPackedZeroBits = Subtarget.hasSSE41() ? NumPackedSignBits : 8;
21176
21177 // Truncate with PACKUS if we are truncating a vector with leading zero bits
21178 // that extend all the way to the packed/truncated value.
21179 // Pre-SSE41 we can only use PACKUSWB.
21180 KnownBits Known = DAG.computeKnownBits(In);
21181 if ((InNumEltBits - NumPackedZeroBits) <= Known.countMinLeadingZeros())
21182 if (SDValue V =
21183 truncateVectorWithPACK(X86ISD::PACKUS, VT, In, DL, DAG, Subtarget))
21184 return V;
21185
21186 // Truncate with PACKSS if we are truncating a vector with sign-bits that
21187 // extend all the way to the packed/truncated value.
21188 if ((InNumEltBits - NumPackedSignBits) < DAG.ComputeNumSignBits(In))
21189 if (SDValue V =
21190 truncateVectorWithPACK(X86ISD::PACKSS, VT, In, DL, DAG, Subtarget))
21191 return V;
21192
21193 // Handle truncation of V256 to V128 using shuffles.
21194 assert(VT.is128BitVector() && InVT.is256BitVector() && "Unexpected types!")(static_cast <bool> (VT.is128BitVector() && InVT
.is256BitVector() && "Unexpected types!") ? void (0) :
__assert_fail ("VT.is128BitVector() && InVT.is256BitVector() && \"Unexpected types!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21194, __extension__ __PRETTY_FUNCTION__))
;
21195
21196 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
21197 In = DAG.getBitcast(MVT::v8i32, In);
21198
21199 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
21200 if (Subtarget.hasInt256()) {
21201 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
21202 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, In, ShufMask);
21203 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
21204 DAG.getIntPtrConstant(0, DL));
21205 }
21206
21207 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
21208 DAG.getIntPtrConstant(0, DL));
21209 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
21210 DAG.getIntPtrConstant(4, DL));
21211 static const int ShufMask[] = {0, 2, 4, 6};
21212 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
21213 }
21214
21215 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
21216 In = DAG.getBitcast(MVT::v32i8, In);
21217
21218 // On AVX2, v8i32 -> v8i16 becomes PSHUFB.
21219 if (Subtarget.hasInt256()) {
21220 // The PSHUFB mask:
21221 static const int ShufMask1[] = { 0, 1, 4, 5, 8, 9, 12, 13,
21222 -1, -1, -1, -1, -1, -1, -1, -1,
21223 16, 17, 20, 21, 24, 25, 28, 29,
21224 -1, -1, -1, -1, -1, -1, -1, -1 };
21225 In = DAG.getVectorShuffle(MVT::v32i8, DL, In, In, ShufMask1);
21226 In = DAG.getBitcast(MVT::v4i64, In);
21227
21228 static const int ShufMask2[] = {0, 2, -1, -1};
21229 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, In, ShufMask2);
21230 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i16,
21231 DAG.getBitcast(MVT::v16i16, In),
21232 DAG.getIntPtrConstant(0, DL));
21233 }
21234
21235 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v16i8, In,
21236 DAG.getIntPtrConstant(0, DL));
21237 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v16i8, In,
21238 DAG.getIntPtrConstant(16, DL));
21239
21240 // The PSHUFB mask:
21241 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
21242 -1, -1, -1, -1, -1, -1, -1, -1};
21243
21244 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, OpLo, ShufMask1);
21245 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, OpHi, ShufMask1);
21246
21247 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
21248 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
21249
21250 // The MOVLHPS Mask:
21251 static const int ShufMask2[] = {0, 1, 4, 5};
21252 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
21253 return DAG.getBitcast(MVT::v8i16, res);
21254 }
21255
21256 if (VT == MVT::v16i8 && InVT == MVT::v16i16) {
21257 // Use an AND to zero uppper bits for PACKUS.
21258 In = DAG.getNode(ISD::AND, DL, InVT, In, DAG.getConstant(255, DL, InVT));
21259
21260 SDValue InLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i16, In,
21261 DAG.getIntPtrConstant(0, DL));
21262 SDValue InHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i16, In,
21263 DAG.getIntPtrConstant(8, DL));
21264 return DAG.getNode(X86ISD::PACKUS, DL, VT, InLo, InHi);
21265 }
21266
21267 llvm_unreachable("All 256->128 cases should have been handled above!")::llvm::llvm_unreachable_internal("All 256->128 cases should have been handled above!"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21267)
;
21268}
21269
21270// We can leverage the specific way the "cvttps2dq/cvttpd2dq" instruction
21271// behaves on out of range inputs to generate optimized conversions.
21272static SDValue expandFP_TO_UINT_SSE(MVT VT, SDValue Src, const SDLoc &dl,
21273 SelectionDAG &DAG,
21274 const X86Subtarget &Subtarget) {
21275 MVT SrcVT = Src.getSimpleValueType();
21276 unsigned DstBits = VT.getScalarSizeInBits();
21277 assert(DstBits == 32 && "expandFP_TO_UINT_SSE - only vXi32 supported")(static_cast <bool> (DstBits == 32 && "expandFP_TO_UINT_SSE - only vXi32 supported"
) ? void (0) : __assert_fail ("DstBits == 32 && \"expandFP_TO_UINT_SSE - only vXi32 supported\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21277, __extension__ __PRETTY_FUNCTION__))
;
21278
21279 // Calculate the converted result for values in the range 0 to
21280 // 2^31-1 ("Small") and from 2^31 to 2^32-1 ("Big").
21281 SDValue Small = DAG.getNode(X86ISD::CVTTP2SI, dl, VT, Src);
21282 SDValue Big =
21283 DAG.getNode(X86ISD::CVTTP2SI, dl, VT,
21284 DAG.getNode(ISD::FSUB, dl, SrcVT, Src,
21285 DAG.getConstantFP(2147483648.0f, dl, SrcVT)));
21286
21287 // The "CVTTP2SI" instruction conveniently sets the sign bit if
21288 // and only if the value was out of range. So we can use that
21289 // as our indicator that we rather use "Big" instead of "Small".
21290 //
21291 // Use "Small" if "IsOverflown" has all bits cleared
21292 // and "0x80000000 | Big" if all bits in "IsOverflown" are set.
21293
21294 // AVX1 can't use the signsplat masking for 256-bit vectors - we have to
21295 // use the slightly slower blendv select instead.
21296 if (VT == MVT::v8i32 && !Subtarget.hasAVX2()) {
21297 SDValue Overflow = DAG.getNode(ISD::OR, dl, VT, Small, Big);
21298 return DAG.getNode(X86ISD::BLENDV, dl, VT, Small, Overflow, Small);
21299 }
21300
21301 SDValue IsOverflown =
21302 DAG.getNode(X86ISD::VSRAI, dl, VT, Small,
21303 DAG.getTargetConstant(DstBits - 1, dl, MVT::i8));
21304 return DAG.getNode(ISD::OR, dl, VT, Small,
21305 DAG.getNode(ISD::AND, dl, VT, Big, IsOverflown));
21306}
21307
21308SDValue X86TargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
21309 bool IsStrict = Op->isStrictFPOpcode();
21310 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
21311 Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
21312 MVT VT = Op->getSimpleValueType(0);
21313 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
21314 MVT SrcVT = Src.getSimpleValueType();
21315 SDLoc dl(Op);
21316
21317 if (VT.isVector()) {
21318 if (VT == MVT::v2i1 && SrcVT == MVT::v2f64) {
21319 MVT ResVT = MVT::v4i32;
21320 MVT TruncVT = MVT::v4i1;
21321 unsigned Opc;
21322 if (IsStrict)
21323 Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
21324 else
21325 Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
21326
21327 if (!IsSigned && !Subtarget.hasVLX()) {
21328 assert(Subtarget.useAVX512Regs() && "Unexpected features!")(static_cast <bool> (Subtarget.useAVX512Regs() &&
"Unexpected features!") ? void (0) : __assert_fail ("Subtarget.useAVX512Regs() && \"Unexpected features!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21328, __extension__ __PRETTY_FUNCTION__))
;
21329 // Widen to 512-bits.
21330 ResVT = MVT::v8i32;
21331 TruncVT = MVT::v8i1;
21332 Opc = Op.getOpcode();
21333 // Need to concat with zero vector for strict fp to avoid spurious
21334 // exceptions.
21335 // TODO: Should we just do this for non-strict as well?
21336 SDValue Tmp = IsStrict ? DAG.getConstantFP(0.0, dl, MVT::v8f64)
21337 : DAG.getUNDEF(MVT::v8f64);
21338 Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8f64, Tmp, Src,
21339 DAG.getIntPtrConstant(0, dl));
21340 }
21341 SDValue Res, Chain;
21342 if (IsStrict) {
21343 Res =
21344 DAG.getNode(Opc, dl, {ResVT, MVT::Other}, {Op->getOperand(0), Src});
21345 Chain = Res.getValue(1);
21346 } else {
21347 Res = DAG.getNode(Opc, dl, ResVT, Src);
21348 }
21349
21350 Res = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Res);
21351 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i1, Res,
21352 DAG.getIntPtrConstant(0, dl));
21353 if (IsStrict)
21354 return DAG.getMergeValues({Res, Chain}, dl);
21355 return Res;
21356 }
21357
21358 // v8f64->v8i32 is legal, but we need v8i32 to be custom for v8f32.
21359 if (VT == MVT::v8i32 && SrcVT == MVT::v8f64) {
21360 assert(!IsSigned && "Expected unsigned conversion!")(static_cast <bool> (!IsSigned && "Expected unsigned conversion!"
) ? void (0) : __assert_fail ("!IsSigned && \"Expected unsigned conversion!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21360, __extension__ __PRETTY_FUNCTION__))
;
21361 assert(Subtarget.useAVX512Regs() && "Requires avx512f")(static_cast <bool> (Subtarget.useAVX512Regs() &&
"Requires avx512f") ? void (0) : __assert_fail ("Subtarget.useAVX512Regs() && \"Requires avx512f\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21361, __extension__ __PRETTY_FUNCTION__))
;
21362 return Op;
21363 }
21364
21365 // Widen vXi32 fp_to_uint with avx512f to 512-bit source.
21366 if ((VT == MVT::v4i32 || VT == MVT::v8i32) &&
21367 (SrcVT == MVT::v4f64 || SrcVT == MVT::v4f32 || SrcVT == MVT::v8f32) &&
21368 Subtarget.useAVX512Regs()) {
21369 assert(!IsSigned && "Expected unsigned conversion!")(static_cast <bool> (!IsSigned && "Expected unsigned conversion!"
) ? void (0) : __assert_fail ("!IsSigned && \"Expected unsigned conversion!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21369, __extension__ __PRETTY_FUNCTION__))
;
21370 assert(!Subtarget.hasVLX() && "Unexpected features!")(static_cast <bool> (!Subtarget.hasVLX() && "Unexpected features!"
) ? void (0) : __assert_fail ("!Subtarget.hasVLX() && \"Unexpected features!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21370, __extension__ __PRETTY_FUNCTION__))
;
21371 MVT WideVT = SrcVT == MVT::v4f64 ? MVT::v8f64 : MVT::v16f32;
21372 MVT ResVT = SrcVT == MVT::v4f64 ? MVT::v8i32 : MVT::v16i32;
21373 // Need to concat with zero vector for strict fp to avoid spurious
21374 // exceptions.
21375 // TODO: Should we just do this for non-strict as well?
21376 SDValue Tmp =
21377 IsStrict ? DAG.getConstantFP(0.0, dl, WideVT) : DAG.getUNDEF(WideVT);
21378 Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVT, Tmp, Src,
21379 DAG.getIntPtrConstant(0, dl));
21380
21381 SDValue Res, Chain;
21382 if (IsStrict) {
21383 Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, dl, {ResVT, MVT::Other},
21384 {Op->getOperand(0), Src});
21385 Chain = Res.getValue(1);
21386 } else {
21387 Res = DAG.getNode(ISD::FP_TO_UINT, dl, ResVT, Src);
21388 }
21389
21390 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
21391 DAG.getIntPtrConstant(0, dl));
21392
21393 if (IsStrict)
21394 return DAG.getMergeValues({Res, Chain}, dl);
21395 return Res;
21396 }
21397
21398 // Widen vXi64 fp_to_uint/fp_to_sint with avx512dq to 512-bit source.
21399 if ((VT == MVT::v2i64 || VT == MVT::v4i64) &&
21400 (SrcVT == MVT::v2f64 || SrcVT == MVT::v4f64 || SrcVT == MVT::v4f32) &&
21401 Subtarget.useAVX512Regs() && Subtarget.hasDQI()) {
21402 assert(!Subtarget.hasVLX() && "Unexpected features!")(static_cast <bool> (!Subtarget.hasVLX() && "Unexpected features!"
) ? void (0) : __assert_fail ("!Subtarget.hasVLX() && \"Unexpected features!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21402, __extension__ __PRETTY_FUNCTION__))
;
21403 MVT WideVT = SrcVT == MVT::v4f32 ? MVT::v8f32 : MVT::v8f64;
21404 // Need to concat with zero vector for strict fp to avoid spurious
21405 // exceptions.
21406 // TODO: Should we just do this for non-strict as well?
21407 SDValue Tmp =
21408 IsStrict ? DAG.getConstantFP(0.0, dl, WideVT) : DAG.getUNDEF(WideVT);
21409 Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVT, Tmp, Src,
21410 DAG.getIntPtrConstant(0, dl));
21411
21412 SDValue Res, Chain;
21413 if (IsStrict) {
21414 Res = DAG.getNode(Op.getOpcode(), dl, {MVT::v8i64, MVT::Other},
21415 {Op->getOperand(0), Src});
21416 Chain = Res.getValue(1);
21417 } else {
21418 Res = DAG.getNode(Op.getOpcode(), dl, MVT::v8i64, Src);
21419 }
21420
21421 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
21422 DAG.getIntPtrConstant(0, dl));
21423
21424 if (IsStrict)
21425 return DAG.getMergeValues({Res, Chain}, dl);
21426 return Res;
21427 }
21428
21429 if (VT == MVT::v2i64 && SrcVT == MVT::v2f32) {
21430 if (!Subtarget.hasVLX()) {
21431 // Non-strict nodes without VLX can we widened to v4f32->v4i64 by type
21432 // legalizer and then widened again by vector op legalization.
21433 if (!IsStrict)
21434 return SDValue();
21435
21436 SDValue Zero = DAG.getConstantFP(0.0, dl, MVT::v2f32);
21437 SDValue Tmp = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8f32,
21438 {Src, Zero, Zero, Zero});
21439 Tmp = DAG.getNode(Op.getOpcode(), dl, {MVT::v8i64, MVT::Other},
21440 {Op->getOperand(0), Tmp});
21441 SDValue Chain = Tmp.getValue(1);
21442 Tmp = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Tmp,
21443 DAG.getIntPtrConstant(0, dl));
21444 return DAG.getMergeValues({Tmp, Chain}, dl);
21445 }
21446
21447 assert(Subtarget.hasDQI() && Subtarget.hasVLX() && "Requires AVX512DQVL")(static_cast <bool> (Subtarget.hasDQI() && Subtarget
.hasVLX() && "Requires AVX512DQVL") ? void (0) : __assert_fail
("Subtarget.hasDQI() && Subtarget.hasVLX() && \"Requires AVX512DQVL\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21447, __extension__ __PRETTY_FUNCTION__))
;
21448 SDValue Tmp = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
21449 DAG.getUNDEF(MVT::v2f32));
21450 if (IsStrict) {
21451 unsigned Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI
21452 : X86ISD::STRICT_CVTTP2UI;
21453 return DAG.getNode(Opc, dl, {VT, MVT::Other}, {Op->getOperand(0), Tmp});
21454 }
21455 unsigned Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
21456 return DAG.getNode(Opc, dl, VT, Tmp);
21457 }
21458
21459 // Generate optimized instructions for pre AVX512 unsigned conversions from
21460 // vXf32 to vXi32.
21461 if ((VT == MVT::v4i32 && SrcVT == MVT::v4f32) ||
21462 (VT == MVT::v4i32 && SrcVT == MVT::v4f64) ||
21463 (VT == MVT::v8i32 && SrcVT == MVT::v8f32)) {
21464 assert(!IsSigned && "Expected unsigned conversion!")(static_cast <bool> (!IsSigned && "Expected unsigned conversion!"
) ? void (0) : __assert_fail ("!IsSigned && \"Expected unsigned conversion!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21464, __extension__ __PRETTY_FUNCTION__))
;
21465 return expandFP_TO_UINT_SSE(VT, Src, dl, DAG, Subtarget);
21466 }
21467
21468 return SDValue();
21469 }
21470
21471 assert(!VT.isVector())(static_cast <bool> (!VT.isVector()) ? void (0) : __assert_fail
("!VT.isVector()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21471, __extension__ __PRETTY_FUNCTION__))
;
21472
21473 bool UseSSEReg = isScalarFPTypeInSSEReg(SrcVT);
21474
21475 if (!IsSigned && UseSSEReg) {
21476 // Conversions from f32/f64 with AVX512 should be legal.
21477 if (Subtarget.hasAVX512())
21478 return Op;
21479
21480 // We can leverage the specific way the "cvttss2si/cvttsd2si" instruction
21481 // behaves on out of range inputs to generate optimized conversions.
21482 if (!IsStrict && ((VT == MVT::i32 && !Subtarget.is64Bit()) ||
21483 (VT == MVT::i64 && Subtarget.is64Bit()))) {
21484 unsigned DstBits = VT.getScalarSizeInBits();
21485 APInt UIntLimit = APInt::getSignMask(DstBits);
21486 SDValue FloatOffset = DAG.getNode(ISD::UINT_TO_FP, dl, SrcVT,
21487 DAG.getConstant(UIntLimit, dl, VT));
21488 MVT SrcVecVT = MVT::getVectorVT(SrcVT, 128 / SrcVT.getScalarSizeInBits());
21489
21490 // Calculate the converted result for values in the range:
21491 // (i32) 0 to 2^31-1 ("Small") and from 2^31 to 2^32-1 ("Big").
21492 // (i64) 0 to 2^63-1 ("Small") and from 2^63 to 2^64-1 ("Big").
21493 SDValue Small =
21494 DAG.getNode(X86ISD::CVTTS2SI, dl, VT,
21495 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, SrcVecVT, Src));
21496 SDValue Big = DAG.getNode(
21497 X86ISD::CVTTS2SI, dl, VT,
21498 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, SrcVecVT,
21499 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FloatOffset)));
21500
21501 // The "CVTTS2SI" instruction conveniently sets the sign bit if
21502 // and only if the value was out of range. So we can use that
21503 // as our indicator that we rather use "Big" instead of "Small".
21504 //
21505 // Use "Small" if "IsOverflown" has all bits cleared
21506 // and "0x80000000 | Big" if all bits in "IsOverflown" are set.
21507 SDValue IsOverflown = DAG.getNode(
21508 ISD::SRA, dl, VT, Small, DAG.getConstant(DstBits - 1, dl, MVT::i8));
21509 return DAG.getNode(ISD::OR, dl, VT, Small,
21510 DAG.getNode(ISD::AND, dl, VT, Big, IsOverflown));
21511 }
21512
21513 // Use default expansion for i64.
21514 if (VT == MVT::i64)
21515 return SDValue();
21516
21517 assert(VT == MVT::i32 && "Unexpected VT!")(static_cast <bool> (VT == MVT::i32 && "Unexpected VT!"
) ? void (0) : __assert_fail ("VT == MVT::i32 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21517, __extension__ __PRETTY_FUNCTION__))
;
21518
21519 // Promote i32 to i64 and use a signed operation on 64-bit targets.
21520 // FIXME: This does not generate an invalid exception if the input does not
21521 // fit in i32. PR44019
21522 if (Subtarget.is64Bit()) {
21523 SDValue Res, Chain;
21524 if (IsStrict) {
21525 Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { MVT::i64, MVT::Other},
21526 { Op.getOperand(0), Src });
21527 Chain = Res.getValue(1);
21528 } else
21529 Res = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i64, Src);
21530
21531 Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
21532 if (IsStrict)
21533 return DAG.getMergeValues({ Res, Chain }, dl);
21534 return Res;
21535 }
21536
21537 // Use default expansion for SSE1/2 targets without SSE3. With SSE3 we can
21538 // use fisttp which will be handled later.
21539 if (!Subtarget.hasSSE3())
21540 return SDValue();
21541 }
21542
21543 // Promote i16 to i32 if we can use a SSE operation or the type is f128.
21544 // FIXME: This does not generate an invalid exception if the input does not
21545 // fit in i16. PR44019
21546 if (VT == MVT::i16 && (UseSSEReg || SrcVT == MVT::f128)) {
21547 assert(IsSigned && "Expected i16 FP_TO_UINT to have been promoted!")(static_cast <bool> (IsSigned && "Expected i16 FP_TO_UINT to have been promoted!"
) ? void (0) : __assert_fail ("IsSigned && \"Expected i16 FP_TO_UINT to have been promoted!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21547, __extension__ __PRETTY_FUNCTION__))
;
21548 SDValue Res, Chain;
21549 if (IsStrict) {
21550 Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { MVT::i32, MVT::Other},
21551 { Op.getOperand(0), Src });
21552 Chain = Res.getValue(1);
21553 } else
21554 Res = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
21555
21556 Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
21557 if (IsStrict)
21558 return DAG.getMergeValues({ Res, Chain }, dl);
21559 return Res;
21560 }
21561
21562 // If this is a FP_TO_SINT using SSEReg we're done.
21563 if (UseSSEReg && IsSigned)
21564 return Op;
21565
21566 // fp128 needs to use a libcall.
21567 if (SrcVT == MVT::f128) {
21568 RTLIB::Libcall LC;
21569 if (IsSigned)
21570 LC = RTLIB::getFPTOSINT(SrcVT, VT);
21571 else
21572 LC = RTLIB::getFPTOUINT(SrcVT, VT);
21573
21574 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
21575 MakeLibCallOptions CallOptions;
21576 std::pair<SDValue, SDValue> Tmp = makeLibCall(DAG, LC, VT, Src, CallOptions,
21577 SDLoc(Op), Chain);
21578
21579 if (IsStrict)
21580 return DAG.getMergeValues({ Tmp.first, Tmp.second }, dl);
21581
21582 return Tmp.first;
21583 }
21584
21585 // Fall back to X87.
21586 SDValue Chain;
21587 if (SDValue V = FP_TO_INTHelper(Op, DAG, IsSigned, Chain)) {
21588 if (IsStrict)
21589 return DAG.getMergeValues({V, Chain}, dl);
21590 return V;
21591 }
21592
21593 llvm_unreachable("Expected FP_TO_INTHelper to handle all remaining cases.")::llvm::llvm_unreachable_internal("Expected FP_TO_INTHelper to handle all remaining cases."
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21593)
;
21594}
21595
21596SDValue X86TargetLowering::LowerLRINT_LLRINT(SDValue Op,
21597 SelectionDAG &DAG) const {
21598 SDValue Src = Op.getOperand(0);
21599 MVT SrcVT = Src.getSimpleValueType();
21600
21601 // If the source is in an SSE register, the node is Legal.
21602 if (isScalarFPTypeInSSEReg(SrcVT))
21603 return Op;
21604
21605 return LRINT_LLRINTHelper(Op.getNode(), DAG);
21606}
21607
21608SDValue X86TargetLowering::LRINT_LLRINTHelper(SDNode *N,
21609 SelectionDAG &DAG) const {
21610 EVT DstVT = N->getValueType(0);
21611 SDValue Src = N->getOperand(0);
21612 EVT SrcVT = Src.getValueType();
21613
21614 if (SrcVT != MVT::f32 && SrcVT != MVT::f64 && SrcVT != MVT::f80) {
21615 // f16 must be promoted before using the lowering in this routine.
21616 // fp128 does not use this lowering.
21617 return SDValue();
21618 }
21619
21620 SDLoc DL(N);
21621 SDValue Chain = DAG.getEntryNode();
21622
21623 bool UseSSE = isScalarFPTypeInSSEReg(SrcVT);
21624
21625 // If we're converting from SSE, the stack slot needs to hold both types.
21626 // Otherwise it only needs to hold the DstVT.
21627 EVT OtherVT = UseSSE ? SrcVT : DstVT;
21628 SDValue StackPtr = DAG.CreateStackTemporary(DstVT, OtherVT);
21629 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
21630 MachinePointerInfo MPI =
21631 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
21632
21633 if (UseSSE) {
21634 assert(DstVT == MVT::i64 && "Invalid LRINT/LLRINT to lower!")(static_cast <bool> (DstVT == MVT::i64 && "Invalid LRINT/LLRINT to lower!"
) ? void (0) : __assert_fail ("DstVT == MVT::i64 && \"Invalid LRINT/LLRINT to lower!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21634, __extension__ __PRETTY_FUNCTION__))
;
21635 Chain = DAG.getStore(Chain, DL, Src, StackPtr, MPI);
21636 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
21637 SDValue Ops[] = { Chain, StackPtr };
21638
21639 Src = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, SrcVT, MPI,
21640 /*Align*/ None, MachineMemOperand::MOLoad);
21641 Chain = Src.getValue(1);
21642 }
21643
21644 SDValue StoreOps[] = { Chain, Src, StackPtr };
21645 Chain = DAG.getMemIntrinsicNode(X86ISD::FIST, DL, DAG.getVTList(MVT::Other),
21646 StoreOps, DstVT, MPI, /*Align*/ None,
21647 MachineMemOperand::MOStore);
21648
21649 return DAG.getLoad(DstVT, DL, Chain, StackPtr, MPI);
21650}
21651
21652SDValue
21653X86TargetLowering::LowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) const {
21654 // This is based on the TargetLowering::expandFP_TO_INT_SAT implementation,
21655 // but making use of X86 specifics to produce better instruction sequences.
21656 SDNode *Node = Op.getNode();
21657 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
21658 unsigned FpToIntOpcode = IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT;
21659 SDLoc dl(SDValue(Node, 0));
21660 SDValue Src = Node->getOperand(0);
21661
21662 // There are three types involved here: SrcVT is the source floating point
21663 // type, DstVT is the type of the result, and TmpVT is the result of the
21664 // intermediate FP_TO_*INT operation we'll use (which may be a promotion of
21665 // DstVT).
21666 EVT SrcVT = Src.getValueType();
21667 EVT DstVT = Node->getValueType(0);
21668 EVT TmpVT = DstVT;
21669
21670 // This code is only for floats and doubles. Fall back to generic code for
21671 // anything else.
21672 if (!isScalarFPTypeInSSEReg(SrcVT))
21673 return SDValue();
21674
21675 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
21676 unsigned SatWidth = SatVT.getScalarSizeInBits();
21677 unsigned DstWidth = DstVT.getScalarSizeInBits();
21678 unsigned TmpWidth = TmpVT.getScalarSizeInBits();
21679 assert(SatWidth <= DstWidth && SatWidth <= TmpWidth &&(static_cast <bool> (SatWidth <= DstWidth &&
SatWidth <= TmpWidth && "Expected saturation width smaller than result width"
) ? void (0) : __assert_fail ("SatWidth <= DstWidth && SatWidth <= TmpWidth && \"Expected saturation width smaller than result width\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21680, __extension__ __PRETTY_FUNCTION__))
21680 "Expected saturation width smaller than result width")(static_cast <bool> (SatWidth <= DstWidth &&
SatWidth <= TmpWidth && "Expected saturation width smaller than result width"
) ? void (0) : __assert_fail ("SatWidth <= DstWidth && SatWidth <= TmpWidth && \"Expected saturation width smaller than result width\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21680, __extension__ __PRETTY_FUNCTION__))
;
21681
21682 // Promote result of FP_TO_*INT to at least 32 bits.
21683 if (TmpWidth < 32) {
21684 TmpVT = MVT::i32;
21685 TmpWidth = 32;
21686 }
21687
21688 // Promote conversions to unsigned 32-bit to 64-bit, because it will allow
21689 // us to use a native signed conversion instead.
21690 if (SatWidth == 32 && !IsSigned && Subtarget.is64Bit()) {
21691 TmpVT = MVT::i64;
21692 TmpWidth = 64;
21693 }
21694
21695 // If the saturation width is smaller than the size of the temporary result,
21696 // we can always use signed conversion, which is native.
21697 if (SatWidth < TmpWidth)
21698 FpToIntOpcode = ISD::FP_TO_SINT;
21699
21700 // Determine minimum and maximum integer values and their corresponding
21701 // floating-point values.
21702 APInt MinInt, MaxInt;
21703 if (IsSigned) {
21704 MinInt = APInt::getSignedMinValue(SatWidth).sextOrSelf(DstWidth);
21705 MaxInt = APInt::getSignedMaxValue(SatWidth).sextOrSelf(DstWidth);
21706 } else {
21707 MinInt = APInt::getMinValue(SatWidth).zextOrSelf(DstWidth);
21708 MaxInt = APInt::getMaxValue(SatWidth).zextOrSelf(DstWidth);
21709 }
21710
21711 APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT));
21712 APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT));
21713
21714 APFloat::opStatus MinStatus = MinFloat.convertFromAPInt(
21715 MinInt, IsSigned, APFloat::rmTowardZero);
21716 APFloat::opStatus MaxStatus = MaxFloat.convertFromAPInt(
21717 MaxInt, IsSigned, APFloat::rmTowardZero);
21718 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact)
21719 && !(MaxStatus & APFloat::opStatus::opInexact);
21720
21721 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
21722 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
21723
21724 // If the integer bounds are exactly representable as floats, emit a
21725 // min+max+fptoi sequence. Otherwise use comparisons and selects.
21726 if (AreExactFloatBounds) {
21727 if (DstVT != TmpVT) {
21728 // Clamp by MinFloat from below. If Src is NaN, propagate NaN.
21729 SDValue MinClamped = DAG.getNode(
21730 X86ISD::FMAX, dl, SrcVT, MinFloatNode, Src);
21731 // Clamp by MaxFloat from above. If Src is NaN, propagate NaN.
21732 SDValue BothClamped = DAG.getNode(
21733 X86ISD::FMIN, dl, SrcVT, MaxFloatNode, MinClamped);
21734 // Convert clamped value to integer.
21735 SDValue FpToInt = DAG.getNode(FpToIntOpcode, dl, TmpVT, BothClamped);
21736
21737 // NaN will become INDVAL, with the top bit set and the rest zero.
21738 // Truncation will discard the top bit, resulting in zero.
21739 return DAG.getNode(ISD::TRUNCATE, dl, DstVT, FpToInt);
21740 }
21741
21742 // Clamp by MinFloat from below. If Src is NaN, the result is MinFloat.
21743 SDValue MinClamped = DAG.getNode(
21744 X86ISD::FMAX, dl, SrcVT, Src, MinFloatNode);
21745 // Clamp by MaxFloat from above. NaN cannot occur.
21746 SDValue BothClamped = DAG.getNode(
21747 X86ISD::FMINC, dl, SrcVT, MinClamped, MaxFloatNode);
21748 // Convert clamped value to integer.
21749 SDValue FpToInt = DAG.getNode(FpToIntOpcode, dl, DstVT, BothClamped);
21750
21751 if (!IsSigned) {
21752 // In the unsigned case we're done, because we mapped NaN to MinFloat,
21753 // which is zero.
21754 return FpToInt;
21755 }
21756
21757 // Otherwise, select zero if Src is NaN.
21758 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
21759 return DAG.getSelectCC(
21760 dl, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
21761 }
21762
21763 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
21764 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
21765
21766 // Result of direct conversion, which may be selected away.
21767 SDValue FpToInt = DAG.getNode(FpToIntOpcode, dl, TmpVT, Src);
21768
21769 if (DstVT != TmpVT) {
21770 // NaN will become INDVAL, with the top bit set and the rest zero.
21771 // Truncation will discard the top bit, resulting in zero.
21772 FpToInt = DAG.getNode(ISD::TRUNCATE, dl, DstVT, FpToInt);
21773 }
21774
21775 SDValue Select = FpToInt;
21776 // For signed conversions where we saturate to the same size as the
21777 // result type of the fptoi instructions, INDVAL coincides with integer
21778 // minimum, so we don't need to explicitly check it.
21779 if (!IsSigned || SatWidth != TmpVT.getScalarSizeInBits()) {
21780 // If Src ULT MinFloat, select MinInt. In particular, this also selects
21781 // MinInt if Src is NaN.
21782 Select = DAG.getSelectCC(
21783 dl, Src, MinFloatNode, MinIntNode, Select, ISD::CondCode::SETULT);
21784 }
21785
21786 // If Src OGT MaxFloat, select MaxInt.
21787 Select = DAG.getSelectCC(
21788 dl, Src, MaxFloatNode, MaxIntNode, Select, ISD::CondCode::SETOGT);
21789
21790 // In the unsigned case we are done, because we mapped NaN to MinInt, which
21791 // is already zero. The promoted case was already handled above.
21792 if (!IsSigned || DstVT != TmpVT) {
21793 return Select;
21794 }
21795
21796 // Otherwise, select 0 if Src is NaN.
21797 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
21798 return DAG.getSelectCC(
21799 dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO);
21800}
21801
21802SDValue X86TargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
21803 bool IsStrict = Op->isStrictFPOpcode();
21804
21805 SDLoc DL(Op);
21806 MVT VT = Op.getSimpleValueType();
21807 SDValue In = Op.getOperand(IsStrict ? 1 : 0);
21808 MVT SVT = In.getSimpleValueType();
21809
21810 if (VT == MVT::f128)
21811 return SDValue();
21812
21813 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!")(static_cast <bool> (SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!"
) ? void (0) : __assert_fail ("SVT == MVT::v2f32 && \"Only customize MVT::v2f32 type legalization!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21813, __extension__ __PRETTY_FUNCTION__))
;
21814
21815 SDValue Res =
21816 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32, In, DAG.getUNDEF(SVT));
21817 if (IsStrict)
21818 return DAG.getNode(X86ISD::STRICT_VFPEXT, DL, {VT, MVT::Other},
21819 {Op->getOperand(0), Res});
21820 return DAG.getNode(X86ISD::VFPEXT, DL, VT, Res);
21821}
21822
21823SDValue X86TargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
21824 bool IsStrict = Op->isStrictFPOpcode();
21825 SDValue In = Op.getOperand(IsStrict ? 1 : 0);
21826 // It's legal except when f128 is involved
21827 if (In.getSimpleValueType() != MVT::f128)
21828 return Op;
21829
21830 return SDValue();
21831}
21832
21833static SDValue LowerFP16_TO_FP(SDValue Op, SelectionDAG &DAG) {
21834 bool IsStrict = Op->isStrictFPOpcode();
21835 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
21836 assert(Src.getValueType() == MVT::i16 && Op.getValueType() == MVT::f32 &&(static_cast <bool> (Src.getValueType() == MVT::i16 &&
Op.getValueType() == MVT::f32 && "Unexpected VT!") ?
void (0) : __assert_fail ("Src.getValueType() == MVT::i16 && Op.getValueType() == MVT::f32 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21837, __extension__ __PRETTY_FUNCTION__))
21837 "Unexpected VT!")(static_cast <bool> (Src.getValueType() == MVT::i16 &&
Op.getValueType() == MVT::f32 && "Unexpected VT!") ?
void (0) : __assert_fail ("Src.getValueType() == MVT::i16 && Op.getValueType() == MVT::f32 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21837, __extension__ __PRETTY_FUNCTION__))
;
21838
21839 SDLoc dl(Op);
21840 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16,
21841 DAG.getConstant(0, dl, MVT::v8i16), Src,
21842 DAG.getIntPtrConstant(0, dl));
21843
21844 SDValue Chain;
21845 if (IsStrict) {
21846 Res = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {MVT::v4f32, MVT::Other},
21847 {Op.getOperand(0), Res});
21848 Chain = Res.getValue(1);
21849 } else {
21850 Res = DAG.getNode(X86ISD::CVTPH2PS, dl, MVT::v4f32, Res);
21851 }
21852
21853 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
21854 DAG.getIntPtrConstant(0, dl));
21855
21856 if (IsStrict)
21857 return DAG.getMergeValues({Res, Chain}, dl);
21858
21859 return Res;
21860}
21861
21862static SDValue LowerFP_TO_FP16(SDValue Op, SelectionDAG &DAG) {
21863 bool IsStrict = Op->isStrictFPOpcode();
21864 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
21865 assert(Src.getValueType() == MVT::f32 && Op.getValueType() == MVT::i16 &&(static_cast <bool> (Src.getValueType() == MVT::f32 &&
Op.getValueType() == MVT::i16 && "Unexpected VT!") ?
void (0) : __assert_fail ("Src.getValueType() == MVT::f32 && Op.getValueType() == MVT::i16 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21866, __extension__ __PRETTY_FUNCTION__))
21866 "Unexpected VT!")(static_cast <bool> (Src.getValueType() == MVT::f32 &&
Op.getValueType() == MVT::i16 && "Unexpected VT!") ?
void (0) : __assert_fail ("Src.getValueType() == MVT::f32 && Op.getValueType() == MVT::i16 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21866, __extension__ __PRETTY_FUNCTION__))
;
21867
21868 SDLoc dl(Op);
21869 SDValue Res, Chain;
21870 if (IsStrict) {
21871 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4f32,
21872 DAG.getConstantFP(0, dl, MVT::v4f32), Src,
21873 DAG.getIntPtrConstant(0, dl));
21874 Res = DAG.getNode(
21875 X86ISD::STRICT_CVTPS2PH, dl, {MVT::v8i16, MVT::Other},
21876 {Op.getOperand(0), Res, DAG.getTargetConstant(4, dl, MVT::i32)});
21877 Chain = Res.getValue(1);
21878 } else {
21879 // FIXME: Should we use zeros for upper elements for non-strict?
21880 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, Src);
21881 Res = DAG.getNode(X86ISD::CVTPS2PH, dl, MVT::v8i16, Res,
21882 DAG.getTargetConstant(4, dl, MVT::i32));
21883 }
21884
21885 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Res,
21886 DAG.getIntPtrConstant(0, dl));
21887
21888 if (IsStrict)
21889 return DAG.getMergeValues({Res, Chain}, dl);
21890
21891 return Res;
21892}
21893
21894/// Depending on uarch and/or optimizing for size, we might prefer to use a
21895/// vector operation in place of the typical scalar operation.
21896static SDValue lowerAddSubToHorizontalOp(SDValue Op, SelectionDAG &DAG,
21897 const X86Subtarget &Subtarget) {
21898 // If both operands have other uses, this is probably not profitable.
21899 SDValue LHS = Op.getOperand(0);
21900 SDValue RHS = Op.getOperand(1);
21901 if (!LHS.hasOneUse() && !RHS.hasOneUse())
21902 return Op;
21903
21904 // FP horizontal add/sub were added with SSE3. Integer with SSSE3.
21905 bool IsFP = Op.getSimpleValueType().isFloatingPoint();
21906 if (IsFP && !Subtarget.hasSSE3())
21907 return Op;
21908 if (!IsFP && !Subtarget.hasSSSE3())
21909 return Op;
21910
21911 // Extract from a common vector.
21912 if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
21913 RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
21914 LHS.getOperand(0) != RHS.getOperand(0) ||
21915 !isa<ConstantSDNode>(LHS.getOperand(1)) ||
21916 !isa<ConstantSDNode>(RHS.getOperand(1)) ||
21917 !shouldUseHorizontalOp(true, DAG, Subtarget))
21918 return Op;
21919
21920 // Allow commuted 'hadd' ops.
21921 // TODO: Allow commuted (f)sub by negating the result of (F)HSUB?
21922 unsigned HOpcode;
21923 switch (Op.getOpcode()) {
21924 case ISD::ADD: HOpcode = X86ISD::HADD; break;
21925 case ISD::SUB: HOpcode = X86ISD::HSUB; break;
21926 case ISD::FADD: HOpcode = X86ISD::FHADD; break;
21927 case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
21928 default:
21929 llvm_unreachable("Trying to lower unsupported opcode to horizontal op")::llvm::llvm_unreachable_internal("Trying to lower unsupported opcode to horizontal op"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21929)
;
21930 }
21931 unsigned LExtIndex = LHS.getConstantOperandVal(1);
21932 unsigned RExtIndex = RHS.getConstantOperandVal(1);
21933 if ((LExtIndex & 1) == 1 && (RExtIndex & 1) == 0 &&
21934 (HOpcode == X86ISD::HADD || HOpcode == X86ISD::FHADD))
21935 std::swap(LExtIndex, RExtIndex);
21936
21937 if ((LExtIndex & 1) != 0 || RExtIndex != (LExtIndex + 1))
21938 return Op;
21939
21940 SDValue X = LHS.getOperand(0);
21941 EVT VecVT = X.getValueType();
21942 unsigned BitWidth = VecVT.getSizeInBits();
21943 unsigned NumLanes = BitWidth / 128;
21944 unsigned NumEltsPerLane = VecVT.getVectorNumElements() / NumLanes;
21945 assert((BitWidth == 128 || BitWidth == 256 || BitWidth == 512) &&(static_cast <bool> ((BitWidth == 128 || BitWidth == 256
|| BitWidth == 512) && "Not expecting illegal vector widths here"
) ? void (0) : __assert_fail ("(BitWidth == 128 || BitWidth == 256 || BitWidth == 512) && \"Not expecting illegal vector widths here\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21946, __extension__ __PRETTY_FUNCTION__))
21946 "Not expecting illegal vector widths here")(static_cast <bool> ((BitWidth == 128 || BitWidth == 256
|| BitWidth == 512) && "Not expecting illegal vector widths here"
) ? void (0) : __assert_fail ("(BitWidth == 128 || BitWidth == 256 || BitWidth == 512) && \"Not expecting illegal vector widths here\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21946, __extension__ __PRETTY_FUNCTION__))
;
21947
21948 // Creating a 256-bit horizontal op would be wasteful, and there is no 512-bit
21949 // equivalent, so extract the 256/512-bit source op to 128-bit if we can.
21950 SDLoc DL(Op);
21951 if (BitWidth == 256 || BitWidth == 512) {
21952 unsigned LaneIdx = LExtIndex / NumEltsPerLane;
21953 X = extract128BitVector(X, LaneIdx * NumEltsPerLane, DAG, DL);
21954 LExtIndex %= NumEltsPerLane;
21955 }
21956
21957 // add (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hadd X, X), 0
21958 // add (extractelt (X, 1), extractelt (X, 0)) --> extractelt (hadd X, X), 0
21959 // add (extractelt (X, 2), extractelt (X, 3)) --> extractelt (hadd X, X), 1
21960 // sub (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hsub X, X), 0
21961 SDValue HOp = DAG.getNode(HOpcode, DL, X.getValueType(), X, X);
21962 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, Op.getSimpleValueType(), HOp,
21963 DAG.getIntPtrConstant(LExtIndex / 2, DL));
21964}
21965
21966/// Depending on uarch and/or optimizing for size, we might prefer to use a
21967/// vector operation in place of the typical scalar operation.
21968SDValue X86TargetLowering::lowerFaddFsub(SDValue Op, SelectionDAG &DAG) const {
21969 assert((Op.getValueType() == MVT::f32 || Op.getValueType() == MVT::f64) &&(static_cast <bool> ((Op.getValueType() == MVT::f32 || Op
.getValueType() == MVT::f64) && "Only expecting float/double"
) ? void (0) : __assert_fail ("(Op.getValueType() == MVT::f32 || Op.getValueType() == MVT::f64) && \"Only expecting float/double\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21970, __extension__ __PRETTY_FUNCTION__))
21970 "Only expecting float/double")(static_cast <bool> ((Op.getValueType() == MVT::f32 || Op
.getValueType() == MVT::f64) && "Only expecting float/double"
) ? void (0) : __assert_fail ("(Op.getValueType() == MVT::f32 || Op.getValueType() == MVT::f64) && \"Only expecting float/double\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 21970, __extension__ __PRETTY_FUNCTION__))
;
21971 return lowerAddSubToHorizontalOp(Op, DAG, Subtarget);
21972}
21973
21974/// ISD::FROUND is defined to round to nearest with ties rounding away from 0.
21975/// This mode isn't supported in hardware on X86. But as long as we aren't
21976/// compiling with trapping math, we can emulate this with
21977/// floor(X + copysign(nextafter(0.5, 0.0), X)).
21978static SDValue LowerFROUND(SDValue Op, SelectionDAG &DAG) {
21979 SDValue N0 = Op.getOperand(0);
21980 SDLoc dl(Op);
21981 MVT VT = Op.getSimpleValueType();
21982
21983 // N0 += copysign(nextafter(0.5, 0.0), N0)
21984 const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
21985 bool Ignored;
21986 APFloat Point5Pred = APFloat(0.5f);
21987 Point5Pred.convert(Sem, APFloat::rmNearestTiesToEven, &Ignored);
21988 Point5Pred.next(/*nextDown*/true);
21989
21990 SDValue Adder = DAG.getNode(ISD::FCOPYSIGN, dl, VT,
21991 DAG.getConstantFP(Point5Pred, dl, VT), N0);
21992 N0 = DAG.getNode(ISD::FADD, dl, VT, N0, Adder);
21993
21994 // Truncate the result to remove fraction.
21995 return DAG.getNode(ISD::FTRUNC, dl, VT, N0);
21996}
21997
21998/// The only differences between FABS and FNEG are the mask and the logic op.
21999/// FNEG also has a folding opportunity for FNEG(FABS(x)).
22000static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
22001 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&(static_cast <bool> ((Op.getOpcode() == ISD::FABS || Op
.getOpcode() == ISD::FNEG) && "Wrong opcode for lowering FABS or FNEG."
) ? void (0) : __assert_fail ("(Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) && \"Wrong opcode for lowering FABS or FNEG.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22002, __extension__ __PRETTY_FUNCTION__))
22002 "Wrong opcode for lowering FABS or FNEG.")(static_cast <bool> ((Op.getOpcode() == ISD::FABS || Op
.getOpcode() == ISD::FNEG) && "Wrong opcode for lowering FABS or FNEG."
) ? void (0) : __assert_fail ("(Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) && \"Wrong opcode for lowering FABS or FNEG.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22002, __extension__ __PRETTY_FUNCTION__))
;
22003
22004 bool IsFABS = (Op.getOpcode() == ISD::FABS);
22005
22006 // If this is a FABS and it has an FNEG user, bail out to fold the combination
22007 // into an FNABS. We'll lower the FABS after that if it is still in use.
22008 if (IsFABS)
22009 for (SDNode *User : Op->uses())
22010 if (User->getOpcode() == ISD::FNEG)
22011 return Op;
22012
22013 SDLoc dl(Op);
22014 MVT VT = Op.getSimpleValueType();
22015
22016 bool IsF128 = (VT == MVT::f128);
22017 assert((VT == MVT::f64 || VT == MVT::f32 || VT == MVT::f128 ||(static_cast <bool> ((VT == MVT::f64 || VT == MVT::f32 ||
VT == MVT::f128 || VT == MVT::v2f64 || VT == MVT::v4f64 || VT
== MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v8f64 || VT ==
MVT::v16f32) && "Unexpected type in LowerFABSorFNEG"
) ? void (0) : __assert_fail ("(VT == MVT::f64 || VT == MVT::f32 || VT == MVT::f128 || VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v8f64 || VT == MVT::v16f32) && \"Unexpected type in LowerFABSorFNEG\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22020, __extension__ __PRETTY_FUNCTION__))
22018 VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v4f32 ||(static_cast <bool> ((VT == MVT::f64 || VT == MVT::f32 ||
VT == MVT::f128 || VT == MVT::v2f64 || VT == MVT::v4f64 || VT
== MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v8f64 || VT ==
MVT::v16f32) && "Unexpected type in LowerFABSorFNEG"
) ? void (0) : __assert_fail ("(VT == MVT::f64 || VT == MVT::f32 || VT == MVT::f128 || VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v8f64 || VT == MVT::v16f32) && \"Unexpected type in LowerFABSorFNEG\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22020, __extension__ __PRETTY_FUNCTION__))
22019 VT == MVT::v8f32 || VT == MVT::v8f64 || VT == MVT::v16f32) &&(static_cast <bool> ((VT == MVT::f64 || VT == MVT::f32 ||
VT == MVT::f128 || VT == MVT::v2f64 || VT == MVT::v4f64 || VT
== MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v8f64 || VT ==
MVT::v16f32) && "Unexpected type in LowerFABSorFNEG"
) ? void (0) : __assert_fail ("(VT == MVT::f64 || VT == MVT::f32 || VT == MVT::f128 || VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v8f64 || VT == MVT::v16f32) && \"Unexpected type in LowerFABSorFNEG\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22020, __extension__ __PRETTY_FUNCTION__))
22020 "Unexpected type in LowerFABSorFNEG")(static_cast <bool> ((VT == MVT::f64 || VT == MVT::f32 ||
VT == MVT::f128 || VT == MVT::v2f64 || VT == MVT::v4f64 || VT
== MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v8f64 || VT ==
MVT::v16f32) && "Unexpected type in LowerFABSorFNEG"
) ? void (0) : __assert_fail ("(VT == MVT::f64 || VT == MVT::f32 || VT == MVT::f128 || VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v8f64 || VT == MVT::v16f32) && \"Unexpected type in LowerFABSorFNEG\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22020, __extension__ __PRETTY_FUNCTION__))
;
22021
22022 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
22023 // decide if we should generate a 16-byte constant mask when we only need 4 or
22024 // 8 bytes for the scalar case.
22025
22026 // There are no scalar bitwise logical SSE/AVX instructions, so we
22027 // generate a 16-byte vector constant and logic op even for the scalar case.
22028 // Using a 16-byte mask allows folding the load of the mask with
22029 // the logic op, so it can save (~4 bytes) on code size.
22030 bool IsFakeVector = !VT.isVector() && !IsF128;
22031 MVT LogicVT = VT;
22032 if (IsFakeVector)
22033 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
22034
22035 unsigned EltBits = VT.getScalarSizeInBits();
22036 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
22037 APInt MaskElt = IsFABS ? APInt::getSignedMaxValue(EltBits) :
22038 APInt::getSignMask(EltBits);
22039 const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
22040 SDValue Mask = DAG.getConstantFP(APFloat(Sem, MaskElt), dl, LogicVT);
22041
22042 SDValue Op0 = Op.getOperand(0);
22043 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
22044 unsigned LogicOp = IsFABS ? X86ISD::FAND :
22045 IsFNABS ? X86ISD::FOR :
22046 X86ISD::FXOR;
22047 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
22048
22049 if (VT.isVector() || IsF128)
22050 return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
22051
22052 // For the scalar case extend to a 128-bit vector, perform the logic op,
22053 // and extract the scalar result back out.
22054 Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
22055 SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
22056 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
22057 DAG.getIntPtrConstant(0, dl));
22058}
22059
22060static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
22061 SDValue Mag = Op.getOperand(0);
22062 SDValue Sign = Op.getOperand(1);
22063 SDLoc dl(Op);
22064
22065 // If the sign operand is smaller, extend it first.
22066 MVT VT = Op.getSimpleValueType();
22067 if (Sign.getSimpleValueType().bitsLT(VT))
22068 Sign = DAG.getNode(ISD::FP_EXTEND, dl, VT, Sign);
22069
22070 // And if it is bigger, shrink it first.
22071 if (Sign.getSimpleValueType().bitsGT(VT))
22072 Sign =
22073 DAG.getNode(ISD::FP_ROUND, dl, VT, Sign, DAG.getIntPtrConstant(0, dl));
22074
22075 // At this point the operands and the result should have the same
22076 // type, and that won't be f80 since that is not custom lowered.
22077 bool IsF128 = (VT == MVT::f128);
22078 assert((VT == MVT::f64 || VT == MVT::f32 || VT == MVT::f128 ||(static_cast <bool> ((VT == MVT::f64 || VT == MVT::f32 ||
VT == MVT::f128 || VT == MVT::v2f64 || VT == MVT::v4f64 || VT
== MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v8f64 || VT ==
MVT::v16f32) && "Unexpected type in LowerFCOPYSIGN")
? void (0) : __assert_fail ("(VT == MVT::f64 || VT == MVT::f32 || VT == MVT::f128 || VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v8f64 || VT == MVT::v16f32) && \"Unexpected type in LowerFCOPYSIGN\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22081, __extension__ __PRETTY_FUNCTION__))
22079 VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v4f32 ||(static_cast <bool> ((VT == MVT::f64 || VT == MVT::f32 ||
VT == MVT::f128 || VT == MVT::v2f64 || VT == MVT::v4f64 || VT
== MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v8f64 || VT ==
MVT::v16f32) && "Unexpected type in LowerFCOPYSIGN")
? void (0) : __assert_fail ("(VT == MVT::f64 || VT == MVT::f32 || VT == MVT::f128 || VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v8f64 || VT == MVT::v16f32) && \"Unexpected type in LowerFCOPYSIGN\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22081, __extension__ __PRETTY_FUNCTION__))
22080 VT == MVT::v8f32 || VT == MVT::v8f64 || VT == MVT::v16f32) &&(static_cast <bool> ((VT == MVT::f64 || VT == MVT::f32 ||
VT == MVT::f128 || VT == MVT::v2f64 || VT == MVT::v4f64 || VT
== MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v8f64 || VT ==
MVT::v16f32) && "Unexpected type in LowerFCOPYSIGN")
? void (0) : __assert_fail ("(VT == MVT::f64 || VT == MVT::f32 || VT == MVT::f128 || VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v8f64 || VT == MVT::v16f32) && \"Unexpected type in LowerFCOPYSIGN\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22081, __extension__ __PRETTY_FUNCTION__))
22081 "Unexpected type in LowerFCOPYSIGN")(static_cast <bool> ((VT == MVT::f64 || VT == MVT::f32 ||
VT == MVT::f128 || VT == MVT::v2f64 || VT == MVT::v4f64 || VT
== MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v8f64 || VT ==
MVT::v16f32) && "Unexpected type in LowerFCOPYSIGN")
? void (0) : __assert_fail ("(VT == MVT::f64 || VT == MVT::f32 || VT == MVT::f128 || VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v8f64 || VT == MVT::v16f32) && \"Unexpected type in LowerFCOPYSIGN\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22081, __extension__ __PRETTY_FUNCTION__))
;
22082
22083 const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
22084
22085 // Perform all scalar logic operations as 16-byte vectors because there are no
22086 // scalar FP logic instructions in SSE.
22087 // TODO: This isn't necessary. If we used scalar types, we might avoid some
22088 // unnecessary splats, but we might miss load folding opportunities. Should
22089 // this decision be based on OptimizeForSize?
22090 bool IsFakeVector = !VT.isVector() && !IsF128;
22091 MVT LogicVT = VT;
22092 if (IsFakeVector)
22093 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
22094
22095 // The mask constants are automatically splatted for vector types.
22096 unsigned EltSizeInBits = VT.getScalarSizeInBits();
22097 SDValue SignMask = DAG.getConstantFP(
22098 APFloat(Sem, APInt::getSignMask(EltSizeInBits)), dl, LogicVT);
22099 SDValue MagMask = DAG.getConstantFP(
22100 APFloat(Sem, APInt::getSignedMaxValue(EltSizeInBits)), dl, LogicVT);
22101
22102 // First, clear all bits but the sign bit from the second operand (sign).
22103 if (IsFakeVector)
22104 Sign = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Sign);
22105 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Sign, SignMask);
22106
22107 // Next, clear the sign bit from the first operand (magnitude).
22108 // TODO: If we had general constant folding for FP logic ops, this check
22109 // wouldn't be necessary.
22110 SDValue MagBits;
22111 if (ConstantFPSDNode *Op0CN = isConstOrConstSplatFP(Mag)) {
22112 APFloat APF = Op0CN->getValueAPF();
22113 APF.clearSign();
22114 MagBits = DAG.getConstantFP(APF, dl, LogicVT);
22115 } else {
22116 // If the magnitude operand wasn't a constant, we need to AND out the sign.
22117 if (IsFakeVector)
22118 Mag = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Mag);
22119 MagBits = DAG.getNode(X86ISD::FAND, dl, LogicVT, Mag, MagMask);
22120 }
22121
22122 // OR the magnitude value with the sign bit.
22123 SDValue Or = DAG.getNode(X86ISD::FOR, dl, LogicVT, MagBits, SignBit);
22124 return !IsFakeVector ? Or : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Or,
22125 DAG.getIntPtrConstant(0, dl));
22126}
22127
22128static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
22129 SDValue N0 = Op.getOperand(0);
22130 SDLoc dl(Op);
22131 MVT VT = Op.getSimpleValueType();
22132
22133 MVT OpVT = N0.getSimpleValueType();
22134 assert((OpVT == MVT::f32 || OpVT == MVT::f64) &&(static_cast <bool> ((OpVT == MVT::f32 || OpVT == MVT::
f64) && "Unexpected type for FGETSIGN") ? void (0) : __assert_fail
("(OpVT == MVT::f32 || OpVT == MVT::f64) && \"Unexpected type for FGETSIGN\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22135, __extension__ __PRETTY_FUNCTION__))
22135 "Unexpected type for FGETSIGN")(static_cast <bool> ((OpVT == MVT::f32 || OpVT == MVT::
f64) && "Unexpected type for FGETSIGN") ? void (0) : __assert_fail
("(OpVT == MVT::f32 || OpVT == MVT::f64) && \"Unexpected type for FGETSIGN\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22135, __extension__ __PRETTY_FUNCTION__))
;
22136
22137 // Lower ISD::FGETSIGN to (AND (X86ISD::MOVMSK ...) 1).
22138 MVT VecVT = (OpVT == MVT::f32 ? MVT::v4f32 : MVT::v2f64);
22139 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, N0);
22140 Res = DAG.getNode(X86ISD::MOVMSK, dl, MVT::i32, Res);
22141 Res = DAG.getZExtOrTrunc(Res, dl, VT);
22142 Res = DAG.getNode(ISD::AND, dl, VT, Res, DAG.getConstant(1, dl, VT));
22143 return Res;
22144}
22145
22146/// Helper for creating a X86ISD::SETCC node.
22147static SDValue getSETCC(X86::CondCode Cond, SDValue EFLAGS, const SDLoc &dl,
22148 SelectionDAG &DAG) {
22149 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
22150 DAG.getTargetConstant(Cond, dl, MVT::i8), EFLAGS);
22151}
22152
22153/// Helper for matching OR(EXTRACTELT(X,0),OR(EXTRACTELT(X,1),...))
22154/// style scalarized (associative) reduction patterns. Partial reductions
22155/// are supported when the pointer SrcMask is non-null.
22156/// TODO - move this to SelectionDAG?
22157static bool matchScalarReduction(SDValue Op, ISD::NodeType BinOp,
22158 SmallVectorImpl<SDValue> &SrcOps,
22159 SmallVectorImpl<APInt> *SrcMask = nullptr) {
22160 SmallVector<SDValue, 8> Opnds;
22161 DenseMap<SDValue, APInt> SrcOpMap;
22162 EVT VT = MVT::Other;
22163
22164 // Recognize a special case where a vector is casted into wide integer to
22165 // test all 0s.
22166 assert(Op.getOpcode() == unsigned(BinOp) &&(static_cast <bool> (Op.getOpcode() == unsigned(BinOp) &&
"Unexpected bit reduction opcode") ? void (0) : __assert_fail
("Op.getOpcode() == unsigned(BinOp) && \"Unexpected bit reduction opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22167, __extension__ __PRETTY_FUNCTION__))
22167 "Unexpected bit reduction opcode")(static_cast <bool> (Op.getOpcode() == unsigned(BinOp) &&
"Unexpected bit reduction opcode") ? void (0) : __assert_fail
("Op.getOpcode() == unsigned(BinOp) && \"Unexpected bit reduction opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22167, __extension__ __PRETTY_FUNCTION__))
;
22168 Opnds.push_back(Op.getOperand(0));
22169 Opnds.push_back(Op.getOperand(1));
22170
22171 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
22172 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
22173 // BFS traverse all BinOp operands.
22174 if (I->getOpcode() == unsigned(BinOp)) {
22175 Opnds.push_back(I->getOperand(0));
22176 Opnds.push_back(I->getOperand(1));
22177 // Re-evaluate the number of nodes to be traversed.
22178 e += 2; // 2 more nodes (LHS and RHS) are pushed.
22179 continue;
22180 }
22181
22182 // Quit if a non-EXTRACT_VECTOR_ELT
22183 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22184 return false;
22185
22186 // Quit if without a constant index.
22187 auto *Idx = dyn_cast<ConstantSDNode>(I->getOperand(1));
22188 if (!Idx)
22189 return false;
22190
22191 SDValue Src = I->getOperand(0);
22192 DenseMap<SDValue, APInt>::iterator M = SrcOpMap.find(Src);
22193 if (M == SrcOpMap.end()) {
22194 VT = Src.getValueType();
22195 // Quit if not the same type.
22196 if (!SrcOpMap.empty() && VT != SrcOpMap.begin()->first.getValueType())
22197 return false;
22198 unsigned NumElts = VT.getVectorNumElements();
22199 APInt EltCount = APInt::getNullValue(NumElts);
22200 M = SrcOpMap.insert(std::make_pair(Src, EltCount)).first;
22201 SrcOps.push_back(Src);
22202 }
22203
22204 // Quit if element already used.
22205 unsigned CIdx = Idx->getZExtValue();
22206 if (M->second[CIdx])
22207 return false;
22208 M->second.setBit(CIdx);
22209 }
22210
22211 if (SrcMask) {
22212 // Collect the source partial masks.
22213 for (SDValue &SrcOp : SrcOps)
22214 SrcMask->push_back(SrcOpMap[SrcOp]);
22215 } else {
22216 // Quit if not all elements are used.
22217 for (const auto &I : SrcOpMap)
22218 if (!I.second.isAllOnesValue())
22219 return false;
22220 }
22221
22222 return true;
22223}
22224
22225// Helper function for comparing all bits of a vector against zero.
22226static SDValue LowerVectorAllZero(const SDLoc &DL, SDValue V, ISD::CondCode CC,
22227 const APInt &Mask,
22228 const X86Subtarget &Subtarget,
22229 SelectionDAG &DAG, X86::CondCode &X86CC) {
22230 EVT VT = V.getValueType();
22231 unsigned ScalarSize = VT.getScalarSizeInBits();
22232 if (Mask.getBitWidth() != ScalarSize) {
22233 assert(ScalarSize == 1 && "Element Mask vs Vector bitwidth mismatch")(static_cast <bool> (ScalarSize == 1 && "Element Mask vs Vector bitwidth mismatch"
) ? void (0) : __assert_fail ("ScalarSize == 1 && \"Element Mask vs Vector bitwidth mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22233, __extension__ __PRETTY_FUNCTION__))
;
22234 return SDValue();
22235 }
22236
22237 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && "Unsupported ISD::CondCode")(static_cast <bool> ((CC == ISD::SETEQ || CC == ISD::SETNE
) && "Unsupported ISD::CondCode") ? void (0) : __assert_fail
("(CC == ISD::SETEQ || CC == ISD::SETNE) && \"Unsupported ISD::CondCode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22237, __extension__ __PRETTY_FUNCTION__))
;
22238 X86CC = (CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE);
22239
22240 auto MaskBits = [&](SDValue Src) {
22241 if (Mask.isAllOnesValue())
22242 return Src;
22243 EVT SrcVT = Src.getValueType();
22244 SDValue MaskValue = DAG.getConstant(Mask, DL, SrcVT);
22245 return DAG.getNode(ISD::AND, DL, SrcVT, Src, MaskValue);
22246 };
22247
22248 // For sub-128-bit vector, cast to (legal) integer and compare with zero.
22249 if (VT.getSizeInBits() < 128) {
22250 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
22251 if (!DAG.getTargetLoweringInfo().isTypeLegal(IntVT))
22252 return SDValue();
22253 return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
22254 DAG.getBitcast(IntVT, MaskBits(V)),
22255 DAG.getConstant(0, DL, IntVT));
22256 }
22257
22258 // Quit if not splittable to 128/256-bit vector.
22259 if (!isPowerOf2_32(VT.getSizeInBits()))
22260 return SDValue();
22261
22262 // Split down to 128/256-bit vector.
22263 unsigned TestSize = Subtarget.hasAVX() ? 256 : 128;
22264 while (VT.getSizeInBits() > TestSize) {
22265 auto Split = DAG.SplitVector(V, DL);
22266 VT = Split.first.getValueType();
22267 V = DAG.getNode(ISD::OR, DL, VT, Split.first, Split.second);
22268 }
22269
22270 bool UsePTEST = Subtarget.hasSSE41();
22271 if (UsePTEST) {
22272 MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
22273 V = DAG.getBitcast(TestVT, MaskBits(V));
22274 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, V, V);
22275 }
22276
22277 // Without PTEST, a masked v2i64 or-reduction is not faster than
22278 // scalarization.
22279 if (!Mask.isAllOnesValue() && VT.getScalarSizeInBits() > 32)
22280 return SDValue();
22281
22282 V = DAG.getBitcast(MVT::v16i8, MaskBits(V));
22283 V = DAG.getNode(X86ISD::PCMPEQ, DL, MVT::v16i8, V,
22284 getZeroVector(MVT::v16i8, Subtarget, DAG, DL));
22285 V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
22286 return DAG.getNode(X86ISD::CMP, DL, MVT::i32, V,
22287 DAG.getConstant(0xFFFF, DL, MVT::i32));
22288}
22289
22290// Check whether an OR'd reduction tree is PTEST-able, or if we can fallback to
22291// CMP(MOVMSK(PCMPEQB(X,0))).
22292static SDValue MatchVectorAllZeroTest(SDValue Op, ISD::CondCode CC,
22293 const SDLoc &DL,
22294 const X86Subtarget &Subtarget,
22295 SelectionDAG &DAG, SDValue &X86CC) {
22296 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && "Unsupported ISD::CondCode")(static_cast <bool> ((CC == ISD::SETEQ || CC == ISD::SETNE
) && "Unsupported ISD::CondCode") ? void (0) : __assert_fail
("(CC == ISD::SETEQ || CC == ISD::SETNE) && \"Unsupported ISD::CondCode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22296, __extension__ __PRETTY_FUNCTION__))
;
22297
22298 if (!Subtarget.hasSSE2() || !Op->hasOneUse())
22299 return SDValue();
22300
22301 // Check whether we're masking/truncating an OR-reduction result, in which
22302 // case track the masked bits.
22303 APInt Mask = APInt::getAllOnesValue(Op.getScalarValueSizeInBits());
22304 switch (Op.getOpcode()) {
22305 case ISD::TRUNCATE: {
22306 SDValue Src = Op.getOperand(0);
22307 Mask = APInt::getLowBitsSet(Src.getScalarValueSizeInBits(),
22308 Op.getScalarValueSizeInBits());
22309 Op = Src;
22310 break;
22311 }
22312 case ISD::AND: {
22313 if (auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22314 Mask = Cst->getAPIntValue();
22315 Op = Op.getOperand(0);
22316 }
22317 break;
22318 }
22319 }
22320
22321 SmallVector<SDValue, 8> VecIns;
22322 if (Op.getOpcode() == ISD::OR && matchScalarReduction(Op, ISD::OR, VecIns)) {
22323 EVT VT = VecIns[0].getValueType();
22324 assert(llvm::all_of(VecIns,(static_cast <bool> (llvm::all_of(VecIns, [VT](SDValue V
) { return VT == V.getValueType(); }) && "Reduction source vector mismatch"
) ? void (0) : __assert_fail ("llvm::all_of(VecIns, [VT](SDValue V) { return VT == V.getValueType(); }) && \"Reduction source vector mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22326, __extension__ __PRETTY_FUNCTION__))
22325 [VT](SDValue V) { return VT == V.getValueType(); }) &&(static_cast <bool> (llvm::all_of(VecIns, [VT](SDValue V
) { return VT == V.getValueType(); }) && "Reduction source vector mismatch"
) ? void (0) : __assert_fail ("llvm::all_of(VecIns, [VT](SDValue V) { return VT == V.getValueType(); }) && \"Reduction source vector mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22326, __extension__ __PRETTY_FUNCTION__))
22326 "Reduction source vector mismatch")(static_cast <bool> (llvm::all_of(VecIns, [VT](SDValue V
) { return VT == V.getValueType(); }) && "Reduction source vector mismatch"
) ? void (0) : __assert_fail ("llvm::all_of(VecIns, [VT](SDValue V) { return VT == V.getValueType(); }) && \"Reduction source vector mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22326, __extension__ __PRETTY_FUNCTION__))
;
22327
22328 // Quit if less than 128-bits or not splittable to 128/256-bit vector.
22329 if (VT.getSizeInBits() < 128 || !isPowerOf2_32(VT.getSizeInBits()))
22330 return SDValue();
22331
22332 // If more than one full vector is evaluated, OR them first before PTEST.
22333 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1;
22334 Slot += 2, e += 1) {
22335 // Each iteration will OR 2 nodes and append the result until there is
22336 // only 1 node left, i.e. the final OR'd value of all vectors.
22337 SDValue LHS = VecIns[Slot];
22338 SDValue RHS = VecIns[Slot + 1];
22339 VecIns.push_back(DAG.getNode(ISD::OR, DL, VT, LHS, RHS));
22340 }
22341
22342 X86::CondCode CCode;
22343 if (SDValue V = LowerVectorAllZero(DL, VecIns.back(), CC, Mask, Subtarget,
22344 DAG, CCode)) {
22345 X86CC = DAG.getTargetConstant(CCode, DL, MVT::i8);
22346 return V;
22347 }
22348 }
22349
22350 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
22351 ISD::NodeType BinOp;
22352 if (SDValue Match =
22353 DAG.matchBinOpReduction(Op.getNode(), BinOp, {ISD::OR})) {
22354 X86::CondCode CCode;
22355 if (SDValue V =
22356 LowerVectorAllZero(DL, Match, CC, Mask, Subtarget, DAG, CCode)) {
22357 X86CC = DAG.getTargetConstant(CCode, DL, MVT::i8);
22358 return V;
22359 }
22360 }
22361 }
22362
22363 return SDValue();
22364}
22365
22366/// return true if \c Op has a use that doesn't just read flags.
22367static bool hasNonFlagsUse(SDValue Op) {
22368 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
22369 ++UI) {
22370 SDNode *User = *UI;
22371 unsigned UOpNo = UI.getOperandNo();
22372 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
22373 // Look pass truncate.
22374 UOpNo = User->use_begin().getOperandNo();
22375 User = *User->use_begin();
22376 }
22377
22378 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
22379 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
22380 return true;
22381 }
22382 return false;
22383}
22384
22385// Transform to an x86-specific ALU node with flags if there is a chance of
22386// using an RMW op or only the flags are used. Otherwise, leave
22387// the node alone and emit a 'cmp' or 'test' instruction.
22388static bool isProfitableToUseFlagOp(SDValue Op) {
22389 for (SDNode *U : Op->uses())
22390 if (U->getOpcode() != ISD::CopyToReg &&
22391 U->getOpcode() != ISD::SETCC &&
22392 U->getOpcode() != ISD::STORE)
22393 return false;
22394
22395 return true;
22396}
22397
22398/// Emit nodes that will be selected as "test Op0,Op0", or something
22399/// equivalent.
22400static SDValue EmitTest(SDValue Op, unsigned X86CC, const SDLoc &dl,
22401 SelectionDAG &DAG, const X86Subtarget &Subtarget) {
22402 // CF and OF aren't always set the way we want. Determine which
22403 // of these we need.
22404 bool NeedCF = false;
22405 bool NeedOF = false;
22406 switch (X86CC) {
22407 default: break;
22408 case X86::COND_A: case X86::COND_AE:
22409 case X86::COND_B: case X86::COND_BE:
22410 NeedCF = true;
22411 break;
22412 case X86::COND_G: case X86::COND_GE:
22413 case X86::COND_L: case X86::COND_LE:
22414 case X86::COND_O: case X86::COND_NO: {
22415 // Check if we really need to set the
22416 // Overflow flag. If NoSignedWrap is present
22417 // that is not actually needed.
22418 switch (Op->getOpcode()) {
22419 case ISD::ADD:
22420 case ISD::SUB:
22421 case ISD::MUL:
22422 case ISD::SHL:
22423 if (Op.getNode()->getFlags().hasNoSignedWrap())
22424 break;
22425 LLVM_FALLTHROUGH[[gnu::fallthrough]];
22426 default:
22427 NeedOF = true;
22428 break;
22429 }
22430 break;
22431 }
22432 }
22433 // See if we can use the EFLAGS value from the operand instead of
22434 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
22435 // we prove that the arithmetic won't overflow, we can't use OF or CF.
22436 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
22437 // Emit a CMP with 0, which is the TEST pattern.
22438 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
22439 DAG.getConstant(0, dl, Op.getValueType()));
22440 }
22441 unsigned Opcode = 0;
22442 unsigned NumOperands = 0;
22443
22444 SDValue ArithOp = Op;
22445
22446 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
22447 // which may be the result of a CAST. We use the variable 'Op', which is the
22448 // non-casted variable when we check for possible users.
22449 switch (ArithOp.getOpcode()) {
22450 case ISD::AND:
22451 // If the primary 'and' result isn't used, don't bother using X86ISD::AND,
22452 // because a TEST instruction will be better.
22453 if (!hasNonFlagsUse(Op))
22454 break;
22455
22456 LLVM_FALLTHROUGH[[gnu::fallthrough]];
22457 case ISD::ADD:
22458 case ISD::SUB:
22459 case ISD::OR:
22460 case ISD::XOR:
22461 if (!isProfitableToUseFlagOp(Op))
22462 break;
22463
22464 // Otherwise use a regular EFLAGS-setting instruction.
22465 switch (ArithOp.getOpcode()) {
22466 default: llvm_unreachable("unexpected operator!")::llvm::llvm_unreachable_internal("unexpected operator!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22466)
;
22467 case ISD::ADD: Opcode = X86ISD::ADD; break;
22468 case ISD::SUB: Opcode = X86ISD::SUB; break;
22469 case ISD::XOR: Opcode = X86ISD::XOR; break;
22470 case ISD::AND: Opcode = X86ISD::AND; break;
22471 case ISD::OR: Opcode = X86ISD::OR; break;
22472 }
22473
22474 NumOperands = 2;
22475 break;
22476 case X86ISD::ADD:
22477 case X86ISD::SUB:
22478 case X86ISD::OR:
22479 case X86ISD::XOR:
22480 case X86ISD::AND:
22481 return SDValue(Op.getNode(), 1);
22482 case ISD::SSUBO:
22483 case ISD::USUBO: {
22484 // /USUBO/SSUBO will become a X86ISD::SUB and we can use its Z flag.
22485 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
22486 return DAG.getNode(X86ISD::SUB, dl, VTs, Op->getOperand(0),
22487 Op->getOperand(1)).getValue(1);
22488 }
22489 default:
22490 break;
22491 }
22492
22493 if (Opcode == 0) {
22494 // Emit a CMP with 0, which is the TEST pattern.
22495 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
22496 DAG.getConstant(0, dl, Op.getValueType()));
22497 }
22498 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
22499 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
22500
22501 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
22502 DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), New);
22503 return SDValue(New.getNode(), 1);
22504}
22505
22506/// Emit nodes that will be selected as "cmp Op0,Op1", or something
22507/// equivalent.
22508static SDValue EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
22509 const SDLoc &dl, SelectionDAG &DAG,
22510 const X86Subtarget &Subtarget) {
22511 if (isNullConstant(Op1))
22512 return EmitTest(Op0, X86CC, dl, DAG, Subtarget);
22513
22514 EVT CmpVT = Op0.getValueType();
22515
22516 assert((CmpVT == MVT::i8 || CmpVT == MVT::i16 ||(static_cast <bool> ((CmpVT == MVT::i8 || CmpVT == MVT::
i16 || CmpVT == MVT::i32 || CmpVT == MVT::i64) && "Unexpected VT!"
) ? void (0) : __assert_fail ("(CmpVT == MVT::i8 || CmpVT == MVT::i16 || CmpVT == MVT::i32 || CmpVT == MVT::i64) && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22517, __extension__ __PRETTY_FUNCTION__))
22517 CmpVT == MVT::i32 || CmpVT == MVT::i64) && "Unexpected VT!")(static_cast <bool> ((CmpVT == MVT::i8 || CmpVT == MVT::
i16 || CmpVT == MVT::i32 || CmpVT == MVT::i64) && "Unexpected VT!"
) ? void (0) : __assert_fail ("(CmpVT == MVT::i8 || CmpVT == MVT::i16 || CmpVT == MVT::i32 || CmpVT == MVT::i64) && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22517, __extension__ __PRETTY_FUNCTION__))
;
22518
22519 // Only promote the compare up to I32 if it is a 16 bit operation
22520 // with an immediate. 16 bit immediates are to be avoided.
22521 if (CmpVT == MVT::i16 && !Subtarget.isAtom() &&
22522 !DAG.getMachineFunction().getFunction().hasMinSize()) {
22523 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
22524 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
22525 // Don't do this if the immediate can fit in 8-bits.
22526 if ((COp0 && !COp0->getAPIntValue().isSignedIntN(8)) ||
22527 (COp1 && !COp1->getAPIntValue().isSignedIntN(8))) {
22528 unsigned ExtendOp =
22529 isX86CCSigned(X86CC) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
22530 if (X86CC == X86::COND_E || X86CC == X86::COND_NE) {
22531 // For equality comparisons try to use SIGN_EXTEND if the input was
22532 // truncate from something with enough sign bits.
22533 if (Op0.getOpcode() == ISD::TRUNCATE) {
22534 SDValue In = Op0.getOperand(0);
22535 unsigned EffBits =
22536 In.getScalarValueSizeInBits() - DAG.ComputeNumSignBits(In) + 1;
22537 if (EffBits <= 16)
22538 ExtendOp = ISD::SIGN_EXTEND;
22539 } else if (Op1.getOpcode() == ISD::TRUNCATE) {
22540 SDValue In = Op1.getOperand(0);
22541 unsigned EffBits =
22542 In.getScalarValueSizeInBits() - DAG.ComputeNumSignBits(In) + 1;
22543 if (EffBits <= 16)
22544 ExtendOp = ISD::SIGN_EXTEND;
22545 }
22546 }
22547
22548 CmpVT = MVT::i32;
22549 Op0 = DAG.getNode(ExtendOp, dl, CmpVT, Op0);
22550 Op1 = DAG.getNode(ExtendOp, dl, CmpVT, Op1);
22551 }
22552 }
22553
22554 // Try to shrink i64 compares if the input has enough zero bits.
22555 // FIXME: Do this for non-constant compares for constant on LHS?
22556 if (CmpVT == MVT::i64 && isa<ConstantSDNode>(Op1) && !isX86CCSigned(X86CC) &&
22557 Op0.hasOneUse() && // Hacky way to not break CSE opportunities with sub.
22558 cast<ConstantSDNode>(Op1)->getAPIntValue().getActiveBits() <= 32 &&
22559 DAG.MaskedValueIsZero(Op0, APInt::getHighBitsSet(64, 32))) {
22560 CmpVT = MVT::i32;
22561 Op0 = DAG.getNode(ISD::TRUNCATE, dl, CmpVT, Op0);
22562 Op1 = DAG.getNode(ISD::TRUNCATE, dl, CmpVT, Op1);
22563 }
22564
22565 // 0-x == y --> x+y == 0
22566 // 0-x != y --> x+y != 0
22567 if (Op0.getOpcode() == ISD::SUB && isNullConstant(Op0.getOperand(0)) &&
22568 Op0.hasOneUse() && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
22569 SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
22570 SDValue Add = DAG.getNode(X86ISD::ADD, dl, VTs, Op0.getOperand(1), Op1);
22571 return Add.getValue(1);
22572 }
22573
22574 // x == 0-y --> x+y == 0
22575 // x != 0-y --> x+y != 0
22576 if (Op1.getOpcode() == ISD::SUB && isNullConstant(Op1.getOperand(0)) &&
22577 Op1.hasOneUse() && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
22578 SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
22579 SDValue Add = DAG.getNode(X86ISD::ADD, dl, VTs, Op0, Op1.getOperand(1));
22580 return Add.getValue(1);
22581 }
22582
22583 // Use SUB instead of CMP to enable CSE between SUB and CMP.
22584 SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
22585 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs, Op0, Op1);
22586 return Sub.getValue(1);
22587}
22588
22589/// Check if replacement of SQRT with RSQRT should be disabled.
22590bool X86TargetLowering::isFsqrtCheap(SDValue Op, SelectionDAG &DAG) const {
22591 EVT VT = Op.getValueType();
22592
22593 // We never want to use both SQRT and RSQRT instructions for the same input.
22594 if (DAG.getNodeIfExists(X86ISD::FRSQRT, DAG.getVTList(VT), Op))
22595 return false;
22596
22597 if (VT.isVector())
22598 return Subtarget.hasFastVectorFSQRT();
22599 return Subtarget.hasFastScalarFSQRT();
22600}
22601
22602/// The minimum architected relative accuracy is 2^-12. We need one
22603/// Newton-Raphson step to have a good float result (24 bits of precision).
22604SDValue X86TargetLowering::getSqrtEstimate(SDValue Op,
22605 SelectionDAG &DAG, int Enabled,
22606 int &RefinementSteps,
22607 bool &UseOneConstNR,
22608 bool Reciprocal) const {
22609 EVT VT = Op.getValueType();
22610
22611 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
22612 // It is likely not profitable to do this for f64 because a double-precision
22613 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
22614 // instructions: convert to single, rsqrtss, convert back to double, refine
22615 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
22616 // along with FMA, this could be a throughput win.
22617 // TODO: SQRT requires SSE2 to prevent the introduction of an illegal v4i32
22618 // after legalize types.
22619 if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
22620 (VT == MVT::v4f32 && Subtarget.hasSSE1() && Reciprocal) ||
22621 (VT == MVT::v4f32 && Subtarget.hasSSE2() && !Reciprocal) ||
22622 (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
22623 (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
22624 if (RefinementSteps == ReciprocalEstimate::Unspecified)
22625 RefinementSteps = 1;
22626
22627 UseOneConstNR = false;
22628 // There is no FSQRT for 512-bits, but there is RSQRT14.
22629 unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RSQRT14 : X86ISD::FRSQRT;
22630 return DAG.getNode(Opcode, SDLoc(Op), VT, Op);
22631 }
22632 return SDValue();
22633}
22634
22635/// The minimum architected relative accuracy is 2^-12. We need one
22636/// Newton-Raphson step to have a good float result (24 bits of precision).
22637SDValue X86TargetLowering::getRecipEstimate(SDValue Op, SelectionDAG &DAG,
22638 int Enabled,
22639 int &RefinementSteps) const {
22640 EVT VT = Op.getValueType();
22641
22642 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
22643 // It is likely not profitable to do this for f64 because a double-precision
22644 // reciprocal estimate with refinement on x86 prior to FMA requires
22645 // 15 instructions: convert to single, rcpss, convert back to double, refine
22646 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
22647 // along with FMA, this could be a throughput win.
22648
22649 if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
22650 (VT == MVT::v4f32 && Subtarget.hasSSE1()) ||
22651 (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
22652 (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
22653 // Enable estimate codegen with 1 refinement step for vector division.
22654 // Scalar division estimates are disabled because they break too much
22655 // real-world code. These defaults are intended to match GCC behavior.
22656 if (VT == MVT::f32 && Enabled == ReciprocalEstimate::Unspecified)
22657 return SDValue();
22658
22659 if (RefinementSteps == ReciprocalEstimate::Unspecified)
22660 RefinementSteps = 1;
22661
22662 // There is no FSQRT for 512-bits, but there is RCP14.
22663 unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RCP14 : X86ISD::FRCP;
22664 return DAG.getNode(Opcode, SDLoc(Op), VT, Op);
22665 }
22666 return SDValue();
22667}
22668
22669/// If we have at least two divisions that use the same divisor, convert to
22670/// multiplication by a reciprocal. This may need to be adjusted for a given
22671/// CPU if a division's cost is not at least twice the cost of a multiplication.
22672/// This is because we still need one division to calculate the reciprocal and
22673/// then we need two multiplies by that reciprocal as replacements for the
22674/// original divisions.
22675unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
22676 return 2;
22677}
22678
22679SDValue
22680X86TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
22681 SelectionDAG &DAG,
22682 SmallVectorImpl<SDNode *> &Created) const {
22683 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
22684 if (isIntDivCheap(N->getValueType(0), Attr))
22685 return SDValue(N,0); // Lower SDIV as SDIV
22686
22687 assert((Divisor.isPowerOf2() || (-Divisor).isPowerOf2()) &&(static_cast <bool> ((Divisor.isPowerOf2() || (-Divisor
).isPowerOf2()) && "Unexpected divisor!") ? void (0) :
__assert_fail ("(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()) && \"Unexpected divisor!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22688, __extension__ __PRETTY_FUNCTION__))
22688 "Unexpected divisor!")(static_cast <bool> ((Divisor.isPowerOf2() || (-Divisor
).isPowerOf2()) && "Unexpected divisor!") ? void (0) :
__assert_fail ("(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()) && \"Unexpected divisor!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22688, __extension__ __PRETTY_FUNCTION__))
;
22689
22690 // Only perform this transform if CMOV is supported otherwise the select
22691 // below will become a branch.
22692 if (!Subtarget.hasCMov())
22693 return SDValue();
22694
22695 // fold (sdiv X, pow2)
22696 EVT VT = N->getValueType(0);
22697 // FIXME: Support i8.
22698 if (VT != MVT::i16 && VT != MVT::i32 &&
22699 !(Subtarget.is64Bit() && VT == MVT::i64))
22700 return SDValue();
22701
22702 unsigned Lg2 = Divisor.countTrailingZeros();
22703
22704 // If the divisor is 2 or -2, the default expansion is better.
22705 if (Lg2 == 1)
22706 return SDValue();
22707
22708 SDLoc DL(N);
22709 SDValue N0 = N->getOperand(0);
22710 SDValue Zero = DAG.getConstant(0, DL, VT);
22711 APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2);
22712 SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT);
22713
22714 // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right.
22715 SDValue Cmp = DAG.getSetCC(DL, MVT::i8, N0, Zero, ISD::SETLT);
22716 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
22717 SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
22718
22719 Created.push_back(Cmp.getNode());
22720 Created.push_back(Add.getNode());
22721 Created.push_back(CMov.getNode());
22722
22723 // Divide by pow2.
22724 SDValue SRA =
22725 DAG.getNode(ISD::SRA, DL, VT, CMov, DAG.getConstant(Lg2, DL, MVT::i8));
22726
22727 // If we're dividing by a positive value, we're done. Otherwise, we must
22728 // negate the result.
22729 if (Divisor.isNonNegative())
22730 return SRA;
22731
22732 Created.push_back(SRA.getNode());
22733 return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA);
22734}
22735
22736/// Result of 'and' is compared against zero. Change to a BT node if possible.
22737/// Returns the BT node and the condition code needed to use it.
22738static SDValue LowerAndToBT(SDValue And, ISD::CondCode CC,
22739 const SDLoc &dl, SelectionDAG &DAG,
22740 SDValue &X86CC) {
22741 assert(And.getOpcode() == ISD::AND && "Expected AND node!")(static_cast <bool> (And.getOpcode() == ISD::AND &&
"Expected AND node!") ? void (0) : __assert_fail ("And.getOpcode() == ISD::AND && \"Expected AND node!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22741, __extension__ __PRETTY_FUNCTION__))
;
22742 SDValue Op0 = And.getOperand(0);
22743 SDValue Op1 = And.getOperand(1);
22744 if (Op0.getOpcode() == ISD::TRUNCATE)
22745 Op0 = Op0.getOperand(0);
22746 if (Op1.getOpcode() == ISD::TRUNCATE)
22747 Op1 = Op1.getOperand(0);
22748
22749 SDValue Src, BitNo;
22750 if (Op1.getOpcode() == ISD::SHL)
22751 std::swap(Op0, Op1);
22752 if (Op0.getOpcode() == ISD::SHL) {
22753 if (isOneConstant(Op0.getOperand(0))) {
22754 // If we looked past a truncate, check that it's only truncating away
22755 // known zeros.
22756 unsigned BitWidth = Op0.getValueSizeInBits();
22757 unsigned AndBitWidth = And.getValueSizeInBits();
22758 if (BitWidth > AndBitWidth) {
22759 KnownBits Known = DAG.computeKnownBits(Op0);
22760 if (Known.countMinLeadingZeros() < BitWidth - AndBitWidth)
22761 return SDValue();
22762 }
22763 Src = Op1;
22764 BitNo = Op0.getOperand(1);
22765 }
22766 } else if (Op1.getOpcode() == ISD::Constant) {
22767 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
22768 uint64_t AndRHSVal = AndRHS->getZExtValue();
22769 SDValue AndLHS = Op0;
22770
22771 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
22772 Src = AndLHS.getOperand(0);
22773 BitNo = AndLHS.getOperand(1);
22774 } else {
22775 // Use BT if the immediate can't be encoded in a TEST instruction or we
22776 // are optimizing for size and the immedaite won't fit in a byte.
22777 bool OptForSize = DAG.shouldOptForSize();
22778 if ((!isUInt<32>(AndRHSVal) || (OptForSize && !isUInt<8>(AndRHSVal))) &&
22779 isPowerOf2_64(AndRHSVal)) {
22780 Src = AndLHS;
22781 BitNo = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl,
22782 Src.getValueType());
22783 }
22784 }
22785 }
22786
22787 // No patterns found, give up.
22788 if (!Src.getNode())
22789 return SDValue();
22790
22791 // If Src is i8, promote it to i32 with any_extend. There is no i8 BT
22792 // instruction. Since the shift amount is in-range-or-undefined, we know
22793 // that doing a bittest on the i32 value is ok. We extend to i32 because
22794 // the encoding for the i16 version is larger than the i32 version.
22795 // Also promote i16 to i32 for performance / code size reason.
22796 if (Src.getValueType() == MVT::i8 || Src.getValueType() == MVT::i16)
22797 Src = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Src);
22798
22799 // See if we can use the 32-bit instruction instead of the 64-bit one for a
22800 // shorter encoding. Since the former takes the modulo 32 of BitNo and the
22801 // latter takes the modulo 64, this is only valid if the 5th bit of BitNo is
22802 // known to be zero.
22803 if (Src.getValueType() == MVT::i64 &&
22804 DAG.MaskedValueIsZero(BitNo, APInt(BitNo.getValueSizeInBits(), 32)))
22805 Src = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
22806
22807 // If the operand types disagree, extend the shift amount to match. Since
22808 // BT ignores high bits (like shifts) we can use anyextend.
22809 if (Src.getValueType() != BitNo.getValueType())
22810 BitNo = DAG.getNode(ISD::ANY_EXTEND, dl, Src.getValueType(), BitNo);
22811
22812 X86CC = DAG.getTargetConstant(CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B,
22813 dl, MVT::i8);
22814 return DAG.getNode(X86ISD::BT, dl, MVT::i32, Src, BitNo);
22815}
22816
22817/// Turns an ISD::CondCode into a value suitable for SSE floating-point mask
22818/// CMPs.
22819static unsigned translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
22820 SDValue &Op1, bool &IsAlwaysSignaling) {
22821 unsigned SSECC;
22822 bool Swap = false;
22823
22824 // SSE Condition code mapping:
22825 // 0 - EQ
22826 // 1 - LT
22827 // 2 - LE
22828 // 3 - UNORD
22829 // 4 - NEQ
22830 // 5 - NLT
22831 // 6 - NLE
22832 // 7 - ORD
22833 switch (SetCCOpcode) {
22834 default: llvm_unreachable("Unexpected SETCC condition")::llvm::llvm_unreachable_internal("Unexpected SETCC condition"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22834)
;
22835 case ISD::SETOEQ:
22836 case ISD::SETEQ: SSECC = 0; break;
22837 case ISD::SETOGT:
22838 case ISD::SETGT: Swap = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
22839 case ISD::SETLT:
22840 case ISD::SETOLT: SSECC = 1; break;
22841 case ISD::SETOGE:
22842 case ISD::SETGE: Swap = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
22843 case ISD::SETLE:
22844 case ISD::SETOLE: SSECC = 2; break;
22845 case ISD::SETUO: SSECC = 3; break;
22846 case ISD::SETUNE:
22847 case ISD::SETNE: SSECC = 4; break;
22848 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
22849 case ISD::SETUGE: SSECC = 5; break;
22850 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
22851 case ISD::SETUGT: SSECC = 6; break;
22852 case ISD::SETO: SSECC = 7; break;
22853 case ISD::SETUEQ: SSECC = 8; break;
22854 case ISD::SETONE: SSECC = 12; break;
22855 }
22856 if (Swap)
22857 std::swap(Op0, Op1);
22858
22859 switch (SetCCOpcode) {
22860 default:
22861 IsAlwaysSignaling = true;
22862 break;
22863 case ISD::SETEQ:
22864 case ISD::SETOEQ:
22865 case ISD::SETUEQ:
22866 case ISD::SETNE:
22867 case ISD::SETONE:
22868 case ISD::SETUNE:
22869 case ISD::SETO:
22870 case ISD::SETUO:
22871 IsAlwaysSignaling = false;
22872 break;
22873 }
22874
22875 return SSECC;
22876}
22877
22878/// Break a VSETCC 256-bit integer VSETCC into two new 128 ones and then
22879/// concatenate the result back.
22880static SDValue splitIntVSETCC(EVT VT, SDValue LHS, SDValue RHS,
22881 ISD::CondCode Cond, SelectionDAG &DAG,
22882 const SDLoc &dl) {
22883 assert(VT.isInteger() && VT == LHS.getValueType() &&(static_cast <bool> (VT.isInteger() && VT == LHS
.getValueType() && VT == RHS.getValueType() &&
"Unsupported VTs!") ? void (0) : __assert_fail ("VT.isInteger() && VT == LHS.getValueType() && VT == RHS.getValueType() && \"Unsupported VTs!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22884, __extension__ __PRETTY_FUNCTION__))
22884 VT == RHS.getValueType() && "Unsupported VTs!")(static_cast <bool> (VT.isInteger() && VT == LHS
.getValueType() && VT == RHS.getValueType() &&
"Unsupported VTs!") ? void (0) : __assert_fail ("VT.isInteger() && VT == LHS.getValueType() && VT == RHS.getValueType() && \"Unsupported VTs!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22884, __extension__ __PRETTY_FUNCTION__))
;
22885
22886 SDValue CC = DAG.getCondCode(Cond);
22887
22888 // Extract the LHS Lo/Hi vectors
22889 SDValue LHS1, LHS2;
22890 std::tie(LHS1, LHS2) = splitVector(LHS, DAG, dl);
22891
22892 // Extract the RHS Lo/Hi vectors
22893 SDValue RHS1, RHS2;
22894 std::tie(RHS1, RHS2) = splitVector(RHS, DAG, dl);
22895
22896 // Issue the operation on the smaller types and concatenate the result back
22897 EVT LoVT, HiVT;
22898 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
22899 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
22900 DAG.getNode(ISD::SETCC, dl, LoVT, LHS1, RHS1, CC),
22901 DAG.getNode(ISD::SETCC, dl, HiVT, LHS2, RHS2, CC));
22902}
22903
22904static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
22905
22906 SDValue Op0 = Op.getOperand(0);
22907 SDValue Op1 = Op.getOperand(1);
22908 SDValue CC = Op.getOperand(2);
22909 MVT VT = Op.getSimpleValueType();
22910 SDLoc dl(Op);
22911
22912 assert(VT.getVectorElementType() == MVT::i1 &&(static_cast <bool> (VT.getVectorElementType() == MVT::
i1 && "Cannot set masked compare for this operation")
? void (0) : __assert_fail ("VT.getVectorElementType() == MVT::i1 && \"Cannot set masked compare for this operation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22913, __extension__ __PRETTY_FUNCTION__))
22913 "Cannot set masked compare for this operation")(static_cast <bool> (VT.getVectorElementType() == MVT::
i1 && "Cannot set masked compare for this operation")
? void (0) : __assert_fail ("VT.getVectorElementType() == MVT::i1 && \"Cannot set masked compare for this operation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 22913, __extension__ __PRETTY_FUNCTION__))
;
22914
22915 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
22916
22917 // Prefer SETGT over SETLT.
22918 if (SetCCOpcode == ISD::SETLT) {
22919 SetCCOpcode = ISD::getSetCCSwappedOperands(SetCCOpcode);
22920 std::swap(Op0, Op1);
22921 }
22922
22923 return DAG.getSetCC(dl, VT, Op0, Op1, SetCCOpcode);
22924}
22925
22926/// Given a buildvector constant, return a new vector constant with each element
22927/// incremented or decremented. If incrementing or decrementing would result in
22928/// unsigned overflow or underflow or this is not a simple vector constant,
22929/// return an empty value.
22930static SDValue incDecVectorConstant(SDValue V, SelectionDAG &DAG, bool IsInc) {
22931 auto *BV = dyn_cast<BuildVectorSDNode>(V.getNode());
22932 if (!BV)
22933 return SDValue();
22934
22935 MVT VT = V.getSimpleValueType();
22936 MVT EltVT = VT.getVectorElementType();
22937 unsigned NumElts = VT.getVectorNumElements();
22938 SmallVector<SDValue, 8> NewVecC;
22939 SDLoc DL(V);
22940 for (unsigned i = 0; i < NumElts; ++i) {
22941 auto *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
22942 if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EltVT)
22943 return SDValue();
22944
22945 // Avoid overflow/underflow.
22946 const APInt &EltC = Elt->getAPIntValue();
22947 if ((IsInc && EltC.isMaxValue()) || (!IsInc && EltC.isNullValue()))
22948 return SDValue();
22949
22950 NewVecC.push_back(DAG.getConstant(EltC + (IsInc ? 1 : -1), DL, EltVT));
22951 }
22952
22953 return DAG.getBuildVector(VT, DL, NewVecC);
22954}
22955
22956/// As another special case, use PSUBUS[BW] when it's profitable. E.g. for
22957/// Op0 u<= Op1:
22958/// t = psubus Op0, Op1
22959/// pcmpeq t, <0..0>
22960static SDValue LowerVSETCCWithSUBUS(SDValue Op0, SDValue Op1, MVT VT,
22961 ISD::CondCode Cond, const SDLoc &dl,
22962 const X86Subtarget &Subtarget,
22963 SelectionDAG &DAG) {
22964 if (!Subtarget.hasSSE2())
22965 return SDValue();
22966
22967 MVT VET = VT.getVectorElementType();
22968 if (VET != MVT::i8 && VET != MVT::i16)
22969 return SDValue();
22970
22971 switch (Cond) {
22972 default:
22973 return SDValue();
22974 case ISD::SETULT: {
22975 // If the comparison is against a constant we can turn this into a
22976 // setule. With psubus, setule does not require a swap. This is
22977 // beneficial because the constant in the register is no longer
22978 // destructed as the destination so it can be hoisted out of a loop.
22979 // Only do this pre-AVX since vpcmp* is no longer destructive.
22980 if (Subtarget.hasAVX())
22981 return SDValue();
22982 SDValue ULEOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/false);
22983 if (!ULEOp1)
22984 return SDValue();
22985 Op1 = ULEOp1;
22986 break;
22987 }
22988 case ISD::SETUGT: {
22989 // If the comparison is against a constant, we can turn this into a setuge.
22990 // This is beneficial because materializing a constant 0 for the PCMPEQ is
22991 // probably cheaper than XOR+PCMPGT using 2 different vector constants:
22992 // cmpgt (xor X, SignMaskC) CmpC --> cmpeq (usubsat (CmpC+1), X), 0
22993 SDValue UGEOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/true);
22994 if (!UGEOp1)
22995 return SDValue();
22996 Op1 = Op0;
22997 Op0 = UGEOp1;
22998 break;
22999 }
23000 // Psubus is better than flip-sign because it requires no inversion.
23001 case ISD::SETUGE:
23002 std::swap(Op0, Op1);
23003 break;
23004 case ISD::SETULE:
23005 break;
23006 }
23007
23008 SDValue Result = DAG.getNode(ISD::USUBSAT, dl, VT, Op0, Op1);
23009 return DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
23010 DAG.getConstant(0, dl, VT));
23011}
23012
23013static SDValue LowerVSETCC(SDValue Op, const X86Subtarget &Subtarget,
23014 SelectionDAG &DAG) {
23015 bool IsStrict = Op.getOpcode() == ISD::STRICT_FSETCC ||
23016 Op.getOpcode() == ISD::STRICT_FSETCCS;
23017 SDValue Op0 = Op.getOperand(IsStrict ? 1 : 0);
23018 SDValue Op1 = Op.getOperand(IsStrict ? 2 : 1);
23019 SDValue CC = Op.getOperand(IsStrict ? 3 : 2);
23020 MVT VT = Op->getSimpleValueType(0);
23021 ISD::CondCode Cond = cast<CondCodeSDNode>(CC)->get();
23022 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
23023 SDLoc dl(Op);
23024
23025 if (isFP) {
23026#ifndef NDEBUG
23027 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
23028 assert(EltVT == MVT::f32 || EltVT == MVT::f64)(static_cast <bool> (EltVT == MVT::f32 || EltVT == MVT::
f64) ? void (0) : __assert_fail ("EltVT == MVT::f32 || EltVT == MVT::f64"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23028, __extension__ __PRETTY_FUNCTION__))
;
23029#endif
23030
23031 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
23032 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
23033
23034 // If we have a strict compare with a vXi1 result and the input is 128/256
23035 // bits we can't use a masked compare unless we have VLX. If we use a wider
23036 // compare like we do for non-strict, we might trigger spurious exceptions
23037 // from the upper elements. Instead emit a AVX compare and convert to mask.
23038 unsigned Opc;
23039 if (Subtarget.hasAVX512() && VT.getVectorElementType() == MVT::i1 &&
23040 (!IsStrict || Subtarget.hasVLX() ||
23041 Op0.getSimpleValueType().is512BitVector())) {
23042 assert(VT.getVectorNumElements() <= 16)(static_cast <bool> (VT.getVectorNumElements() <= 16
) ? void (0) : __assert_fail ("VT.getVectorNumElements() <= 16"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23042, __extension__ __PRETTY_FUNCTION__))
;
23043 Opc = IsStrict ? X86ISD::STRICT_CMPM : X86ISD::CMPM;
23044 } else {
23045 Opc = IsStrict ? X86ISD::STRICT_CMPP : X86ISD::CMPP;
23046 // The SSE/AVX packed FP comparison nodes are defined with a
23047 // floating-point vector result that matches the operand type. This allows
23048 // them to work with an SSE1 target (integer vector types are not legal).
23049 VT = Op0.getSimpleValueType();
23050 }
23051
23052 SDValue Cmp;
23053 bool IsAlwaysSignaling;
23054 unsigned SSECC = translateX86FSETCC(Cond, Op0, Op1, IsAlwaysSignaling);
23055 if (!Subtarget.hasAVX()) {
23056 // TODO: We could use following steps to handle a quiet compare with
23057 // signaling encodings.
23058 // 1. Get ordered masks from a quiet ISD::SETO
23059 // 2. Use the masks to mask potential unordered elements in operand A, B
23060 // 3. Get the compare results of masked A, B
23061 // 4. Calculating final result using the mask and result from 3
23062 // But currently, we just fall back to scalar operations.
23063 if (IsStrict && IsAlwaysSignaling && !IsSignaling)
23064 return SDValue();
23065
23066 // Insert an extra signaling instruction to raise exception.
23067 if (IsStrict && !IsAlwaysSignaling && IsSignaling) {
23068 SDValue SignalCmp = DAG.getNode(
23069 Opc, dl, {VT, MVT::Other},
23070 {Chain, Op0, Op1, DAG.getTargetConstant(1, dl, MVT::i8)}); // LT_OS
23071 // FIXME: It seems we need to update the flags of all new strict nodes.
23072 // Otherwise, mayRaiseFPException in MI will return false due to
23073 // NoFPExcept = false by default. However, I didn't find it in other
23074 // patches.
23075 SignalCmp->setFlags(Op->getFlags());
23076 Chain = SignalCmp.getValue(1);
23077 }
23078
23079 // In the two cases not handled by SSE compare predicates (SETUEQ/SETONE),
23080 // emit two comparisons and a logic op to tie them together.
23081 if (SSECC >= 8) {
23082 // LLVM predicate is SETUEQ or SETONE.
23083 unsigned CC0, CC1;
23084 unsigned CombineOpc;
23085 if (Cond == ISD::SETUEQ) {
23086 CC0 = 3; // UNORD
23087 CC1 = 0; // EQ
23088 CombineOpc = X86ISD::FOR;
23089 } else {
23090 assert(Cond == ISD::SETONE)(static_cast <bool> (Cond == ISD::SETONE) ? void (0) : __assert_fail
("Cond == ISD::SETONE", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23090, __extension__ __PRETTY_FUNCTION__))
;
23091 CC0 = 7; // ORD
23092 CC1 = 4; // NEQ
23093 CombineOpc = X86ISD::FAND;
23094 }
23095
23096 SDValue Cmp0, Cmp1;
23097 if (IsStrict) {
23098 Cmp0 = DAG.getNode(
23099 Opc, dl, {VT, MVT::Other},
23100 {Chain, Op0, Op1, DAG.getTargetConstant(CC0, dl, MVT::i8)});
23101 Cmp1 = DAG.getNode(
23102 Opc, dl, {VT, MVT::Other},
23103 {Chain, Op0, Op1, DAG.getTargetConstant(CC1, dl, MVT::i8)});
23104 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Cmp0.getValue(1),
23105 Cmp1.getValue(1));
23106 } else {
23107 Cmp0 = DAG.getNode(
23108 Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(CC0, dl, MVT::i8));
23109 Cmp1 = DAG.getNode(
23110 Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(CC1, dl, MVT::i8));
23111 }
23112 Cmp = DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
23113 } else {
23114 if (IsStrict) {
23115 Cmp = DAG.getNode(
23116 Opc, dl, {VT, MVT::Other},
23117 {Chain, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8)});
23118 Chain = Cmp.getValue(1);
23119 } else
23120 Cmp = DAG.getNode(
23121 Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8));
23122 }
23123 } else {
23124 // Handle all other FP comparisons here.
23125 if (IsStrict) {
23126 // Make a flip on already signaling CCs before setting bit 4 of AVX CC.
23127 SSECC |= (IsAlwaysSignaling ^ IsSignaling) << 4;
23128 Cmp = DAG.getNode(
23129 Opc, dl, {VT, MVT::Other},
23130 {Chain, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8)});
23131 Chain = Cmp.getValue(1);
23132 } else
23133 Cmp = DAG.getNode(
23134 Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8));
23135 }
23136
23137 if (VT.getFixedSizeInBits() >
23138 Op.getSimpleValueType().getFixedSizeInBits()) {
23139 // We emitted a compare with an XMM/YMM result. Finish converting to a
23140 // mask register using a vptestm.
23141 EVT CastVT = EVT(VT).changeVectorElementTypeToInteger();
23142 Cmp = DAG.getBitcast(CastVT, Cmp);
23143 Cmp = DAG.getSetCC(dl, Op.getSimpleValueType(), Cmp,
23144 DAG.getConstant(0, dl, CastVT), ISD::SETNE);
23145 } else {
23146 // If this is SSE/AVX CMPP, bitcast the result back to integer to match
23147 // the result type of SETCC. The bitcast is expected to be optimized
23148 // away during combining/isel.
23149 Cmp = DAG.getBitcast(Op.getSimpleValueType(), Cmp);
23150 }
23151
23152 if (IsStrict)
23153 return DAG.getMergeValues({Cmp, Chain}, dl);
23154
23155 return Cmp;
23156 }
23157
23158 assert(!IsStrict && "Strict SETCC only handles FP operands.")(static_cast <bool> (!IsStrict && "Strict SETCC only handles FP operands."
) ? void (0) : __assert_fail ("!IsStrict && \"Strict SETCC only handles FP operands.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23158, __extension__ __PRETTY_FUNCTION__))
;
23159
23160 MVT VTOp0 = Op0.getSimpleValueType();
23161 (void)VTOp0;
23162 assert(VTOp0 == Op1.getSimpleValueType() &&(static_cast <bool> (VTOp0 == Op1.getSimpleValueType() &&
"Expected operands with same type!") ? void (0) : __assert_fail
("VTOp0 == Op1.getSimpleValueType() && \"Expected operands with same type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23163, __extension__ __PRETTY_FUNCTION__))
23163 "Expected operands with same type!")(static_cast <bool> (VTOp0 == Op1.getSimpleValueType() &&
"Expected operands with same type!") ? void (0) : __assert_fail
("VTOp0 == Op1.getSimpleValueType() && \"Expected operands with same type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23163, __extension__ __PRETTY_FUNCTION__))
;
23164 assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&(static_cast <bool> (VT.getVectorNumElements() == VTOp0
.getVectorNumElements() && "Invalid number of packed elements for source and destination!"
) ? void (0) : __assert_fail ("VT.getVectorNumElements() == VTOp0.getVectorNumElements() && \"Invalid number of packed elements for source and destination!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23165, __extension__ __PRETTY_FUNCTION__))
23165 "Invalid number of packed elements for source and destination!")(static_cast <bool> (VT.getVectorNumElements() == VTOp0
.getVectorNumElements() && "Invalid number of packed elements for source and destination!"
) ? void (0) : __assert_fail ("VT.getVectorNumElements() == VTOp0.getVectorNumElements() && \"Invalid number of packed elements for source and destination!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23165, __extension__ __PRETTY_FUNCTION__))
;
23166
23167 // The non-AVX512 code below works under the assumption that source and
23168 // destination types are the same.
23169 assert((Subtarget.hasAVX512() || (VT == VTOp0)) &&(static_cast <bool> ((Subtarget.hasAVX512() || (VT == VTOp0
)) && "Value types for source and destination must be the same!"
) ? void (0) : __assert_fail ("(Subtarget.hasAVX512() || (VT == VTOp0)) && \"Value types for source and destination must be the same!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23170, __extension__ __PRETTY_FUNCTION__))
23170 "Value types for source and destination must be the same!")(static_cast <bool> ((Subtarget.hasAVX512() || (VT == VTOp0
)) && "Value types for source and destination must be the same!"
) ? void (0) : __assert_fail ("(Subtarget.hasAVX512() || (VT == VTOp0)) && \"Value types for source and destination must be the same!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23170, __extension__ __PRETTY_FUNCTION__))
;
23171
23172 // The result is boolean, but operands are int/float
23173 if (VT.getVectorElementType() == MVT::i1) {
23174 // In AVX-512 architecture setcc returns mask with i1 elements,
23175 // But there is no compare instruction for i8 and i16 elements in KNL.
23176 assert((VTOp0.getScalarSizeInBits() >= 32 || Subtarget.hasBWI()) &&(static_cast <bool> ((VTOp0.getScalarSizeInBits() >=
32 || Subtarget.hasBWI()) && "Unexpected operand type"
) ? void (0) : __assert_fail ("(VTOp0.getScalarSizeInBits() >= 32 || Subtarget.hasBWI()) && \"Unexpected operand type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23177, __extension__ __PRETTY_FUNCTION__))
23177 "Unexpected operand type")(static_cast <bool> ((VTOp0.getScalarSizeInBits() >=
32 || Subtarget.hasBWI()) && "Unexpected operand type"
) ? void (0) : __assert_fail ("(VTOp0.getScalarSizeInBits() >= 32 || Subtarget.hasBWI()) && \"Unexpected operand type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23177, __extension__ __PRETTY_FUNCTION__))
;
23178 return LowerIntVSETCC_AVX512(Op, DAG);
23179 }
23180
23181 // Lower using XOP integer comparisons.
23182 if (VT.is128BitVector() && Subtarget.hasXOP()) {
23183 // Translate compare code to XOP PCOM compare mode.
23184 unsigned CmpMode = 0;
23185 switch (Cond) {
23186 default: llvm_unreachable("Unexpected SETCC condition")::llvm::llvm_unreachable_internal("Unexpected SETCC condition"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23186)
;
23187 case ISD::SETULT:
23188 case ISD::SETLT: CmpMode = 0x00; break;
23189 case ISD::SETULE:
23190 case ISD::SETLE: CmpMode = 0x01; break;
23191 case ISD::SETUGT:
23192 case ISD::SETGT: CmpMode = 0x02; break;
23193 case ISD::SETUGE:
23194 case ISD::SETGE: CmpMode = 0x03; break;
23195 case ISD::SETEQ: CmpMode = 0x04; break;
23196 case ISD::SETNE: CmpMode = 0x05; break;
23197 }
23198
23199 // Are we comparing unsigned or signed integers?
23200 unsigned Opc =
23201 ISD::isUnsignedIntSetCC(Cond) ? X86ISD::VPCOMU : X86ISD::VPCOM;
23202
23203 return DAG.getNode(Opc, dl, VT, Op0, Op1,
23204 DAG.getTargetConstant(CmpMode, dl, MVT::i8));
23205 }
23206
23207 // (X & Y) != 0 --> (X & Y) == Y iff Y is power-of-2.
23208 // Revert part of the simplifySetCCWithAnd combine, to avoid an invert.
23209 if (Cond == ISD::SETNE && ISD::isBuildVectorAllZeros(Op1.getNode())) {
23210 SDValue BC0 = peekThroughBitcasts(Op0);
23211 if (BC0.getOpcode() == ISD::AND) {
23212 APInt UndefElts;
23213 SmallVector<APInt, 64> EltBits;
23214 if (getTargetConstantBitsFromNode(BC0.getOperand(1),
23215 VT.getScalarSizeInBits(), UndefElts,
23216 EltBits, false, false)) {
23217 if (llvm::all_of(EltBits, [](APInt &V) { return V.isPowerOf2(); })) {
23218 Cond = ISD::SETEQ;
23219 Op1 = DAG.getBitcast(VT, BC0.getOperand(1));
23220 }
23221 }
23222 }
23223 }
23224
23225 // ICMP_EQ(AND(X,C),C) -> SRA(SHL(X,LOG2(C)),BW-1) iff C is power-of-2.
23226 if (Cond == ISD::SETEQ && Op0.getOpcode() == ISD::AND &&
23227 Op0.getOperand(1) == Op1 && Op0.hasOneUse()) {
23228 ConstantSDNode *C1 = isConstOrConstSplat(Op1);
23229 if (C1 && C1->getAPIntValue().isPowerOf2()) {
23230 unsigned BitWidth = VT.getScalarSizeInBits();
23231 unsigned ShiftAmt = BitWidth - C1->getAPIntValue().logBase2() - 1;
23232
23233 SDValue Result = Op0.getOperand(0);
23234 Result = DAG.getNode(ISD::SHL, dl, VT, Result,
23235 DAG.getConstant(ShiftAmt, dl, VT));
23236 Result = DAG.getNode(ISD::SRA, dl, VT, Result,
23237 DAG.getConstant(BitWidth - 1, dl, VT));
23238 return Result;
23239 }
23240 }
23241
23242 // Break 256-bit integer vector compare into smaller ones.
23243 if (VT.is256BitVector() && !Subtarget.hasInt256())
23244 return splitIntVSETCC(VT, Op0, Op1, Cond, DAG, dl);
23245
23246 if (VT == MVT::v32i16 || VT == MVT::v64i8) {
23247 assert(!Subtarget.hasBWI() && "Unexpected VT with AVX512BW!")(static_cast <bool> (!Subtarget.hasBWI() && "Unexpected VT with AVX512BW!"
) ? void (0) : __assert_fail ("!Subtarget.hasBWI() && \"Unexpected VT with AVX512BW!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23247, __extension__ __PRETTY_FUNCTION__))
;
23248 return splitIntVSETCC(VT, Op0, Op1, Cond, DAG, dl);
23249 }
23250
23251 // If we have a limit constant, try to form PCMPGT (signed cmp) to avoid
23252 // not-of-PCMPEQ:
23253 // X != INT_MIN --> X >s INT_MIN
23254 // X != INT_MAX --> X <s INT_MAX --> INT_MAX >s X
23255 // +X != 0 --> +X >s 0
23256 APInt ConstValue;
23257 if (Cond == ISD::SETNE &&
23258 ISD::isConstantSplatVector(Op1.getNode(), ConstValue)) {
23259 if (ConstValue.isMinSignedValue())
23260 Cond = ISD::SETGT;
23261 else if (ConstValue.isMaxSignedValue())
23262 Cond = ISD::SETLT;
23263 else if (ConstValue.isNullValue() && DAG.SignBitIsZero(Op0))
23264 Cond = ISD::SETGT;
23265 }
23266
23267 // If both operands are known non-negative, then an unsigned compare is the
23268 // same as a signed compare and there's no need to flip signbits.
23269 // TODO: We could check for more general simplifications here since we're
23270 // computing known bits.
23271 bool FlipSigns = ISD::isUnsignedIntSetCC(Cond) &&
23272 !(DAG.SignBitIsZero(Op0) && DAG.SignBitIsZero(Op1));
23273
23274 // Special case: Use min/max operations for unsigned compares.
23275 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23276 if (ISD::isUnsignedIntSetCC(Cond) &&
23277 (FlipSigns || ISD::isTrueWhenEqual(Cond)) &&
23278 TLI.isOperationLegal(ISD::UMIN, VT)) {
23279 // If we have a constant operand, increment/decrement it and change the
23280 // condition to avoid an invert.
23281 if (Cond == ISD::SETUGT) {
23282 // X > C --> X >= (C+1) --> X == umax(X, C+1)
23283 if (SDValue UGTOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/true)) {
23284 Op1 = UGTOp1;
23285 Cond = ISD::SETUGE;
23286 }
23287 }
23288 if (Cond == ISD::SETULT) {
23289 // X < C --> X <= (C-1) --> X == umin(X, C-1)
23290 if (SDValue ULTOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/false)) {
23291 Op1 = ULTOp1;
23292 Cond = ISD::SETULE;
23293 }
23294 }
23295 bool Invert = false;
23296 unsigned Opc;
23297 switch (Cond) {
23298 default: llvm_unreachable("Unexpected condition code")::llvm::llvm_unreachable_internal("Unexpected condition code"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23298)
;
23299 case ISD::SETUGT: Invert = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
23300 case ISD::SETULE: Opc = ISD::UMIN; break;
23301 case ISD::SETULT: Invert = true; LLVM_FALLTHROUGH[[gnu::fallthrough]];
23302 case ISD::SETUGE: Opc = ISD::UMAX; break;
23303 }
23304
23305 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
23306 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
23307
23308 // If the logical-not of the result is required, perform that now.
23309 if (Invert)
23310 Result = DAG.getNOT(dl, Result, VT);
23311
23312 return Result;
23313 }
23314
23315 // Try to use SUBUS and PCMPEQ.
23316 if (FlipSigns)
23317 if (SDValue V =
23318 LowerVSETCCWithSUBUS(Op0, Op1, VT, Cond, dl, Subtarget, DAG))
23319 return V;
23320
23321 // We are handling one of the integer comparisons here. Since SSE only has
23322 // GT and EQ comparisons for integer, swapping operands and multiple
23323 // operations may be required for some comparisons.
23324 unsigned Opc = (Cond == ISD::SETEQ || Cond == ISD::SETNE) ? X86ISD::PCMPEQ
23325 : X86ISD::PCMPGT;
23326 bool Swap = Cond == ISD::SETLT || Cond == ISD::SETULT ||
23327 Cond == ISD::SETGE || Cond == ISD::SETUGE;
23328 bool Invert = Cond == ISD::SETNE ||
23329 (Cond != ISD::SETEQ && ISD::isTrueWhenEqual(Cond));
23330
23331 if (Swap)
23332 std::swap(Op0, Op1);
23333
23334 // Check that the operation in question is available (most are plain SSE2,
23335 // but PCMPGTQ and PCMPEQQ have different requirements).
23336 if (VT == MVT::v2i64) {
23337 if (Opc == X86ISD::PCMPGT && !Subtarget.hasSSE42()) {
23338 assert(Subtarget.hasSSE2() && "Don't know how to lower!")(static_cast <bool> (Subtarget.hasSSE2() && "Don't know how to lower!"
) ? void (0) : __assert_fail ("Subtarget.hasSSE2() && \"Don't know how to lower!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23338, __extension__ __PRETTY_FUNCTION__))
;
23339
23340 // Special case for sign bit test. We can use a v4i32 PCMPGT and shuffle
23341 // the odd elements over the even elements.
23342 if (!FlipSigns && !Invert && ISD::isBuildVectorAllZeros(Op0.getNode())) {
23343 Op0 = DAG.getConstant(0, dl, MVT::v4i32);
23344 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
23345
23346 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
23347 static const int MaskHi[] = { 1, 1, 3, 3 };
23348 SDValue Result = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
23349
23350 return DAG.getBitcast(VT, Result);
23351 }
23352
23353 if (!FlipSigns && !Invert && ISD::isBuildVectorAllOnes(Op1.getNode())) {
23354 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
23355 Op1 = DAG.getConstant(-1, dl, MVT::v4i32);
23356
23357 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
23358 static const int MaskHi[] = { 1, 1, 3, 3 };
23359 SDValue Result = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
23360
23361 return DAG.getBitcast(VT, Result);
23362 }
23363
23364 // Since SSE has no unsigned integer comparisons, we need to flip the sign
23365 // bits of the inputs before performing those operations. The lower
23366 // compare is always unsigned.
23367 SDValue SB;
23368 if (FlipSigns) {
23369 SB = DAG.getConstant(0x8000000080000000ULL, dl, MVT::v2i64);
23370 } else {
23371 SB = DAG.getConstant(0x0000000080000000ULL, dl, MVT::v2i64);
23372 }
23373 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op0, SB);
23374 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op1, SB);
23375
23376 // Cast everything to the right type.
23377 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
23378 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
23379
23380 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
23381 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
23382 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
23383
23384 // Create masks for only the low parts/high parts of the 64 bit integers.
23385 static const int MaskHi[] = { 1, 1, 3, 3 };
23386 static const int MaskLo[] = { 0, 0, 2, 2 };
23387 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
23388 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
23389 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
23390
23391 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
23392 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
23393
23394 if (Invert)
23395 Result = DAG.getNOT(dl, Result, MVT::v4i32);
23396
23397 return DAG.getBitcast(VT, Result);
23398 }
23399
23400 if (Opc == X86ISD::PCMPEQ && !Subtarget.hasSSE41()) {
23401 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
23402 // pcmpeqd + pshufd + pand.
23403 assert(Subtarget.hasSSE2() && !FlipSigns && "Don't know how to lower!")(static_cast <bool> (Subtarget.hasSSE2() && !FlipSigns
&& "Don't know how to lower!") ? void (0) : __assert_fail
("Subtarget.hasSSE2() && !FlipSigns && \"Don't know how to lower!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23403, __extension__ __PRETTY_FUNCTION__))
;
23404
23405 // First cast everything to the right type.
23406 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
23407 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
23408
23409 // Do the compare.
23410 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
23411
23412 // Make sure the lower and upper halves are both all-ones.
23413 static const int Mask[] = { 1, 0, 3, 2 };
23414 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
23415 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
23416
23417 if (Invert)
23418 Result = DAG.getNOT(dl, Result, MVT::v4i32);
23419
23420 return DAG.getBitcast(VT, Result);
23421 }
23422 }
23423
23424 // Since SSE has no unsigned integer comparisons, we need to flip the sign
23425 // bits of the inputs before performing those operations.
23426 if (FlipSigns) {
23427 MVT EltVT = VT.getVectorElementType();
23428 SDValue SM = DAG.getConstant(APInt::getSignMask(EltVT.getSizeInBits()), dl,
23429 VT);
23430 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SM);
23431 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SM);
23432 }
23433
23434 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
23435
23436 // If the logical-not of the result is required, perform that now.
23437 if (Invert)
23438 Result = DAG.getNOT(dl, Result, VT);
23439
23440 return Result;
23441}
23442
23443// Try to select this as a KORTEST+SETCC or KTEST+SETCC if possible.
23444static SDValue EmitAVX512Test(SDValue Op0, SDValue Op1, ISD::CondCode CC,
23445 const SDLoc &dl, SelectionDAG &DAG,
23446 const X86Subtarget &Subtarget,
23447 SDValue &X86CC) {
23448 // Only support equality comparisons.
23449 if (CC != ISD::SETEQ && CC != ISD::SETNE)
23450 return SDValue();
23451
23452 // Must be a bitcast from vXi1.
23453 if (Op0.getOpcode() != ISD::BITCAST)
23454 return SDValue();
23455
23456 Op0 = Op0.getOperand(0);
23457 MVT VT = Op0.getSimpleValueType();
23458 if (!(Subtarget.hasAVX512() && VT == MVT::v16i1) &&
23459 !(Subtarget.hasDQI() && VT == MVT::v8i1) &&
23460 !(Subtarget.hasBWI() && (VT == MVT::v32i1 || VT == MVT::v64i1)))
23461 return SDValue();
23462
23463 X86::CondCode X86Cond;
23464 if (isNullConstant(Op1)) {
23465 X86Cond = CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE;
23466 } else if (isAllOnesConstant(Op1)) {
23467 // C flag is set for all ones.
23468 X86Cond = CC == ISD::SETEQ ? X86::COND_B : X86::COND_AE;
23469 } else
23470 return SDValue();
23471
23472 // If the input is an AND, we can combine it's operands into the KTEST.
23473 bool KTestable = false;
23474 if (Subtarget.hasDQI() && (VT == MVT::v8i1 || VT == MVT::v16i1))
23475 KTestable = true;
23476 if (Subtarget.hasBWI() && (VT == MVT::v32i1 || VT == MVT::v64i1))
23477 KTestable = true;
23478 if (!isNullConstant(Op1))
23479 KTestable = false;
23480 if (KTestable && Op0.getOpcode() == ISD::AND && Op0.hasOneUse()) {
23481 SDValue LHS = Op0.getOperand(0);
23482 SDValue RHS = Op0.getOperand(1);
23483 X86CC = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
23484 return DAG.getNode(X86ISD::KTEST, dl, MVT::i32, LHS, RHS);
23485 }
23486
23487 // If the input is an OR, we can combine it's operands into the KORTEST.
23488 SDValue LHS = Op0;
23489 SDValue RHS = Op0;
23490 if (Op0.getOpcode() == ISD::OR && Op0.hasOneUse()) {
23491 LHS = Op0.getOperand(0);
23492 RHS = Op0.getOperand(1);
23493 }
23494
23495 X86CC = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
23496 return DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
23497}
23498
23499/// Emit flags for the given setcc condition and operands. Also returns the
23500/// corresponding X86 condition code constant in X86CC.
23501SDValue X86TargetLowering::emitFlagsForSetcc(SDValue Op0, SDValue Op1,
23502 ISD::CondCode CC, const SDLoc &dl,
23503 SelectionDAG &DAG,
23504 SDValue &X86CC) const {
23505 // Optimize to BT if possible.
23506 // Lower (X & (1 << N)) == 0 to BT(X, N).
23507 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
23508 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
23509 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() && isNullConstant(Op1) &&
23510 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
23511 if (SDValue BT = LowerAndToBT(Op0, CC, dl, DAG, X86CC))
23512 return BT;
23513 }
23514
23515 // Try to use PTEST/PMOVMSKB for a tree ORs equality compared with 0.
23516 // TODO: We could do AND tree with all 1s as well by using the C flag.
23517 if (isNullConstant(Op1) && (CC == ISD::SETEQ || CC == ISD::SETNE))
23518 if (SDValue CmpZ =
23519 MatchVectorAllZeroTest(Op0, CC, dl, Subtarget, DAG, X86CC))
23520 return CmpZ;
23521
23522 // Try to lower using KORTEST or KTEST.
23523 if (SDValue Test = EmitAVX512Test(Op0, Op1, CC, dl, DAG, Subtarget, X86CC))
23524 return Test;
23525
23526 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
23527 // these.
23528 if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
23529 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
23530 // If the input is a setcc, then reuse the input setcc or use a new one with
23531 // the inverted condition.
23532 if (Op0.getOpcode() == X86ISD::SETCC) {
23533 bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
23534
23535 X86CC = Op0.getOperand(0);
23536 if (Invert) {
23537 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
23538 CCode = X86::GetOppositeBranchCondition(CCode);
23539 X86CC = DAG.getTargetConstant(CCode, dl, MVT::i8);
23540 }
23541
23542 return Op0.getOperand(1);
23543 }
23544 }
23545
23546 // Try to use the carry flag from the add in place of an separate CMP for:
23547 // (seteq (add X, -1), -1). Similar for setne.
23548 if (isAllOnesConstant(Op1) && Op0.getOpcode() == ISD::ADD &&
23549 Op0.getOperand(1) == Op1 && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
23550 if (isProfitableToUseFlagOp(Op0)) {
23551 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
23552
23553 SDValue New = DAG.getNode(X86ISD::ADD, dl, VTs, Op0.getOperand(0),
23554 Op0.getOperand(1));
23555 DAG.ReplaceAllUsesOfValueWith(SDValue(Op0.getNode(), 0), New);
23556 X86::CondCode CCode = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
23557 X86CC = DAG.getTargetConstant(CCode, dl, MVT::i8);
23558 return SDValue(New.getNode(), 1);
23559 }
23560 }
23561
23562 X86::CondCode CondCode =
23563 TranslateX86CC(CC, dl, /*IsFP*/ false, Op0, Op1, DAG);
23564 assert(CondCode != X86::COND_INVALID && "Unexpected condition code!")(static_cast <bool> (CondCode != X86::COND_INVALID &&
"Unexpected condition code!") ? void (0) : __assert_fail ("CondCode != X86::COND_INVALID && \"Unexpected condition code!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23564, __extension__ __PRETTY_FUNCTION__))
;
23565
23566 SDValue EFLAGS = EmitCmp(Op0, Op1, CondCode, dl, DAG, Subtarget);
23567 X86CC = DAG.getTargetConstant(CondCode, dl, MVT::i8);
23568 return EFLAGS;
23569}
23570
23571SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
23572
23573 bool IsStrict = Op.getOpcode() == ISD::STRICT_FSETCC ||
23574 Op.getOpcode() == ISD::STRICT_FSETCCS;
23575 MVT VT = Op->getSimpleValueType(0);
23576
23577 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
23578
23579 assert(VT == MVT::i8 && "SetCC type must be 8-bit integer")(static_cast <bool> (VT == MVT::i8 && "SetCC type must be 8-bit integer"
) ? void (0) : __assert_fail ("VT == MVT::i8 && \"SetCC type must be 8-bit integer\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23579, __extension__ __PRETTY_FUNCTION__))
;
23580 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
23581 SDValue Op0 = Op.getOperand(IsStrict ? 1 : 0);
23582 SDValue Op1 = Op.getOperand(IsStrict ? 2 : 1);
23583 SDLoc dl(Op);
23584 ISD::CondCode CC =
23585 cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
23586
23587 // Handle f128 first, since one possible outcome is a normal integer
23588 // comparison which gets handled by emitFlagsForSetcc.
23589 if (Op0.getValueType() == MVT::f128) {
23590 softenSetCCOperands(DAG, MVT::f128, Op0, Op1, CC, dl, Op0, Op1, Chain,
23591 Op.getOpcode() == ISD::STRICT_FSETCCS);
23592
23593 // If softenSetCCOperands returned a scalar, use it.
23594 if (!Op1.getNode()) {
23595 assert(Op0.getValueType() == Op.getValueType() &&(static_cast <bool> (Op0.getValueType() == Op.getValueType
() && "Unexpected setcc expansion!") ? void (0) : __assert_fail
("Op0.getValueType() == Op.getValueType() && \"Unexpected setcc expansion!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23596, __extension__ __PRETTY_FUNCTION__))
23596 "Unexpected setcc expansion!")(static_cast <bool> (Op0.getValueType() == Op.getValueType
() && "Unexpected setcc expansion!") ? void (0) : __assert_fail
("Op0.getValueType() == Op.getValueType() && \"Unexpected setcc expansion!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23596, __extension__ __PRETTY_FUNCTION__))
;
23597 if (IsStrict)
23598 return DAG.getMergeValues({Op0, Chain}, dl);
23599 return Op0;
23600 }
23601 }
23602
23603 if (Op0.getSimpleValueType().isInteger()) {
23604 // Attempt to canonicalize SGT/UGT -> SGE/UGE compares with constant which
23605 // reduces the number of EFLAGs bit reads (the GE conditions don't read ZF),
23606 // this may translate to less uops depending on uarch implementation. The
23607 // equivalent for SLE/ULE -> SLT/ULT isn't likely to happen as we already
23608 // canonicalize to that CondCode.
23609 // NOTE: Only do this if incrementing the constant doesn't increase the bit
23610 // encoding size - so it must either already be a i8 or i32 immediate, or it
23611 // shrinks down to that. We don't do this for any i64's to avoid additional
23612 // constant materializations.
23613 // TODO: Can we move this to TranslateX86CC to handle jumps/branches too?
23614 if (auto *Op1C = dyn_cast<ConstantSDNode>(Op1)) {
23615 const APInt &Op1Val = Op1C->getAPIntValue();
23616 if (!Op1Val.isNullValue()) {
23617 // Ensure the constant+1 doesn't overflow.
23618 if ((CC == ISD::CondCode::SETGT && !Op1Val.isMaxSignedValue()) ||
23619 (CC == ISD::CondCode::SETUGT && !Op1Val.isMaxValue())) {
23620 APInt Op1ValPlusOne = Op1Val + 1;
23621 if (Op1ValPlusOne.isSignedIntN(32) &&
23622 (!Op1Val.isSignedIntN(8) || Op1ValPlusOne.isSignedIntN(8))) {
23623 Op1 = DAG.getConstant(Op1ValPlusOne, dl, Op0.getValueType());
23624 CC = CC == ISD::CondCode::SETGT ? ISD::CondCode::SETGE
23625 : ISD::CondCode::SETUGE;
23626 }
23627 }
23628 }
23629 }
23630
23631 SDValue X86CC;
23632 SDValue EFLAGS = emitFlagsForSetcc(Op0, Op1, CC, dl, DAG, X86CC);
23633 SDValue Res = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, X86CC, EFLAGS);
23634 return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
23635 }
23636
23637 // Handle floating point.
23638 X86::CondCode CondCode = TranslateX86CC(CC, dl, /*IsFP*/ true, Op0, Op1, DAG);
23639 if (CondCode == X86::COND_INVALID)
23640 return SDValue();
23641
23642 SDValue EFLAGS;
23643 if (IsStrict) {
23644 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
23645 EFLAGS =
23646 DAG.getNode(IsSignaling ? X86ISD::STRICT_FCMPS : X86ISD::STRICT_FCMP,
23647 dl, {MVT::i32, MVT::Other}, {Chain, Op0, Op1});
23648 Chain = EFLAGS.getValue(1);
23649 } else {
23650 EFLAGS = DAG.getNode(X86ISD::FCMP, dl, MVT::i32, Op0, Op1);
23651 }
23652
23653 SDValue X86CC = DAG.getTargetConstant(CondCode, dl, MVT::i8);
23654 SDValue Res = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, X86CC, EFLAGS);
23655 return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
23656}
23657
23658SDValue X86TargetLowering::LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) const {
23659 SDValue LHS = Op.getOperand(0);
23660 SDValue RHS = Op.getOperand(1);
23661 SDValue Carry = Op.getOperand(2);
23662 SDValue Cond = Op.getOperand(3);
23663 SDLoc DL(Op);
23664
23665 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-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23665, __extension__ __PRETTY_FUNCTION__))
;
23666 X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
23667
23668 // Recreate the carry if needed.
23669 EVT CarryVT = Carry.getValueType();
23670 Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
23671 Carry, DAG.getAllOnesConstant(DL, CarryVT));
23672
23673 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
23674 SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry.getValue(1));
23675 return getSETCC(CC, Cmp.getValue(1), DL, DAG);
23676}
23677
23678// This function returns three things: the arithmetic computation itself
23679// (Value), an EFLAGS result (Overflow), and a condition code (Cond). The
23680// flag and the condition code define the case in which the arithmetic
23681// computation overflows.
23682static std::pair<SDValue, SDValue>
23683getX86XALUOOp(X86::CondCode &Cond, SDValue Op, SelectionDAG &DAG) {
23684 assert(Op.getResNo() == 0 && "Unexpected result number!")(static_cast <bool> (Op.getResNo() == 0 && "Unexpected result number!"
) ? void (0) : __assert_fail ("Op.getResNo() == 0 && \"Unexpected result number!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23684, __extension__ __PRETTY_FUNCTION__))
;
23685 SDValue Value, Overflow;
23686 SDValue LHS = Op.getOperand(0);
23687 SDValue RHS = Op.getOperand(1);
23688 unsigned BaseOp = 0;
23689 SDLoc DL(Op);
23690 switch (Op.getOpcode()) {
23691 default: llvm_unreachable("Unknown ovf instruction!")::llvm::llvm_unreachable_internal("Unknown ovf instruction!",
"/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23691)
;
23692 case ISD::SADDO:
23693 BaseOp = X86ISD::ADD;
23694 Cond = X86::COND_O;
23695 break;
23696 case ISD::UADDO:
23697 BaseOp = X86ISD::ADD;
23698 Cond = isOneConstant(RHS) ? X86::COND_E : X86::COND_B;
23699 break;
23700 case ISD::SSUBO:
23701 BaseOp = X86ISD::SUB;
23702 Cond = X86::COND_O;
23703 break;
23704 case ISD::USUBO:
23705 BaseOp = X86ISD::SUB;
23706 Cond = X86::COND_B;
23707 break;
23708 case ISD::SMULO:
23709 BaseOp = X86ISD::SMUL;
23710 Cond = X86::COND_O;
23711 break;
23712 case ISD::UMULO:
23713 BaseOp = X86ISD::UMUL;
23714 Cond = X86::COND_O;
23715 break;
23716 }
23717
23718 if (BaseOp) {
23719 // Also sets EFLAGS.
23720 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
23721 Value = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
23722 Overflow = Value.getValue(1);
23723 }
23724
23725 return std::make_pair(Value, Overflow);
23726}
23727
23728static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
23729 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
23730 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
23731 // looks for this combo and may remove the "setcc" instruction if the "setcc"
23732 // has only one use.
23733 SDLoc DL(Op);
23734 X86::CondCode Cond;
23735 SDValue Value, Overflow;
23736 std::tie(Value, Overflow) = getX86XALUOOp(Cond, Op, DAG);
23737
23738 SDValue SetCC = getSETCC(Cond, Overflow, DL, DAG);
23739 assert(Op->getValueType(1) == MVT::i8 && "Unexpected VT!")(static_cast <bool> (Op->getValueType(1) == MVT::i8 &&
"Unexpected VT!") ? void (0) : __assert_fail ("Op->getValueType(1) == MVT::i8 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23739, __extension__ __PRETTY_FUNCTION__))
;
23740 return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(), Value, SetCC);
23741}
23742
23743/// Return true if opcode is a X86 logical comparison.
23744static bool isX86LogicalCmp(SDValue Op) {
23745 unsigned Opc = Op.getOpcode();
23746 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
23747 Opc == X86ISD::FCMP)
23748 return true;
23749 if (Op.getResNo() == 1 &&
23750 (Opc == X86ISD::ADD || Opc == X86ISD::SUB || Opc == X86ISD::ADC ||
23751 Opc == X86ISD::SBB || Opc == X86ISD::SMUL || Opc == X86ISD::UMUL ||
23752 Opc == X86ISD::OR || Opc == X86ISD::XOR || Opc == X86ISD::AND))
23753 return true;
23754
23755 return false;
23756}
23757
23758static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
23759 if (V.getOpcode() != ISD::TRUNCATE)
23760 return false;
23761
23762 SDValue VOp0 = V.getOperand(0);
23763 unsigned InBits = VOp0.getValueSizeInBits();
23764 unsigned Bits = V.getValueSizeInBits();
23765 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
23766}
23767
23768SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
23769 bool AddTest = true;
23770 SDValue Cond = Op.getOperand(0);
23771 SDValue Op1 = Op.getOperand(1);
23772 SDValue Op2 = Op.getOperand(2);
23773 SDLoc DL(Op);
23774 MVT VT = Op1.getSimpleValueType();
23775 SDValue CC;
23776
23777 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
23778 // are available or VBLENDV if AVX is available.
23779 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
23780 if (Cond.getOpcode() == ISD::SETCC && isScalarFPTypeInSSEReg(VT) &&
23781 VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
23782 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
23783 bool IsAlwaysSignaling;
23784 unsigned SSECC =
23785 translateX86FSETCC(cast<CondCodeSDNode>(Cond.getOperand(2))->get(),
23786 CondOp0, CondOp1, IsAlwaysSignaling);
23787
23788 if (Subtarget.hasAVX512()) {
23789 SDValue Cmp =
23790 DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CondOp0, CondOp1,
23791 DAG.getTargetConstant(SSECC, DL, MVT::i8));
23792 assert(!VT.isVector() && "Not a scalar type?")(static_cast <bool> (!VT.isVector() && "Not a scalar type?"
) ? void (0) : __assert_fail ("!VT.isVector() && \"Not a scalar type?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 23792, __extension__ __PRETTY_FUNCTION__))
;
23793 return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
23794 }
23795
23796 if (SSECC < 8 || Subtarget.hasAVX()) {
23797 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
23798 DAG.getTargetConstant(SSECC, DL, MVT::i8));
23799
23800 // If we have AVX, we can use a variable vector select (VBLENDV) instead
23801 // of 3 logic instructions for size savings and potentially speed.
23802 // Unfortunately, there is no scalar form of VBLENDV.
23803
23804 // If either operand is a +0.0 constant, don't try this. We can expect to
23805 // optimize away at least one of the logic instructions later in that
23806 // case, so that sequence would be faster than a variable blend.
23807
23808 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
23809 // uses XMM0 as the selection register. That may need just as many
23810 // instructions as the AND/ANDN/OR sequence due to register moves, so
23811 // don't bother.
23812 if (Subtarget.hasAVX() && !isNullFPConstant(Op1) &&
23813 !isNullFPConstant(Op2)) {
23814 // Convert to vectors, do a VSELECT, and convert back to scalar.
23815 // All of the conversions should be optimized away.
23816 MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
23817 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
23818 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
23819 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
23820
23821 MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
23822 VCmp = DAG.getBitcast(VCmpVT, VCmp);
23823
23824 SDValue VSel = DAG.getSelect(DL, VecVT, VCmp, VOp1, VOp2);
23825
23826 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
23827 VSel, DAG.getIntPtrConstant(0, DL));
23828 }
23829 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
23830 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
23831 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
23832 }
23833 }
23834
23835 // AVX512 fallback is to lower selects of scalar floats to masked moves.
23836 if (isScalarFPTypeInSSEReg(VT) && Subtarget.hasAVX512()) {
23837 SDValue Cmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1, Cond);
23838 return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
23839 }
23840
23841 if (Cond.getOpcode() == ISD::SETCC) {
23842 if (SDValue NewCond = LowerSETCC(Cond, DAG)) {
23843 Cond = NewCond;
23844 // If the condition was updated, it's possible that the operands of the
23845 // select were also updated (for example, EmitTest has a RAUW). Refresh
23846 // the local references to the select operands in case they got stale.
23847 Op1 = Op.getOperand(1);
23848 Op2 = Op.getOperand(2);
23849 }
23850 }
23851
23852 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
23853 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
23854 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
23855 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
23856 // (select (and (x , 0x1) == 0), y, (z ^ y) ) -> (-(and (x , 0x1)) & z ) ^ y
23857 // (select (and (x , 0x1) == 0), y, (z | y) ) -> (-(and (x , 0x1)) & z ) | y
23858 if (Cond.getOpcode() == X86ISD::SETCC &&
23859 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
23860 isNullConstant(Cond.getOperand(1).getOperand(1))) {
23861 SDValue Cmp = Cond.getOperand(1);
23862 SDValue CmpOp0 = Cmp.getOperand(0);
23863 unsigned CondCode = Cond.getConstantOperandVal(0);
23864
23865 // Special handling for __builtin_ffs(X) - 1 pattern which looks like
23866 // (select (seteq X, 0), -1, (cttz_zero_undef X)). Disable the special
23867 // handle to keep the CMP with 0. This should be removed by
23868 // optimizeCompareInst by using the flags from the BSR/TZCNT used for the
23869 // cttz_zero_undef.
23870 auto MatchFFSMinus1 = [&](SDValue Op1, SDValue Op2) {
23871 return (Op1.getOpcode() == ISD::CTTZ_ZERO_UNDEF && Op1.hasOneUse() &&
23872 Op1.getOperand(0) == CmpOp0 && isAllOnesConstant(Op2));
23873 };
23874 if (Subtarget.hasCMov() && (VT == MVT::i32 || VT == MVT::i64) &&
23875 ((CondCode == X86::COND_NE && MatchFFSMinus1(Op1, Op2)) ||
23876 (CondCode == X86::COND_E && MatchFFSMinus1(Op2, Op1)))) {
23877 // Keep Cmp.
23878 } else if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
23879 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
23880 SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
23881
23882 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
23883 SDVTList CmpVTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
23884
23885 // Apply further optimizations for special cases
23886 // (select (x != 0), -1, 0) -> neg & sbb
23887 // (select (x == 0), 0, -1) -> neg & sbb
23888 if (isNullConstant(Y) &&
23889 (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
23890 SDValue Zero = DAG.getConstant(0, DL, CmpOp0.getValueType());
23891 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, CmpVTs, Zero, CmpOp0);
23892 Zero = DAG.getConstant(0, DL, Op.getValueType());
23893 return DAG.getNode(X86ISD::SBB, DL, VTs, Zero, Zero, Neg.getValue(1));
23894 }
23895
23896 Cmp = DAG.getNode(X86ISD::SUB, DL, CmpVTs,
23897 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
23898
23899 SDValue Zero = DAG.getConstant(0, DL, Op.getValueType());
23900 SDValue Res = // Res = 0 or -1.
23901 DAG.getNode(X86ISD::SBB, DL, VTs, Zero, Zero, Cmp.getValue(1));
23902
23903 if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
23904 Res = DAG.getNOT(DL, Res, Res.getValueType());
23905
23906 return DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
23907 } else if (!Subtarget.hasCMov() && CondCode == X86::COND_E &&
23908 Cmp.getOperand(0).getOpcode() == ISD::AND &&
23909 isOneConstant(Cmp.getOperand(0).getOperand(1))) {
23910 SDValue Src1, Src2;
23911 // true if Op2 is XOR or OR operator and one of its operands
23912 // is equal to Op1
23913 // ( a , a op b) || ( b , a op b)
23914 auto isOrXorPattern = [&]() {
23915 if ((Op2.getOpcode() == ISD::XOR || Op2.getOpcode() == ISD::OR) &&
23916 (Op2.getOperand(0) == Op1 || Op2.getOperand(1) == Op1)) {
23917 Src1 =
23918 Op2.getOperand(0) == Op1 ? Op2.getOperand(1) : Op2.getOperand(0);
23919 Src2 = Op1;
23920 return true;
23921 }
23922 return false;
23923 };
23924
23925 if (isOrXorPattern()) {
23926 SDValue Neg;
23927 unsigned int CmpSz = CmpOp0.getSimpleValueType().getSizeInBits();
23928 // we need mask of all zeros or ones with same size of the other
23929 // operands.
23930 if (CmpSz > VT.getSizeInBits())
23931 Neg = DAG.getNode(ISD::TRUNCATE, DL, VT, CmpOp0);
23932 else if (CmpSz < VT.getSizeInBits())
23933 Neg = DAG.getNode(ISD::AND, DL, VT,
23934 DAG.getNode(ISD::ANY_EXTEND, DL, VT, CmpOp0.getOperand(0)),
23935 DAG.getConstant(1, DL, VT));
23936 else
23937 Neg = CmpOp0;
23938 SDValue Mask = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
23939 Neg); // -(and (x, 0x1))
23940 SDValue And = DAG.getNode(ISD::AND, DL, VT, Mask, Src1); // Mask & z
23941 return DAG.getNode(Op2.getOpcode(), DL, VT, And, Src2); // And Op y
23942 }
23943 }
23944 }
23945
23946 // Look past (and (setcc_carry (cmp ...)), 1).
23947 if (Cond.getOpcode() == ISD::AND &&
23948 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
23949 isOneConstant(Cond.getOperand(1)))
23950 Cond = Cond.getOperand(0);
23951
23952 // If condition flag is set by a X86ISD::CMP, then use it as the condition
23953 // setting operand in place of the X86ISD::SETCC.
23954 unsigned CondOpcode = Cond.getOpcode();
23955 if (CondOpcode == X86ISD::SETCC ||
23956 CondOpcode == X86ISD::SETCC_CARRY) {
23957 CC = Cond.getOperand(0);
23958
23959 SDValue Cmp = Cond.getOperand(1);
23960 bool IllegalFPCMov = false;
23961 if (VT.isFloatingPoint() && !VT.isVector() &&
23962 !isScalarFPTypeInSSEReg(VT) && Subtarget.hasCMov()) // FPStack?
23963 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
23964
23965 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
23966 Cmp.getOpcode() == X86ISD::BT) { // FIXME
23967 Cond = Cmp;
23968 AddTest = false;
23969 }
23970 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
23971 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
23972 CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) {
23973 SDValue Value;
23974 X86::CondCode X86Cond;
23975 std::tie(Value, Cond) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
23976
23977 CC = DAG.getTargetConstant(X86Cond, DL, MVT::i8);
23978 AddTest = false;
23979 }
23980
23981 if (AddTest) {
23982 // Look past the truncate if the high bits are known zero.
23983 if (isTruncWithZeroHighBitsInput(Cond, DAG))
23984 Cond = Cond.getOperand(0);
23985
23986 // We know the result of AND is compared against zero. Try to match
23987 // it to BT.
23988 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
23989 SDValue BTCC;
23990 if (SDValue BT = LowerAndToBT(Cond, ISD::SETNE, DL, DAG, BTCC)) {
23991 CC = BTCC;
23992 Cond = BT;
23993 AddTest = false;
23994 }
23995 }
23996 }
23997
23998 if (AddTest) {
23999 CC = DAG.getTargetConstant(X86::COND_NE, DL, MVT::i8);
24000 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG, Subtarget);
24001 }
24002
24003 // a < b ? -1 : 0 -> RES = ~setcc_carry
24004 // a < b ? 0 : -1 -> RES = setcc_carry
24005 // a >= b ? -1 : 0 -> RES = setcc_carry
24006 // a >= b ? 0 : -1 -> RES = ~setcc_carry
24007 if (Cond.getOpcode() == X86ISD::SUB) {
24008 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
24009
24010 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
24011 (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
24012 (isNullConstant(Op1) || isNullConstant(Op2))) {
24013 SDValue Res =
24014 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
24015 DAG.getTargetConstant(X86::COND_B, DL, MVT::i8), Cond);
24016 if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
24017 return DAG.getNOT(DL, Res, Res.getValueType());
24018 return Res;
24019 }
24020 }
24021
24022 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
24023 // widen the cmov and push the truncate through. This avoids introducing a new
24024 // branch during isel and doesn't add any extensions.
24025 if (Op.getValueType() == MVT::i8 &&
24026 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
24027 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
24028 if (T1.getValueType() == T2.getValueType() &&
24029 // Exclude CopyFromReg to avoid partial register stalls.
24030 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
24031 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, T1.getValueType(), T2, T1,
24032 CC, Cond);
24033 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
24034 }
24035 }
24036
24037 // Or finally, promote i8 cmovs if we have CMOV,
24038 // or i16 cmovs if it won't prevent folding a load.
24039 // FIXME: we should not limit promotion of i8 case to only when the CMOV is
24040 // legal, but EmitLoweredSelect() can not deal with these extensions
24041 // being inserted between two CMOV's. (in i16 case too TBN)
24042 // https://bugs.llvm.org/show_bug.cgi?id=40974
24043 if ((Op.getValueType() == MVT::i8 && Subtarget.hasCMov()) ||
24044 (Op.getValueType() == MVT::i16 && !MayFoldLoad(Op1) &&
24045 !MayFoldLoad(Op2))) {
24046 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
24047 Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
24048 SDValue Ops[] = { Op2, Op1, CC, Cond };
24049 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, MVT::i32, Ops);
24050 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
24051 }
24052
24053 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
24054 // condition is true.
24055 SDValue Ops[] = { Op2, Op1, CC, Cond };
24056 return DAG.getNode(X86ISD::CMOV, DL, Op.getValueType(), Ops);
24057}
24058
24059static SDValue LowerSIGN_EXTEND_Mask(SDValue Op,
24060 const X86Subtarget &Subtarget,
24061 SelectionDAG &DAG) {
24062 MVT VT = Op->getSimpleValueType(0);
24063 SDValue In = Op->getOperand(0);
24064 MVT InVT = In.getSimpleValueType();
24065 assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!")(static_cast <bool> (InVT.getVectorElementType() == MVT
::i1 && "Unexpected input type!") ? void (0) : __assert_fail
("InVT.getVectorElementType() == MVT::i1 && \"Unexpected input type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24065, __extension__ __PRETTY_FUNCTION__))
;
24066 MVT VTElt = VT.getVectorElementType();
24067 SDLoc dl(Op);
24068
24069 unsigned NumElts = VT.getVectorNumElements();
24070
24071 // Extend VT if the scalar type is i8/i16 and BWI is not supported.
24072 MVT ExtVT = VT;
24073 if (!Subtarget.hasBWI() && VTElt.getSizeInBits() <= 16) {
24074 // If v16i32 is to be avoided, we'll need to split and concatenate.
24075 if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
24076 return SplitAndExtendv16i1(Op.getOpcode(), VT, In, dl, DAG);
24077
24078 ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
24079 }
24080
24081 // Widen to 512-bits if VLX is not supported.
24082 MVT WideVT = ExtVT;
24083 if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
24084 NumElts *= 512 / ExtVT.getSizeInBits();
24085 InVT = MVT::getVectorVT(MVT::i1, NumElts);
24086 In = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, InVT, DAG.getUNDEF(InVT),
24087 In, DAG.getIntPtrConstant(0, dl));
24088 WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(), NumElts);
24089 }
24090
24091 SDValue V;
24092 MVT WideEltVT = WideVT.getVectorElementType();
24093 if ((Subtarget.hasDQI() && WideEltVT.getSizeInBits() >= 32) ||
24094 (Subtarget.hasBWI() && WideEltVT.getSizeInBits() <= 16)) {
24095 V = DAG.getNode(Op.getOpcode(), dl, WideVT, In);
24096 } else {
24097 SDValue NegOne = DAG.getConstant(-1, dl, WideVT);
24098 SDValue Zero = DAG.getConstant(0, dl, WideVT);
24099 V = DAG.getSelect(dl, WideVT, In, NegOne, Zero);
24100 }
24101
24102 // Truncate if we had to extend i16/i8 above.
24103 if (VT != ExtVT) {
24104 WideVT = MVT::getVectorVT(VTElt, NumElts);
24105 V = DAG.getNode(ISD::TRUNCATE, dl, WideVT, V);
24106 }
24107
24108 // Extract back to 128/256-bit if we widened.
24109 if (WideVT != VT)
24110 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, V,
24111 DAG.getIntPtrConstant(0, dl));
24112
24113 return V;
24114}
24115
24116static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
24117 SelectionDAG &DAG) {
24118 SDValue In = Op->getOperand(0);
24119 MVT InVT = In.getSimpleValueType();
24120
24121 if (InVT.getVectorElementType() == MVT::i1)
24122 return LowerSIGN_EXTEND_Mask(Op, Subtarget, DAG);
24123
24124 assert(Subtarget.hasAVX() && "Expected AVX support")(static_cast <bool> (Subtarget.hasAVX() && "Expected AVX support"
) ? void (0) : __assert_fail ("Subtarget.hasAVX() && \"Expected AVX support\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24124, __extension__ __PRETTY_FUNCTION__))
;
24125 return LowerAVXExtend(Op, DAG, Subtarget);
24126}
24127
24128// Lowering for SIGN_EXTEND_VECTOR_INREG and ZERO_EXTEND_VECTOR_INREG.
24129// For sign extend this needs to handle all vector sizes and SSE4.1 and
24130// non-SSE4.1 targets. For zero extend this should only handle inputs of
24131// MVT::v64i8 when BWI is not supported, but AVX512 is.
24132static SDValue LowerEXTEND_VECTOR_INREG(SDValue Op,
24133 const X86Subtarget &Subtarget,
24134 SelectionDAG &DAG) {
24135 SDValue In = Op->getOperand(0);
24136 MVT VT = Op->getSimpleValueType(0);
24137 MVT InVT = In.getSimpleValueType();
24138
24139 MVT SVT = VT.getVectorElementType();
24140 MVT InSVT = InVT.getVectorElementType();
24141 assert(SVT.getFixedSizeInBits() > InSVT.getFixedSizeInBits())(static_cast <bool> (SVT.getFixedSizeInBits() > InSVT
.getFixedSizeInBits()) ? void (0) : __assert_fail ("SVT.getFixedSizeInBits() > InSVT.getFixedSizeInBits()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24141, __extension__ __PRETTY_FUNCTION__))
;
24142
24143 if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16)
24144 return SDValue();
24145 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
24146 return SDValue();
24147 if (!(VT.is128BitVector() && Subtarget.hasSSE2()) &&
24148 !(VT.is256BitVector() && Subtarget.hasAVX()) &&
24149 !(VT.is512BitVector() && Subtarget.hasAVX512()))
24150 return SDValue();
24151
24152 SDLoc dl(Op);
24153 unsigned Opc = Op.getOpcode();
24154 unsigned NumElts = VT.getVectorNumElements();
24155
24156 // For 256-bit vectors, we only need the lower (128-bit) half of the input.
24157 // For 512-bit vectors, we need 128-bits or 256-bits.
24158 if (InVT.getSizeInBits() > 128) {
24159 // Input needs to be at least the same number of elements as output, and
24160 // at least 128-bits.
24161 int InSize = InSVT.getSizeInBits() * NumElts;
24162 In = extractSubVector(In, 0, DAG, dl, std::max(InSize, 128));
24163 InVT = In.getSimpleValueType();
24164 }
24165
24166 // SSE41 targets can use the pmov[sz]x* instructions directly for 128-bit results,
24167 // so are legal and shouldn't occur here. AVX2/AVX512 pmovsx* instructions still
24168 // need to be handled here for 256/512-bit results.
24169 if (Subtarget.hasInt256()) {
24170 assert(VT.getSizeInBits() > 128 && "Unexpected 128-bit vector extension")(static_cast <bool> (VT.getSizeInBits() > 128 &&
"Unexpected 128-bit vector extension") ? void (0) : __assert_fail
("VT.getSizeInBits() > 128 && \"Unexpected 128-bit vector extension\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24170, __extension__ __PRETTY_FUNCTION__))
;
24171
24172 if (InVT.getVectorNumElements() != NumElts)
24173 return DAG.getNode(Op.getOpcode(), dl, VT, In);
24174
24175 // FIXME: Apparently we create inreg operations that could be regular
24176 // extends.
24177 unsigned ExtOpc =
24178 Opc == ISD::SIGN_EXTEND_VECTOR_INREG ? ISD::SIGN_EXTEND
24179 : ISD::ZERO_EXTEND;
24180 return DAG.getNode(ExtOpc, dl, VT, In);
24181 }
24182
24183 // pre-AVX2 256-bit extensions need to be split into 128-bit instructions.
24184 if (Subtarget.hasAVX()) {
24185 assert(VT.is256BitVector() && "256-bit vector expected")(static_cast <bool> (VT.is256BitVector() && "256-bit vector expected"
) ? void (0) : __assert_fail ("VT.is256BitVector() && \"256-bit vector expected\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24185, __extension__ __PRETTY_FUNCTION__))
;
24186 MVT HalfVT = VT.getHalfNumVectorElementsVT();
24187 int HalfNumElts = HalfVT.getVectorNumElements();
24188
24189 unsigned NumSrcElts = InVT.getVectorNumElements();
24190 SmallVector<int, 16> HiMask(NumSrcElts, SM_SentinelUndef);
24191 for (int i = 0; i != HalfNumElts; ++i)
24192 HiMask[i] = HalfNumElts + i;
24193
24194 SDValue Lo = DAG.getNode(Opc, dl, HalfVT, In);
24195 SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, DAG.getUNDEF(InVT), HiMask);
24196 Hi = DAG.getNode(Opc, dl, HalfVT, Hi);
24197 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
24198 }
24199
24200 // We should only get here for sign extend.
24201 assert(Opc == ISD::SIGN_EXTEND_VECTOR_INREG && "Unexpected opcode!")(static_cast <bool> (Opc == ISD::SIGN_EXTEND_VECTOR_INREG
&& "Unexpected opcode!") ? void (0) : __assert_fail (
"Opc == ISD::SIGN_EXTEND_VECTOR_INREG && \"Unexpected opcode!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24201, __extension__ __PRETTY_FUNCTION__))
;
24202 assert(VT.is128BitVector() && InVT.is128BitVector() && "Unexpected VTs")(static_cast <bool> (VT.is128BitVector() && InVT
.is128BitVector() && "Unexpected VTs") ? void (0) : __assert_fail
("VT.is128BitVector() && InVT.is128BitVector() && \"Unexpected VTs\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24202, __extension__ __PRETTY_FUNCTION__))
;
24203
24204 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
24205 SDValue Curr = In;
24206 SDValue SignExt = Curr;
24207
24208 // As SRAI is only available on i16/i32 types, we expand only up to i32
24209 // and handle i64 separately.
24210 if (InVT != MVT::v4i32) {
24211 MVT DestVT = VT == MVT::v2i64 ? MVT::v4i32 : VT;
24212
24213 unsigned DestWidth = DestVT.getScalarSizeInBits();
24214 unsigned Scale = DestWidth / InSVT.getSizeInBits();
24215
24216 unsigned InNumElts = InVT.getVectorNumElements();
24217 unsigned DestElts = DestVT.getVectorNumElements();
24218
24219 // Build a shuffle mask that takes each input element and places it in the
24220 // MSBs of the new element size.
24221 SmallVector<int, 16> Mask(InNumElts, SM_SentinelUndef);
24222 for (unsigned i = 0; i != DestElts; ++i)
24223 Mask[i * Scale + (Scale - 1)] = i;
24224
24225 Curr = DAG.getVectorShuffle(InVT, dl, In, In, Mask);
24226 Curr = DAG.getBitcast(DestVT, Curr);
24227
24228 unsigned SignExtShift = DestWidth - InSVT.getSizeInBits();
24229 SignExt = DAG.getNode(X86ISD::VSRAI, dl, DestVT, Curr,
24230 DAG.getTargetConstant(SignExtShift, dl, MVT::i8));
24231 }
24232
24233 if (VT == MVT::v2i64) {
24234 assert(Curr.getValueType() == MVT::v4i32 && "Unexpected input VT")(static_cast <bool> (Curr.getValueType() == MVT::v4i32 &&
"Unexpected input VT") ? void (0) : __assert_fail ("Curr.getValueType() == MVT::v4i32 && \"Unexpected input VT\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24234, __extension__ __PRETTY_FUNCTION__))
;
24235 SDValue Zero = DAG.getConstant(0, dl, MVT::v4i32);
24236 SDValue Sign = DAG.getSetCC(dl, MVT::v4i32, Zero, Curr, ISD::SETGT);
24237 SignExt = DAG.getVectorShuffle(MVT::v4i32, dl, SignExt, Sign, {0, 4, 1, 5});
24238 SignExt = DAG.getBitcast(VT, SignExt);
24239 }
24240
24241 return SignExt;
24242}
24243
24244static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
24245 SelectionDAG &DAG) {
24246 MVT VT = Op->getSimpleValueType(0);
24247 SDValue In = Op->getOperand(0);
24248 MVT InVT = In.getSimpleValueType();
24249 SDLoc dl(Op);
24250
24251 if (InVT.getVectorElementType() == MVT::i1)
24252 return LowerSIGN_EXTEND_Mask(Op, Subtarget, DAG);
24253
24254 assert(VT.isVector() && InVT.isVector() && "Expected vector type")(static_cast <bool> (VT.isVector() && InVT.isVector
() && "Expected vector type") ? void (0) : __assert_fail
("VT.isVector() && InVT.isVector() && \"Expected vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24254, __extension__ __PRETTY_FUNCTION__))
;
24255 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&(static_cast <bool> (VT.getVectorNumElements() == InVT.
getVectorNumElements() && "Expected same number of elements"
) ? void (0) : __assert_fail ("VT.getVectorNumElements() == InVT.getVectorNumElements() && \"Expected same number of elements\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24256, __extension__ __PRETTY_FUNCTION__))
24256 "Expected same number of elements")(static_cast <bool> (VT.getVectorNumElements() == InVT.
getVectorNumElements() && "Expected same number of elements"
) ? void (0) : __assert_fail ("VT.getVectorNumElements() == InVT.getVectorNumElements() && \"Expected same number of elements\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24256, __extension__ __PRETTY_FUNCTION__))
;
24257 assert((VT.getVectorElementType() == MVT::i16 ||(static_cast <bool> ((VT.getVectorElementType() == MVT::
i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType
() == MVT::i64) && "Unexpected element type") ? void (
0) : __assert_fail ("(VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType() == MVT::i64) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24260, __extension__ __PRETTY_FUNCTION__))
24258 VT.getVectorElementType() == MVT::i32 ||(static_cast <bool> ((VT.getVectorElementType() == MVT::
i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType
() == MVT::i64) && "Unexpected element type") ? void (
0) : __assert_fail ("(VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType() == MVT::i64) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24260, __extension__ __PRETTY_FUNCTION__))
24259 VT.getVectorElementType() == MVT::i64) &&(static_cast <bool> ((VT.getVectorElementType() == MVT::
i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType
() == MVT::i64) && "Unexpected element type") ? void (
0) : __assert_fail ("(VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType() == MVT::i64) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24260, __extension__ __PRETTY_FUNCTION__))
24260 "Unexpected element type")(static_cast <bool> ((VT.getVectorElementType() == MVT::
i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType
() == MVT::i64) && "Unexpected element type") ? void (
0) : __assert_fail ("(VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType() == MVT::i64) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24260, __extension__ __PRETTY_FUNCTION__))
;
24261 assert((InVT.getVectorElementType() == MVT::i8 ||(static_cast <bool> ((InVT.getVectorElementType() == MVT
::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType
() == MVT::i32) && "Unexpected element type") ? void (
0) : __assert_fail ("(InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24264, __extension__ __PRETTY_FUNCTION__))
24262 InVT.getVectorElementType() == MVT::i16 ||(static_cast <bool> ((InVT.getVectorElementType() == MVT
::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType
() == MVT::i32) && "Unexpected element type") ? void (
0) : __assert_fail ("(InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24264, __extension__ __PRETTY_FUNCTION__))
24263 InVT.getVectorElementType() == MVT::i32) &&(static_cast <bool> ((InVT.getVectorElementType() == MVT
::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType
() == MVT::i32) && "Unexpected element type") ? void (
0) : __assert_fail ("(InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24264, __extension__ __PRETTY_FUNCTION__))
24264 "Unexpected element type")(static_cast <bool> ((InVT.getVectorElementType() == MVT
::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType
() == MVT::i32) && "Unexpected element type") ? void (
0) : __assert_fail ("(InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24264, __extension__ __PRETTY_FUNCTION__))
;
24265
24266 if (VT == MVT::v32i16 && !Subtarget.hasBWI()) {
24267 assert(InVT == MVT::v32i8 && "Unexpected VT!")(static_cast <bool> (InVT == MVT::v32i8 && "Unexpected VT!"
) ? void (0) : __assert_fail ("InVT == MVT::v32i8 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24267, __extension__ __PRETTY_FUNCTION__))
;
24268 return splitVectorIntUnary(Op, DAG);
24269 }
24270
24271 if (Subtarget.hasInt256())
24272 return Op;
24273
24274 // Optimize vectors in AVX mode
24275 // Sign extend v8i16 to v8i32 and
24276 // v4i32 to v4i64
24277 //
24278 // Divide input vector into two parts
24279 // for v4i32 the high shuffle mask will be {2, 3, -1, -1}
24280 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
24281 // concat the vectors to original VT
24282 MVT HalfVT = VT.getHalfNumVectorElementsVT();
24283 SDValue OpLo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, HalfVT, In);
24284
24285 unsigned NumElems = InVT.getVectorNumElements();
24286 SmallVector<int,8> ShufMask(NumElems, -1);
24287 for (unsigned i = 0; i != NumElems/2; ++i)
24288 ShufMask[i] = i + NumElems/2;
24289
24290 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
24291 OpHi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, HalfVT, OpHi);
24292
24293 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
24294}
24295
24296/// Change a vector store into a pair of half-size vector stores.
24297static SDValue splitVectorStore(StoreSDNode *Store, SelectionDAG &DAG) {
24298 SDValue StoredVal = Store->getValue();
24299 assert((StoredVal.getValueType().is256BitVector() ||(static_cast <bool> ((StoredVal.getValueType().is256BitVector
() || StoredVal.getValueType().is512BitVector()) && "Expecting 256/512-bit op"
) ? void (0) : __assert_fail ("(StoredVal.getValueType().is256BitVector() || StoredVal.getValueType().is512BitVector()) && \"Expecting 256/512-bit op\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24301, __extension__ __PRETTY_FUNCTION__))
24300 StoredVal.getValueType().is512BitVector()) &&(static_cast <bool> ((StoredVal.getValueType().is256BitVector
() || StoredVal.getValueType().is512BitVector()) && "Expecting 256/512-bit op"
) ? void (0) : __assert_fail ("(StoredVal.getValueType().is256BitVector() || StoredVal.getValueType().is512BitVector()) && \"Expecting 256/512-bit op\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24301, __extension__ __PRETTY_FUNCTION__))
24301 "Expecting 256/512-bit op")(static_cast <bool> ((StoredVal.getValueType().is256BitVector
() || StoredVal.getValueType().is512BitVector()) && "Expecting 256/512-bit op"
) ? void (0) : __assert_fail ("(StoredVal.getValueType().is256BitVector() || StoredVal.getValueType().is512BitVector()) && \"Expecting 256/512-bit op\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24301, __extension__ __PRETTY_FUNCTION__))
;
24302
24303 // Splitting volatile memory ops is not allowed unless the operation was not
24304 // legal to begin with. Assume the input store is legal (this transform is
24305 // only used for targets with AVX). Note: It is possible that we have an
24306 // illegal type like v2i128, and so we could allow splitting a volatile store
24307 // in that case if that is important.
24308 if (!Store->isSimple())
24309 return SDValue();
24310
24311 SDLoc DL(Store);
24312 SDValue Value0, Value1;
24313 std::tie(Value0, Value1) = splitVector(StoredVal, DAG, DL);
24314 unsigned HalfOffset = Value0.getValueType().getStoreSize();
24315 SDValue Ptr0 = Store->getBasePtr();
24316 SDValue Ptr1 =
24317 DAG.getMemBasePlusOffset(Ptr0, TypeSize::Fixed(HalfOffset), DL);
24318 SDValue Ch0 =
24319 DAG.getStore(Store->getChain(), DL, Value0, Ptr0, Store->getPointerInfo(),
24320 Store->getOriginalAlign(),
24321 Store->getMemOperand()->getFlags());
24322 SDValue Ch1 = DAG.getStore(Store->getChain(), DL, Value1, Ptr1,
24323 Store->getPointerInfo().getWithOffset(HalfOffset),
24324 Store->getOriginalAlign(),
24325 Store->getMemOperand()->getFlags());
24326 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Ch0, Ch1);
24327}
24328
24329/// Scalarize a vector store, bitcasting to TargetVT to determine the scalar
24330/// type.
24331static SDValue scalarizeVectorStore(StoreSDNode *Store, MVT StoreVT,
24332 SelectionDAG &DAG) {
24333 SDValue StoredVal = Store->getValue();
24334 assert(StoreVT.is128BitVector() &&(static_cast <bool> (StoreVT.is128BitVector() &&
StoredVal.getValueType().is128BitVector() && "Expecting 128-bit op"
) ? void (0) : __assert_fail ("StoreVT.is128BitVector() && StoredVal.getValueType().is128BitVector() && \"Expecting 128-bit op\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24335, __extension__ __PRETTY_FUNCTION__))
24335 StoredVal.getValueType().is128BitVector() && "Expecting 128-bit op")(static_cast <bool> (StoreVT.is128BitVector() &&
StoredVal.getValueType().is128BitVector() && "Expecting 128-bit op"
) ? void (0) : __assert_fail ("StoreVT.is128BitVector() && StoredVal.getValueType().is128BitVector() && \"Expecting 128-bit op\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24335, __extension__ __PRETTY_FUNCTION__))
;
24336 StoredVal = DAG.getBitcast(StoreVT, StoredVal);
24337
24338 // Splitting volatile memory ops is not allowed unless the operation was not
24339 // legal to begin with. We are assuming the input op is legal (this transform
24340 // is only used for targets with AVX).
24341 if (!Store->isSimple())
24342 return SDValue();
24343
24344 MVT StoreSVT = StoreVT.getScalarType();
24345 unsigned NumElems = StoreVT.getVectorNumElements();
24346 unsigned ScalarSize = StoreSVT.getStoreSize();
24347
24348 SDLoc DL(Store);
24349 SmallVector<SDValue, 4> Stores;
24350 for (unsigned i = 0; i != NumElems; ++i) {
24351 unsigned Offset = i * ScalarSize;
24352 SDValue Ptr = DAG.getMemBasePlusOffset(Store->getBasePtr(),
24353 TypeSize::Fixed(Offset), DL);
24354 SDValue Scl = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreSVT, StoredVal,
24355 DAG.getIntPtrConstant(i, DL));
24356 SDValue Ch = DAG.getStore(Store->getChain(), DL, Scl, Ptr,
24357 Store->getPointerInfo().getWithOffset(Offset),
24358 Store->getOriginalAlign(),
24359 Store->getMemOperand()->getFlags());
24360 Stores.push_back(Ch);
24361 }
24362 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
24363}
24364
24365static SDValue LowerStore(SDValue Op, const X86Subtarget &Subtarget,
24366 SelectionDAG &DAG) {
24367 StoreSDNode *St = cast<StoreSDNode>(Op.getNode());
24368 SDLoc dl(St);
24369 SDValue StoredVal = St->getValue();
24370
24371 // Without AVX512DQ, we need to use a scalar type for v2i1/v4i1/v8i1 stores.
24372 if (StoredVal.getValueType().isVector() &&
24373 StoredVal.getValueType().getVectorElementType() == MVT::i1) {
24374 unsigned NumElts = StoredVal.getValueType().getVectorNumElements();
24375 assert(NumElts <= 8 && "Unexpected VT")(static_cast <bool> (NumElts <= 8 && "Unexpected VT"
) ? void (0) : __assert_fail ("NumElts <= 8 && \"Unexpected VT\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24375, __extension__ __PRETTY_FUNCTION__))
;
24376 assert(!St->isTruncatingStore() && "Expected non-truncating store")(static_cast <bool> (!St->isTruncatingStore() &&
"Expected non-truncating store") ? void (0) : __assert_fail (
"!St->isTruncatingStore() && \"Expected non-truncating store\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24376, __extension__ __PRETTY_FUNCTION__))
;
24377 assert(Subtarget.hasAVX512() && !Subtarget.hasDQI() &&(static_cast <bool> (Subtarget.hasAVX512() && !
Subtarget.hasDQI() && "Expected AVX512F without AVX512DQI"
) ? void (0) : __assert_fail ("Subtarget.hasAVX512() && !Subtarget.hasDQI() && \"Expected AVX512F without AVX512DQI\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24378, __extension__ __PRETTY_FUNCTION__))
24378 "Expected AVX512F without AVX512DQI")(static_cast <bool> (Subtarget.hasAVX512() && !
Subtarget.hasDQI() && "Expected AVX512F without AVX512DQI"
) ? void (0) : __assert_fail ("Subtarget.hasAVX512() && !Subtarget.hasDQI() && \"Expected AVX512F without AVX512DQI\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24378, __extension__ __PRETTY_FUNCTION__))
;
24379
24380 // We must pad with zeros to ensure we store zeroes to any unused bits.
24381 StoredVal = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i1,
24382 DAG.getUNDEF(MVT::v16i1), StoredVal,
24383 DAG.getIntPtrConstant(0, dl));
24384 StoredVal = DAG.getBitcast(MVT::i16, StoredVal);
24385 StoredVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, StoredVal);
24386 // Make sure we store zeros in the extra bits.
24387 if (NumElts < 8)
24388 StoredVal = DAG.getZeroExtendInReg(
24389 StoredVal, dl, EVT::getIntegerVT(*DAG.getContext(), NumElts));
24390
24391 return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
24392 St->getPointerInfo(), St->getOriginalAlign(),
24393 St->getMemOperand()->getFlags());
24394 }
24395
24396 if (St->isTruncatingStore())
24397 return SDValue();
24398
24399 // If this is a 256-bit store of concatenated ops, we are better off splitting
24400 // that store into two 128-bit stores. This avoids spurious use of 256-bit ops
24401 // and each half can execute independently. Some cores would split the op into
24402 // halves anyway, so the concat (vinsertf128) is purely an extra op.
24403 MVT StoreVT = StoredVal.getSimpleValueType();
24404 if (StoreVT.is256BitVector() ||
24405 ((StoreVT == MVT::v32i16 || StoreVT == MVT::v64i8) &&
24406 !Subtarget.hasBWI())) {
24407 SmallVector<SDValue, 4> CatOps;
24408 if (StoredVal.hasOneUse() && collectConcatOps(StoredVal.getNode(), CatOps))
24409 return splitVectorStore(St, DAG);
24410 return SDValue();
24411 }
24412
24413 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24414 assert(StoreVT.isVector() && StoreVT.getSizeInBits() == 64 &&(static_cast <bool> (StoreVT.isVector() && StoreVT
.getSizeInBits() == 64 && "Unexpected VT") ? void (0)
: __assert_fail ("StoreVT.isVector() && StoreVT.getSizeInBits() == 64 && \"Unexpected VT\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24415, __extension__ __PRETTY_FUNCTION__))
24415 "Unexpected VT")(static_cast <bool> (StoreVT.isVector() && StoreVT
.getSizeInBits() == 64 && "Unexpected VT") ? void (0)
: __assert_fail ("StoreVT.isVector() && StoreVT.getSizeInBits() == 64 && \"Unexpected VT\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24415, __extension__ __PRETTY_FUNCTION__))
;
24416 assert(TLI.getTypeAction(*DAG.getContext(), StoreVT) ==(static_cast <bool> (TLI.getTypeAction(*DAG.getContext(
), StoreVT) == TargetLowering::TypeWidenVector && "Unexpected type action!"
) ? void (0) : __assert_fail ("TLI.getTypeAction(*DAG.getContext(), StoreVT) == TargetLowering::TypeWidenVector && \"Unexpected type action!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24417, __extension__ __PRETTY_FUNCTION__))
24417 TargetLowering::TypeWidenVector && "Unexpected type action!")(static_cast <bool> (TLI.getTypeAction(*DAG.getContext(
), StoreVT) == TargetLowering::TypeWidenVector && "Unexpected type action!"
) ? void (0) : __assert_fail ("TLI.getTypeAction(*DAG.getContext(), StoreVT) == TargetLowering::TypeWidenVector && \"Unexpected type action!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24417, __extension__ __PRETTY_FUNCTION__))
;
24418
24419 EVT WideVT = TLI.getTypeToTransformTo(*DAG.getContext(), StoreVT);
24420 StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, StoredVal,
24421 DAG.getUNDEF(StoreVT));
24422
24423 if (Subtarget.hasSSE2()) {
24424 // Widen the vector, cast to a v2x64 type, extract the single 64-bit element
24425 // and store it.
24426 MVT StVT = Subtarget.is64Bit() && StoreVT.isInteger() ? MVT::i64 : MVT::f64;
24427 MVT CastVT = MVT::getVectorVT(StVT, 2);
24428 StoredVal = DAG.getBitcast(CastVT, StoredVal);
24429 StoredVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, StVT, StoredVal,
24430 DAG.getIntPtrConstant(0, dl));
24431
24432 return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
24433 St->getPointerInfo(), St->getOriginalAlign(),
24434 St->getMemOperand()->getFlags());
24435 }
24436 assert(Subtarget.hasSSE1() && "Expected SSE")(static_cast <bool> (Subtarget.hasSSE1() && "Expected SSE"
) ? void (0) : __assert_fail ("Subtarget.hasSSE1() && \"Expected SSE\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24436, __extension__ __PRETTY_FUNCTION__))
;
24437 SDVTList Tys = DAG.getVTList(MVT::Other);
24438 SDValue Ops[] = {St->getChain(), StoredVal, St->getBasePtr()};
24439 return DAG.getMemIntrinsicNode(X86ISD::VEXTRACT_STORE, dl, Tys, Ops, MVT::i64,
24440 St->getMemOperand());
24441}
24442
24443// Lower vector extended loads using a shuffle. If SSSE3 is not available we
24444// may emit an illegal shuffle but the expansion is still better than scalar
24445// code. We generate sext/sext_invec for SEXTLOADs if it's available, otherwise
24446// we'll emit a shuffle and a arithmetic shift.
24447// FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
24448// TODO: It is possible to support ZExt by zeroing the undef values during
24449// the shuffle phase or after the shuffle.
24450static SDValue LowerLoad(SDValue Op, const X86Subtarget &Subtarget,
24451 SelectionDAG &DAG) {
24452 MVT RegVT = Op.getSimpleValueType();
24453 assert(RegVT.isVector() && "We only custom lower vector loads.")(static_cast <bool> (RegVT.isVector() && "We only custom lower vector loads."
) ? void (0) : __assert_fail ("RegVT.isVector() && \"We only custom lower vector loads.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24453, __extension__ __PRETTY_FUNCTION__))
;
24454 assert(RegVT.isInteger() &&(static_cast <bool> (RegVT.isInteger() && "We only custom lower integer vector loads."
) ? void (0) : __assert_fail ("RegVT.isInteger() && \"We only custom lower integer vector loads.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24455, __extension__ __PRETTY_FUNCTION__))
24455 "We only custom lower integer vector loads.")(static_cast <bool> (RegVT.isInteger() && "We only custom lower integer vector loads."
) ? void (0) : __assert_fail ("RegVT.isInteger() && \"We only custom lower integer vector loads.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24455, __extension__ __PRETTY_FUNCTION__))
;
24456
24457 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
24458 SDLoc dl(Ld);
24459
24460 // Without AVX512DQ, we need to use a scalar type for v2i1/v4i1/v8i1 loads.
24461 if (RegVT.getVectorElementType() == MVT::i1) {
24462 assert(EVT(RegVT) == Ld->getMemoryVT() && "Expected non-extending load")(static_cast <bool> (EVT(RegVT) == Ld->getMemoryVT()
&& "Expected non-extending load") ? void (0) : __assert_fail
("EVT(RegVT) == Ld->getMemoryVT() && \"Expected non-extending load\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24462, __extension__ __PRETTY_FUNCTION__))
;
24463 assert(RegVT.getVectorNumElements() <= 8 && "Unexpected VT")(static_cast <bool> (RegVT.getVectorNumElements() <=
8 && "Unexpected VT") ? void (0) : __assert_fail ("RegVT.getVectorNumElements() <= 8 && \"Unexpected VT\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24463, __extension__ __PRETTY_FUNCTION__))
;
24464 assert(Subtarget.hasAVX512() && !Subtarget.hasDQI() &&(static_cast <bool> (Subtarget.hasAVX512() && !
Subtarget.hasDQI() && "Expected AVX512F without AVX512DQI"
) ? void (0) : __assert_fail ("Subtarget.hasAVX512() && !Subtarget.hasDQI() && \"Expected AVX512F without AVX512DQI\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24465, __extension__ __PRETTY_FUNCTION__))
24465 "Expected AVX512F without AVX512DQI")(static_cast <bool> (Subtarget.hasAVX512() && !
Subtarget.hasDQI() && "Expected AVX512F without AVX512DQI"
) ? void (0) : __assert_fail ("Subtarget.hasAVX512() && !Subtarget.hasDQI() && \"Expected AVX512F without AVX512DQI\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24465, __extension__ __PRETTY_FUNCTION__))
;
24466
24467 SDValue NewLd = DAG.getLoad(MVT::i8, dl, Ld->getChain(), Ld->getBasePtr(),
24468 Ld->getPointerInfo(), Ld->getOriginalAlign(),
24469 Ld->getMemOperand()->getFlags());
24470
24471 // Replace chain users with the new chain.
24472 assert(NewLd->getNumValues() == 2 && "Loads must carry a chain!")(static_cast <bool> (NewLd->getNumValues() == 2 &&
"Loads must carry a chain!") ? void (0) : __assert_fail ("NewLd->getNumValues() == 2 && \"Loads must carry a chain!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24472, __extension__ __PRETTY_FUNCTION__))
;
24473
24474 SDValue Val = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i16, NewLd);
24475 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, RegVT,
24476 DAG.getBitcast(MVT::v16i1, Val),
24477 DAG.getIntPtrConstant(0, dl));
24478 return DAG.getMergeValues({Val, NewLd.getValue(1)}, dl);
24479 }
24480
24481 return SDValue();
24482}
24483
24484/// Return true if node is an ISD::AND or ISD::OR of two X86ISD::SETCC nodes
24485/// each of which has no other use apart from the AND / OR.
24486static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
24487 Opc = Op.getOpcode();
24488 if (Opc != ISD::OR && Opc != ISD::AND)
24489 return false;
24490 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
24491 Op.getOperand(0).hasOneUse() &&
24492 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
24493 Op.getOperand(1).hasOneUse());
24494}
24495
24496SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
24497 SDValue Chain = Op.getOperand(0);
24498 SDValue Cond = Op.getOperand(1);
24499 SDValue Dest = Op.getOperand(2);
24500 SDLoc dl(Op);
24501
24502 if (Cond.getOpcode() == ISD::SETCC &&
24503 Cond.getOperand(0).getValueType() != MVT::f128) {
24504 SDValue LHS = Cond.getOperand(0);
24505 SDValue RHS = Cond.getOperand(1);
24506 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24507
24508 // Special case for
24509 // setcc([su]{add,sub,mul}o == 0)
24510 // setcc([su]{add,sub,mul}o != 1)
24511 if (ISD::isOverflowIntrOpRes(LHS) &&
24512 (CC == ISD::SETEQ || CC == ISD::SETNE) &&
24513 (isNullConstant(RHS) || isOneConstant(RHS))) {
24514 SDValue Value, Overflow;
24515 X86::CondCode X86Cond;
24516 std::tie(Value, Overflow) = getX86XALUOOp(X86Cond, LHS.getValue(0), DAG);
24517
24518 if ((CC == ISD::SETEQ) == isNullConstant(RHS))
24519 X86Cond = X86::GetOppositeBranchCondition(X86Cond);
24520
24521 SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
24522 return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
24523 Overflow);
24524 }
24525
24526 if (LHS.getSimpleValueType().isInteger()) {
24527 SDValue CCVal;
24528 SDValue EFLAGS = emitFlagsForSetcc(LHS, RHS, CC, SDLoc(Cond), DAG, CCVal);
24529 return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
24530 EFLAGS);
24531 }
24532
24533 if (CC == ISD::SETOEQ) {
24534 // For FCMP_OEQ, we can emit
24535 // two branches instead of an explicit AND instruction with a
24536 // separate test. However, we only do this if this block doesn't
24537 // have a fall-through edge, because this requires an explicit
24538 // jmp when the condition is false.
24539 if (Op.getNode()->hasOneUse()) {
24540 SDNode *User = *Op.getNode()->use_begin();
24541 // Look for an unconditional branch following this conditional branch.
24542 // We need this because we need to reverse the successors in order
24543 // to implement FCMP_OEQ.
24544 if (User->getOpcode() == ISD::BR) {
24545 SDValue FalseBB = User->getOperand(1);
24546 SDNode *NewBR =
24547 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
24548 assert(NewBR == User)(static_cast <bool> (NewBR == User) ? void (0) : __assert_fail
("NewBR == User", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24548, __extension__ __PRETTY_FUNCTION__))
;
24549 (void)NewBR;
24550 Dest = FalseBB;
24551
24552 SDValue Cmp =
24553 DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
24554 SDValue CCVal = DAG.getTargetConstant(X86::COND_NE, dl, MVT::i8);
24555 Chain = DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest,
24556 CCVal, Cmp);
24557 CCVal = DAG.getTargetConstant(X86::COND_P, dl, MVT::i8);
24558 return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
24559 Cmp);
24560 }
24561 }
24562 } else if (CC == ISD::SETUNE) {
24563 // For FCMP_UNE, we can emit
24564 // two branches instead of an explicit OR instruction with a
24565 // separate test.
24566 SDValue Cmp = DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
24567 SDValue CCVal = DAG.getTargetConstant(X86::COND_NE, dl, MVT::i8);
24568 Chain =
24569 DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, Cmp);
24570 CCVal = DAG.getTargetConstant(X86::COND_P, dl, MVT::i8);
24571 return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
24572 Cmp);
24573 } else {
24574 X86::CondCode X86Cond =
24575 TranslateX86CC(CC, dl, /*IsFP*/ true, LHS, RHS, DAG);
24576 SDValue Cmp = DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
24577 SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
24578 return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
24579 Cmp);
24580 }
24581 }
24582
24583 if (ISD::isOverflowIntrOpRes(Cond)) {
24584 SDValue Value, Overflow;
24585 X86::CondCode X86Cond;
24586 std::tie(Value, Overflow) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
24587
24588 SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
24589 return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
24590 Overflow);
24591 }
24592
24593 // Look past the truncate if the high bits are known zero.
24594 if (isTruncWithZeroHighBitsInput(Cond, DAG))
24595 Cond = Cond.getOperand(0);
24596
24597 EVT CondVT = Cond.getValueType();
24598
24599 // Add an AND with 1 if we don't already have one.
24600 if (!(Cond.getOpcode() == ISD::AND && isOneConstant(Cond.getOperand(1))))
24601 Cond =
24602 DAG.getNode(ISD::AND, dl, CondVT, Cond, DAG.getConstant(1, dl, CondVT));
24603
24604 SDValue LHS = Cond;
24605 SDValue RHS = DAG.getConstant(0, dl, CondVT);
24606
24607 SDValue CCVal;
24608 SDValue EFLAGS = emitFlagsForSetcc(LHS, RHS, ISD::SETNE, dl, DAG, CCVal);
24609 return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
24610 EFLAGS);
24611}
24612
24613// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
24614// Calls to _alloca are needed to probe the stack when allocating more than 4k
24615// bytes in one go. Touching the stack at 4K increments is necessary to ensure
24616// that the guard pages used by the OS virtual memory manager are allocated in
24617// correct sequence.
24618SDValue
24619X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
24620 SelectionDAG &DAG) const {
24621 MachineFunction &MF = DAG.getMachineFunction();
24622 bool SplitStack = MF.shouldSplitStack();
24623 bool EmitStackProbeCall = hasStackProbeSymbol(MF);
24624 bool Lower = (Subtarget.isOSWindows() && !Subtarget.isTargetMachO()) ||
24625 SplitStack || EmitStackProbeCall;
24626 SDLoc dl(Op);
24627
24628 // Get the inputs.
24629 SDNode *Node = Op.getNode();
24630 SDValue Chain = Op.getOperand(0);
24631 SDValue Size = Op.getOperand(1);
24632 MaybeAlign Alignment(Op.getConstantOperandVal(2));
24633 EVT VT = Node->getValueType(0);
24634
24635 // Chain the dynamic stack allocation so that it doesn't modify the stack
24636 // pointer when other instructions are using the stack.
24637 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
24638
24639 bool Is64Bit = Subtarget.is64Bit();
24640 MVT SPTy = getPointerTy(DAG.getDataLayout());
24641
24642 SDValue Result;
24643 if (!Lower) {
24644 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24645 Register SPReg = TLI.getStackPointerRegisterToSaveRestore();
24646 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"(static_cast <bool> (SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
" not tell us which reg is the stack pointer!") ? void (0) :
__assert_fail ("SPReg && \"Target cannot require DYNAMIC_STACKALLOC expansion and\" \" not tell us which reg is the stack pointer!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24647, __extension__ __PRETTY_FUNCTION__))
24647 " not tell us which reg is the stack pointer!")(static_cast <bool> (SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
" not tell us which reg is the stack pointer!") ? void (0) :
__assert_fail ("SPReg && \"Target cannot require DYNAMIC_STACKALLOC expansion and\" \" not tell us which reg is the stack pointer!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24647, __extension__ __PRETTY_FUNCTION__))
;
24648
24649 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
24650 const Align StackAlign = TFI.getStackAlign();
24651 if (hasInlineStackProbe(MF)) {
24652 MachineRegisterInfo &MRI = MF.getRegInfo();
24653
24654 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
24655 Register Vreg = MRI.createVirtualRegister(AddrRegClass);
24656 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
24657 Result = DAG.getNode(X86ISD::PROBED_ALLOCA, dl, SPTy, Chain,
24658 DAG.getRegister(Vreg, SPTy));
24659 } else {
24660 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
24661 Chain = SP.getValue(1);
24662 Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
24663 }
24664 if (Alignment && *Alignment > StackAlign)
24665 Result =
24666 DAG.getNode(ISD::AND, dl, VT, Result,
24667 DAG.getConstant(~(Alignment->value() - 1ULL), dl, VT));
24668 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
24669 } else if (SplitStack) {
24670 MachineRegisterInfo &MRI = MF.getRegInfo();
24671
24672 if (Is64Bit) {
24673 // The 64 bit implementation of segmented stacks needs to clobber both r10
24674 // r11. This makes it impossible to use it along with nested parameters.
24675 const Function &F = MF.getFunction();
24676 for (const auto &A : F.args()) {
24677 if (A.hasNestAttr())
24678 report_fatal_error("Cannot use segmented stacks with functions that "
24679 "have nested arguments.");
24680 }
24681 }
24682
24683 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
24684 Register Vreg = MRI.createVirtualRegister(AddrRegClass);
24685 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
24686 Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
24687 DAG.getRegister(Vreg, SPTy));
24688 } else {
24689 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
24690 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Size);
24691 MF.getInfo<X86MachineFunctionInfo>()->setHasWinAlloca(true);
24692
24693 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
24694 Register SPReg = RegInfo->getStackRegister();
24695 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
24696 Chain = SP.getValue(1);
24697
24698 if (Alignment) {
24699 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
24700 DAG.getConstant(~(Alignment->value() - 1ULL), dl, VT));
24701 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
24702 }
24703
24704 Result = SP;
24705 }
24706
24707 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
24708 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
24709
24710 SDValue Ops[2] = {Result, Chain};
24711 return DAG.getMergeValues(Ops, dl);
24712}
24713
24714SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
24715 MachineFunction &MF = DAG.getMachineFunction();
24716 auto PtrVT = getPointerTy(MF.getDataLayout());
24717 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
24718
24719 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
24720 SDLoc DL(Op);
24721
24722 if (!Subtarget.is64Bit() ||
24723 Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv())) {
24724 // vastart just stores the address of the VarArgsFrameIndex slot into the
24725 // memory location argument.
24726 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
24727 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
24728 MachinePointerInfo(SV));
24729 }
24730
24731 // __va_list_tag:
24732 // gp_offset (0 - 6 * 8)
24733 // fp_offset (48 - 48 + 8 * 16)
24734 // overflow_arg_area (point to parameters coming in memory).
24735 // reg_save_area
24736 SmallVector<SDValue, 8> MemOps;
24737 SDValue FIN = Op.getOperand(1);
24738 // Store gp_offset
24739 SDValue Store = DAG.getStore(
24740 Op.getOperand(0), DL,
24741 DAG.getConstant(FuncInfo->getVarArgsGPOffset(), DL, MVT::i32), FIN,
24742 MachinePointerInfo(SV));
24743 MemOps.push_back(Store);
24744
24745 // Store fp_offset
24746 FIN = DAG.getMemBasePlusOffset(FIN, TypeSize::Fixed(4), DL);
24747 Store = DAG.getStore(
24748 Op.getOperand(0), DL,
24749 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL, MVT::i32), FIN,
24750 MachinePointerInfo(SV, 4));
24751 MemOps.push_back(Store);
24752
24753 // Store ptr to overflow_arg_area
24754 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
24755 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
24756 Store =
24757 DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, MachinePointerInfo(SV, 8));
24758 MemOps.push_back(Store);
24759
24760 // Store ptr to reg_save_area.
24761 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
24762 Subtarget.isTarget64BitLP64() ? 8 : 4, DL));
24763 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
24764 Store = DAG.getStore(
24765 Op.getOperand(0), DL, RSFIN, FIN,
24766 MachinePointerInfo(SV, Subtarget.isTarget64BitLP64() ? 16 : 12));
24767 MemOps.push_back(Store);
24768 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
24769}
24770
24771SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
24772 assert(Subtarget.is64Bit() &&(static_cast <bool> (Subtarget.is64Bit() && "LowerVAARG only handles 64-bit va_arg!"
) ? void (0) : __assert_fail ("Subtarget.is64Bit() && \"LowerVAARG only handles 64-bit va_arg!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24773, __extension__ __PRETTY_FUNCTION__))
24773 "LowerVAARG only handles 64-bit va_arg!")(static_cast <bool> (Subtarget.is64Bit() && "LowerVAARG only handles 64-bit va_arg!"
) ? void (0) : __assert_fail ("Subtarget.is64Bit() && \"LowerVAARG only handles 64-bit va_arg!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24773, __extension__ __PRETTY_FUNCTION__))
;
24774 assert(Op.getNumOperands() == 4)(static_cast <bool> (Op.getNumOperands() == 4) ? void (
0) : __assert_fail ("Op.getNumOperands() == 4", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24774, __extension__ __PRETTY_FUNCTION__))
;
24775
24776 MachineFunction &MF = DAG.getMachineFunction();
24777 if (Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()))
24778 // The Win64 ABI uses char* instead of a structure.
24779 return DAG.expandVAArg(Op.getNode());
24780
24781 SDValue Chain = Op.getOperand(0);
24782 SDValue SrcPtr = Op.getOperand(1);
24783 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
24784 unsigned Align = Op.getConstantOperandVal(3);
24785 SDLoc dl(Op);
24786
24787 EVT ArgVT = Op.getNode()->getValueType(0);
24788 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
24789 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
24790 uint8_t ArgMode;
24791
24792 // Decide which area this value should be read from.
24793 // TODO: Implement the AMD64 ABI in its entirety. This simple
24794 // selection mechanism works only for the basic types.
24795 assert(ArgVT != MVT::f80 && "va_arg for f80 not yet implemented")(static_cast <bool> (ArgVT != MVT::f80 && "va_arg for f80 not yet implemented"
) ? void (0) : __assert_fail ("ArgVT != MVT::f80 && \"va_arg for f80 not yet implemented\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24795, __extension__ __PRETTY_FUNCTION__))
;
24796 if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
24797 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
24798 } else {
24799 assert(ArgVT.isInteger() && ArgSize <= 32 /*bytes*/ &&(static_cast <bool> (ArgVT.isInteger() && ArgSize
<= 32 && "Unhandled argument type in LowerVAARG")
? void (0) : __assert_fail ("ArgVT.isInteger() && ArgSize <= 32 && \"Unhandled argument type in LowerVAARG\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24800, __extension__ __PRETTY_FUNCTION__))
24800 "Unhandled argument type in LowerVAARG")(static_cast <bool> (ArgVT.isInteger() && ArgSize
<= 32 && "Unhandled argument type in LowerVAARG")
? void (0) : __assert_fail ("ArgVT.isInteger() && ArgSize <= 32 && \"Unhandled argument type in LowerVAARG\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24800, __extension__ __PRETTY_FUNCTION__))
;
24801 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
24802 }
24803
24804 if (ArgMode == 2) {
24805 // Sanity Check: Make sure using fp_offset makes sense.
24806 assert(!Subtarget.useSoftFloat() &&(static_cast <bool> (!Subtarget.useSoftFloat() &&
!(MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat
)) && Subtarget.hasSSE1()) ? void (0) : __assert_fail
("!Subtarget.useSoftFloat() && !(MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat)) && Subtarget.hasSSE1()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24808, __extension__ __PRETTY_FUNCTION__))
24807 !(MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat)) &&(static_cast <bool> (!Subtarget.useSoftFloat() &&
!(MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat
)) && Subtarget.hasSSE1()) ? void (0) : __assert_fail
("!Subtarget.useSoftFloat() && !(MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat)) && Subtarget.hasSSE1()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24808, __extension__ __PRETTY_FUNCTION__))
24808 Subtarget.hasSSE1())(static_cast <bool> (!Subtarget.useSoftFloat() &&
!(MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat
)) && Subtarget.hasSSE1()) ? void (0) : __assert_fail
("!Subtarget.useSoftFloat() && !(MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat)) && Subtarget.hasSSE1()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24808, __extension__ __PRETTY_FUNCTION__))
;
24809 }
24810
24811 // Insert VAARG node into the DAG
24812 // VAARG returns two values: Variable Argument Address, Chain
24813 SDValue InstOps[] = {Chain, SrcPtr,
24814 DAG.getTargetConstant(ArgSize, dl, MVT::i32),
24815 DAG.getTargetConstant(ArgMode, dl, MVT::i8),
24816 DAG.getTargetConstant(Align, dl, MVT::i32)};
24817 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
24818 SDValue VAARG = DAG.getMemIntrinsicNode(
24819 Subtarget.isTarget64BitLP64() ? X86ISD::VAARG_64 : X86ISD::VAARG_X32, dl,
24820 VTs, InstOps, MVT::i64, MachinePointerInfo(SV),
24821 /*Alignment=*/None,
24822 MachineMemOperand::MOLoad | MachineMemOperand::MOStore);
24823 Chain = VAARG.getValue(1);
24824
24825 // Load the next argument and return it
24826 return DAG.getLoad(ArgVT, dl, Chain, VAARG, MachinePointerInfo());
24827}
24828
24829static SDValue LowerVACOPY(SDValue Op, const X86Subtarget &Subtarget,
24830 SelectionDAG &DAG) {
24831 // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
24832 // where a va_list is still an i8*.
24833 assert(Subtarget.is64Bit() && "This code only handles 64-bit va_copy!")(static_cast <bool> (Subtarget.is64Bit() && "This code only handles 64-bit va_copy!"
) ? void (0) : __assert_fail ("Subtarget.is64Bit() && \"This code only handles 64-bit va_copy!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24833, __extension__ __PRETTY_FUNCTION__))
;
24834 if (Subtarget.isCallingConvWin64(
24835 DAG.getMachineFunction().getFunction().getCallingConv()))
24836 // Probably a Win64 va_copy.
24837 return DAG.expandVACopy(Op.getNode());
24838
24839 SDValue Chain = Op.getOperand(0);
24840 SDValue DstPtr = Op.getOperand(1);
24841 SDValue SrcPtr = Op.getOperand(2);
24842 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
24843 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
24844 SDLoc DL(Op);
24845
24846 return DAG.getMemcpy(
24847 Chain, DL, DstPtr, SrcPtr,
24848 DAG.getIntPtrConstant(Subtarget.isTarget64BitLP64() ? 24 : 16, DL),
24849 Align(Subtarget.isTarget64BitLP64() ? 8 : 4), /*isVolatile*/ false, false,
24850 false, MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
24851}
24852
24853// Helper to get immediate/variable SSE shift opcode from other shift opcodes.
24854static unsigned getTargetVShiftUniformOpcode(unsigned Opc, bool IsVariable) {
24855 switch (Opc) {
24856 case ISD::SHL:
24857 case X86ISD::VSHL:
24858 case X86ISD::VSHLI:
24859 return IsVariable ? X86ISD::VSHL : X86ISD::VSHLI;
24860 case ISD::SRL:
24861 case X86ISD::VSRL:
24862 case X86ISD::VSRLI:
24863 return IsVariable ? X86ISD::VSRL : X86ISD::VSRLI;
24864 case ISD::SRA:
24865 case X86ISD::VSRA:
24866 case X86ISD::VSRAI:
24867 return IsVariable ? X86ISD::VSRA : X86ISD::VSRAI;
24868 }
24869 llvm_unreachable("Unknown target vector shift node")::llvm::llvm_unreachable_internal("Unknown target vector shift node"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24869)
;
24870}
24871
24872/// Handle vector element shifts where the shift amount is a constant.
24873/// Takes immediate version of shift as input.
24874static SDValue getTargetVShiftByConstNode(unsigned Opc, const SDLoc &dl, MVT VT,
24875 SDValue SrcOp, uint64_t ShiftAmt,
24876 SelectionDAG &DAG) {
24877 MVT ElementType = VT.getVectorElementType();
24878
24879 // Bitcast the source vector to the output type, this is mainly necessary for
24880 // vXi8/vXi64 shifts.
24881 if (VT != SrcOp.getSimpleValueType())
24882 SrcOp = DAG.getBitcast(VT, SrcOp);
24883
24884 // Fold this packed shift into its first operand if ShiftAmt is 0.
24885 if (ShiftAmt == 0)
24886 return SrcOp;
24887
24888 // Check for ShiftAmt >= element width
24889 if (ShiftAmt >= ElementType.getSizeInBits()) {
24890 if (Opc == X86ISD::VSRAI)
24891 ShiftAmt = ElementType.getSizeInBits() - 1;
24892 else
24893 return DAG.getConstant(0, dl, VT);
24894 }
24895
24896 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)(static_cast <bool> ((Opc == X86ISD::VSHLI || Opc == X86ISD
::VSRLI || Opc == X86ISD::VSRAI) && "Unknown target vector shift-by-constant node"
) ? void (0) : __assert_fail ("(Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI) && \"Unknown target vector shift-by-constant node\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24897, __extension__ __PRETTY_FUNCTION__))
24897 && "Unknown target vector shift-by-constant node")(static_cast <bool> ((Opc == X86ISD::VSHLI || Opc == X86ISD
::VSRLI || Opc == X86ISD::VSRAI) && "Unknown target vector shift-by-constant node"
) ? void (0) : __assert_fail ("(Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI) && \"Unknown target vector shift-by-constant node\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24897, __extension__ __PRETTY_FUNCTION__))
;
24898
24899 // Fold this packed vector shift into a build vector if SrcOp is a
24900 // vector of Constants or UNDEFs.
24901 if (ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
24902 SmallVector<SDValue, 8> Elts;
24903 unsigned NumElts = SrcOp->getNumOperands();
24904
24905 switch (Opc) {
24906 default: llvm_unreachable("Unknown opcode!")::llvm::llvm_unreachable_internal("Unknown opcode!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24906)
;
24907 case X86ISD::VSHLI:
24908 for (unsigned i = 0; i != NumElts; ++i) {
24909 SDValue CurrentOp = SrcOp->getOperand(i);
24910 if (CurrentOp->isUndef()) {
24911 // Must produce 0s in the correct bits.
24912 Elts.push_back(DAG.getConstant(0, dl, ElementType));
24913 continue;
24914 }
24915 auto *ND = cast<ConstantSDNode>(CurrentOp);
24916 const APInt &C = ND->getAPIntValue();
24917 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
24918 }
24919 break;
24920 case X86ISD::VSRLI:
24921 for (unsigned i = 0; i != NumElts; ++i) {
24922 SDValue CurrentOp = SrcOp->getOperand(i);
24923 if (CurrentOp->isUndef()) {
24924 // Must produce 0s in the correct bits.
24925 Elts.push_back(DAG.getConstant(0, dl, ElementType));
24926 continue;
24927 }
24928 auto *ND = cast<ConstantSDNode>(CurrentOp);
24929 const APInt &C = ND->getAPIntValue();
24930 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
24931 }
24932 break;
24933 case X86ISD::VSRAI:
24934 for (unsigned i = 0; i != NumElts; ++i) {
24935 SDValue CurrentOp = SrcOp->getOperand(i);
24936 if (CurrentOp->isUndef()) {
24937 // All shifted in bits must be the same so use 0.
24938 Elts.push_back(DAG.getConstant(0, dl, ElementType));
24939 continue;
24940 }
24941 auto *ND = cast<ConstantSDNode>(CurrentOp);
24942 const APInt &C = ND->getAPIntValue();
24943 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
24944 }
24945 break;
24946 }
24947
24948 return DAG.getBuildVector(VT, dl, Elts);
24949 }
24950
24951 return DAG.getNode(Opc, dl, VT, SrcOp,
24952 DAG.getTargetConstant(ShiftAmt, dl, MVT::i8));
24953}
24954
24955/// Handle vector element shifts where the shift amount may or may not be a
24956/// constant. Takes immediate version of shift as input.
24957static SDValue getTargetVShiftNode(unsigned Opc, const SDLoc &dl, MVT VT,
24958 SDValue SrcOp, SDValue ShAmt,
24959 const X86Subtarget &Subtarget,
24960 SelectionDAG &DAG) {
24961 MVT SVT = ShAmt.getSimpleValueType();
24962 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!")(static_cast <bool> ((SVT == MVT::i32 || SVT == MVT::i64
) && "Unexpected value type!") ? void (0) : __assert_fail
("(SVT == MVT::i32 || SVT == MVT::i64) && \"Unexpected value type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 24962, __extension__ __PRETTY_FUNCTION__))
;
24963
24964 // Catch shift-by-constant.
24965 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
24966 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
24967 CShAmt->getZExtValue(), DAG);
24968
24969 // Change opcode to non-immediate version.
24970 Opc = getTargetVShiftUniformOpcode(Opc, true);
24971
24972 // Need to build a vector containing shift amount.
24973 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
24974 // +====================+============+=======================================+
24975 // | ShAmt is | HasSSE4.1? | Construct ShAmt vector as |
24976 // +====================+============+=======================================+
24977 // | i64 | Yes, No | Use ShAmt as lowest elt |
24978 // | i32 | Yes | zero-extend in-reg |
24979 // | (i32 zext(i16/i8)) | Yes | zero-extend in-reg |
24980 // | (i32 zext(i16/i8)) | No | byte-shift-in-reg |
24981 // | i16/i32 | No | v4i32 build_vector(ShAmt, 0, ud, ud)) |
24982 // +====================+============+=======================================+
24983
24984 if (SVT == MVT::i64)
24985 ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(ShAmt), MVT::v2i64, ShAmt);
24986 else if (ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
24987 ShAmt.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24988 (ShAmt.getOperand(0).getSimpleValueType() == MVT::i16 ||
24989 ShAmt.getOperand(0).getSimpleValueType() == MVT::i8)) {
24990 ShAmt = ShAmt.getOperand(0);
24991 MVT AmtTy = ShAmt.getSimpleValueType() == MVT::i8 ? MVT::v16i8 : MVT::v8i16;
24992 ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(ShAmt), AmtTy, ShAmt);
24993 if (Subtarget.hasSSE41())
24994 ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
24995 MVT::v2i64, ShAmt);
24996 else {
24997 SDValue ByteShift = DAG.getTargetConstant(
24998 (128 - AmtTy.getScalarSizeInBits()) / 8, SDLoc(ShAmt), MVT::i8);
24999 ShAmt = DAG.getBitcast(MVT::v16i8, ShAmt);
25000 ShAmt = DAG.getNode(X86ISD::VSHLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
25001 ByteShift);
25002 ShAmt = DAG.getNode(X86ISD::VSRLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
25003 ByteShift);
25004 }
25005 } else if (Subtarget.hasSSE41() &&
25006 ShAmt.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
25007 ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(ShAmt), MVT::v4i32, ShAmt);
25008 ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
25009 MVT::v2i64, ShAmt);
25010 } else {
25011 SDValue ShOps[4] = {ShAmt, DAG.getConstant(0, dl, SVT), DAG.getUNDEF(SVT),
25012 DAG.getUNDEF(SVT)};
25013 ShAmt = DAG.getBuildVector(MVT::v4i32, dl, ShOps);
25014 }
25015
25016 // The return type has to be a 128-bit type with the same element
25017 // type as the input type.
25018 MVT EltVT = VT.getVectorElementType();
25019 MVT ShVT = MVT::getVectorVT(EltVT, 128 / EltVT.getSizeInBits());
25020
25021 ShAmt = DAG.getBitcast(ShVT, ShAmt);
25022 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
25023}
25024
25025/// Return Mask with the necessary casting or extending
25026/// for \p Mask according to \p MaskVT when lowering masking intrinsics
25027static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
25028 const X86Subtarget &Subtarget, SelectionDAG &DAG,
25029 const SDLoc &dl) {
25030
25031 if (isAllOnesConstant(Mask))
25032 return DAG.getConstant(1, dl, MaskVT);
25033 if (X86::isZeroNode(Mask))
25034 return DAG.getConstant(0, dl, MaskVT);
25035
25036 assert(MaskVT.bitsLE(Mask.getSimpleValueType()) && "Unexpected mask size!")(static_cast <bool> (MaskVT.bitsLE(Mask.getSimpleValueType
()) && "Unexpected mask size!") ? void (0) : __assert_fail
("MaskVT.bitsLE(Mask.getSimpleValueType()) && \"Unexpected mask size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 25036, __extension__ __PRETTY_FUNCTION__))
;
25037
25038 if (Mask.getSimpleValueType() == MVT::i64 && Subtarget.is32Bit()) {
25039 assert(MaskVT == MVT::v64i1 && "Expected v64i1 mask!")(static_cast <bool> (MaskVT == MVT::v64i1 && "Expected v64i1 mask!"
) ? void (0) : __assert_fail ("MaskVT == MVT::v64i1 && \"Expected v64i1 mask!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 25039, __extension__ __PRETTY_FUNCTION__))
;
25040 assert(Subtarget.hasBWI() && "Expected AVX512BW target!")(static_cast <bool> (Subtarget.hasBWI() && "Expected AVX512BW target!"
) ? void (0) : __assert_fail ("Subtarget.hasBWI() && \"Expected AVX512BW target!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 25040, __extension__ __PRETTY_FUNCTION__))
;
25041 // In case 32bit mode, bitcast i64 is illegal, extend/split it.
25042 SDValue Lo, Hi;
25043 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
25044 DAG.getConstant(0, dl, MVT::i32));
25045 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
25046 DAG.getConstant(1, dl, MVT::i32));
25047
25048 Lo = DAG.getBitcast(MVT::v32i1, Lo);
25049 Hi = DAG.getBitcast(MVT::v32i1, Hi);
25050
25051 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
25052 } else {
25053 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
25054 Mask.getSimpleValueType().getSizeInBits());
25055 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
25056 // are extracted by EXTRACT_SUBVECTOR.
25057 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
25058 DAG.getBitcast(BitcastVT, Mask),
25059 DAG.getIntPtrConstant(0, dl));
25060 }
25061}
25062
25063/// Return (and \p Op, \p Mask) for compare instructions or
25064/// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
25065/// necessary casting or extending for \p Mask when lowering masking intrinsics
25066static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
25067 SDValue PreservedSrc,
25068 const X86Subtarget &Subtarget,
25069 SelectionDAG &DAG) {
25070 MVT VT = Op.getSimpleValueType();
25071 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
25072 unsigned OpcodeSelect = ISD::VSELECT;
25073 SDLoc dl(Op);
25074
25075 if (isAllOnesConstant(Mask))
25076 return Op;
25077
25078 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
25079
25080 if (PreservedSrc.isUndef())
25081 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
25082 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
25083}
25084
25085/// Creates an SDNode for a predicated scalar operation.
25086/// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
25087/// The mask is coming as MVT::i8 and it should be transformed
25088/// to MVT::v1i1 while lowering masking intrinsics.
25089/// The main difference between ScalarMaskingNode and VectorMaskingNode is using
25090/// "X86select" instead of "vselect". We just can't create the "vselect" node
25091/// for a scalar instruction.
25092static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
25093 SDValue PreservedSrc,
25094 const X86Subtarget &Subtarget,
25095 SelectionDAG &DAG) {
25096
25097 if (auto *MaskConst = dyn_cast<ConstantSDNode>(Mask))
25098 if (MaskConst->getZExtValue() & 0x1)
25099 return Op;
25100
25101 MVT VT = Op.getSimpleValueType();
25102 SDLoc dl(Op);
25103
25104 assert(Mask.getValueType() == MVT::i8 && "Unexpect type")(static_cast <bool> (Mask.getValueType() == MVT::i8 &&
"Unexpect type") ? void (0) : __assert_fail ("Mask.getValueType() == MVT::i8 && \"Unexpect type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 25104, __extension__ __PRETTY_FUNCTION__))
;
25105 SDValue IMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v1i1,
25106 DAG.getBitcast(MVT::v8i1, Mask),
25107 DAG.getIntPtrConstant(0, dl));
25108 if (Op.getOpcode() == X86ISD::FSETCCM ||
25109 Op.getOpcode() == X86ISD::FSETCCM_SAE ||
25110 Op.getOpcode() == X86ISD::VFPCLASSS)
25111 return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
25112
25113 if (PreservedSrc.isUndef())
25114 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
25115 return DAG.getNode(X86ISD::SELECTS, dl, VT, IMask, Op, PreservedSrc);
25116}
25117
25118static int getSEHRegistrationNodeSize(const Function *Fn) {
25119 if (!Fn->hasPersonalityFn())
25120 report_fatal_error(
25121 "querying registration node size for function without personality");
25122 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
25123 // WinEHStatePass for the full struct definition.
25124 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
25125 case EHPersonality::MSVC_X86SEH: return 24;
25126 case EHPersonality::MSVC_CXX: return 16;
25127 default: break;
25128 }
25129 report_fatal_error(
25130 "can only recover FP for 32-bit MSVC EH personality functions");
25131}
25132
25133/// When the MSVC runtime transfers control to us, either to an outlined
25134/// function or when returning to a parent frame after catching an exception, we
25135/// recover the parent frame pointer by doing arithmetic on the incoming EBP.
25136/// Here's the math:
25137/// RegNodeBase = EntryEBP - RegNodeSize
25138/// ParentFP = RegNodeBase - ParentFrameOffset
25139/// Subtracting RegNodeSize takes us to the offset of the registration node, and
25140/// subtracting the offset (negative on x86) takes us back to the parent FP.
25141static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
25142 SDValue EntryEBP) {
25143 MachineFunction &MF = DAG.getMachineFunction();
25144 SDLoc dl;
25145
25146 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25147 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
25148
25149 // It's possible that the parent function no longer has a personality function
25150 // if the exceptional code was optimized away, in which case we just return
25151 // the incoming EBP.
25152 if (!Fn->hasPersonalityFn())
25153 return EntryEBP;
25154
25155 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
25156 // registration, or the .set_setframe offset.
25157 MCSymbol *OffsetSym =
25158 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
25159 GlobalValue::dropLLVMManglingEscape(Fn->getName()));
25160 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
25161 SDValue ParentFrameOffset =
25162 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
25163
25164 // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
25165 // prologue to RBP in the parent function.
25166 const X86Subtarget &Subtarget =
25167 static_cast<const X86Subtarget &>(DAG.getSubtarget());
25168 if (Subtarget.is64Bit())
25169 return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
25170
25171 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
25172 // RegNodeBase = EntryEBP - RegNodeSize
25173 // ParentFP = RegNodeBase - ParentFrameOffset
25174 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
25175 DAG.getConstant(RegNodeSize, dl, PtrVT));
25176 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
25177}
25178
25179SDValue X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
25180 SelectionDAG &DAG) const {
25181 // Helper to detect if the operand is CUR_DIRECTION rounding mode.
25182 auto isRoundModeCurDirection = [](SDValue Rnd) {
25183 if (auto *C = dyn_cast<ConstantSDNode>(Rnd))
25184 return C->getAPIntValue() == X86::STATIC_ROUNDING::CUR_DIRECTION;
25185
25186 return false;
25187 };
25188 auto isRoundModeSAE = [](SDValue Rnd) {
25189 if (auto *C = dyn_cast<ConstantSDNode>(Rnd)) {
25190 unsigned RC = C->getZExtValue();
25191 if (RC & X86::STATIC_ROUNDING::NO_EXC) {
25192 // Clear the NO_EXC bit and check remaining bits.
25193 RC ^= X86::STATIC_ROUNDING::NO_EXC;
25194 // As a convenience we allow no other bits or explicitly
25195 // current direction.
25196 return RC == 0 || RC == X86::STATIC_ROUNDING::CUR_DIRECTION;
25197 }
25198 }
25199
25200 return false;
25201 };
25202 auto isRoundModeSAEToX = [](SDValue Rnd, unsigned &RC) {
25203 if (auto *C = dyn_cast<ConstantSDNode>(Rnd)) {
25204 RC = C->getZExtValue();
25205 if (RC & X86::STATIC_ROUNDING::NO_EXC) {
25206 // Clear the NO_EXC bit and check remaining bits.
25207 RC ^= X86::STATIC_ROUNDING::NO_EXC;
25208 return RC == X86::STATIC_ROUNDING::TO_NEAREST_INT ||
25209 RC == X86::STATIC_ROUNDING::TO_NEG_INF ||
25210 RC == X86::STATIC_ROUNDING::TO_POS_INF ||
25211 RC == X86::STATIC_ROUNDING::TO_ZERO;
25212 }
25213 }
25214
25215 return false;
25216 };
25217
25218 SDLoc dl(Op);
25219 unsigned IntNo = Op.getConstantOperandVal(0);
25220 MVT VT = Op.getSimpleValueType();
25221 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
25222
25223 // Propagate flags from original node to transformed node(s).
25224 SelectionDAG::FlagInserter FlagsInserter(DAG, Op->getFlags());
25225
25226 if (IntrData) {
25227 switch(IntrData->Type) {
25228 case INTR_TYPE_1OP: {
25229 // We specify 2 possible opcodes for intrinsics with rounding modes.
25230 // First, we check if the intrinsic may have non-default rounding mode,
25231 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
25232 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25233 if (IntrWithRoundingModeOpcode != 0) {
25234 SDValue Rnd = Op.getOperand(2);
25235 unsigned RC = 0;
25236 if (isRoundModeSAEToX(Rnd, RC))
25237 return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
25238 Op.getOperand(1),
25239 DAG.getTargetConstant(RC, dl, MVT::i32));
25240 if (!isRoundModeCurDirection(Rnd))
25241 return SDValue();
25242 }
25243 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25244 Op.getOperand(1));
25245 }
25246 case INTR_TYPE_1OP_SAE: {
25247 SDValue Sae = Op.getOperand(2);
25248
25249 unsigned Opc;
25250 if (isRoundModeCurDirection(Sae))
25251 Opc = IntrData->Opc0;
25252 else if (isRoundModeSAE(Sae))
25253 Opc = IntrData->Opc1;
25254 else
25255 return SDValue();
25256
25257 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1));
25258 }
25259 case INTR_TYPE_2OP: {
25260 SDValue Src2 = Op.getOperand(2);
25261
25262 // We specify 2 possible opcodes for intrinsics with rounding modes.
25263 // First, we check if the intrinsic may have non-default rounding mode,
25264 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
25265 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25266 if (IntrWithRoundingModeOpcode != 0) {
25267 SDValue Rnd = Op.getOperand(3);
25268 unsigned RC = 0;
25269 if (isRoundModeSAEToX(Rnd, RC))
25270 return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
25271 Op.getOperand(1), Src2,
25272 DAG.getTargetConstant(RC, dl, MVT::i32));
25273 if (!isRoundModeCurDirection(Rnd))
25274 return SDValue();
25275 }
25276
25277 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25278 Op.getOperand(1), Src2);
25279 }
25280 case INTR_TYPE_2OP_SAE: {
25281 SDValue Sae = Op.getOperand(3);
25282
25283 unsigned Opc;
25284 if (isRoundModeCurDirection(Sae))
25285 Opc = IntrData->Opc0;
25286 else if (isRoundModeSAE(Sae))
25287 Opc = IntrData->Opc1;
25288 else
25289 return SDValue();
25290
25291 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
25292 Op.getOperand(2));
25293 }
25294 case INTR_TYPE_3OP:
25295 case INTR_TYPE_3OP_IMM8: {
25296 SDValue Src1 = Op.getOperand(1);
25297 SDValue Src2 = Op.getOperand(2);
25298 SDValue Src3 = Op.getOperand(3);
25299
25300 if (IntrData->Type == INTR_TYPE_3OP_IMM8 &&
25301 Src3.getValueType() != MVT::i8) {
25302 Src3 = DAG.getTargetConstant(
25303 cast<ConstantSDNode>(Src3)->getZExtValue() & 0xff, dl, MVT::i8);
25304 }
25305
25306 // We specify 2 possible opcodes for intrinsics with rounding modes.
25307 // First, we check if the intrinsic may have non-default rounding mode,
25308 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
25309 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25310 if (IntrWithRoundingModeOpcode != 0) {
25311 SDValue Rnd = Op.getOperand(4);
25312 unsigned RC = 0;
25313 if (isRoundModeSAEToX(Rnd, RC))
25314 return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
25315 Src1, Src2, Src3,
25316 DAG.getTargetConstant(RC, dl, MVT::i32));
25317 if (!isRoundModeCurDirection(Rnd))
25318 return SDValue();
25319 }
25320
25321 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25322 {Src1, Src2, Src3});
25323 }
25324 case INTR_TYPE_4OP_IMM8: {
25325 assert(Op.getOperand(4)->getOpcode() == ISD::TargetConstant)(static_cast <bool> (Op.getOperand(4)->getOpcode() ==
ISD::TargetConstant) ? void (0) : __assert_fail ("Op.getOperand(4)->getOpcode() == ISD::TargetConstant"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 25325, __extension__ __PRETTY_FUNCTION__))
;
25326 SDValue Src4 = Op.getOperand(4);
25327 if (Src4.getValueType() != MVT::i8) {
25328 Src4 = DAG.getTargetConstant(
25329 cast<ConstantSDNode>(Src4)->getZExtValue() & 0xff, dl, MVT::i8);
25330 }
25331
25332 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25333 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
25334 Src4);
25335 }
25336 case INTR_TYPE_1OP_MASK: {
25337 SDValue Src = Op.getOperand(1);
25338 SDValue PassThru = Op.getOperand(2);
25339 SDValue Mask = Op.getOperand(3);
25340 // We add rounding mode to the Node when
25341 // - RC Opcode is specified and
25342 // - RC is not "current direction".
25343 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25344 if (IntrWithRoundingModeOpcode != 0) {
25345 SDValue Rnd = Op.getOperand(4);
25346 unsigned RC = 0;
25347 if (isRoundModeSAEToX(Rnd, RC))
25348 return getVectorMaskingNode(
25349 DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
25350 Src, DAG.getTargetConstant(RC, dl, MVT::i32)),
25351 Mask, PassThru, Subtarget, DAG);
25352 if (!isRoundModeCurDirection(Rnd))
25353 return SDValue();
25354 }
25355 return getVectorMaskingNode(
25356 DAG.getNode(IntrData->Opc0, dl, VT, Src), Mask, PassThru,
25357 Subtarget, DAG);
25358 }
25359 case INTR_TYPE_1OP_MASK_SAE: {
25360 SDValue Src = Op.getOperand(1);
25361 SDValue PassThru = Op.getOperand(2);
25362 SDValue Mask = Op.getOperand(3);
25363 SDValue Rnd = Op.getOperand(4);
25364
25365 unsigned Opc;
25366 if (isRoundModeCurDirection(Rnd))
25367 Opc = IntrData->Opc0;
25368 else if (isRoundModeSAE(Rnd))
25369 Opc = IntrData->Opc1;
25370 else
25371 return SDValue();
25372
25373 return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src), Mask, PassThru,
25374 Subtarget, DAG);
25375 }
25376 case INTR_TYPE_SCALAR_MASK: {
25377 SDValue Src1 = Op.getOperand(1);
25378 SDValue Src2 = Op.getOperand(2);
25379 SDValue passThru = Op.getOperand(3);
25380 SDValue Mask = Op.getOperand(4);
25381 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25382 // There are 2 kinds of intrinsics in this group:
25383 // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
25384 // (2) With rounding mode and sae - 7 operands.
25385 bool HasRounding = IntrWithRoundingModeOpcode != 0;
25386 if (Op.getNumOperands() == (5U + HasRounding)) {
25387 if (HasRounding) {
25388 SDValue Rnd = Op.getOperand(5);
25389 unsigned RC = 0;
25390 if (isRoundModeSAEToX(Rnd, RC))
25391 return getScalarMaskingNode(
25392 DAG.getNode(IntrWithRoundingModeOpcode, dl, VT, Src1, Src2,
25393 DAG.getTargetConstant(RC, dl, MVT::i32)),
25394 Mask, passThru, Subtarget, DAG);
25395 if (!isRoundModeCurDirection(Rnd))
25396 return SDValue();
25397 }
25398 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
25399 Src2),
25400 Mask, passThru, Subtarget, DAG);
25401 }
25402
25403 assert(Op.getNumOperands() == (6U + HasRounding) &&(static_cast <bool> (Op.getNumOperands() == (6U + HasRounding
) && "Unexpected intrinsic form") ? void (0) : __assert_fail
("Op.getNumOperands() == (6U + HasRounding) && \"Unexpected intrinsic form\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 25404, __extension__ __PRETTY_FUNCTION__))
25404 "Unexpected intrinsic form")(static_cast <bool> (Op.getNumOperands() == (6U + HasRounding
) && "Unexpected intrinsic form") ? void (0) : __assert_fail
("Op.getNumOperands() == (6U + HasRounding) && \"Unexpected intrinsic form\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 25404, __extension__ __PRETTY_FUNCTION__))
;
25405 SDValue RoundingMode = Op.getOperand(5);
25406 unsigned Opc = IntrData->Opc0;
25407 if (HasRounding) {
25408 SDValue Sae = Op.getOperand(6);
25409 if (isRoundModeSAE(Sae))
25410 Opc = IntrWithRoundingModeOpcode;
25411 else if (!isRoundModeCurDirection(Sae))
25412 return SDValue();
25413 }
25414 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1,
25415 Src2, RoundingMode),
25416 Mask, passThru, Subtarget, DAG);
25417 }
25418 case INTR_TYPE_SCALAR_MASK_RND: {
25419 SDValue Src1 = Op.getOperand(1);
25420 SDValue Src2 = Op.getOperand(2);
25421 SDValue passThru = Op.getOperand(3);
25422 SDValue Mask = Op.getOperand(4);
25423 SDValue Rnd = Op.getOperand(5);
25424
25425 SDValue NewOp;
25426 unsigned RC = 0;
25427 if (isRoundModeCurDirection(Rnd))
25428 NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2);
25429 else if (isRoundModeSAEToX(Rnd, RC))
25430 NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2,
25431 DAG.getTargetConstant(RC, dl, MVT::i32));
25432 else
25433 return SDValue();
25434
25435 return getScalarMaskingNode(NewOp, Mask, passThru, Subtarget, DAG);
25436 }
25437 case INTR_TYPE_SCALAR_MASK_SAE: {
25438 SDValue Src1 = Op.getOperand(1);
25439 SDValue Src2 = Op.getOperand(2);
25440 SDValue passThru = Op.getOperand(3);
25441 SDValue Mask = Op.getOperand(4);
25442 SDValue Sae = Op.getOperand(5);
25443 unsigned Opc;
25444 if (isRoundModeCurDirection(Sae))
25445 Opc = IntrData->Opc0;
25446 else if (isRoundModeSAE(Sae))
25447 Opc = IntrData->Opc1;
25448 else
25449 return SDValue();
25450
25451 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2),
25452 Mask, passThru, Subtarget, DAG);
25453 }
25454 case INTR_TYPE_2OP_MASK: {
25455 SDValue Src1 = Op.getOperand(1);
25456 SDValue Src2 = Op.getOperand(2);
25457 SDValue PassThru = Op.getOperand(3);
25458 SDValue Mask = Op.getOperand(4);
25459 SDValue NewOp;
25460 if (IntrData->Opc1 != 0) {
25461 SDValue Rnd = Op.getOperand(5);
25462 unsigned RC = 0;
25463 if (isRoundModeSAEToX(Rnd, RC))
25464 NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2,
25465 DAG.getTargetConstant(RC, dl, MVT::i32));
25466 else if (!isRoundModeCurDirection(Rnd))
25467 return SDValue();
25468 }
25469 if (!NewOp)
25470 NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2);
25471 return getVectorMaskingNode(NewOp, Mask, PassThru, Subtarget, DAG);
25472 }
25473 case INTR_TYPE_2OP_MASK_SAE: {
25474 SDValue Src1 = Op.getOperand(1);
25475 SDValue Src2 = Op.getOperand(2);
25476 SDValue PassThru = Op.getOperand(3);
25477 SDValue Mask = Op.getOperand(4);
25478
25479 unsigned Opc = IntrData->Opc0;
25480 if (IntrData->Opc1 != 0) {
25481 SDValue Sae = Op.getOperand(5);
25482 if (isRoundModeSAE(Sae))
25483 Opc = IntrData->Opc1;
25484 else if (!isRoundModeCurDirection(Sae))
25485 return SDValue();
25486 }
25487
25488 return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2),
25489 Mask, PassThru, Subtarget, DAG);
25490 }
25491 case INTR_TYPE_3OP_SCALAR_MASK_SAE: {
25492 SDValue Src1 = Op.getOperand(1);
25493 SDValue Src2 = Op.getOperand(2);
25494 SDValue Src3 = Op.getOperand(3);
25495 SDValue PassThru = Op.getOperand(4);
25496 SDValue Mask = Op.getOperand(5);
25497 SDValue Sae = Op.getOperand(6);
25498 unsigned Opc;
25499 if (isRoundModeCurDirection(Sae))
25500 Opc = IntrData->Opc0;
25501 else if (isRoundModeSAE(Sae))
25502 Opc = IntrData->Opc1;
25503 else
25504 return SDValue();
25505
25506 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2, Src3),
25507 Mask, PassThru, Subtarget, DAG);
25508 }
25509 case INTR_TYPE_3OP_MASK_SAE: {
25510 SDValue Src1 = Op.getOperand(1);
25511 SDValue Src2 = Op.getOperand(2);
25512 SDValue Src3 = Op.getOperand(3);
25513 SDValue PassThru = Op.getOperand(4);
25514 SDValue Mask = Op.getOperand(5);
25515
25516 unsigned Opc = IntrData->Opc0;
25517 if (IntrData->Opc1 != 0) {
25518 SDValue Sae = Op.getOperand(6);
25519 if (isRoundModeSAE(Sae))
25520 Opc = IntrData->Opc1;
25521 else if (!isRoundModeCurDirection(Sae))
25522 return SDValue();
25523 }
25524 return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2, Src3),
25525 Mask, PassThru, Subtarget, DAG);
25526 }
25527 case BLENDV: {
25528 SDValue Src1 = Op.getOperand(1);
25529 SDValue Src2 = Op.getOperand(2);
25530 SDValue Src3 = Op.getOperand(3);
25531
25532 EVT MaskVT = Src3.getValueType().changeVectorElementTypeToInteger();
25533 Src3 = DAG.getBitcast(MaskVT, Src3);
25534
25535 // Reverse the operands to match VSELECT order.
25536 return DAG.getNode(IntrData->Opc0, dl, VT, Src3, Src2, Src1);
25537 }
25538 case VPERM_2OP : {
25539 SDValue Src1 = Op.getOperand(1);
25540 SDValue Src2 = Op.getOperand(2);
25541
25542 // Swap Src1 and Src2 in the node creation
25543 return DAG.getNode(IntrData->Opc0, dl, VT,Src2, Src1);
25544 }
25545 case IFMA_OP:
25546 // NOTE: We need to swizzle the operands to pass the multiply operands
25547 // first.
25548 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25549 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
25550 case FPCLASSS: {
25551 SDValue Src1 = Op.getOperand(1);
25552 SDValue Imm = Op.getOperand(2);
25553 SDValue Mask = Op.getOperand(3);
25554 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Imm);
25555 SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask, SDValue(),
25556 Subtarget, DAG);
25557 // Need to fill with zeros to ensure the bitcast will produce zeroes
25558 // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
25559 SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
25560 DAG.getConstant(0, dl, MVT::v8i1),
25561 FPclassMask, DAG.getIntPtrConstant(0, dl));
25562 return DAG.getBitcast(MVT::i8, Ins);
25563 }
25564
25565 case CMP_MASK_CC: {
25566 MVT MaskVT = Op.getSimpleValueType();
25567 SDValue CC = Op.getOperand(3);
25568 SDValue Mask = Op.getOperand(4);
25569 // We specify 2 possible opcodes for intrinsics with rounding modes.
25570 // First, we check if the intrinsic may have non-default rounding mode,
25571 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
25572 if (IntrData->Opc1 != 0) {
25573 SDValue Sae = Op.getOperand(5);
25574 if (isRoundModeSAE(Sae))
25575 return DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
25576 Op.getOperand(2), CC, Mask, Sae);
25577 if (!isRoundModeCurDirection(Sae))
25578 return SDValue();
25579 }
25580 //default rounding mode
25581 return DAG.getNode(IntrData->Opc0, dl, MaskVT,
25582 {Op.getOperand(1), Op.getOperand(2), CC, Mask});
25583 }
25584 case CMP_MASK_SCALAR_CC: {
25585 SDValue Src1 = Op.getOperand(1);
25586 SDValue Src2 = Op.getOperand(2);
25587 SDValue CC = Op.getOperand(3);
25588 SDValue Mask = Op.getOperand(4);
25589
25590 SDValue Cmp;
25591 if (IntrData->Opc1 != 0) {
25592 SDValue Sae = Op.getOperand(5);
25593 if (isRoundModeSAE(Sae))
25594 Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::v1i1, Src1, Src2, CC, Sae);
25595 else if (!isRoundModeCurDirection(Sae))
25596 return SDValue();
25597 }
25598 //default rounding mode
25599 if (!Cmp.getNode())
25600 Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Src2, CC);
25601
25602 SDValue CmpMask = getScalarMaskingNode(Cmp, Mask, SDValue(),
25603 Subtarget, DAG);
25604 // Need to fill with zeros to ensure the bitcast will produce zeroes
25605 // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
25606 SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
25607 DAG.getConstant(0, dl, MVT::v8i1),
25608 CmpMask, DAG.getIntPtrConstant(0, dl));
25609 return DAG.getBitcast(MVT::i8, Ins);
25610 }
25611 case COMI: { // Comparison intrinsics
25612 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
25613 SDValue LHS = Op.getOperand(1);
25614 SDValue RHS = Op.getOperand(2);
25615 // Some conditions require the operands to be swapped.
25616 if (CC == ISD::SETLT || CC == ISD::SETLE)
25617 std::swap(LHS, RHS);
25618
25619 SDValue Comi = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
25620 SDValue SetCC;
25621 switch (CC) {
25622 case ISD::SETEQ: { // (ZF = 0 and PF = 0)
25623 SetCC = getSETCC(X86::COND_E, Comi, dl, DAG);
25624 SDValue SetNP = getSETCC(X86::COND_NP, Comi, dl, DAG);
25625 SetCC = DAG.getNode(ISD::AND, dl, MVT::i8, SetCC, SetNP);
25626 break;
25627 }
25628 case ISD::SETNE: { // (ZF = 1 or PF = 1)
25629 SetCC = getSETCC(X86::COND_NE, Comi, dl, DAG);
25630 SDValue SetP = getSETCC(X86::COND_P, Comi, dl, DAG);
25631 SetCC = DAG.getNode(ISD::OR, dl, MVT::i8, SetCC, SetP);
25632 break;
25633 }
25634 case ISD::SETGT: // (CF = 0 and ZF = 0)
25635 case ISD::SETLT: { // Condition opposite to GT. Operands swapped above.
25636 SetCC = getSETCC(X86::COND_A, Comi, dl, DAG);
25637 break;
25638 }
25639 case ISD::SETGE: // CF = 0
25640 case ISD::SETLE: // Condition opposite to GE. Operands swapped above.
25641 SetCC = getSETCC(X86::COND_AE, Comi, dl, DAG);
25642 break;
25643 default:
25644 llvm_unreachable("Unexpected illegal condition!")::llvm::llvm_unreachable_internal("Unexpected illegal condition!"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 25644)
;
25645 }
25646 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
25647 }
25648 case COMI_RM: { // Comparison intrinsics with Sae
25649 SDValue LHS = Op.getOperand(1);
25650 SDValue RHS = Op.getOperand(2);
25651 unsigned CondVal = Op.getConstantOperandVal(3);
25652 SDValue Sae = Op.getOperand(4);
25653
25654 SDValue FCmp;
25655 if (isRoundModeCurDirection(Sae))
25656 FCmp = DAG.getNode(X86ISD::FSETCCM, dl, MVT::v1i1, LHS, RHS,
25657 DAG.getTargetConstant(CondVal, dl, MVT::i8));
25658 else if (isRoundModeSAE(Sae))
25659 FCmp = DAG.getNode(X86ISD::FSETCCM_SAE, dl, MVT::v1i1, LHS, RHS,
25660 DAG.getTargetConstant(CondVal, dl, MVT::i8), Sae);
25661 else
25662 return SDValue();
25663 // Need to fill with zeros to ensure the bitcast will produce zeroes
25664 // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
25665 SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i1,
25666 DAG.getConstant(0, dl, MVT::v16i1),
25667 FCmp, DAG.getIntPtrConstant(0, dl));
25668 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32,
25669 DAG.getBitcast(MVT::i16, Ins));
25670 }
25671 case VSHIFT:
25672 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
25673 Op.getOperand(1), Op.getOperand(2), Subtarget,
25674 DAG);
25675 case COMPRESS_EXPAND_IN_REG: {
25676 SDValue Mask = Op.getOperand(3);
25677 SDValue DataToCompress = Op.getOperand(1);
25678 SDValue PassThru = Op.getOperand(2);
25679 if (ISD::isBuildVectorAllOnes(Mask.getNode())) // return data as is
25680 return Op.getOperand(1);
25681
25682 // Avoid false dependency.
25683 if (PassThru.isUndef())
25684 PassThru = DAG.getConstant(0, dl, VT);
25685
25686 return DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress, PassThru,
25687 Mask);
25688 }
25689 case FIXUPIMM:
25690 case FIXUPIMM_MASKZ: {
25691 SDValue Src1 = Op.getOperand(1);
25692 SDValue Src2 = Op.getOperand(2);
25693 SDValue Src3 = Op.getOperand(3);
25694 SDValue Imm = Op.getOperand(4);
25695 SDValue Mask = Op.getOperand(5);
25696 SDValue Passthru = (IntrData->Type == FIXUPIMM)
25697 ? Src1
25698 : getZeroVector(VT, Subtarget, DAG, dl);
25699
25700 unsigned Opc = IntrData->Opc0;
25701 if (IntrData->Opc1 != 0) {
25702 SDValue Sae = Op.getOperand(6);
25703 if (isRoundModeSAE(Sae))
25704 Opc = IntrData->Opc1;
25705 else if (!isRoundModeCurDirection(Sae))
25706 return SDValue();
25707 }
25708
25709 SDValue FixupImm = DAG.getNode(Opc, dl, VT, Src1, Src2, Src3, Imm);
25710
25711 if (Opc == X86ISD::VFIXUPIMM || Opc == X86ISD::VFIXUPIMM_SAE)
25712 return getVectorMaskingNode(FixupImm, Mask, Passthru, Subtarget, DAG);
25713
25714 return getScalarMaskingNode(FixupImm, Mask, Passthru, Subtarget, DAG);
25715 }
25716 case ROUNDP: {
25717 assert(IntrData->Opc0 == X86ISD::VRNDSCALE && "Unexpected opcode")(static_cast <bool> (IntrData->Opc0 == X86ISD::VRNDSCALE
&& "Unexpected opcode") ? void (0) : __assert_fail (
"IntrData->Opc0 == X86ISD::VRNDSCALE && \"Unexpected opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 25717, __extension__ __PRETTY_FUNCTION__))
;
25718 // Clear the upper bits of the rounding immediate so that the legacy
25719 // intrinsic can't trigger the scaling behavior of VRNDSCALE.
25720 auto Round = cast<ConstantSDNode>(Op.getOperand(2));
25721 SDValue RoundingMode =
25722 DAG.getTargetConstant(Round->getZExtValue() & 0xf, dl, MVT::i32);
25723 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25724 Op.getOperand(1), RoundingMode);
25725 }
25726 case ROUNDS: {
25727 assert(IntrData->Opc0 == X86ISD::VRNDSCALES && "Unexpected opcode")(static_cast <bool> (IntrData->Opc0 == X86ISD::VRNDSCALES
&& "Unexpected opcode") ? void (0) : __assert_fail (
"IntrData->Opc0 == X86ISD::VRNDSCALES && \"Unexpected opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 25727, __extension__ __PRETTY_FUNCTION__))
;
25728 // Clear the upper bits of the rounding immediate so that the legacy
25729 // intrinsic can't trigger the scaling behavior of VRNDSCALE.
25730 auto Round = cast<ConstantSDNode>(Op.getOperand(3));
25731 SDValue RoundingMode =
25732 DAG.getTargetConstant(Round->getZExtValue() & 0xf, dl, MVT::i32);
25733 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25734 Op.getOperand(1), Op.getOperand(2), RoundingMode);
25735 }
25736 case BEXTRI: {
25737 assert(IntrData->Opc0 == X86ISD::BEXTRI && "Unexpected opcode")(static_cast <bool> (IntrData->Opc0 == X86ISD::BEXTRI
&& "Unexpected opcode") ? void (0) : __assert_fail (
"IntrData->Opc0 == X86ISD::BEXTRI && \"Unexpected opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 25737, __extension__ __PRETTY_FUNCTION__))
;
25738
25739 uint64_t Imm = Op.getConstantOperandVal(2);
25740 SDValue Control = DAG.getTargetConstant(Imm & 0xffff, dl,
25741 Op.getValueType());
25742 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25743 Op.getOperand(1), Control);
25744 }
25745 // ADC/ADCX/SBB
25746 case ADX: {
25747 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
25748 SDVTList VTs = DAG.getVTList(Op.getOperand(2).getValueType(), MVT::i32);
25749
25750 SDValue Res;
25751 // If the carry in is zero, then we should just use ADD/SUB instead of
25752 // ADC/SBB.
25753 if (isNullConstant(Op.getOperand(1))) {
25754 Res = DAG.getNode(IntrData->Opc1, dl, VTs, Op.getOperand(2),
25755 Op.getOperand(3));
25756 } else {
25757 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(1),
25758 DAG.getConstant(-1, dl, MVT::i8));
25759 Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(2),
25760 Op.getOperand(3), GenCF.getValue(1));
25761 }
25762 SDValue SetCC = getSETCC(X86::COND_B, Res.getValue(1), dl, DAG);
25763 SDValue Results[] = { SetCC, Res };
25764 return DAG.getMergeValues(Results, dl);
25765 }
25766 case CVTPD2PS_MASK:
25767 case CVTPD2DQ_MASK:
25768 case CVTQQ2PS_MASK:
25769 case TRUNCATE_TO_REG: {
25770 SDValue Src = Op.getOperand(1);
25771 SDValue PassThru = Op.getOperand(2);
25772 SDValue Mask = Op.getOperand(3);
25773
25774 if (isAllOnesConstant(Mask))
25775 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src);
25776
25777 MVT SrcVT = Src.getSimpleValueType();
25778 MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
25779 Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
25780 return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(),
25781 {Src, PassThru, Mask});
25782 }
25783 case CVTPS2PH_MASK: {
25784 SDValue Src = Op.getOperand(1);
25785 SDValue Rnd = Op.getOperand(2);
25786 SDValue PassThru = Op.getOperand(3);
25787 SDValue Mask = Op.getOperand(4);
25788
25789 if (isAllOnesConstant(Mask))
25790 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src, Rnd);
25791
25792 MVT SrcVT = Src.getSimpleValueType();
25793 MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
25794 Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
25795 return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(), Src, Rnd,
25796 PassThru, Mask);
25797
25798 }
25799 case CVTNEPS2BF16_MASK: {
25800 SDValue Src = Op.getOperand(1);
25801 SDValue PassThru = Op.getOperand(2);
25802 SDValue Mask = Op.getOperand(3);
25803
25804 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
25805 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src);
25806
25807 // Break false dependency.
25808 if (PassThru.isUndef())
25809 PassThru = DAG.getConstant(0, dl, PassThru.getValueType());
25810
25811 return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(), Src, PassThru,
25812 Mask);
25813 }
25814 default:
25815 break;
25816 }
25817 }
25818
25819 switch (IntNo) {
25820 default: return SDValue(); // Don't custom lower most intrinsics.
25821
25822 // ptest and testp intrinsics. The intrinsic these come from are designed to
25823 // return an integer value, not just an instruction so lower it to the ptest
25824 // or testp pattern and a setcc for the result.
25825 case Intrinsic::x86_avx512_ktestc_b:
25826 case Intrinsic::x86_avx512_ktestc_w:
25827 case Intrinsic::x86_avx512_ktestc_d:
25828 case Intrinsic::x86_avx512_ktestc_q:
25829 case Intrinsic::x86_avx512_ktestz_b:
25830 case Intrinsic::x86_avx512_ktestz_w:
25831 case Intrinsic::x86_avx512_ktestz_d:
25832 case Intrinsic::x86_avx512_ktestz_q:
25833 case Intrinsic::x86_sse41_ptestz:
25834 case Intrinsic::x86_sse41_ptestc:
25835 case Intrinsic::x86_sse41_ptestnzc:
25836 case Intrinsic::x86_avx_ptestz_256:
25837 case Intrinsic::x86_avx_ptestc_256:
25838 case Intrinsic::x86_avx_ptestnzc_256:
25839 case Intrinsic::x86_avx_vtestz_ps:
25840 case Intrinsic::x86_avx_vtestc_ps:
25841 case Intrinsic::x86_avx_vtestnzc_ps:
25842 case Intrinsic::x86_avx_vtestz_pd:
25843 case Intrinsic::x86_avx_vtestc_pd:
25844 case Intrinsic::x86_avx_vtestnzc_pd:
25845 case Intrinsic::x86_avx_vtestz_ps_256:
25846 case Intrinsic::x86_avx_vtestc_ps_256:
25847 case Intrinsic::x86_avx_vtestnzc_ps_256:
25848 case Intrinsic::x86_avx_vtestz_pd_256:
25849 case Intrinsic::x86_avx_vtestc_pd_256:
25850 case Intrinsic::x86_avx_vtestnzc_pd_256: {
25851 unsigned TestOpc = X86ISD::PTEST;
25852 X86::CondCode X86CC;
25853 switch (IntNo) {
25854 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.")::llvm::llvm_unreachable_internal("Bad fallthrough in Intrinsic lowering."
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 25854)
;
25855 case Intrinsic::x86_avx512_ktestc_b:
25856 case Intrinsic::x86_avx512_ktestc_w:
25857 case Intrinsic::x86_avx512_ktestc_d:
25858 case Intrinsic::x86_avx512_ktestc_q:
25859 // CF = 1
25860 TestOpc = X86ISD::KTEST;
25861 X86CC = X86::COND_B;
25862 break;
25863 case Intrinsic::x86_avx512_ktestz_b:
25864 case Intrinsic::x86_avx512_ktestz_w:
25865 case Intrinsic::x86_avx512_ktestz_d:
25866 case Intrinsic::x86_avx512_ktestz_q:
25867 TestOpc = X86ISD::KTEST;
25868 X86CC = X86::COND_E;
25869 break;
25870 case Intrinsic::x86_avx_vtestz_ps:
25871 case Intrinsic::x86_avx_vtestz_pd:
25872 case Intrinsic::x86_avx_vtestz_ps_256:
25873 case Intrinsic::x86_avx_vtestz_pd_256:
25874 TestOpc = X86ISD::TESTP;
25875 LLVM_FALLTHROUGH[[gnu::fallthrough]];
25876 case Intrinsic::x86_sse41_ptestz:
25877 case Intrinsic::x86_avx_ptestz_256:
25878 // ZF = 1
25879 X86CC = X86::COND_E;
25880 break;
25881 case Intrinsic::x86_avx_vtestc_ps:
25882 case Intrinsic::x86_avx_vtestc_pd:
25883 case Intrinsic::x86_avx_vtestc_ps_256:
25884 case Intrinsic::x86_avx_vtestc_pd_256:
25885 TestOpc = X86ISD::TESTP;
25886 LLVM_FALLTHROUGH[[gnu::fallthrough]];
25887 case Intrinsic::x86_sse41_ptestc:
25888 case Intrinsic::x86_avx_ptestc_256:
25889 // CF = 1
25890 X86CC = X86::COND_B;
25891 break;
25892 case Intrinsic::x86_avx_vtestnzc_ps:
25893 case Intrinsic::x86_avx_vtestnzc_pd:
25894 case Intrinsic::x86_avx_vtestnzc_ps_256:
25895 case Intrinsic::x86_avx_vtestnzc_pd_256:
25896 TestOpc = X86ISD::TESTP;
25897 LLVM_FALLTHROUGH[[gnu::fallthrough]];
25898 case Intrinsic::x86_sse41_ptestnzc:
25899 case Intrinsic::x86_avx_ptestnzc_256:
25900 // ZF and CF = 0
25901 X86CC = X86::COND_A;
25902 break;
25903 }
25904
25905 SDValue LHS = Op.getOperand(1);
25906 SDValue RHS = Op.getOperand(2);
25907 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
25908 SDValue SetCC = getSETCC(X86CC, Test, dl, DAG);
25909 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
25910 }
25911
25912 case Intrinsic::x86_sse42_pcmpistria128:
25913 case Intrinsic::x86_sse42_pcmpestria128:
25914 case Intrinsic::x86_sse42_pcmpistric128:
25915 case Intrinsic::x86_sse42_pcmpestric128:
25916 case Intrinsic::x86_sse42_pcmpistrio128:
25917 case Intrinsic::x86_sse42_pcmpestrio128:
25918 case Intrinsic::x86_sse42_pcmpistris128:
25919 case Intrinsic::x86_sse42_pcmpestris128:
25920 case Intrinsic::x86_sse42_pcmpistriz128:
25921 case Intrinsic::x86_sse42_pcmpestriz128: {
25922 unsigned Opcode;
25923 X86::CondCode X86CC;
25924 switch (IntNo) {
25925 default: llvm_unreachable("Impossible intrinsic")::llvm::llvm_unreachable_internal("Impossible intrinsic", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 25925)
; // Can't reach here.
25926 case Intrinsic::x86_sse42_pcmpistria128:
25927 Opcode = X86ISD::PCMPISTR;
25928 X86CC = X86::COND_A;
25929 break;
25930 case Intrinsic::x86_sse42_pcmpestria128:
25931 Opcode = X86ISD::PCMPESTR;
25932 X86CC = X86::COND_A;
25933 break;
25934 case Intrinsic::x86_sse42_pcmpistric128:
25935 Opcode = X86ISD::PCMPISTR;
25936 X86CC = X86::COND_B;
25937 break;
25938 case Intrinsic::x86_sse42_pcmpestric128:
25939 Opcode = X86ISD::PCMPESTR;
25940 X86CC = X86::COND_B;
25941 break;
25942 case Intrinsic::x86_sse42_pcmpistrio128:
25943 Opcode = X86ISD::PCMPISTR;
25944 X86CC = X86::COND_O;
25945 break;
25946 case Intrinsic::x86_sse42_pcmpestrio128:
25947 Opcode = X86ISD::PCMPESTR;
25948 X86CC = X86::COND_O;
25949 break;
25950 case Intrinsic::x86_sse42_pcmpistris128:
25951 Opcode = X86ISD::PCMPISTR;
25952 X86CC = X86::COND_S;
25953 break;
25954 case Intrinsic::x86_sse42_pcmpestris128:
25955 Opcode = X86ISD::PCMPESTR;
25956 X86CC = X86::COND_S;
25957 break;
25958 case Intrinsic::x86_sse42_pcmpistriz128:
25959 Opcode = X86ISD::PCMPISTR;
25960 X86CC = X86::COND_E;
25961 break;
25962 case Intrinsic::x86_sse42_pcmpestriz128:
25963 Opcode = X86ISD::PCMPESTR;
25964 X86CC = X86::COND_E;
25965 break;
25966 }
25967 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
25968 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
25969 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps).getValue(2);
25970 SDValue SetCC = getSETCC(X86CC, PCMP, dl, DAG);
25971 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
25972 }
25973
25974 case Intrinsic::x86_sse42_pcmpistri128:
25975 case Intrinsic::x86_sse42_pcmpestri128: {
25976 unsigned Opcode;
25977 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
25978 Opcode = X86ISD::PCMPISTR;
25979 else
25980 Opcode = X86ISD::PCMPESTR;
25981
25982 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
25983 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
25984 return DAG.getNode(Opcode, dl, VTs, NewOps);
25985 }
25986
25987 case Intrinsic::x86_sse42_pcmpistrm128:
25988 case Intrinsic::x86_sse42_pcmpestrm128: {
25989 unsigned Opcode;
25990 if (IntNo == Intrinsic::x86_sse42_pcmpistrm128)
25991 Opcode = X86ISD::PCMPISTR;
25992 else
25993 Opcode = X86ISD::PCMPESTR;
25994
25995 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
25996 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
25997 return DAG.getNode(Opcode, dl, VTs, NewOps).getValue(1);
25998 }
25999
26000 case Intrinsic::eh_sjlj_lsda: {
26001 MachineFunction &MF = DAG.getMachineFunction();
26002 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26003 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
26004 auto &Context = MF.getMMI().getContext();
26005 MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
26006 Twine(MF.getFunctionNumber()));
26007 return DAG.getNode(getGlobalWrapperKind(), dl, VT,
26008 DAG.getMCSymbol(S, PtrVT));
26009 }
26010
26011 case Intrinsic::x86_seh_lsda: {
26012 // Compute the symbol for the LSDA. We know it'll get emitted later.
26013 MachineFunction &MF = DAG.getMachineFunction();
26014 SDValue Op1 = Op.getOperand(1);
26015 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
26016 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
26017 GlobalValue::dropLLVMManglingEscape(Fn->getName()));
26018
26019 // Generate a simple absolute symbol reference. This intrinsic is only
26020 // supported on 32-bit Windows, which isn't PIC.
26021 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
26022 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
26023 }
26024
26025 case Intrinsic::eh_recoverfp: {
26026 SDValue FnOp = Op.getOperand(1);
26027 SDValue IncomingFPOp = Op.getOperand(2);
26028 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
26029 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
26030 if (!Fn)
26031 report_fatal_error(
26032 "llvm.eh.recoverfp must take a function as the first argument");
26033 return recoverFramePointer(DAG, Fn, IncomingFPOp);
26034 }
26035
26036 case Intrinsic::localaddress: {
26037 // Returns one of the stack, base, or frame pointer registers, depending on
26038 // which is used to reference local variables.
26039 MachineFunction &MF = DAG.getMachineFunction();
26040 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
26041 unsigned Reg;
26042 if (RegInfo->hasBasePointer(MF))
26043 Reg = RegInfo->getBaseRegister();
26044 else { // Handles the SP or FP case.
26045 bool CantUseFP = RegInfo->hasStackRealignment(MF);
26046 if (CantUseFP)
26047 Reg = RegInfo->getPtrSizedStackRegister(MF);
26048 else
26049 Reg = RegInfo->getPtrSizedFrameRegister(MF);
26050 }
26051 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
26052 }
26053 case Intrinsic::swift_async_context_addr: {
26054 auto &MF = DAG.getMachineFunction();
26055 auto X86FI = MF.getInfo<X86MachineFunctionInfo>();
26056 if (Subtarget.is64Bit()) {
26057 MF.getFrameInfo().setFrameAddressIsTaken(true);
26058 X86FI->setHasSwiftAsyncContext(true);
26059 return SDValue(
26060 DAG.getMachineNode(
26061 X86::SUB64ri8, dl, MVT::i64,
26062 DAG.getCopyFromReg(DAG.getEntryNode(), dl, X86::RBP, MVT::i64),
26063 DAG.getTargetConstant(8, dl, MVT::i32)),
26064 0);
26065 } else {
26066 // 32-bit so no special extended frame, create or reuse an existing stack
26067 // slot.
26068 if (!X86FI->getSwiftAsyncContextFrameIdx())
26069 X86FI->setSwiftAsyncContextFrameIdx(
26070 MF.getFrameInfo().CreateStackObject(4, Align(4), false));
26071 return DAG.getFrameIndex(*X86FI->getSwiftAsyncContextFrameIdx(), MVT::i32);
26072 }
26073 }
26074 case Intrinsic::x86_avx512_vp2intersect_q_512:
26075 case Intrinsic::x86_avx512_vp2intersect_q_256:
26076 case Intrinsic::x86_avx512_vp2intersect_q_128:
26077 case Intrinsic::x86_avx512_vp2intersect_d_512:
26078 case Intrinsic::x86_avx512_vp2intersect_d_256:
26079 case Intrinsic::x86_avx512_vp2intersect_d_128: {
26080 MVT MaskVT = Op.getSimpleValueType();
26081
26082 SDVTList VTs = DAG.getVTList(MVT::Untyped, MVT::Other);
26083 SDLoc DL(Op);
26084
26085 SDValue Operation =
26086 DAG.getNode(X86ISD::VP2INTERSECT, DL, VTs,
26087 Op->getOperand(1), Op->getOperand(2));
26088
26089 SDValue Result0 = DAG.getTargetExtractSubreg(X86::sub_mask_0, DL,
26090 MaskVT, Operation);
26091 SDValue Result1 = DAG.getTargetExtractSubreg(X86::sub_mask_1, DL,
26092 MaskVT, Operation);
26093 return DAG.getMergeValues({Result0, Result1}, DL);
26094 }
26095 case Intrinsic::x86_mmx_pslli_w:
26096 case Intrinsic::x86_mmx_pslli_d:
26097 case Intrinsic::x86_mmx_pslli_q:
26098 case Intrinsic::x86_mmx_psrli_w:
26099 case Intrinsic::x86_mmx_psrli_d:
26100 case Intrinsic::x86_mmx_psrli_q:
26101 case Intrinsic::x86_mmx_psrai_w:
26102 case Intrinsic::x86_mmx_psrai_d: {
26103 SDLoc DL(Op);
26104 SDValue ShAmt = Op.getOperand(2);
26105 // If the argument is a constant, convert it to a target constant.
26106 if (auto *C = dyn_cast<ConstantSDNode>(ShAmt)) {
26107 // Clamp out of bounds shift amounts since they will otherwise be masked
26108 // to 8-bits which may make it no longer out of bounds.
26109 unsigned ShiftAmount = C->getAPIntValue().getLimitedValue(255);
26110 if (ShiftAmount == 0)
26111 return Op.getOperand(1);
26112
26113 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
26114 Op.getOperand(0), Op.getOperand(1),
26115 DAG.getTargetConstant(ShiftAmount, DL, MVT::i32));
26116 }
26117
26118 unsigned NewIntrinsic;
26119 switch (IntNo) {
26120 default: llvm_unreachable("Impossible intrinsic")::llvm::llvm_unreachable_internal("Impossible intrinsic", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 26120)
; // Can't reach here.
26121 case Intrinsic::x86_mmx_pslli_w:
26122 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
26123 break;
26124 case Intrinsic::x86_mmx_pslli_d:
26125 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
26126 break;
26127 case Intrinsic::x86_mmx_pslli_q:
26128 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
26129 break;
26130 case Intrinsic::x86_mmx_psrli_w:
26131 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
26132 break;
26133 case Intrinsic::x86_mmx_psrli_d:
26134 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
26135 break;
26136 case Intrinsic::x86_mmx_psrli_q:
26137 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
26138 break;
26139 case Intrinsic::x86_mmx_psrai_w:
26140 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
26141 break;
26142 case Intrinsic::x86_mmx_psrai_d:
26143 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
26144 break;
26145 }
26146
26147 // The vector shift intrinsics with scalars uses 32b shift amounts but
26148 // the sse2/mmx shift instructions reads 64 bits. Copy the 32 bits to an
26149 // MMX register.
26150 ShAmt = DAG.getNode(X86ISD::MMX_MOVW2D, DL, MVT::x86mmx, ShAmt);
26151 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
26152 DAG.getTargetConstant(NewIntrinsic, DL,
26153 getPointerTy(DAG.getDataLayout())),
26154 Op.getOperand(1), ShAmt);
26155 }
26156 }
26157}
26158
26159static SDValue getAVX2GatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
26160 SDValue Src, SDValue Mask, SDValue Base,
26161 SDValue Index, SDValue ScaleOp, SDValue Chain,
26162 const X86Subtarget &Subtarget) {
26163 SDLoc dl(Op);
26164 auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
26165 // Scale must be constant.
26166 if (!C)
26167 return SDValue();
26168 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26169 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
26170 TLI.getPointerTy(DAG.getDataLayout()));
26171 EVT MaskVT = Mask.getValueType().changeVectorElementTypeToInteger();
26172 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Other);
26173 // If source is undef or we know it won't be used, use a zero vector
26174 // to break register dependency.
26175 // TODO: use undef instead and let BreakFalseDeps deal with it?
26176 if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
26177 Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
26178
26179 // Cast mask to an integer type.
26180 Mask = DAG.getBitcast(MaskVT, Mask);
26181
26182 MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
26183
26184 SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale };
26185 SDValue Res =
26186 DAG.getMemIntrinsicNode(X86ISD::MGATHER, dl, VTs, Ops,
26187 MemIntr->getMemoryVT(), MemIntr->getMemOperand());
26188 return DAG.getMergeValues({Res, Res.getValue(1)}, dl);
26189}
26190
26191static SDValue getGatherNode(SDValue Op, SelectionDAG &DAG,
26192 SDValue Src, SDValue Mask, SDValue Base,
26193 SDValue Index, SDValue ScaleOp, SDValue Chain,
26194 const X86Subtarget &Subtarget) {
26195 MVT VT = Op.getSimpleValueType();
26196 SDLoc dl(Op);
26197 auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
26198 // Scale must be constant.
26199 if (!C)
26200 return SDValue();
26201 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26202 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
26203 TLI.getPointerTy(DAG.getDataLayout()));
26204 unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
26205 VT.getVectorNumElements());
26206 MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
26207
26208 // We support two versions of the gather intrinsics. One with scalar mask and
26209 // one with vXi1 mask. Convert scalar to vXi1 if necessary.
26210 if (Mask.getValueType() != MaskVT)
26211 Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26212
26213 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Other);
26214 // If source is undef or we know it won't be used, use a zero vector
26215 // to break register dependency.
26216 // TODO: use undef instead and let BreakFalseDeps deal with it?
26217 if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
26218 Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
26219
26220 MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
26221
26222 SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale };
26223 SDValue Res =
26224 DAG.getMemIntrinsicNode(X86ISD::MGATHER, dl, VTs, Ops,
26225 MemIntr->getMemoryVT(), MemIntr->getMemOperand());
26226 return DAG.getMergeValues({Res, Res.getValue(1)}, dl);
26227}
26228
26229static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
26230 SDValue Src, SDValue Mask, SDValue Base,
26231 SDValue Index, SDValue ScaleOp, SDValue Chain,
26232 const X86Subtarget &Subtarget) {
26233 SDLoc dl(Op);
26234 auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
26235 // Scale must be constant.
26236 if (!C)
26237 return SDValue();
26238 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26239 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
26240 TLI.getPointerTy(DAG.getDataLayout()));
26241 unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
26242 Src.getSimpleValueType().getVectorNumElements());
26243 MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
26244
26245 // We support two versions of the scatter intrinsics. One with scalar mask and
26246 // one with vXi1 mask. Convert scalar to vXi1 if necessary.
26247 if (Mask.getValueType() != MaskVT)
26248 Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26249
26250 MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
26251
26252 SDVTList VTs = DAG.getVTList(MVT::Other);
26253 SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale};
26254 SDValue Res =
26255 DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
26256 MemIntr->getMemoryVT(), MemIntr->getMemOperand());
26257 return Res;
26258}
26259
26260static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
26261 SDValue Mask, SDValue Base, SDValue Index,
26262 SDValue ScaleOp, SDValue Chain,
26263 const X86Subtarget &Subtarget) {
26264 SDLoc dl(Op);
26265 auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
26266 // Scale must be constant.
26267 if (!C)
26268 return SDValue();
26269 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26270 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
26271 TLI.getPointerTy(DAG.getDataLayout()));
26272 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
26273 SDValue Segment = DAG.getRegister(0, MVT::i32);
26274 MVT MaskVT =
26275 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
26276 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26277 SDValue Ops[] = {VMask, Base, Scale, Index, Disp, Segment, Chain};
26278 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
26279 return SDValue(Res, 0);
26280}
26281
26282/// Handles the lowering of builtin intrinsics with chain that return their
26283/// value into registers EDX:EAX.
26284/// If operand ScrReg is a valid register identifier, then operand 2 of N is
26285/// copied to SrcReg. The assumption is that SrcReg is an implicit input to
26286/// TargetOpcode.
26287/// Returns a Glue value which can be used to add extra copy-from-reg if the
26288/// expanded intrinsics implicitly defines extra registers (i.e. not just
26289/// EDX:EAX).
26290static SDValue expandIntrinsicWChainHelper(SDNode *N, const SDLoc &DL,
26291 SelectionDAG &DAG,
26292 unsigned TargetOpcode,
26293 unsigned SrcReg,
26294 const X86Subtarget &Subtarget,
26295 SmallVectorImpl<SDValue> &Results) {
26296 SDValue Chain = N->getOperand(0);
26297 SDValue Glue;
26298
26299 if (SrcReg) {
26300 assert(N->getNumOperands() == 3 && "Unexpected number of operands!")(static_cast <bool> (N->getNumOperands() == 3 &&
"Unexpected number of operands!") ? void (0) : __assert_fail
("N->getNumOperands() == 3 && \"Unexpected number of operands!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 26300, __extension__ __PRETTY_FUNCTION__))
;
26301 Chain = DAG.getCopyToReg(Chain, DL, SrcReg, N->getOperand(2), Glue);
26302 Glue = Chain.getValue(1);
26303 }
26304
26305 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
26306 SDValue N1Ops[] = {Chain, Glue};
26307 SDNode *N1 = DAG.getMachineNode(
26308 TargetOpcode, DL, Tys, ArrayRef<SDValue>(N1Ops, Glue.getNode() ? 2 : 1));
26309 Chain = SDValue(N1, 0);
26310
26311 // Reads the content of XCR and returns it in registers EDX:EAX.
26312 SDValue LO, HI;
26313 if (Subtarget.is64Bit()) {
26314 LO = DAG.getCopyFromReg(Chain, DL, X86::RAX, MVT::i64, SDValue(N1, 1));
26315 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
26316 LO.getValue(2));
26317 } else {
26318 LO = DAG.getCopyFromReg(Chain, DL, X86::EAX, MVT::i32, SDValue(N1, 1));
26319 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
26320 LO.getValue(2));
26321 }
26322 Chain = HI.getValue(1);
26323 Glue = HI.getValue(2);
26324
26325 if (Subtarget.is64Bit()) {
26326 // Merge the two 32-bit values into a 64-bit one.
26327 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
26328 DAG.getConstant(32, DL, MVT::i8));
26329 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
26330 Results.push_back(Chain);
26331 return Glue;
26332 }
26333
26334 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
26335 SDValue Ops[] = { LO, HI };
26336 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
26337 Results.push_back(Pair);
26338 Results.push_back(Chain);
26339 return Glue;
26340}
26341
26342/// Handles the lowering of builtin intrinsics that read the time stamp counter
26343/// (x86_rdtsc and x86_rdtscp). This function is also used to custom lower
26344/// READCYCLECOUNTER nodes.
26345static void getReadTimeStampCounter(SDNode *N, const SDLoc &DL, unsigned Opcode,
26346 SelectionDAG &DAG,
26347 const X86Subtarget &Subtarget,
26348 SmallVectorImpl<SDValue> &Results) {
26349 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
26350 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
26351 // and the EAX register is loaded with the low-order 32 bits.
26352 SDValue Glue = expandIntrinsicWChainHelper(N, DL, DAG, Opcode,
26353 /* NoRegister */0, Subtarget,
26354 Results);
26355 if (Opcode != X86::RDTSCP)
26356 return;
26357
26358 SDValue Chain = Results[1];
26359 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
26360 // the ECX register. Add 'ecx' explicitly to the chain.
26361 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32, Glue);
26362 Results[1] = ecx;
26363 Results.push_back(ecx.getValue(1));
26364}
26365
26366static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget &Subtarget,
26367 SelectionDAG &DAG) {
26368 SmallVector<SDValue, 3> Results;
26369 SDLoc DL(Op);
26370 getReadTimeStampCounter(Op.getNode(), DL, X86::RDTSC, DAG, Subtarget,
26371 Results);
26372 return DAG.getMergeValues(Results, DL);
26373}
26374
26375static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
26376 MachineFunction &MF = DAG.getMachineFunction();
26377 SDValue Chain = Op.getOperand(0);
26378 SDValue RegNode = Op.getOperand(2);
26379 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
26380 if (!EHInfo)
26381 report_fatal_error("EH registrations only live in functions using WinEH");
26382
26383 // Cast the operand to an alloca, and remember the frame index.
26384 auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
26385 if (!FINode)
26386 report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
26387 EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
26388
26389 // Return the chain operand without making any DAG nodes.
26390 return Chain;
26391}
26392
26393static SDValue MarkEHGuard(SDValue Op, SelectionDAG &DAG) {
26394 MachineFunction &MF = DAG.getMachineFunction();
26395 SDValue Chain = Op.getOperand(0);
26396 SDValue EHGuard = Op.getOperand(2);
26397 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
26398 if (!EHInfo)
26399 report_fatal_error("EHGuard only live in functions using WinEH");
26400
26401 // Cast the operand to an alloca, and remember the frame index.
26402 auto *FINode = dyn_cast<FrameIndexSDNode>(EHGuard);
26403 if (!FINode)
26404 report_fatal_error("llvm.x86.seh.ehguard expects a static alloca");
26405 EHInfo->EHGuardFrameIndex = FINode->getIndex();
26406
26407 // Return the chain operand without making any DAG nodes.
26408 return Chain;
26409}
26410
26411/// Emit Truncating Store with signed or unsigned saturation.
26412static SDValue
26413EmitTruncSStore(bool SignedSat, SDValue Chain, const SDLoc &Dl, SDValue Val,
26414 SDValue Ptr, EVT MemVT, MachineMemOperand *MMO,
26415 SelectionDAG &DAG) {
26416 SDVTList VTs = DAG.getVTList(MVT::Other);
26417 SDValue Undef = DAG.getUNDEF(Ptr.getValueType());
26418 SDValue Ops[] = { Chain, Val, Ptr, Undef };
26419 unsigned Opc = SignedSat ? X86ISD::VTRUNCSTORES : X86ISD::VTRUNCSTOREUS;
26420 return DAG.getMemIntrinsicNode(Opc, Dl, VTs, Ops, MemVT, MMO);
26421}
26422
26423/// Emit Masked Truncating Store with signed or unsigned saturation.
26424static SDValue
26425EmitMaskedTruncSStore(bool SignedSat, SDValue Chain, const SDLoc &Dl,
26426 SDValue Val, SDValue Ptr, SDValue Mask, EVT MemVT,
26427 MachineMemOperand *MMO, SelectionDAG &DAG) {
26428 SDVTList VTs = DAG.getVTList(MVT::Other);
26429 SDValue Ops[] = { Chain, Val, Ptr, Mask };
26430 unsigned Opc = SignedSat ? X86ISD::VMTRUNCSTORES : X86ISD::VMTRUNCSTOREUS;
26431 return DAG.getMemIntrinsicNode(Opc, Dl, VTs, Ops, MemVT, MMO);
26432}
26433
26434static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget &Subtarget,
26435 SelectionDAG &DAG) {
26436 unsigned IntNo = Op.getConstantOperandVal(1);
26437 const IntrinsicData *IntrData = getIntrinsicWithChain(IntNo);
26438 if (!IntrData) {
26439 switch (IntNo) {
26440 case llvm::Intrinsic::x86_seh_ehregnode:
26441 return MarkEHRegistrationNode(Op, DAG);
26442 case llvm::Intrinsic::x86_seh_ehguard:
26443 return MarkEHGuard(Op, DAG);
26444 case llvm::Intrinsic::x86_rdpkru: {
26445 SDLoc dl(Op);
26446 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
26447 // Create a RDPKRU node and pass 0 to the ECX parameter.
26448 return DAG.getNode(X86ISD::RDPKRU, dl, VTs, Op.getOperand(0),
26449 DAG.getConstant(0, dl, MVT::i32));
26450 }
26451 case llvm::Intrinsic::x86_wrpkru: {
26452 SDLoc dl(Op);
26453 // Create a WRPKRU node, pass the input to the EAX parameter, and pass 0
26454 // to the EDX and ECX parameters.
26455 return DAG.getNode(X86ISD::WRPKRU, dl, MVT::Other,
26456 Op.getOperand(0), Op.getOperand(2),
26457 DAG.getConstant(0, dl, MVT::i32),
26458 DAG.getConstant(0, dl, MVT::i32));
26459 }
26460 case llvm::Intrinsic::x86_flags_read_u32:
26461 case llvm::Intrinsic::x86_flags_read_u64:
26462 case llvm::Intrinsic::x86_flags_write_u32:
26463 case llvm::Intrinsic::x86_flags_write_u64: {
26464 // We need a frame pointer because this will get lowered to a PUSH/POP
26465 // sequence.
26466 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
26467 MFI.setHasCopyImplyingStackAdjustment(true);
26468 // Don't do anything here, we will expand these intrinsics out later
26469 // during FinalizeISel in EmitInstrWithCustomInserter.
26470 return Op;
26471 }
26472 case Intrinsic::x86_lwpins32:
26473 case Intrinsic::x86_lwpins64:
26474 case Intrinsic::x86_umwait:
26475 case Intrinsic::x86_tpause: {
26476 SDLoc dl(Op);
26477 SDValue Chain = Op->getOperand(0);
26478 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
26479 unsigned Opcode;
26480
26481 switch (IntNo) {
26482 default: llvm_unreachable("Impossible intrinsic")::llvm::llvm_unreachable_internal("Impossible intrinsic", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 26482)
;
26483 case Intrinsic::x86_umwait:
26484 Opcode = X86ISD::UMWAIT;
26485 break;
26486 case Intrinsic::x86_tpause:
26487 Opcode = X86ISD::TPAUSE;
26488 break;
26489 case Intrinsic::x86_lwpins32:
26490 case Intrinsic::x86_lwpins64:
26491 Opcode = X86ISD::LWPINS;
26492 break;
26493 }
26494
26495 SDValue Operation =
26496 DAG.getNode(Opcode, dl, VTs, Chain, Op->getOperand(2),
26497 Op->getOperand(3), Op->getOperand(4));
26498 SDValue SetCC = getSETCC(X86::COND_B, Operation.getValue(0), dl, DAG);
26499 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
26500 Operation.getValue(1));
26501 }
26502 case Intrinsic::x86_enqcmd:
26503 case Intrinsic::x86_enqcmds: {
26504 SDLoc dl(Op);
26505 SDValue Chain = Op.getOperand(0);
26506 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
26507 unsigned Opcode;
26508 switch (IntNo) {
26509 default: llvm_unreachable("Impossible intrinsic!")::llvm::llvm_unreachable_internal("Impossible intrinsic!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 26509)
;
26510 case Intrinsic::x86_enqcmd:
26511 Opcode = X86ISD::ENQCMD;
26512 break;
26513 case Intrinsic::x86_enqcmds:
26514 Opcode = X86ISD::ENQCMDS;
26515 break;
26516 }
26517 SDValue Operation = DAG.getNode(Opcode, dl, VTs, Chain, Op.getOperand(2),
26518 Op.getOperand(3));
26519 SDValue SetCC = getSETCC(X86::COND_E, Operation.getValue(0), dl, DAG);
26520 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
26521 Operation.getValue(1));
26522 }
26523 case Intrinsic::x86_aesenc128kl:
26524 case Intrinsic::x86_aesdec128kl:
26525 case Intrinsic::x86_aesenc256kl:
26526 case Intrinsic::x86_aesdec256kl: {
26527 SDLoc DL(Op);
26528 SDVTList VTs = DAG.getVTList(MVT::v2i64, MVT::i32, MVT::Other);
26529 SDValue Chain = Op.getOperand(0);
26530 unsigned Opcode;
26531
26532 switch (IntNo) {
26533 default: llvm_unreachable("Impossible intrinsic")::llvm::llvm_unreachable_internal("Impossible intrinsic", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 26533)
;
26534 case Intrinsic::x86_aesenc128kl:
26535 Opcode = X86ISD::AESENC128KL;
26536 break;
26537 case Intrinsic::x86_aesdec128kl:
26538 Opcode = X86ISD::AESDEC128KL;
26539 break;
26540 case Intrinsic::x86_aesenc256kl:
26541 Opcode = X86ISD::AESENC256KL;
26542 break;
26543 case Intrinsic::x86_aesdec256kl:
26544 Opcode = X86ISD::AESDEC256KL;
26545 break;
26546 }
26547
26548 MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
26549 MachineMemOperand *MMO = MemIntr->getMemOperand();
26550 EVT MemVT = MemIntr->getMemoryVT();
26551 SDValue Operation = DAG.getMemIntrinsicNode(
26552 Opcode, DL, VTs, {Chain, Op.getOperand(2), Op.getOperand(3)}, MemVT,
26553 MMO);
26554 SDValue ZF = getSETCC(X86::COND_E, Operation.getValue(1), DL, DAG);
26555
26556 return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
26557 {ZF, Operation.getValue(0), Operation.getValue(2)});
26558 }
26559 case Intrinsic::x86_aesencwide128kl:
26560 case Intrinsic::x86_aesdecwide128kl:
26561 case Intrinsic::x86_aesencwide256kl:
26562 case Intrinsic::x86_aesdecwide256kl: {
26563 SDLoc DL(Op);
26564 SDVTList VTs = DAG.getVTList(
26565 {MVT::i32, MVT::v2i64, MVT::v2i64, MVT::v2i64, MVT::v2i64, MVT::v2i64,
26566 MVT::v2i64, MVT::v2i64, MVT::v2i64, MVT::Other});
26567 SDValue Chain = Op.getOperand(0);
26568 unsigned Opcode;
26569
26570 switch (IntNo) {
26571 default: llvm_unreachable("Impossible intrinsic")::llvm::llvm_unreachable_internal("Impossible intrinsic", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 26571)
;
26572 case Intrinsic::x86_aesencwide128kl:
26573 Opcode = X86ISD::AESENCWIDE128KL;
26574 break;
26575 case Intrinsic::x86_aesdecwide128kl:
26576 Opcode = X86ISD::AESDECWIDE128KL;
26577 break;
26578 case Intrinsic::x86_aesencwide256kl:
26579 Opcode = X86ISD::AESENCWIDE256KL;
26580 break;
26581 case Intrinsic::x86_aesdecwide256kl:
26582 Opcode = X86ISD::AESDECWIDE256KL;
26583 break;
26584 }
26585
26586 MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
26587 MachineMemOperand *MMO = MemIntr->getMemOperand();
26588 EVT MemVT = MemIntr->getMemoryVT();
26589 SDValue Operation = DAG.getMemIntrinsicNode(
26590 Opcode, DL, VTs,
26591 {Chain, Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
26592 Op.getOperand(5), Op.getOperand(6), Op.getOperand(7),
26593 Op.getOperand(8), Op.getOperand(9), Op.getOperand(10)},
26594 MemVT, MMO);
26595 SDValue ZF = getSETCC(X86::COND_E, Operation.getValue(0), DL, DAG);
26596
26597 return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
26598 {ZF, Operation.getValue(1), Operation.getValue(2),
26599 Operation.getValue(3), Operation.getValue(4),
26600 Operation.getValue(5), Operation.getValue(6),
26601 Operation.getValue(7), Operation.getValue(8),
26602 Operation.getValue(9)});
26603 }
26604 case Intrinsic::x86_testui: {
26605 SDLoc dl(Op);
26606 SDValue Chain = Op.getOperand(0);
26607 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
26608 SDValue Operation = DAG.getNode(X86ISD::TESTUI, dl, VTs, Chain);
26609 SDValue SetCC = getSETCC(X86::COND_B, Operation.getValue(0), dl, DAG);
26610 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
26611 Operation.getValue(1));
26612 }
26613 }
26614 return SDValue();
26615 }
26616
26617 SDLoc dl(Op);
26618 switch(IntrData->Type) {
26619 default: llvm_unreachable("Unknown Intrinsic Type")::llvm::llvm_unreachable_internal("Unknown Intrinsic Type", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 26619)
;
26620 case RDSEED:
26621 case RDRAND: {
26622 // Emit the node with the right value type.
26623 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32, MVT::Other);
26624 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
26625
26626 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
26627 // Otherwise return the value from Rand, which is always 0, casted to i32.
26628 SDValue Ops[] = {DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
26629 DAG.getConstant(1, dl, Op->getValueType(1)),
26630 DAG.getTargetConstant(X86::COND_B, dl, MVT::i8),
26631 SDValue(Result.getNode(), 1)};
26632 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl, Op->getValueType(1), Ops);
26633
26634 // Return { result, isValid, chain }.
26635 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
26636 SDValue(Result.getNode(), 2));
26637 }
26638 case GATHER_AVX2: {
26639 SDValue Chain = Op.getOperand(0);
26640 SDValue Src = Op.getOperand(2);
26641 SDValue Base = Op.getOperand(3);
26642 SDValue Index = Op.getOperand(4);
26643 SDValue Mask = Op.getOperand(5);
26644 SDValue Scale = Op.getOperand(6);
26645 return getAVX2GatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
26646 Scale, Chain, Subtarget);
26647 }
26648 case GATHER: {
26649 //gather(v1, mask, index, base, scale);
26650 SDValue Chain = Op.getOperand(0);
26651 SDValue Src = Op.getOperand(2);
26652 SDValue Base = Op.getOperand(3);
26653 SDValue Index = Op.getOperand(4);
26654 SDValue Mask = Op.getOperand(5);
26655 SDValue Scale = Op.getOperand(6);
26656 return getGatherNode(Op, DAG, Src, Mask, Base, Index, Scale,
26657 Chain, Subtarget);
26658 }
26659 case SCATTER: {
26660 //scatter(base, mask, index, v1, scale);
26661 SDValue Chain = Op.getOperand(0);
26662 SDValue Base = Op.getOperand(2);
26663 SDValue Mask = Op.getOperand(3);
26664 SDValue Index = Op.getOperand(4);
26665 SDValue Src = Op.getOperand(5);
26666 SDValue Scale = Op.getOperand(6);
26667 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
26668 Scale, Chain, Subtarget);
26669 }
26670 case PREFETCH: {
26671 const APInt &HintVal = Op.getConstantOperandAPInt(6);
26672 assert((HintVal == 2 || HintVal == 3) &&(static_cast <bool> ((HintVal == 2 || HintVal == 3) &&
"Wrong prefetch hint in intrinsic: should be 2 or 3") ? void
(0) : __assert_fail ("(HintVal == 2 || HintVal == 3) && \"Wrong prefetch hint in intrinsic: should be 2 or 3\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 26673, __extension__ __PRETTY_FUNCTION__))
26673 "Wrong prefetch hint in intrinsic: should be 2 or 3")(static_cast <bool> ((HintVal == 2 || HintVal == 3) &&
"Wrong prefetch hint in intrinsic: should be 2 or 3") ? void
(0) : __assert_fail ("(HintVal == 2 || HintVal == 3) && \"Wrong prefetch hint in intrinsic: should be 2 or 3\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 26673, __extension__ __PRETTY_FUNCTION__))
;
26674 unsigned Opcode = (HintVal == 2 ? IntrData->Opc1 : IntrData->Opc0);
26675 SDValue Chain = Op.getOperand(0);
26676 SDValue Mask = Op.getOperand(2);
26677 SDValue Index = Op.getOperand(3);
26678 SDValue Base = Op.getOperand(4);
26679 SDValue Scale = Op.getOperand(5);
26680 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain,
26681 Subtarget);
26682 }
26683 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
26684 case RDTSC: {
26685 SmallVector<SDValue, 2> Results;
26686 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
26687 Results);
26688 return DAG.getMergeValues(Results, dl);
26689 }
26690 // Read Performance Monitoring Counters.
26691 case RDPMC:
26692 // GetExtended Control Register.
26693 case XGETBV: {
26694 SmallVector<SDValue, 2> Results;
26695
26696 // RDPMC uses ECX to select the index of the performance counter to read.
26697 // XGETBV uses ECX to select the index of the XCR register to return.
26698 // The result is stored into registers EDX:EAX.
26699 expandIntrinsicWChainHelper(Op.getNode(), dl, DAG, IntrData->Opc0, X86::ECX,
26700 Subtarget, Results);
26701 return DAG.getMergeValues(Results, dl);
26702 }
26703 // XTEST intrinsics.
26704 case XTEST: {
26705 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
26706 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
26707
26708 SDValue SetCC = getSETCC(X86::COND_NE, InTrans, dl, DAG);
26709 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
26710 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
26711 Ret, SDValue(InTrans.getNode(), 1));
26712 }
26713 case TRUNCATE_TO_MEM_VI8:
26714 case TRUNCATE_TO_MEM_VI16:
26715 case TRUNCATE_TO_MEM_VI32: {
26716 SDValue Mask = Op.getOperand(4);
26717 SDValue DataToTruncate = Op.getOperand(3);
26718 SDValue Addr = Op.getOperand(2);
26719 SDValue Chain = Op.getOperand(0);
26720
26721 MemIntrinsicSDNode *MemIntr = dyn_cast<MemIntrinsicSDNode>(Op);
26722 assert(MemIntr && "Expected MemIntrinsicSDNode!")(static_cast <bool> (MemIntr && "Expected MemIntrinsicSDNode!"
) ? void (0) : __assert_fail ("MemIntr && \"Expected MemIntrinsicSDNode!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 26722, __extension__ __PRETTY_FUNCTION__))
;
26723
26724 EVT MemVT = MemIntr->getMemoryVT();
26725
26726 uint16_t TruncationOp = IntrData->Opc0;
26727 switch (TruncationOp) {
26728 case X86ISD::VTRUNC: {
26729 if (isAllOnesConstant(Mask)) // return just a truncate store
26730 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr, MemVT,
26731 MemIntr->getMemOperand());
26732
26733 MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
26734 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26735 SDValue Offset = DAG.getUNDEF(VMask.getValueType());
26736
26737 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr, Offset, VMask,
26738 MemVT, MemIntr->getMemOperand(), ISD::UNINDEXED,
26739 true /* truncating */);
26740 }
26741 case X86ISD::VTRUNCUS:
26742 case X86ISD::VTRUNCS: {
26743 bool IsSigned = (TruncationOp == X86ISD::VTRUNCS);
26744 if (isAllOnesConstant(Mask))
26745 return EmitTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr, MemVT,
26746 MemIntr->getMemOperand(), DAG);
26747
26748 MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
26749 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26750
26751 return EmitMaskedTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr,
26752 VMask, MemVT, MemIntr->getMemOperand(), DAG);
26753 }
26754 default:
26755 llvm_unreachable("Unsupported truncstore intrinsic")::llvm::llvm_unreachable_internal("Unsupported truncstore intrinsic"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 26755)
;
26756 }
26757 }
26758 }
26759}
26760
26761SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
26762 SelectionDAG &DAG) const {
26763 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
26764 MFI.setReturnAddressIsTaken(true);
26765
26766 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
26767 return SDValue();
26768
26769 unsigned Depth = Op.getConstantOperandVal(0);
26770 SDLoc dl(Op);
26771 EVT PtrVT = getPointerTy(DAG.getDataLayout());
26772
26773 if (Depth > 0) {
26774 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
26775 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
26776 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
26777 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
26778 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
26779 MachinePointerInfo());
26780 }
26781
26782 // Just load the return address.
26783 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
26784 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
26785 MachinePointerInfo());
26786}
26787
26788SDValue X86TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
26789 SelectionDAG &DAG) const {
26790 DAG.getMachineFunction().getFrameInfo().setReturnAddressIsTaken(true);
26791 return getReturnAddressFrameIndex(DAG);
26792}
26793
26794SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
26795 MachineFunction &MF = DAG.getMachineFunction();
26796 MachineFrameInfo &MFI = MF.getFrameInfo();
26797 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
26798 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
26799 EVT VT = Op.getValueType();
26800
26801 MFI.setFrameAddressIsTaken(true);
26802
26803 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
26804 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
26805 // is not possible to crawl up the stack without looking at the unwind codes
26806 // simultaneously.
26807 int FrameAddrIndex = FuncInfo->getFAIndex();
26808 if (!FrameAddrIndex) {
26809 // Set up a frame object for the return address.
26810 unsigned SlotSize = RegInfo->getSlotSize();
26811 FrameAddrIndex = MF.getFrameInfo().CreateFixedObject(
26812 SlotSize, /*SPOffset=*/0, /*IsImmutable=*/false);
26813 FuncInfo->setFAIndex(FrameAddrIndex);
26814 }
26815 return DAG.getFrameIndex(FrameAddrIndex, VT);
26816 }
26817
26818 unsigned FrameReg =
26819 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
26820 SDLoc dl(Op); // FIXME probably not meaningful
26821 unsigned Depth = Op.getConstantOperandVal(0);
26822 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||(static_cast <bool> (((FrameReg == X86::RBP && VT
== MVT::i64) || (FrameReg == X86::EBP && VT == MVT::
i32)) && "Invalid Frame Register!") ? void (0) : __assert_fail
("((FrameReg == X86::RBP && VT == MVT::i64) || (FrameReg == X86::EBP && VT == MVT::i32)) && \"Invalid Frame Register!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 26824, __extension__ __PRETTY_FUNCTION__))
26823 (FrameReg == X86::EBP && VT == MVT::i32)) &&(static_cast <bool> (((FrameReg == X86::RBP && VT
== MVT::i64) || (FrameReg == X86::EBP && VT == MVT::
i32)) && "Invalid Frame Register!") ? void (0) : __assert_fail
("((FrameReg == X86::RBP && VT == MVT::i64) || (FrameReg == X86::EBP && VT == MVT::i32)) && \"Invalid Frame Register!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 26824, __extension__ __PRETTY_FUNCTION__))
26824 "Invalid Frame Register!")(static_cast <bool> (((FrameReg == X86::RBP && VT
== MVT::i64) || (FrameReg == X86::EBP && VT == MVT::
i32)) && "Invalid Frame Register!") ? void (0) : __assert_fail
("((FrameReg == X86::RBP && VT == MVT::i64) || (FrameReg == X86::EBP && VT == MVT::i32)) && \"Invalid Frame Register!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 26824, __extension__ __PRETTY_FUNCTION__))
;
26825 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
26826 while (Depth--)
26827 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
26828 MachinePointerInfo());
26829 return FrameAddr;
26830}
26831
26832// FIXME? Maybe this could be a TableGen attribute on some registers and
26833// this table could be generated automatically from RegInfo.
26834Register X86TargetLowering::getRegisterByName(const char* RegName, LLT VT,
26835 const MachineFunction &MF) const {
26836 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
26837
26838 Register Reg = StringSwitch<unsigned>(RegName)
26839 .Case("esp", X86::ESP)
26840 .Case("rsp", X86::RSP)
26841 .Case("ebp", X86::EBP)
26842 .Case("rbp", X86::RBP)
26843 .Default(0);
26844
26845 if (Reg == X86::EBP || Reg == X86::RBP) {
26846 if (!TFI.hasFP(MF))
26847 report_fatal_error("register " + StringRef(RegName) +
26848 " is allocatable: function has no frame pointer");
26849#ifndef NDEBUG
26850 else {
26851 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
26852 Register FrameReg = RegInfo->getPtrSizedFrameRegister(MF);
26853 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&(static_cast <bool> ((FrameReg == X86::EBP || FrameReg ==
X86::RBP) && "Invalid Frame Register!") ? void (0) :
__assert_fail ("(FrameReg == X86::EBP || FrameReg == X86::RBP) && \"Invalid Frame Register!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 26854, __extension__ __PRETTY_FUNCTION__))
26854 "Invalid Frame Register!")(static_cast <bool> ((FrameReg == X86::EBP || FrameReg ==
X86::RBP) && "Invalid Frame Register!") ? void (0) :
__assert_fail ("(FrameReg == X86::EBP || FrameReg == X86::RBP) && \"Invalid Frame Register!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 26854, __extension__ __PRETTY_FUNCTION__))
;
26855 }
26856#endif
26857 }
26858
26859 if (Reg)
26860 return Reg;
26861
26862 report_fatal_error("Invalid register name global variable");
26863}
26864
26865SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
26866 SelectionDAG &DAG) const {
26867 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
26868 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
26869}
26870
26871Register X86TargetLowering::getExceptionPointerRegister(
26872 const Constant *PersonalityFn) const {
26873 if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
26874 return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
26875
26876 return Subtarget.isTarget64BitLP64() ? X86::RAX : X86::EAX;
26877}
26878
26879Register X86TargetLowering::getExceptionSelectorRegister(
26880 const Constant *PersonalityFn) const {
26881 // Funclet personalities don't use selectors (the runtime does the selection).
26882 if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))
26883 return X86::NoRegister;
26884 return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
26885}
26886
26887bool X86TargetLowering::needsFixedCatchObjects() const {
26888 return Subtarget.isTargetWin64();
26889}
26890
26891SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
26892 SDValue Chain = Op.getOperand(0);
26893 SDValue Offset = Op.getOperand(1);
26894 SDValue Handler = Op.getOperand(2);
26895 SDLoc dl (Op);
26896
26897 EVT PtrVT = getPointerTy(DAG.getDataLayout());
26898 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
26899 Register FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
26900 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||(static_cast <bool> (((FrameReg == X86::RBP && PtrVT
== MVT::i64) || (FrameReg == X86::EBP && PtrVT == MVT
::i32)) && "Invalid Frame Register!") ? void (0) : __assert_fail
("((FrameReg == X86::RBP && PtrVT == MVT::i64) || (FrameReg == X86::EBP && PtrVT == MVT::i32)) && \"Invalid Frame Register!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 26902, __extension__ __PRETTY_FUNCTION__))
26901 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&(static_cast <bool> (((FrameReg == X86::RBP && PtrVT
== MVT::i64) || (FrameReg == X86::EBP && PtrVT == MVT
::i32)) && "Invalid Frame Register!") ? void (0) : __assert_fail
("((FrameReg == X86::RBP && PtrVT == MVT::i64) || (FrameReg == X86::EBP && PtrVT == MVT::i32)) && \"Invalid Frame Register!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 26902, __extension__ __PRETTY_FUNCTION__))
26902 "Invalid Frame Register!")(static_cast <bool> (((FrameReg == X86::RBP && PtrVT
== MVT::i64) || (FrameReg == X86::EBP && PtrVT == MVT
::i32)) && "Invalid Frame Register!") ? void (0) : __assert_fail
("((FrameReg == X86::RBP && PtrVT == MVT::i64) || (FrameReg == X86::EBP && PtrVT == MVT::i32)) && \"Invalid Frame Register!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 26902, __extension__ __PRETTY_FUNCTION__))
;
26903 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
26904 Register StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
26905
26906 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
26907 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
26908 dl));
26909 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
26910 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo());
26911 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
26912
26913 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
26914 DAG.getRegister(StoreAddrReg, PtrVT));
26915}
26916
26917SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
26918 SelectionDAG &DAG) const {
26919 SDLoc DL(Op);
26920 // If the subtarget is not 64bit, we may need the global base reg
26921 // after isel expand pseudo, i.e., after CGBR pass ran.
26922 // Therefore, ask for the GlobalBaseReg now, so that the pass
26923 // inserts the code for us in case we need it.
26924 // Otherwise, we will end up in a situation where we will
26925 // reference a virtual register that is not defined!
26926 if (!Subtarget.is64Bit()) {
26927 const X86InstrInfo *TII = Subtarget.getInstrInfo();
26928 (void)TII->getGlobalBaseReg(&DAG.getMachineFunction());
26929 }
26930 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
26931 DAG.getVTList(MVT::i32, MVT::Other),
26932 Op.getOperand(0), Op.getOperand(1));
26933}
26934
26935SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
26936 SelectionDAG &DAG) const {
26937 SDLoc DL(Op);
26938 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
26939 Op.getOperand(0), Op.getOperand(1));
26940}
26941
26942SDValue X86TargetLowering::lowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
26943 SelectionDAG &DAG) const {
26944 SDLoc DL(Op);
26945 return DAG.getNode(X86ISD::EH_SJLJ_SETUP_DISPATCH, DL, MVT::Other,
26946 Op.getOperand(0));
26947}
26948
26949static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
26950 return Op.getOperand(0);
26951}
26952
26953SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
26954 SelectionDAG &DAG) const {
26955 SDValue Root = Op.getOperand(0);
26956 SDValue Trmp = Op.getOperand(1); // trampoline
26957 SDValue FPtr = Op.getOperand(2); // nested function
26958 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
26959 SDLoc dl (Op);
26960
26961 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
26962 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
26963
26964 if (Subtarget.is64Bit()) {
26965 SDValue OutChains[6];
26966
26967 // Large code-model.
26968 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
26969 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
26970
26971 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
26972 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
26973
26974 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
26975
26976 // Load the pointer to the nested function into R11.
26977 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
26978 SDValue Addr = Trmp;
26979 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
26980 Addr, MachinePointerInfo(TrmpAddr));
26981
26982 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
26983 DAG.getConstant(2, dl, MVT::i64));
26984 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
26985 MachinePointerInfo(TrmpAddr, 2), Align(2));
26986
26987 // Load the 'nest' parameter value into R10.
26988 // R10 is specified in X86CallingConv.td
26989 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
26990 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
26991 DAG.getConstant(10, dl, MVT::i64));
26992 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
26993 Addr, MachinePointerInfo(TrmpAddr, 10));
26994
26995 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
26996 DAG.getConstant(12, dl, MVT::i64));
26997 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
26998 MachinePointerInfo(TrmpAddr, 12), Align(2));
26999
27000 // Jump to the nested function.
27001 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
27002 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
27003 DAG.getConstant(20, dl, MVT::i64));
27004 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
27005 Addr, MachinePointerInfo(TrmpAddr, 20));
27006
27007 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
27008 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
27009 DAG.getConstant(22, dl, MVT::i64));
27010 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
27011 Addr, MachinePointerInfo(TrmpAddr, 22));
27012
27013 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
27014 } else {
27015 const Function *Func =
27016 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
27017 CallingConv::ID CC = Func->getCallingConv();
27018 unsigned NestReg;
27019
27020 switch (CC) {
27021 default:
27022 llvm_unreachable("Unsupported calling convention")::llvm::llvm_unreachable_internal("Unsupported calling convention"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27022)
;
27023 case CallingConv::C:
27024 case CallingConv::X86_StdCall: {
27025 // Pass 'nest' parameter in ECX.
27026 // Must be kept in sync with X86CallingConv.td
27027 NestReg = X86::ECX;
27028
27029 // Check that ECX wasn't needed by an 'inreg' parameter.
27030 FunctionType *FTy = Func->getFunctionType();
27031 const AttributeList &Attrs = Func->getAttributes();
27032
27033 if (!Attrs.isEmpty() && !Func->isVarArg()) {
27034 unsigned InRegCount = 0;
27035 unsigned Idx = 1;
27036
27037 for (FunctionType::param_iterator I = FTy->param_begin(),
27038 E = FTy->param_end(); I != E; ++I, ++Idx)
27039 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
27040 const DataLayout &DL = DAG.getDataLayout();
27041 // FIXME: should only count parameters that are lowered to integers.
27042 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
27043 }
27044
27045 if (InRegCount > 2) {
27046 report_fatal_error("Nest register in use - reduce number of inreg"
27047 " parameters!");
27048 }
27049 }
27050 break;
27051 }
27052 case CallingConv::X86_FastCall:
27053 case CallingConv::X86_ThisCall:
27054 case CallingConv::Fast:
27055 case CallingConv::Tail:
27056 case CallingConv::SwiftTail:
27057 // Pass 'nest' parameter in EAX.
27058 // Must be kept in sync with X86CallingConv.td
27059 NestReg = X86::EAX;
27060 break;
27061 }
27062
27063 SDValue OutChains[4];
27064 SDValue Addr, Disp;
27065
27066 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
27067 DAG.getConstant(10, dl, MVT::i32));
27068 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
27069
27070 // This is storing the opcode for MOV32ri.
27071 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
27072 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
27073 OutChains[0] =
27074 DAG.getStore(Root, dl, DAG.getConstant(MOV32ri | N86Reg, dl, MVT::i8),
27075 Trmp, MachinePointerInfo(TrmpAddr));
27076
27077 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
27078 DAG.getConstant(1, dl, MVT::i32));
27079 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
27080 MachinePointerInfo(TrmpAddr, 1), Align(1));
27081
27082 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
27083 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
27084 DAG.getConstant(5, dl, MVT::i32));
27085 OutChains[2] =
27086 DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8), Addr,
27087 MachinePointerInfo(TrmpAddr, 5), Align(1));
27088
27089 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
27090 DAG.getConstant(6, dl, MVT::i32));
27091 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
27092 MachinePointerInfo(TrmpAddr, 6), Align(1));
27093
27094 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
27095 }
27096}
27097
27098SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
27099 SelectionDAG &DAG) const {
27100 /*
27101 The rounding mode is in bits 11:10 of FPSR, and has the following
27102 settings:
27103 00 Round to nearest
27104 01 Round to -inf
27105 10 Round to +inf
27106 11 Round to 0
27107
27108 FLT_ROUNDS, on the other hand, expects the following:
27109 -1 Undefined
27110 0 Round to 0
27111 1 Round to nearest
27112 2 Round to +inf
27113 3 Round to -inf
27114
27115 To perform the conversion, we use a packed lookup table of the four 2-bit
27116 values that we can index by FPSP[11:10]
27117 0x2d --> (0b00,10,11,01) --> (0,2,3,1) >> FPSR[11:10]
27118
27119 (0x2d >> ((FPSR & 0xc00) >> 9)) & 3
27120 */
27121
27122 MachineFunction &MF = DAG.getMachineFunction();
27123 MVT VT = Op.getSimpleValueType();
27124 SDLoc DL(Op);
27125
27126 // Save FP Control Word to stack slot
27127 int SSFI = MF.getFrameInfo().CreateStackObject(2, Align(2), false);
27128 SDValue StackSlot =
27129 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
27130
27131 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, SSFI);
27132
27133 SDValue Chain = Op.getOperand(0);
27134 SDValue Ops[] = {Chain, StackSlot};
27135 Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
27136 DAG.getVTList(MVT::Other), Ops, MVT::i16, MPI,
27137 Align(2), MachineMemOperand::MOStore);
27138
27139 // Load FP Control Word from stack slot
27140 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, MPI, Align(2));
27141 Chain = CWD.getValue(1);
27142
27143 // Mask and turn the control bits into a shift for the lookup table.
27144 SDValue Shift =
27145 DAG.getNode(ISD::SRL, DL, MVT::i16,
27146 DAG.getNode(ISD::AND, DL, MVT::i16,
27147 CWD, DAG.getConstant(0xc00, DL, MVT::i16)),
27148 DAG.getConstant(9, DL, MVT::i8));
27149 Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, Shift);
27150
27151 SDValue LUT = DAG.getConstant(0x2d, DL, MVT::i32);
27152 SDValue RetVal =
27153 DAG.getNode(ISD::AND, DL, MVT::i32,
27154 DAG.getNode(ISD::SRL, DL, MVT::i32, LUT, Shift),
27155 DAG.getConstant(3, DL, MVT::i32));
27156
27157 RetVal = DAG.getZExtOrTrunc(RetVal, DL, VT);
27158
27159 return DAG.getMergeValues({RetVal, Chain}, DL);
27160}
27161
27162SDValue X86TargetLowering::LowerSET_ROUNDING(SDValue Op,
27163 SelectionDAG &DAG) const {
27164 MachineFunction &MF = DAG.getMachineFunction();
27165 SDLoc DL(Op);
27166 SDValue Chain = Op.getNode()->getOperand(0);
27167
27168 // FP control word may be set only from data in memory. So we need to allocate
27169 // stack space to save/load FP control word.
27170 int OldCWFrameIdx = MF.getFrameInfo().CreateStackObject(4, Align(4), false);
27171 SDValue StackSlot =
27172 DAG.getFrameIndex(OldCWFrameIdx, getPointerTy(DAG.getDataLayout()));
27173 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, OldCWFrameIdx);
27174 MachineMemOperand *MMO =
27175 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 2, Align(2));
27176
27177 // Store FP control word into memory.
27178 SDValue Ops[] = {Chain, StackSlot};
27179 Chain = DAG.getMemIntrinsicNode(
27180 X86ISD::FNSTCW16m, DL, DAG.getVTList(MVT::Other), Ops, MVT::i16, MMO);
27181
27182 // Load FP Control Word from stack slot and clear RM field (bits 11:10).
27183 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, MPI);
27184 Chain = CWD.getValue(1);
27185 CWD = DAG.getNode(ISD::AND, DL, MVT::i16, CWD.getValue(0),
27186 DAG.getConstant(0xf3ff, DL, MVT::i16));
27187
27188 // Calculate new rounding mode.
27189 SDValue NewRM = Op.getNode()->getOperand(1);
27190 SDValue RMBits;
27191 if (auto *CVal = dyn_cast<ConstantSDNode>(NewRM)) {
27192 uint64_t RM = CVal->getZExtValue();
27193 int FieldVal;
27194 switch (static_cast<RoundingMode>(RM)) {
27195 case RoundingMode::NearestTiesToEven: FieldVal = X86::rmToNearest; break;
27196 case RoundingMode::TowardNegative: FieldVal = X86::rmDownward; break;
27197 case RoundingMode::TowardPositive: FieldVal = X86::rmUpward; break;
27198 case RoundingMode::TowardZero: FieldVal = X86::rmTowardZero; break;
27199 default:
27200 llvm_unreachable("rounding mode is not supported by X86 hardware")::llvm::llvm_unreachable_internal("rounding mode is not supported by X86 hardware"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27200)
;
27201 }
27202 RMBits = DAG.getConstant(FieldVal, DL, MVT::i16);
27203 } else {
27204 // Need to convert argument into bits of control word:
27205 // 0 Round to 0 -> 11
27206 // 1 Round to nearest -> 00
27207 // 2 Round to +inf -> 10
27208 // 3 Round to -inf -> 01
27209 // The 2-bit value needs then to be shifted so that it occupies bits 11:10.
27210 // To make the conversion, put all these values into a value 0xc9 and shift
27211 // it left depending on the rounding mode:
27212 // (0xc9 << 4) & 0xc00 = X86::rmTowardZero
27213 // (0xc9 << 6) & 0xc00 = X86::rmToNearest
27214 // ...
27215 // (0xc9 << (2 * NewRM + 4)) & 0xc00
27216 SDValue ShiftValue =
27217 DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
27218 DAG.getNode(ISD::ADD, DL, MVT::i32,
27219 DAG.getNode(ISD::SHL, DL, MVT::i32, NewRM,
27220 DAG.getConstant(1, DL, MVT::i8)),
27221 DAG.getConstant(4, DL, MVT::i32)));
27222 SDValue Shifted =
27223 DAG.getNode(ISD::SHL, DL, MVT::i16, DAG.getConstant(0xc9, DL, MVT::i16),
27224 ShiftValue);
27225 RMBits = DAG.getNode(ISD::AND, DL, MVT::i16, Shifted,
27226 DAG.getConstant(0xc00, DL, MVT::i16));
27227 }
27228
27229 // Update rounding mode bits and store the new FP Control Word into stack.
27230 CWD = DAG.getNode(ISD::OR, DL, MVT::i16, CWD, RMBits);
27231 Chain = DAG.getStore(Chain, DL, CWD, StackSlot, MPI, /* Alignment = */ 2);
27232
27233 // Load FP control word from the slot.
27234 SDValue OpsLD[] = {Chain, StackSlot};
27235 MachineMemOperand *MMOL =
27236 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 2, Align(2));
27237 Chain = DAG.getMemIntrinsicNode(
27238 X86ISD::FLDCW16m, DL, DAG.getVTList(MVT::Other), OpsLD, MVT::i16, MMOL);
27239
27240 // If target supports SSE, set MXCSR as well. Rounding mode is encoded in the
27241 // same way but in bits 14:13.
27242 if (Subtarget.hasSSE1()) {
27243 // Store MXCSR into memory.
27244 Chain = DAG.getNode(
27245 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Chain,
27246 DAG.getTargetConstant(Intrinsic::x86_sse_stmxcsr, DL, MVT::i32),
27247 StackSlot);
27248
27249 // Load MXCSR from stack slot and clear RM field (bits 14:13).
27250 SDValue CWD = DAG.getLoad(MVT::i32, DL, Chain, StackSlot, MPI);
27251 Chain = CWD.getValue(1);
27252 CWD = DAG.getNode(ISD::AND, DL, MVT::i32, CWD.getValue(0),
27253 DAG.getConstant(0xffff9fff, DL, MVT::i32));
27254
27255 // Shift X87 RM bits from 11:10 to 14:13.
27256 RMBits = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, RMBits);
27257 RMBits = DAG.getNode(ISD::SHL, DL, MVT::i32, RMBits,
27258 DAG.getConstant(3, DL, MVT::i8));
27259
27260 // Update rounding mode bits and store the new FP Control Word into stack.
27261 CWD = DAG.getNode(ISD::OR, DL, MVT::i32, CWD, RMBits);
27262 Chain = DAG.getStore(Chain, DL, CWD, StackSlot, MPI, /* Alignment = */ 4);
27263
27264 // Load MXCSR from the slot.
27265 Chain = DAG.getNode(
27266 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Chain,
27267 DAG.getTargetConstant(Intrinsic::x86_sse_ldmxcsr, DL, MVT::i32),
27268 StackSlot);
27269 }
27270
27271 return Chain;
27272}
27273
27274/// Lower a vector CTLZ using native supported vector CTLZ instruction.
27275//
27276// i8/i16 vector implemented using dword LZCNT vector instruction
27277// ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
27278// split the vector, perform operation on it's Lo a Hi part and
27279// concatenate the results.
27280static SDValue LowerVectorCTLZ_AVX512CDI(SDValue Op, SelectionDAG &DAG,
27281 const X86Subtarget &Subtarget) {
27282 assert(Op.getOpcode() == ISD::CTLZ)(static_cast <bool> (Op.getOpcode() == ISD::CTLZ) ? void
(0) : __assert_fail ("Op.getOpcode() == ISD::CTLZ", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27282, __extension__ __PRETTY_FUNCTION__))
;
27283 SDLoc dl(Op);
27284 MVT VT = Op.getSimpleValueType();
27285 MVT EltVT = VT.getVectorElementType();
27286 unsigned NumElems = VT.getVectorNumElements();
27287
27288 assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&(static_cast <bool> ((EltVT == MVT::i8 || EltVT == MVT::
i16) && "Unsupported element type") ? void (0) : __assert_fail
("(EltVT == MVT::i8 || EltVT == MVT::i16) && \"Unsupported element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27289, __extension__ __PRETTY_FUNCTION__))
27289 "Unsupported element type")(static_cast <bool> ((EltVT == MVT::i8 || EltVT == MVT::
i16) && "Unsupported element type") ? void (0) : __assert_fail
("(EltVT == MVT::i8 || EltVT == MVT::i16) && \"Unsupported element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27289, __extension__ __PRETTY_FUNCTION__))
;
27290
27291 // Split vector, it's Lo and Hi parts will be handled in next iteration.
27292 if (NumElems > 16 ||
27293 (NumElems == 16 && !Subtarget.canExtendTo512DQ()))
27294 return splitVectorIntUnary(Op, DAG);
27295
27296 MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
27297 assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&(static_cast <bool> ((NewVT.is256BitVector() || NewVT.is512BitVector
()) && "Unsupported value type for operation") ? void
(0) : __assert_fail ("(NewVT.is256BitVector() || NewVT.is512BitVector()) && \"Unsupported value type for operation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27298, __extension__ __PRETTY_FUNCTION__))
27298 "Unsupported value type for operation")(static_cast <bool> ((NewVT.is256BitVector() || NewVT.is512BitVector
()) && "Unsupported value type for operation") ? void
(0) : __assert_fail ("(NewVT.is256BitVector() || NewVT.is512BitVector()) && \"Unsupported value type for operation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27298, __extension__ __PRETTY_FUNCTION__))
;
27299
27300 // Use native supported vector instruction vplzcntd.
27301 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
27302 SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
27303 SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
27304 SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
27305
27306 return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
27307}
27308
27309// Lower CTLZ using a PSHUFB lookup table implementation.
27310static SDValue LowerVectorCTLZInRegLUT(SDValue Op, const SDLoc &DL,
27311 const X86Subtarget &Subtarget,
27312 SelectionDAG &DAG) {
27313 MVT VT = Op.getSimpleValueType();
27314 int NumElts = VT.getVectorNumElements();
27315 int NumBytes = NumElts * (VT.getScalarSizeInBits() / 8);
27316 MVT CurrVT = MVT::getVectorVT(MVT::i8, NumBytes);
27317
27318 // Per-nibble leading zero PSHUFB lookup table.
27319 const int LUT[16] = {/* 0 */ 4, /* 1 */ 3, /* 2 */ 2, /* 3 */ 2,
27320 /* 4 */ 1, /* 5 */ 1, /* 6 */ 1, /* 7 */ 1,
27321 /* 8 */ 0, /* 9 */ 0, /* a */ 0, /* b */ 0,
27322 /* c */ 0, /* d */ 0, /* e */ 0, /* f */ 0};
27323
27324 SmallVector<SDValue, 64> LUTVec;
27325 for (int i = 0; i < NumBytes; ++i)
27326 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
27327 SDValue InRegLUT = DAG.getBuildVector(CurrVT, DL, LUTVec);
27328
27329 // Begin by bitcasting the input to byte vector, then split those bytes
27330 // into lo/hi nibbles and use the PSHUFB LUT to perform CLTZ on each of them.
27331 // If the hi input nibble is zero then we add both results together, otherwise
27332 // we just take the hi result (by masking the lo result to zero before the
27333 // add).
27334 SDValue Op0 = DAG.getBitcast(CurrVT, Op.getOperand(0));
27335 SDValue Zero = DAG.getConstant(0, DL, CurrVT);
27336
27337 SDValue NibbleShift = DAG.getConstant(0x4, DL, CurrVT);
27338 SDValue Lo = Op0;
27339 SDValue Hi = DAG.getNode(ISD::SRL, DL, CurrVT, Op0, NibbleShift);
27340 SDValue HiZ;
27341 if (CurrVT.is512BitVector()) {
27342 MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
27343 HiZ = DAG.getSetCC(DL, MaskVT, Hi, Zero, ISD::SETEQ);
27344 HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
27345 } else {
27346 HiZ = DAG.getSetCC(DL, CurrVT, Hi, Zero, ISD::SETEQ);
27347 }
27348
27349 Lo = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Lo);
27350 Hi = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Hi);
27351 Lo = DAG.getNode(ISD::AND, DL, CurrVT, Lo, HiZ);
27352 SDValue Res = DAG.getNode(ISD::ADD, DL, CurrVT, Lo, Hi);
27353
27354 // Merge result back from vXi8 back to VT, working on the lo/hi halves
27355 // of the current vector width in the same way we did for the nibbles.
27356 // If the upper half of the input element is zero then add the halves'
27357 // leading zero counts together, otherwise just use the upper half's.
27358 // Double the width of the result until we are at target width.
27359 while (CurrVT != VT) {
27360 int CurrScalarSizeInBits = CurrVT.getScalarSizeInBits();
27361 int CurrNumElts = CurrVT.getVectorNumElements();
27362 MVT NextSVT = MVT::getIntegerVT(CurrScalarSizeInBits * 2);
27363 MVT NextVT = MVT::getVectorVT(NextSVT, CurrNumElts / 2);
27364 SDValue Shift = DAG.getConstant(CurrScalarSizeInBits, DL, NextVT);
27365
27366 // Check if the upper half of the input element is zero.
27367 if (CurrVT.is512BitVector()) {
27368 MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
27369 HiZ = DAG.getSetCC(DL, MaskVT, DAG.getBitcast(CurrVT, Op0),
27370 DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
27371 HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
27372 } else {
27373 HiZ = DAG.getSetCC(DL, CurrVT, DAG.getBitcast(CurrVT, Op0),
27374 DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
27375 }
27376 HiZ = DAG.getBitcast(NextVT, HiZ);
27377
27378 // Move the upper/lower halves to the lower bits as we'll be extending to
27379 // NextVT. Mask the lower result to zero if HiZ is true and add the results
27380 // together.
27381 SDValue ResNext = Res = DAG.getBitcast(NextVT, Res);
27382 SDValue R0 = DAG.getNode(ISD::SRL, DL, NextVT, ResNext, Shift);
27383 SDValue R1 = DAG.getNode(ISD::SRL, DL, NextVT, HiZ, Shift);
27384 R1 = DAG.getNode(ISD::AND, DL, NextVT, ResNext, R1);
27385 Res = DAG.getNode(ISD::ADD, DL, NextVT, R0, R1);
27386 CurrVT = NextVT;
27387 }
27388
27389 return Res;
27390}
27391
27392static SDValue LowerVectorCTLZ(SDValue Op, const SDLoc &DL,
27393 const X86Subtarget &Subtarget,
27394 SelectionDAG &DAG) {
27395 MVT VT = Op.getSimpleValueType();
27396
27397 if (Subtarget.hasCDI() &&
27398 // vXi8 vectors need to be promoted to 512-bits for vXi32.
27399 (Subtarget.canExtendTo512DQ() || VT.getVectorElementType() != MVT::i8))
27400 return LowerVectorCTLZ_AVX512CDI(Op, DAG, Subtarget);
27401
27402 // Decompose 256-bit ops into smaller 128-bit ops.
27403 if (VT.is256BitVector() && !Subtarget.hasInt256())
27404 return splitVectorIntUnary(Op, DAG);
27405
27406 // Decompose 512-bit ops into smaller 256-bit ops.
27407 if (VT.is512BitVector() && !Subtarget.hasBWI())
27408 return splitVectorIntUnary(Op, DAG);
27409
27410 assert(Subtarget.hasSSSE3() && "Expected SSSE3 support for PSHUFB")(static_cast <bool> (Subtarget.hasSSSE3() && "Expected SSSE3 support for PSHUFB"
) ? void (0) : __assert_fail ("Subtarget.hasSSSE3() && \"Expected SSSE3 support for PSHUFB\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27410, __extension__ __PRETTY_FUNCTION__))
;
27411 return LowerVectorCTLZInRegLUT(Op, DL, Subtarget, DAG);
27412}
27413
27414static SDValue LowerCTLZ(SDValue Op, const X86Subtarget &Subtarget,
27415 SelectionDAG &DAG) {
27416 MVT VT = Op.getSimpleValueType();
27417 MVT OpVT = VT;
27418 unsigned NumBits = VT.getSizeInBits();
27419 SDLoc dl(Op);
27420 unsigned Opc = Op.getOpcode();
27421
27422 if (VT.isVector())
27423 return LowerVectorCTLZ(Op, dl, Subtarget, DAG);
27424
27425 Op = Op.getOperand(0);
27426 if (VT == MVT::i8) {
27427 // Zero extend to i32 since there is not an i8 bsr.
27428 OpVT = MVT::i32;
27429 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
27430 }
27431
27432 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
27433 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
27434 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
27435
27436 if (Opc == ISD::CTLZ) {
27437 // If src is zero (i.e. bsr sets ZF), returns NumBits.
27438 SDValue Ops[] = {Op, DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
27439 DAG.getTargetConstant(X86::COND_E, dl, MVT::i8),
27440 Op.getValue(1)};
27441 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
27442 }
27443
27444 // Finally xor with NumBits-1.
27445 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
27446 DAG.getConstant(NumBits - 1, dl, OpVT));
27447
27448 if (VT == MVT::i8)
27449 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
27450 return Op;
27451}
27452
27453static SDValue LowerCTTZ(SDValue Op, const X86Subtarget &Subtarget,
27454 SelectionDAG &DAG) {
27455 MVT VT = Op.getSimpleValueType();
27456 unsigned NumBits = VT.getScalarSizeInBits();
27457 SDValue N0 = Op.getOperand(0);
27458 SDLoc dl(Op);
27459
27460 assert(!VT.isVector() && Op.getOpcode() == ISD::CTTZ &&(static_cast <bool> (!VT.isVector() && Op.getOpcode
() == ISD::CTTZ && "Only scalar CTTZ requires custom lowering"
) ? void (0) : __assert_fail ("!VT.isVector() && Op.getOpcode() == ISD::CTTZ && \"Only scalar CTTZ requires custom lowering\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27461, __extension__ __PRETTY_FUNCTION__))
27461 "Only scalar CTTZ requires custom lowering")(static_cast <bool> (!VT.isVector() && Op.getOpcode
() == ISD::CTTZ && "Only scalar CTTZ requires custom lowering"
) ? void (0) : __assert_fail ("!VT.isVector() && Op.getOpcode() == ISD::CTTZ && \"Only scalar CTTZ requires custom lowering\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27461, __extension__ __PRETTY_FUNCTION__))
;
27462
27463 // Issue a bsf (scan bits forward) which also sets EFLAGS.
27464 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
27465 Op = DAG.getNode(X86ISD::BSF, dl, VTs, N0);
27466
27467 // If src is zero (i.e. bsf sets ZF), returns NumBits.
27468 SDValue Ops[] = {Op, DAG.getConstant(NumBits, dl, VT),
27469 DAG.getTargetConstant(X86::COND_E, dl, MVT::i8),
27470 Op.getValue(1)};
27471 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
27472}
27473
27474static SDValue lowerAddSub(SDValue Op, SelectionDAG &DAG,
27475 const X86Subtarget &Subtarget) {
27476 MVT VT = Op.getSimpleValueType();
27477 if (VT == MVT::i16 || VT == MVT::i32)
27478 return lowerAddSubToHorizontalOp(Op, DAG, Subtarget);
27479
27480 if (VT == MVT::v32i16 || VT == MVT::v64i8)
27481 return splitVectorIntBinary(Op, DAG);
27482
27483 assert(Op.getSimpleValueType().is256BitVector() &&(static_cast <bool> (Op.getSimpleValueType().is256BitVector
() && Op.getSimpleValueType().isInteger() && "Only handle AVX 256-bit vector integer operation"
) ? void (0) : __assert_fail ("Op.getSimpleValueType().is256BitVector() && Op.getSimpleValueType().isInteger() && \"Only handle AVX 256-bit vector integer operation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27485, __extension__ __PRETTY_FUNCTION__))
27484 Op.getSimpleValueType().isInteger() &&(static_cast <bool> (Op.getSimpleValueType().is256BitVector
() && Op.getSimpleValueType().isInteger() && "Only handle AVX 256-bit vector integer operation"
) ? void (0) : __assert_fail ("Op.getSimpleValueType().is256BitVector() && Op.getSimpleValueType().isInteger() && \"Only handle AVX 256-bit vector integer operation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27485, __extension__ __PRETTY_FUNCTION__))
27485 "Only handle AVX 256-bit vector integer operation")(static_cast <bool> (Op.getSimpleValueType().is256BitVector
() && Op.getSimpleValueType().isInteger() && "Only handle AVX 256-bit vector integer operation"
) ? void (0) : __assert_fail ("Op.getSimpleValueType().is256BitVector() && Op.getSimpleValueType().isInteger() && \"Only handle AVX 256-bit vector integer operation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27485, __extension__ __PRETTY_FUNCTION__))
;
27486 return splitVectorIntBinary(Op, DAG);
27487}
27488
27489static SDValue LowerADDSAT_SUBSAT(SDValue Op, SelectionDAG &DAG,
27490 const X86Subtarget &Subtarget) {
27491 MVT VT = Op.getSimpleValueType();
27492 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
27493 unsigned Opcode = Op.getOpcode();
27494 SDLoc DL(Op);
27495
27496 if (VT == MVT::v32i16 || VT == MVT::v64i8 ||
27497 (VT.is256BitVector() && !Subtarget.hasInt256())) {
27498 assert(Op.getSimpleValueType().isInteger() &&(static_cast <bool> (Op.getSimpleValueType().isInteger(
) && "Only handle AVX vector integer operation") ? void
(0) : __assert_fail ("Op.getSimpleValueType().isInteger() && \"Only handle AVX vector integer operation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27499, __extension__ __PRETTY_FUNCTION__))
27499 "Only handle AVX vector integer operation")(static_cast <bool> (Op.getSimpleValueType().isInteger(
) && "Only handle AVX vector integer operation") ? void
(0) : __assert_fail ("Op.getSimpleValueType().isInteger() && \"Only handle AVX vector integer operation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27499, __extension__ __PRETTY_FUNCTION__))
;
27500 return splitVectorIntBinary(Op, DAG);
27501 }
27502
27503 // Avoid the generic expansion with min/max if we don't have pminu*/pmaxu*.
27504 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27505 EVT SetCCResultType =
27506 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
27507
27508 if (Opcode == ISD::USUBSAT && !TLI.isOperationLegal(ISD::UMAX, VT)) {
27509 // usubsat X, Y --> (X >u Y) ? X - Y : 0
27510 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, X, Y);
27511 SDValue Cmp = DAG.getSetCC(DL, SetCCResultType, X, Y, ISD::SETUGT);
27512 // TODO: Move this to DAGCombiner?
27513 if (SetCCResultType == VT &&
27514 DAG.ComputeNumSignBits(Cmp) == VT.getScalarSizeInBits())
27515 return DAG.getNode(ISD::AND, DL, VT, Cmp, Sub);
27516 return DAG.getSelect(DL, VT, Cmp, Sub, DAG.getConstant(0, DL, VT));
27517 }
27518
27519 // Use default expansion.
27520 return SDValue();
27521}
27522
27523static SDValue LowerABS(SDValue Op, const X86Subtarget &Subtarget,
27524 SelectionDAG &DAG) {
27525 MVT VT = Op.getSimpleValueType();
27526 if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) {
27527 // Since X86 does not have CMOV for 8-bit integer, we don't convert
27528 // 8-bit integer abs to NEG and CMOV.
27529 SDLoc DL(Op);
27530 SDValue N0 = Op.getOperand(0);
27531 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
27532 DAG.getConstant(0, DL, VT), N0);
27533 SDValue Ops[] = {N0, Neg, DAG.getTargetConstant(X86::COND_GE, DL, MVT::i8),
27534 SDValue(Neg.getNode(), 1)};
27535 return DAG.getNode(X86ISD::CMOV, DL, VT, Ops);
27536 }
27537
27538 // ABS(vXi64 X) --> VPBLENDVPD(X, 0-X, X).
27539 if ((VT == MVT::v2i64 || VT == MVT::v4i64) && Subtarget.hasSSE41()) {
27540 SDLoc DL(Op);
27541 SDValue Src = Op.getOperand(0);
27542 SDValue Sub =
27543 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
27544 return DAG.getNode(X86ISD::BLENDV, DL, VT, Src, Sub, Src);
27545 }
27546
27547 if (VT.is256BitVector() && !Subtarget.hasInt256()) {
27548 assert(VT.isInteger() &&(static_cast <bool> (VT.isInteger() && "Only handle AVX 256-bit vector integer operation"
) ? void (0) : __assert_fail ("VT.isInteger() && \"Only handle AVX 256-bit vector integer operation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27549, __extension__ __PRETTY_FUNCTION__))
27549 "Only handle AVX 256-bit vector integer operation")(static_cast <bool> (VT.isInteger() && "Only handle AVX 256-bit vector integer operation"
) ? void (0) : __assert_fail ("VT.isInteger() && \"Only handle AVX 256-bit vector integer operation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27549, __extension__ __PRETTY_FUNCTION__))
;
27550 return splitVectorIntUnary(Op, DAG);
27551 }
27552
27553 if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
27554 return splitVectorIntUnary(Op, DAG);
27555
27556 // Default to expand.
27557 return SDValue();
27558}
27559
27560static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
27561 MVT VT = Op.getSimpleValueType();
27562
27563 // For AVX1 cases, split to use legal ops (everything but v4i64).
27564 if (VT.getScalarType() != MVT::i64 && VT.is256BitVector())
27565 return splitVectorIntBinary(Op, DAG);
27566
27567 if (VT == MVT::v32i16 || VT == MVT::v64i8)
27568 return splitVectorIntBinary(Op, DAG);
27569
27570 // Default to expand.
27571 return SDValue();
27572}
27573
27574static SDValue LowerMUL(SDValue Op, const X86Subtarget &Subtarget,
27575 SelectionDAG &DAG) {
27576 SDLoc dl(Op);
27577 MVT VT = Op.getSimpleValueType();
27578
27579 // Decompose 256-bit ops into 128-bit ops.
27580 if (VT.is256BitVector() && !Subtarget.hasInt256())
27581 return splitVectorIntBinary(Op, DAG);
27582
27583 if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
27584 return splitVectorIntBinary(Op, DAG);
27585
27586 SDValue A = Op.getOperand(0);
27587 SDValue B = Op.getOperand(1);
27588
27589 // Lower v16i8/v32i8/v64i8 mul as sign-extension to v8i16/v16i16/v32i16
27590 // vector pairs, multiply and truncate.
27591 if (VT == MVT::v16i8 || VT == MVT::v32i8 || VT == MVT::v64i8) {
27592 unsigned NumElts = VT.getVectorNumElements();
27593
27594 if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
27595 (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
27596 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
27597 return DAG.getNode(
27598 ISD::TRUNCATE, dl, VT,
27599 DAG.getNode(ISD::MUL, dl, ExVT,
27600 DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, A),
27601 DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, B)));
27602 }
27603
27604 MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
27605
27606 // Extract the lo/hi parts to any extend to i16.
27607 // We're going to mask off the low byte of each result element of the
27608 // pmullw, so it doesn't matter what's in the high byte of each 16-bit
27609 // element.
27610 SDValue Undef = DAG.getUNDEF(VT);
27611 SDValue ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A, Undef));
27612 SDValue AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A, Undef));
27613
27614 SDValue BLo, BHi;
27615 if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
27616 // If the RHS is a constant, manually unpackl/unpackh.
27617 SmallVector<SDValue, 16> LoOps, HiOps;
27618 for (unsigned i = 0; i != NumElts; i += 16) {
27619 for (unsigned j = 0; j != 8; ++j) {
27620 LoOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j), dl,
27621 MVT::i16));
27622 HiOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j + 8), dl,
27623 MVT::i16));
27624 }
27625 }
27626
27627 BLo = DAG.getBuildVector(ExVT, dl, LoOps);
27628 BHi = DAG.getBuildVector(ExVT, dl, HiOps);
27629 } else {
27630 BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B, Undef));
27631 BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B, Undef));
27632 }
27633
27634 // Multiply, mask the lower 8bits of the lo/hi results and pack.
27635 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
27636 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
27637 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
27638 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
27639 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
27640 }
27641
27642 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
27643 if (VT == MVT::v4i32) {
27644 assert(Subtarget.hasSSE2() && !Subtarget.hasSSE41() &&(static_cast <bool> (Subtarget.hasSSE2() && !Subtarget
.hasSSE41() && "Should not custom lower when pmulld is available!"
) ? void (0) : __assert_fail ("Subtarget.hasSSE2() && !Subtarget.hasSSE41() && \"Should not custom lower when pmulld is available!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27645, __extension__ __PRETTY_FUNCTION__))
27645 "Should not custom lower when pmulld is available!")(static_cast <bool> (Subtarget.hasSSE2() && !Subtarget
.hasSSE41() && "Should not custom lower when pmulld is available!"
) ? void (0) : __assert_fail ("Subtarget.hasSSE2() && !Subtarget.hasSSE41() && \"Should not custom lower when pmulld is available!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27645, __extension__ __PRETTY_FUNCTION__))
;
27646
27647 // Extract the odd parts.
27648 static const int UnpackMask[] = { 1, -1, 3, -1 };
27649 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
27650 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
27651
27652 // Multiply the even parts.
27653 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
27654 DAG.getBitcast(MVT::v2i64, A),
27655 DAG.getBitcast(MVT::v2i64, B));
27656 // Now multiply odd parts.
27657 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
27658 DAG.getBitcast(MVT::v2i64, Aodds),
27659 DAG.getBitcast(MVT::v2i64, Bodds));
27660
27661 Evens = DAG.getBitcast(VT, Evens);
27662 Odds = DAG.getBitcast(VT, Odds);
27663
27664 // Merge the two vectors back together with a shuffle. This expands into 2
27665 // shuffles.
27666 static const int ShufMask[] = { 0, 4, 2, 6 };
27667 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
27668 }
27669
27670 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&(static_cast <bool> ((VT == MVT::v2i64 || VT == MVT::v4i64
|| VT == MVT::v8i64) && "Only know how to lower V2I64/V4I64/V8I64 multiply"
) ? void (0) : __assert_fail ("(VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) && \"Only know how to lower V2I64/V4I64/V8I64 multiply\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27671, __extension__ __PRETTY_FUNCTION__))
27671 "Only know how to lower V2I64/V4I64/V8I64 multiply")(static_cast <bool> ((VT == MVT::v2i64 || VT == MVT::v4i64
|| VT == MVT::v8i64) && "Only know how to lower V2I64/V4I64/V8I64 multiply"
) ? void (0) : __assert_fail ("(VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) && \"Only know how to lower V2I64/V4I64/V8I64 multiply\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27671, __extension__ __PRETTY_FUNCTION__))
;
27672 assert(!Subtarget.hasDQI() && "DQI should use MULLQ")(static_cast <bool> (!Subtarget.hasDQI() && "DQI should use MULLQ"
) ? void (0) : __assert_fail ("!Subtarget.hasDQI() && \"DQI should use MULLQ\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27672, __extension__ __PRETTY_FUNCTION__))
;
27673
27674 // Ahi = psrlqi(a, 32);
27675 // Bhi = psrlqi(b, 32);
27676 //
27677 // AloBlo = pmuludq(a, b);
27678 // AloBhi = pmuludq(a, Bhi);
27679 // AhiBlo = pmuludq(Ahi, b);
27680 //
27681 // Hi = psllqi(AloBhi + AhiBlo, 32);
27682 // return AloBlo + Hi;
27683 KnownBits AKnown = DAG.computeKnownBits(A);
27684 KnownBits BKnown = DAG.computeKnownBits(B);
27685
27686 APInt LowerBitsMask = APInt::getLowBitsSet(64, 32);
27687 bool ALoIsZero = LowerBitsMask.isSubsetOf(AKnown.Zero);
27688 bool BLoIsZero = LowerBitsMask.isSubsetOf(BKnown.Zero);
27689
27690 APInt UpperBitsMask = APInt::getHighBitsSet(64, 32);
27691 bool AHiIsZero = UpperBitsMask.isSubsetOf(AKnown.Zero);
27692 bool BHiIsZero = UpperBitsMask.isSubsetOf(BKnown.Zero);
27693
27694 SDValue Zero = DAG.getConstant(0, dl, VT);
27695
27696 // Only multiply lo/hi halves that aren't known to be zero.
27697 SDValue AloBlo = Zero;
27698 if (!ALoIsZero && !BLoIsZero)
27699 AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
27700
27701 SDValue AloBhi = Zero;
27702 if (!ALoIsZero && !BHiIsZero) {
27703 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
27704 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
27705 }
27706
27707 SDValue AhiBlo = Zero;
27708 if (!AHiIsZero && !BLoIsZero) {
27709 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
27710 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
27711 }
27712
27713 SDValue Hi = DAG.getNode(ISD::ADD, dl, VT, AloBhi, AhiBlo);
27714 Hi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Hi, 32, DAG);
27715
27716 return DAG.getNode(ISD::ADD, dl, VT, AloBlo, Hi);
27717}
27718
27719static SDValue LowervXi8MulWithUNPCK(SDValue A, SDValue B, const SDLoc &dl,
27720 MVT VT, bool IsSigned,
27721 const X86Subtarget &Subtarget,
27722 SelectionDAG &DAG,
27723 SDValue *Low = nullptr) {
27724 unsigned NumElts = VT.getVectorNumElements();
27725
27726 // For vXi8 we will unpack the low and high half of each 128 bit lane to widen
27727 // to a vXi16 type. Do the multiplies, shift the results and pack the half
27728 // lane results back together.
27729
27730 // We'll take different approaches for signed and unsigned.
27731 // For unsigned we'll use punpcklbw/punpckhbw to put zero extend the bytes
27732 // and use pmullw to calculate the full 16-bit product.
27733 // For signed we'll use punpcklbw/punpckbw to extend the bytes to words and
27734 // shift them left into the upper byte of each word. This allows us to use
27735 // pmulhw to calculate the full 16-bit product. This trick means we don't
27736 // need to sign extend the bytes to use pmullw.
27737
27738 MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
27739 SDValue Zero = DAG.getConstant(0, dl, VT);
27740
27741 SDValue ALo, AHi;
27742 if (IsSigned) {
27743 ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, Zero, A));
27744 AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, Zero, A));
27745 } else {
27746 ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A, Zero));
27747 AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A, Zero));
27748 }
27749
27750 SDValue BLo, BHi;
27751 if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
27752 // If the RHS is a constant, manually unpackl/unpackh and extend.
27753 SmallVector<SDValue, 16> LoOps, HiOps;
27754 for (unsigned i = 0; i != NumElts; i += 16) {
27755 for (unsigned j = 0; j != 8; ++j) {
27756 SDValue LoOp = B.getOperand(i + j);
27757 SDValue HiOp = B.getOperand(i + j + 8);
27758
27759 if (IsSigned) {
27760 LoOp = DAG.getAnyExtOrTrunc(LoOp, dl, MVT::i16);
27761 HiOp = DAG.getAnyExtOrTrunc(HiOp, dl, MVT::i16);
27762 LoOp = DAG.getNode(ISD::SHL, dl, MVT::i16, LoOp,
27763 DAG.getConstant(8, dl, MVT::i16));
27764 HiOp = DAG.getNode(ISD::SHL, dl, MVT::i16, HiOp,
27765 DAG.getConstant(8, dl, MVT::i16));
27766 } else {
27767 LoOp = DAG.getZExtOrTrunc(LoOp, dl, MVT::i16);
27768 HiOp = DAG.getZExtOrTrunc(HiOp, dl, MVT::i16);
27769 }
27770
27771 LoOps.push_back(LoOp);
27772 HiOps.push_back(HiOp);
27773 }
27774 }
27775
27776 BLo = DAG.getBuildVector(ExVT, dl, LoOps);
27777 BHi = DAG.getBuildVector(ExVT, dl, HiOps);
27778 } else if (IsSigned) {
27779 BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, Zero, B));
27780 BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, Zero, B));
27781 } else {
27782 BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B, Zero));
27783 BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B, Zero));
27784 }
27785
27786 // Multiply, lshr the upper 8bits to the lower 8bits of the lo/hi results and
27787 // pack back to vXi8.
27788 unsigned MulOpc = IsSigned ? ISD::MULHS : ISD::MUL;
27789 SDValue RLo = DAG.getNode(MulOpc, dl, ExVT, ALo, BLo);
27790 SDValue RHi = DAG.getNode(MulOpc, dl, ExVT, AHi, BHi);
27791
27792 if (Low) {
27793 // Mask the lower bits and pack the results to rejoin the halves.
27794 SDValue Mask = DAG.getConstant(255, dl, ExVT);
27795 SDValue LLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, Mask);
27796 SDValue LHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, Mask);
27797 *Low = DAG.getNode(X86ISD::PACKUS, dl, VT, LLo, LHi);
27798 }
27799
27800 RLo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, RLo, 8, DAG);
27801 RHi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, RHi, 8, DAG);
27802
27803 // Bitcast back to VT and then pack all the even elements from Lo and Hi.
27804 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
27805}
27806
27807static SDValue LowerMULH(SDValue Op, const X86Subtarget &Subtarget,
27808 SelectionDAG &DAG) {
27809 SDLoc dl(Op);
27810 MVT VT = Op.getSimpleValueType();
27811 bool IsSigned = Op->getOpcode() == ISD::MULHS;
27812 unsigned NumElts = VT.getVectorNumElements();
27813 SDValue A = Op.getOperand(0);
27814 SDValue B = Op.getOperand(1);
27815
27816 // Decompose 256-bit ops into 128-bit ops.
27817 if (VT.is256BitVector() && !Subtarget.hasInt256())
27818 return splitVectorIntBinary(Op, DAG);
27819
27820 if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
27821 return splitVectorIntBinary(Op, DAG);
27822
27823 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32) {
27824 assert((VT == MVT::v4i32 && Subtarget.hasSSE2()) ||(static_cast <bool> ((VT == MVT::v4i32 && Subtarget
.hasSSE2()) || (VT == MVT::v8i32 && Subtarget.hasInt256
()) || (VT == MVT::v16i32 && Subtarget.hasAVX512())) ?
void (0) : __assert_fail ("(VT == MVT::v4i32 && Subtarget.hasSSE2()) || (VT == MVT::v8i32 && Subtarget.hasInt256()) || (VT == MVT::v16i32 && Subtarget.hasAVX512())"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27826, __extension__ __PRETTY_FUNCTION__))
27825 (VT == MVT::v8i32 && Subtarget.hasInt256()) ||(static_cast <bool> ((VT == MVT::v4i32 && Subtarget
.hasSSE2()) || (VT == MVT::v8i32 && Subtarget.hasInt256
()) || (VT == MVT::v16i32 && Subtarget.hasAVX512())) ?
void (0) : __assert_fail ("(VT == MVT::v4i32 && Subtarget.hasSSE2()) || (VT == MVT::v8i32 && Subtarget.hasInt256()) || (VT == MVT::v16i32 && Subtarget.hasAVX512())"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27826, __extension__ __PRETTY_FUNCTION__))
27826 (VT == MVT::v16i32 && Subtarget.hasAVX512()))(static_cast <bool> ((VT == MVT::v4i32 && Subtarget
.hasSSE2()) || (VT == MVT::v8i32 && Subtarget.hasInt256
()) || (VT == MVT::v16i32 && Subtarget.hasAVX512())) ?
void (0) : __assert_fail ("(VT == MVT::v4i32 && Subtarget.hasSSE2()) || (VT == MVT::v8i32 && Subtarget.hasInt256()) || (VT == MVT::v16i32 && Subtarget.hasAVX512())"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27826, __extension__ __PRETTY_FUNCTION__))
;
27827
27828 // PMULxD operations multiply each even value (starting at 0) of LHS with
27829 // the related value of RHS and produce a widen result.
27830 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
27831 // => <2 x i64> <ae|cg>
27832 //
27833 // In other word, to have all the results, we need to perform two PMULxD:
27834 // 1. one with the even values.
27835 // 2. one with the odd values.
27836 // To achieve #2, with need to place the odd values at an even position.
27837 //
27838 // Place the odd value at an even position (basically, shift all values 1
27839 // step to the left):
27840 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1,
27841 9, -1, 11, -1, 13, -1, 15, -1};
27842 // <a|b|c|d> => <b|undef|d|undef>
27843 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, A, A,
27844 makeArrayRef(&Mask[0], NumElts));
27845 // <e|f|g|h> => <f|undef|h|undef>
27846 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, B, B,
27847 makeArrayRef(&Mask[0], NumElts));
27848
27849 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
27850 // ints.
27851 MVT MulVT = MVT::getVectorVT(MVT::i64, NumElts / 2);
27852 unsigned Opcode =
27853 (IsSigned && Subtarget.hasSSE41()) ? X86ISD::PMULDQ : X86ISD::PMULUDQ;
27854 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
27855 // => <2 x i64> <ae|cg>
27856 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
27857 DAG.getBitcast(MulVT, A),
27858 DAG.getBitcast(MulVT, B)));
27859 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
27860 // => <2 x i64> <bf|dh>
27861 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
27862 DAG.getBitcast(MulVT, Odd0),
27863 DAG.getBitcast(MulVT, Odd1)));
27864
27865 // Shuffle it back into the right order.
27866 SmallVector<int, 16> ShufMask(NumElts);
27867 for (int i = 0; i != (int)NumElts; ++i)
27868 ShufMask[i] = (i / 2) * 2 + ((i % 2) * NumElts) + 1;
27869
27870 SDValue Res = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, ShufMask);
27871
27872 // If we have a signed multiply but no PMULDQ fix up the result of an
27873 // unsigned multiply.
27874 if (IsSigned && !Subtarget.hasSSE41()) {
27875 SDValue Zero = DAG.getConstant(0, dl, VT);
27876 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
27877 DAG.getSetCC(dl, VT, Zero, A, ISD::SETGT), B);
27878 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
27879 DAG.getSetCC(dl, VT, Zero, B, ISD::SETGT), A);
27880
27881 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
27882 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Fixup);
27883 }
27884
27885 return Res;
27886 }
27887
27888 // Only i8 vectors should need custom lowering after this.
27889 assert((VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) ||(static_cast <bool> ((VT == MVT::v16i8 || (VT == MVT::v32i8
&& Subtarget.hasInt256()) || (VT == MVT::v64i8 &&
Subtarget.hasBWI())) && "Unsupported vector type") ?
void (0) : __assert_fail ("(VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) || (VT == MVT::v64i8 && Subtarget.hasBWI())) && \"Unsupported vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27891, __extension__ __PRETTY_FUNCTION__))
27890 (VT == MVT::v64i8 && Subtarget.hasBWI())) &&(static_cast <bool> ((VT == MVT::v16i8 || (VT == MVT::v32i8
&& Subtarget.hasInt256()) || (VT == MVT::v64i8 &&
Subtarget.hasBWI())) && "Unsupported vector type") ?
void (0) : __assert_fail ("(VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) || (VT == MVT::v64i8 && Subtarget.hasBWI())) && \"Unsupported vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27891, __extension__ __PRETTY_FUNCTION__))
27891 "Unsupported vector type")(static_cast <bool> ((VT == MVT::v16i8 || (VT == MVT::v32i8
&& Subtarget.hasInt256()) || (VT == MVT::v64i8 &&
Subtarget.hasBWI())) && "Unsupported vector type") ?
void (0) : __assert_fail ("(VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) || (VT == MVT::v64i8 && Subtarget.hasBWI())) && \"Unsupported vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 27891, __extension__ __PRETTY_FUNCTION__))
;
27892
27893 // Lower v16i8/v32i8 as extension to v8i16/v16i16 vector pairs, multiply,
27894 // logical shift down the upper half and pack back to i8.
27895
27896 // With SSE41 we can use sign/zero extend, but for pre-SSE41 we unpack
27897 // and then ashr/lshr the upper bits down to the lower bits before multiply.
27898
27899 if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
27900 (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
27901 MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
27902 unsigned ExAVX = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
27903 SDValue ExA = DAG.getNode(ExAVX, dl, ExVT, A);
27904 SDValue ExB = DAG.getNode(ExAVX, dl, ExVT, B);
27905 SDValue Mul = DAG.getNode(ISD::MUL, dl, ExVT, ExA, ExB);
27906 Mul = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
27907 return DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
27908 }
27909
27910 return LowervXi8MulWithUNPCK(A, B, dl, VT, IsSigned, Subtarget, DAG);
27911}
27912
27913// Custom lowering for SMULO/UMULO.
27914static SDValue LowerMULO(SDValue Op, const X86Subtarget &Subtarget,
27915 SelectionDAG &DAG) {
27916 MVT VT = Op.getSimpleValueType();
27917
27918 // Scalars defer to LowerXALUO.
27919 if (!VT.isVector())
27920 return LowerXALUO(Op, DAG);
27921
27922 SDLoc dl(Op);
27923 bool IsSigned = Op->getOpcode() == ISD::SMULO;
27924 SDValue A = Op.getOperand(0);
27925 SDValue B = Op.getOperand(1);
27926 EVT OvfVT = Op->getValueType(1);
27927
27928 if ((VT == MVT::v32i8 && !Subtarget.hasInt256()) ||
27929 (VT == MVT::v64i8 && !Subtarget.hasBWI())) {
27930 // Extract the LHS Lo/Hi vectors
27931 SDValue LHSLo, LHSHi;
27932 std::tie(LHSLo, LHSHi) = splitVector(A, DAG, dl);
27933
27934 // Extract the RHS Lo/Hi vectors
27935 SDValue RHSLo, RHSHi;
27936 std::tie(RHSLo, RHSHi) = splitVector(B, DAG, dl);
27937
27938 EVT LoOvfVT, HiOvfVT;
27939 std::tie(LoOvfVT, HiOvfVT) = DAG.GetSplitDestVTs(OvfVT);
27940 SDVTList LoVTs = DAG.getVTList(LHSLo.getValueType(), LoOvfVT);
27941 SDVTList HiVTs = DAG.getVTList(LHSHi.getValueType(), HiOvfVT);
27942
27943 // Issue the split operations.
27944 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, LoVTs, LHSLo, RHSLo);
27945 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, HiVTs, LHSHi, RHSHi);
27946
27947 // Join the separate data results and the overflow results.
27948 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
27949 SDValue Ovf = DAG.getNode(ISD::CONCAT_VECTORS, dl, OvfVT, Lo.getValue(1),
27950 Hi.getValue(1));
27951
27952 return DAG.getMergeValues({Res, Ovf}, dl);
27953 }
27954
27955 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27956 EVT SetccVT =
27957 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
27958
27959 if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
27960 (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
27961 unsigned NumElts = VT.getVectorNumElements();
27962 MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
27963 unsigned ExAVX = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
27964 SDValue ExA = DAG.getNode(ExAVX, dl, ExVT, A);
27965 SDValue ExB = DAG.getNode(ExAVX, dl, ExVT, B);
27966 SDValue Mul = DAG.getNode(ISD::MUL, dl, ExVT, ExA, ExB);
27967
27968 SDValue Low = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
27969
27970 SDValue Ovf;
27971 if (IsSigned) {
27972 SDValue High, LowSign;
27973 if (OvfVT.getVectorElementType() == MVT::i1 &&
27974 (Subtarget.hasBWI() || Subtarget.canExtendTo512DQ())) {
27975 // Rather the truncating try to do the compare on vXi16 or vXi32.
27976 // Shift the high down filling with sign bits.
27977 High = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Mul, 8, DAG);
27978 // Fill all 16 bits with the sign bit from the low.
27979 LowSign =
27980 getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ExVT, Mul, 8, DAG);
27981 LowSign = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, LowSign,
27982 15, DAG);
27983 SetccVT = OvfVT;
27984 if (!Subtarget.hasBWI()) {
27985 // We can't do a vXi16 compare so sign extend to v16i32.
27986 High = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v16i32, High);
27987 LowSign = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v16i32, LowSign);
27988 }
27989 } else {
27990 // Otherwise do the compare at vXi8.
27991 High = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
27992 High = DAG.getNode(ISD::TRUNCATE, dl, VT, High);
27993 LowSign =
27994 DAG.getNode(ISD::SRA, dl, VT, Low, DAG.getConstant(7, dl, VT));
27995 }
27996
27997 Ovf = DAG.getSetCC(dl, SetccVT, LowSign, High, ISD::SETNE);
27998 } else {
27999 SDValue High =
28000 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
28001 if (OvfVT.getVectorElementType() == MVT::i1 &&
28002 (Subtarget.hasBWI() || Subtarget.canExtendTo512DQ())) {
28003 // Rather the truncating try to do the compare on vXi16 or vXi32.
28004 SetccVT = OvfVT;
28005 if (!Subtarget.hasBWI()) {
28006 // We can't do a vXi16 compare so sign extend to v16i32.
28007 High = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, High);
28008 }
28009 } else {
28010 // Otherwise do the compare at vXi8.
28011 High = DAG.getNode(ISD::TRUNCATE, dl, VT, High);
28012 }
28013
28014 Ovf =
28015 DAG.getSetCC(dl, SetccVT, High,
28016 DAG.getConstant(0, dl, High.getValueType()), ISD::SETNE);
28017 }
28018
28019 Ovf = DAG.getSExtOrTrunc(Ovf, dl, OvfVT);
28020
28021 return DAG.getMergeValues({Low, Ovf}, dl);
28022 }
28023
28024 SDValue Low;
28025 SDValue High =
28026 LowervXi8MulWithUNPCK(A, B, dl, VT, IsSigned, Subtarget, DAG, &Low);
28027
28028 SDValue Ovf;
28029 if (IsSigned) {
28030 // SMULO overflows if the high bits don't match the sign of the low.
28031 SDValue LowSign =
28032 DAG.getNode(ISD::SRA, dl, VT, Low, DAG.getConstant(7, dl, VT));
28033 Ovf = DAG.getSetCC(dl, SetccVT, LowSign, High, ISD::SETNE);
28034 } else {
28035 // UMULO overflows if the high bits are non-zero.
28036 Ovf =
28037 DAG.getSetCC(dl, SetccVT, High, DAG.getConstant(0, dl, VT), ISD::SETNE);
28038 }
28039
28040 Ovf = DAG.getSExtOrTrunc(Ovf, dl, OvfVT);
28041
28042 return DAG.getMergeValues({Low, Ovf}, dl);
28043}
28044
28045SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
28046 assert(Subtarget.isTargetWin64() && "Unexpected target")(static_cast <bool> (Subtarget.isTargetWin64() &&
"Unexpected target") ? void (0) : __assert_fail ("Subtarget.isTargetWin64() && \"Unexpected target\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28046, __extension__ __PRETTY_FUNCTION__))
;
28047 EVT VT = Op.getValueType();
28048 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&(static_cast <bool> (VT.isInteger() && VT.getSizeInBits
() == 128 && "Unexpected return type for lowering") ?
void (0) : __assert_fail ("VT.isInteger() && VT.getSizeInBits() == 128 && \"Unexpected return type for lowering\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28049, __extension__ __PRETTY_FUNCTION__))
28049 "Unexpected return type for lowering")(static_cast <bool> (VT.isInteger() && VT.getSizeInBits
() == 128 && "Unexpected return type for lowering") ?
void (0) : __assert_fail ("VT.isInteger() && VT.getSizeInBits() == 128 && \"Unexpected return type for lowering\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28049, __extension__ __PRETTY_FUNCTION__))
;
28050
28051 RTLIB::Libcall LC;
28052 bool isSigned;
28053 switch (Op->getOpcode()) {
28054 default: llvm_unreachable("Unexpected request for libcall!")::llvm::llvm_unreachable_internal("Unexpected request for libcall!"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28054)
;
28055 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
28056 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
28057 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
28058 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
28059 }
28060
28061 SDLoc dl(Op);
28062 SDValue InChain = DAG.getEntryNode();
28063
28064 TargetLowering::ArgListTy Args;
28065 TargetLowering::ArgListEntry Entry;
28066 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
28067 EVT ArgVT = Op->getOperand(i).getValueType();
28068 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&(static_cast <bool> (ArgVT.isInteger() && ArgVT
.getSizeInBits() == 128 && "Unexpected argument type for lowering"
) ? void (0) : __assert_fail ("ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 && \"Unexpected argument type for lowering\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28069, __extension__ __PRETTY_FUNCTION__))
28069 "Unexpected argument type for lowering")(static_cast <bool> (ArgVT.isInteger() && ArgVT
.getSizeInBits() == 128 && "Unexpected argument type for lowering"
) ? void (0) : __assert_fail ("ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 && \"Unexpected argument type for lowering\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28069, __extension__ __PRETTY_FUNCTION__))
;
28070 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
28071 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
28072 MachinePointerInfo MPI =
28073 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
28074 Entry.Node = StackPtr;
28075 InChain =
28076 DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MPI, Align(16));
28077 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
28078 Entry.Ty = PointerType::get(ArgTy,0);
28079 Entry.IsSExt = false;
28080 Entry.IsZExt = false;
28081 Args.push_back(Entry);
28082 }
28083
28084 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
28085 getPointerTy(DAG.getDataLayout()));
28086
28087 TargetLowering::CallLoweringInfo CLI(DAG);
28088 CLI.setDebugLoc(dl)
28089 .setChain(InChain)
28090 .setLibCallee(
28091 getLibcallCallingConv(LC),
28092 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()), Callee,
28093 std::move(Args))
28094 .setInRegister()
28095 .setSExtResult(isSigned)
28096 .setZExtResult(!isSigned);
28097
28098 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
28099 return DAG.getBitcast(VT, CallInfo.first);
28100}
28101
28102// Return true if the required (according to Opcode) shift-imm form is natively
28103// supported by the Subtarget
28104static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget &Subtarget,
28105 unsigned Opcode) {
28106 if (VT.getScalarSizeInBits() < 16)
28107 return false;
28108
28109 if (VT.is512BitVector() && Subtarget.hasAVX512() &&
28110 (VT.getScalarSizeInBits() > 16 || Subtarget.hasBWI()))
28111 return true;
28112
28113 bool LShift = (VT.is128BitVector() && Subtarget.hasSSE2()) ||
28114 (VT.is256BitVector() && Subtarget.hasInt256());
28115
28116 bool AShift = LShift && (Subtarget.hasAVX512() ||
28117 (VT != MVT::v2i64 && VT != MVT::v4i64));
28118 return (Opcode == ISD::SRA) ? AShift : LShift;
28119}
28120
28121// The shift amount is a variable, but it is the same for all vector lanes.
28122// These instructions are defined together with shift-immediate.
28123static
28124bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget &Subtarget,
28125 unsigned Opcode) {
28126 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
28127}
28128
28129// Return true if the required (according to Opcode) variable-shift form is
28130// natively supported by the Subtarget
28131static bool SupportedVectorVarShift(MVT VT, const X86Subtarget &Subtarget,
28132 unsigned Opcode) {
28133
28134 if (!Subtarget.hasInt256() || VT.getScalarSizeInBits() < 16)
28135 return false;
28136
28137 // vXi16 supported only on AVX-512, BWI
28138 if (VT.getScalarSizeInBits() == 16 && !Subtarget.hasBWI())
28139 return false;
28140
28141 if (Subtarget.hasAVX512())
28142 return true;
28143
28144 bool LShift = VT.is128BitVector() || VT.is256BitVector();
28145 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
28146 return (Opcode == ISD::SRA) ? AShift : LShift;
28147}
28148
28149static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
28150 const X86Subtarget &Subtarget) {
28151 MVT VT = Op.getSimpleValueType();
28152 SDLoc dl(Op);
28153 SDValue R = Op.getOperand(0);
28154 SDValue Amt = Op.getOperand(1);
28155 unsigned X86Opc = getTargetVShiftUniformOpcode(Op.getOpcode(), false);
28156
28157 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
28158 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type")(static_cast <bool> ((VT == MVT::v2i64 || VT == MVT::v4i64
) && "Unexpected SRA type") ? void (0) : __assert_fail
("(VT == MVT::v2i64 || VT == MVT::v4i64) && \"Unexpected SRA type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28158, __extension__ __PRETTY_FUNCTION__))
;
28159 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
28160 SDValue Ex = DAG.getBitcast(ExVT, R);
28161
28162 // ashr(R, 63) === cmp_slt(R, 0)
28163 if (ShiftAmt == 63 && Subtarget.hasSSE42()) {
28164 assert((VT != MVT::v4i64 || Subtarget.hasInt256()) &&(static_cast <bool> ((VT != MVT::v4i64 || Subtarget.hasInt256
()) && "Unsupported PCMPGT op") ? void (0) : __assert_fail
("(VT != MVT::v4i64 || Subtarget.hasInt256()) && \"Unsupported PCMPGT op\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28165, __extension__ __PRETTY_FUNCTION__))
28165 "Unsupported PCMPGT op")(static_cast <bool> ((VT != MVT::v4i64 || Subtarget.hasInt256
()) && "Unsupported PCMPGT op") ? void (0) : __assert_fail
("(VT != MVT::v4i64 || Subtarget.hasInt256()) && \"Unsupported PCMPGT op\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28165, __extension__ __PRETTY_FUNCTION__))
;
28166 return DAG.getNode(X86ISD::PCMPGT, dl, VT, DAG.getConstant(0, dl, VT), R);
28167 }
28168
28169 if (ShiftAmt >= 32) {
28170 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
28171 SDValue Upper =
28172 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
28173 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
28174 ShiftAmt - 32, DAG);
28175 if (VT == MVT::v2i64)
28176 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
28177 if (VT == MVT::v4i64)
28178 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
28179 {9, 1, 11, 3, 13, 5, 15, 7});
28180 } else {
28181 // SRA upper i32, SRL whole i64 and select lower i32.
28182 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
28183 ShiftAmt, DAG);
28184 SDValue Lower =
28185 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
28186 Lower = DAG.getBitcast(ExVT, Lower);
28187 if (VT == MVT::v2i64)
28188 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
28189 if (VT == MVT::v4i64)
28190 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
28191 {8, 1, 10, 3, 12, 5, 14, 7});
28192 }
28193 return DAG.getBitcast(VT, Ex);
28194 };
28195
28196 // Optimize shl/srl/sra with constant shift amount.
28197 APInt APIntShiftAmt;
28198 if (!X86::isConstantSplat(Amt, APIntShiftAmt))
28199 return SDValue();
28200
28201 // If the shift amount is out of range, return undef.
28202 if (APIntShiftAmt.uge(VT.getScalarSizeInBits()))
28203 return DAG.getUNDEF(VT);
28204
28205 uint64_t ShiftAmt = APIntShiftAmt.getZExtValue();
28206
28207 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
28208 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
28209
28210 // i64 SRA needs to be performed as partial shifts.
28211 if (((!Subtarget.hasXOP() && VT == MVT::v2i64) ||
28212 (Subtarget.hasInt256() && VT == MVT::v4i64)) &&
28213 Op.getOpcode() == ISD::SRA)
28214 return ArithmeticShiftRight64(ShiftAmt);
28215
28216 if (VT == MVT::v16i8 || (Subtarget.hasInt256() && VT == MVT::v32i8) ||
28217 (Subtarget.hasBWI() && VT == MVT::v64i8)) {
28218 unsigned NumElts = VT.getVectorNumElements();
28219 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
28220
28221 // Simple i8 add case
28222 if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
28223 return DAG.getNode(ISD::ADD, dl, VT, R, R);
28224
28225 // ashr(R, 7) === cmp_slt(R, 0)
28226 if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
28227 SDValue Zeros = DAG.getConstant(0, dl, VT);
28228 if (VT.is512BitVector()) {
28229 assert(VT == MVT::v64i8 && "Unexpected element type!")(static_cast <bool> (VT == MVT::v64i8 && "Unexpected element type!"
) ? void (0) : __assert_fail ("VT == MVT::v64i8 && \"Unexpected element type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28229, __extension__ __PRETTY_FUNCTION__))
;
28230 SDValue CMP = DAG.getSetCC(dl, MVT::v64i1, Zeros, R, ISD::SETGT);
28231 return DAG.getNode(ISD::SIGN_EXTEND, dl, VT, CMP);
28232 }
28233 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
28234 }
28235
28236 // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
28237 if (VT == MVT::v16i8 && Subtarget.hasXOP())
28238 return SDValue();
28239
28240 if (Op.getOpcode() == ISD::SHL) {
28241 // Make a large shift.
28242 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT, R,
28243 ShiftAmt, DAG);
28244 SHL = DAG.getBitcast(VT, SHL);
28245 // Zero out the rightmost bits.
28246 APInt Mask = APInt::getHighBitsSet(8, 8 - ShiftAmt);
28247 return DAG.getNode(ISD::AND, dl, VT, SHL, DAG.getConstant(Mask, dl, VT));
28248 }
28249 if (Op.getOpcode() == ISD::SRL) {
28250 // Make a large shift.
28251 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT, R,
28252 ShiftAmt, DAG);
28253 SRL = DAG.getBitcast(VT, SRL);
28254 // Zero out the leftmost bits.
28255 APInt Mask = APInt::getLowBitsSet(8, 8 - ShiftAmt);
28256 return DAG.getNode(ISD::AND, dl, VT, SRL, DAG.getConstant(Mask, dl, VT));
28257 }
28258 if (Op.getOpcode() == ISD::SRA) {
28259 // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
28260 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
28261
28262 SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
28263 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
28264 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
28265 return Res;
28266 }
28267 llvm_unreachable("Unknown shift opcode.")::llvm::llvm_unreachable_internal("Unknown shift opcode.", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28267)
;
28268 }
28269
28270 return SDValue();
28271}
28272
28273static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
28274 const X86Subtarget &Subtarget) {
28275 MVT VT = Op.getSimpleValueType();
28276 SDLoc dl(Op);
28277 SDValue R = Op.getOperand(0);
28278 SDValue Amt = Op.getOperand(1);
28279 unsigned Opcode = Op.getOpcode();
28280 unsigned X86OpcI = getTargetVShiftUniformOpcode(Opcode, false);
28281 unsigned X86OpcV = getTargetVShiftUniformOpcode(Opcode, true);
28282
28283 if (SDValue BaseShAmt = DAG.getSplatValue(Amt)) {
28284 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Opcode)) {
28285 MVT EltVT = VT.getVectorElementType();
28286 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!")(static_cast <bool> (EltVT.bitsLE(MVT::i64) && "Unexpected element type!"
) ? void (0) : __assert_fail ("EltVT.bitsLE(MVT::i64) && \"Unexpected element type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28286, __extension__ __PRETTY_FUNCTION__))
;
28287 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
28288 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
28289 else if (EltVT.bitsLT(MVT::i32))
28290 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
28291
28292 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, Subtarget, DAG);
28293 }
28294
28295 // vXi8 shifts - shift as v8i16 + mask result.
28296 if (((VT == MVT::v16i8 && !Subtarget.canExtendTo512DQ()) ||
28297 (VT == MVT::v32i8 && !Subtarget.canExtendTo512BW()) ||
28298 VT == MVT::v64i8) &&
28299 !Subtarget.hasXOP()) {
28300 unsigned NumElts = VT.getVectorNumElements();
28301 MVT ExtVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
28302 if (SupportedVectorShiftWithBaseAmnt(ExtVT, Subtarget, Opcode)) {
28303 unsigned LogicalOp = (Opcode == ISD::SHL ? ISD::SHL : ISD::SRL);
28304 unsigned LogicalX86Op = getTargetVShiftUniformOpcode(LogicalOp, false);
28305 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
28306
28307 // Create the mask using vXi16 shifts. For shift-rights we need to move
28308 // the upper byte down before splatting the vXi8 mask.
28309 SDValue BitMask = DAG.getConstant(-1, dl, ExtVT);
28310 BitMask = getTargetVShiftNode(LogicalX86Op, dl, ExtVT, BitMask,
28311 BaseShAmt, Subtarget, DAG);
28312 if (Opcode != ISD::SHL)
28313 BitMask = getTargetVShiftByConstNode(LogicalX86Op, dl, ExtVT, BitMask,
28314 8, DAG);
28315 BitMask = DAG.getBitcast(VT, BitMask);
28316 BitMask = DAG.getVectorShuffle(VT, dl, BitMask, BitMask,
28317 SmallVector<int, 64>(NumElts, 0));
28318
28319 SDValue Res = getTargetVShiftNode(LogicalX86Op, dl, ExtVT,
28320 DAG.getBitcast(ExtVT, R), BaseShAmt,
28321 Subtarget, DAG);
28322 Res = DAG.getBitcast(VT, Res);
28323 Res = DAG.getNode(ISD::AND, dl, VT, Res, BitMask);
28324
28325 if (Opcode == ISD::SRA) {
28326 // ashr(R, Amt) === sub(xor(lshr(R, Amt), SignMask), SignMask)
28327 // SignMask = lshr(SignBit, Amt) - safe to do this with PSRLW.
28328 SDValue SignMask = DAG.getConstant(0x8080, dl, ExtVT);
28329 SignMask = getTargetVShiftNode(LogicalX86Op, dl, ExtVT, SignMask,
28330 BaseShAmt, Subtarget, DAG);
28331 SignMask = DAG.getBitcast(VT, SignMask);
28332 Res = DAG.getNode(ISD::XOR, dl, VT, Res, SignMask);
28333 Res = DAG.getNode(ISD::SUB, dl, VT, Res, SignMask);
28334 }
28335 return Res;
28336 }
28337 }
28338 }
28339
28340 // Check cases (mainly 32-bit) where i64 is expanded into high and low parts.
28341 if (VT == MVT::v2i64 && Amt.getOpcode() == ISD::BITCAST &&
28342 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
28343 Amt = Amt.getOperand(0);
28344 unsigned Ratio = 64 / Amt.getScalarValueSizeInBits();
28345 std::vector<SDValue> Vals(Ratio);
28346 for (unsigned i = 0; i != Ratio; ++i)
28347 Vals[i] = Amt.getOperand(i);
28348 for (unsigned i = Ratio, e = Amt.getNumOperands(); i != e; i += Ratio) {
28349 for (unsigned j = 0; j != Ratio; ++j)
28350 if (Vals[j] != Amt.getOperand(i + j))
28351 return SDValue();
28352 }
28353
28354 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
28355 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
28356 }
28357 return SDValue();
28358}
28359
28360// Convert a shift/rotate left amount to a multiplication scale factor.
28361static SDValue convertShiftLeftToScale(SDValue Amt, const SDLoc &dl,
28362 const X86Subtarget &Subtarget,
28363 SelectionDAG &DAG) {
28364 MVT VT = Amt.getSimpleValueType();
28365 if (!(VT == MVT::v8i16 || VT == MVT::v4i32 ||
28366 (Subtarget.hasInt256() && VT == MVT::v16i16) ||
28367 (Subtarget.hasVBMI2() && VT == MVT::v32i16) ||
28368 (!Subtarget.hasAVX512() && VT == MVT::v16i8)))
28369 return SDValue();
28370
28371 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
28372 SmallVector<SDValue, 8> Elts;
28373 MVT SVT = VT.getVectorElementType();
28374 unsigned SVTBits = SVT.getSizeInBits();
28375 APInt One(SVTBits, 1);
28376 unsigned NumElems = VT.getVectorNumElements();
28377
28378 for (unsigned i = 0; i != NumElems; ++i) {
28379 SDValue Op = Amt->getOperand(i);
28380 if (Op->isUndef()) {
28381 Elts.push_back(Op);
28382 continue;
28383 }
28384
28385 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
28386 APInt C(SVTBits, ND->getZExtValue());
28387 uint64_t ShAmt = C.getZExtValue();
28388 if (ShAmt >= SVTBits) {
28389 Elts.push_back(DAG.getUNDEF(SVT));
28390 continue;
28391 }
28392 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
28393 }
28394 return DAG.getBuildVector(VT, dl, Elts);
28395 }
28396
28397 // If the target doesn't support variable shifts, use either FP conversion
28398 // or integer multiplication to avoid shifting each element individually.
28399 if (VT == MVT::v4i32) {
28400 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
28401 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt,
28402 DAG.getConstant(0x3f800000U, dl, VT));
28403 Amt = DAG.getBitcast(MVT::v4f32, Amt);
28404 return DAG.getNode(ISD::FP_TO_SINT, dl, VT, Amt);
28405 }
28406
28407 // AVX2 can more effectively perform this as a zext/trunc to/from v8i32.
28408 if (VT == MVT::v8i16 && !Subtarget.hasAVX2()) {
28409 SDValue Z = DAG.getConstant(0, dl, VT);
28410 SDValue Lo = DAG.getBitcast(MVT::v4i32, getUnpackl(DAG, dl, VT, Amt, Z));
28411 SDValue Hi = DAG.getBitcast(MVT::v4i32, getUnpackh(DAG, dl, VT, Amt, Z));
28412 Lo = convertShiftLeftToScale(Lo, dl, Subtarget, DAG);
28413 Hi = convertShiftLeftToScale(Hi, dl, Subtarget, DAG);
28414 if (Subtarget.hasSSE41())
28415 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
28416
28417 return DAG.getVectorShuffle(VT, dl, DAG.getBitcast(VT, Lo),
28418 DAG.getBitcast(VT, Hi),
28419 {0, 2, 4, 6, 8, 10, 12, 14});
28420 }
28421
28422 return SDValue();
28423}
28424
28425static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
28426 SelectionDAG &DAG) {
28427 MVT VT = Op.getSimpleValueType();
28428 SDLoc dl(Op);
28429 SDValue R = Op.getOperand(0);
28430 SDValue Amt = Op.getOperand(1);
28431 unsigned EltSizeInBits = VT.getScalarSizeInBits();
28432 bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
28433
28434 unsigned Opc = Op.getOpcode();
28435 unsigned X86OpcV = getTargetVShiftUniformOpcode(Opc, true);
28436 unsigned X86OpcI = getTargetVShiftUniformOpcode(Opc, false);
28437
28438 assert(VT.isVector() && "Custom lowering only for vector shifts!")(static_cast <bool> (VT.isVector() && "Custom lowering only for vector shifts!"
) ? void (0) : __assert_fail ("VT.isVector() && \"Custom lowering only for vector shifts!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28438, __extension__ __PRETTY_FUNCTION__))
;
28439 assert(Subtarget.hasSSE2() && "Only custom lower when we have SSE2!")(static_cast <bool> (Subtarget.hasSSE2() && "Only custom lower when we have SSE2!"
) ? void (0) : __assert_fail ("Subtarget.hasSSE2() && \"Only custom lower when we have SSE2!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28439, __extension__ __PRETTY_FUNCTION__))
;
28440
28441 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
28442 return V;
28443
28444 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
28445 return V;
28446
28447 if (SupportedVectorVarShift(VT, Subtarget, Opc))
28448 return Op;
28449
28450 // XOP has 128-bit variable logical/arithmetic shifts.
28451 // +ve/-ve Amt = shift left/right.
28452 if (Subtarget.hasXOP() && (VT == MVT::v2i64 || VT == MVT::v4i32 ||
28453 VT == MVT::v8i16 || VT == MVT::v16i8)) {
28454 if (Opc == ISD::SRL || Opc == ISD::SRA) {
28455 SDValue Zero = DAG.getConstant(0, dl, VT);
28456 Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
28457 }
28458 if (Opc == ISD::SHL || Opc == ISD::SRL)
28459 return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
28460 if (Opc == ISD::SRA)
28461 return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
28462 }
28463
28464 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
28465 // shifts per-lane and then shuffle the partial results back together.
28466 if (VT == MVT::v2i64 && Opc != ISD::SRA) {
28467 // Splat the shift amounts so the scalar shifts above will catch it.
28468 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
28469 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
28470 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
28471 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
28472 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
28473 }
28474
28475 // i64 vector arithmetic shift can be emulated with the transform:
28476 // M = lshr(SIGN_MASK, Amt)
28477 // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
28478 if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget.hasInt256())) &&
28479 Opc == ISD::SRA) {
28480 SDValue S = DAG.getConstant(APInt::getSignMask(64), dl, VT);
28481 SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
28482 R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
28483 R = DAG.getNode(ISD::XOR, dl, VT, R, M);
28484 R = DAG.getNode(ISD::SUB, dl, VT, R, M);
28485 return R;
28486 }
28487
28488 // If possible, lower this shift as a sequence of two shifts by
28489 // constant plus a BLENDing shuffle instead of scalarizing it.
28490 // Example:
28491 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
28492 //
28493 // Could be rewritten as:
28494 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
28495 //
28496 // The advantage is that the two shifts from the example would be
28497 // lowered as X86ISD::VSRLI nodes in parallel before blending.
28498 if (ConstantAmt && (VT == MVT::v8i16 || VT == MVT::v4i32 ||
28499 (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
28500 SDValue Amt1, Amt2;
28501 unsigned NumElts = VT.getVectorNumElements();
28502 SmallVector<int, 8> ShuffleMask;
28503 for (unsigned i = 0; i != NumElts; ++i) {
28504 SDValue A = Amt->getOperand(i);
28505 if (A.isUndef()) {
28506 ShuffleMask.push_back(SM_SentinelUndef);
28507 continue;
28508 }
28509 if (!Amt1 || Amt1 == A) {
28510 ShuffleMask.push_back(i);
28511 Amt1 = A;
28512 continue;
28513 }
28514 if (!Amt2 || Amt2 == A) {
28515 ShuffleMask.push_back(i + NumElts);
28516 Amt2 = A;
28517 continue;
28518 }
28519 break;
28520 }
28521
28522 // Only perform this blend if we can perform it without loading a mask.
28523 if (ShuffleMask.size() == NumElts && Amt1 && Amt2 &&
28524 (VT != MVT::v16i16 ||
28525 is128BitLaneRepeatedShuffleMask(VT, ShuffleMask)) &&
28526 (VT == MVT::v4i32 || Subtarget.hasSSE41() || Opc != ISD::SHL ||
28527 canWidenShuffleElements(ShuffleMask))) {
28528 auto *Cst1 = dyn_cast<ConstantSDNode>(Amt1);
28529 auto *Cst2 = dyn_cast<ConstantSDNode>(Amt2);
28530 if (Cst1 && Cst2 && Cst1->getAPIntValue().ult(EltSizeInBits) &&
28531 Cst2->getAPIntValue().ult(EltSizeInBits)) {
28532 SDValue Shift1 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
28533 Cst1->getZExtValue(), DAG);
28534 SDValue Shift2 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
28535 Cst2->getZExtValue(), DAG);
28536 return DAG.getVectorShuffle(VT, dl, Shift1, Shift2, ShuffleMask);
28537 }
28538 }
28539 }
28540
28541 // If possible, lower this packed shift into a vector multiply instead of
28542 // expanding it into a sequence of scalar shifts.
28543 if (Opc == ISD::SHL)
28544 if (SDValue Scale = convertShiftLeftToScale(Amt, dl, Subtarget, DAG))
28545 return DAG.getNode(ISD::MUL, dl, VT, R, Scale);
28546
28547 // Constant ISD::SRL can be performed efficiently on vXi16 vectors as we
28548 // can replace with ISD::MULHU, creating scale factor from (NumEltBits - Amt).
28549 if (Opc == ISD::SRL && ConstantAmt &&
28550 (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
28551 SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
28552 SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
28553 if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
28554 SDValue Zero = DAG.getConstant(0, dl, VT);
28555 SDValue ZAmt = DAG.getSetCC(dl, VT, Amt, Zero, ISD::SETEQ);
28556 SDValue Res = DAG.getNode(ISD::MULHU, dl, VT, R, Scale);
28557 return DAG.getSelect(dl, VT, ZAmt, R, Res);
28558 }
28559 }
28560
28561 // Constant ISD::SRA can be performed efficiently on vXi16 vectors as we
28562 // can replace with ISD::MULHS, creating scale factor from (NumEltBits - Amt).
28563 // TODO: Special case handling for shift by 0/1, really we can afford either
28564 // of these cases in pre-SSE41/XOP/AVX512 but not both.
28565 if (Opc == ISD::SRA && ConstantAmt &&
28566 (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256())) &&
28567 ((Subtarget.hasSSE41() && !Subtarget.hasXOP() &&
28568 !Subtarget.hasAVX512()) ||
28569 DAG.isKnownNeverZero(Amt))) {
28570 SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
28571 SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
28572 if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
28573 SDValue Amt0 =
28574 DAG.getSetCC(dl, VT, Amt, DAG.getConstant(0, dl, VT), ISD::SETEQ);
28575 SDValue Amt1 =
28576 DAG.getSetCC(dl, VT, Amt, DAG.getConstant(1, dl, VT), ISD::SETEQ);
28577 SDValue Sra1 =
28578 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, 1, DAG);
28579 SDValue Res = DAG.getNode(ISD::MULHS, dl, VT, R, Scale);
28580 Res = DAG.getSelect(dl, VT, Amt0, R, Res);
28581 return DAG.getSelect(dl, VT, Amt1, Sra1, Res);
28582 }
28583 }
28584
28585 // v4i32 Non Uniform Shifts.
28586 // If the shift amount is constant we can shift each lane using the SSE2
28587 // immediate shifts, else we need to zero-extend each lane to the lower i64
28588 // and shift using the SSE2 variable shifts.
28589 // The separate results can then be blended together.
28590 if (VT == MVT::v4i32) {
28591 SDValue Amt0, Amt1, Amt2, Amt3;
28592 if (ConstantAmt) {
28593 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
28594 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
28595 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
28596 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
28597 } else {
28598 // The SSE2 shifts use the lower i64 as the same shift amount for
28599 // all lanes and the upper i64 is ignored. On AVX we're better off
28600 // just zero-extending, but for SSE just duplicating the top 16-bits is
28601 // cheaper and has the same effect for out of range values.
28602 if (Subtarget.hasAVX()) {
28603 SDValue Z = DAG.getConstant(0, dl, VT);
28604 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
28605 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
28606 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
28607 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
28608 } else {
28609 SDValue Amt01 = DAG.getBitcast(MVT::v8i16, Amt);
28610 SDValue Amt23 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
28611 {4, 5, 6, 7, -1, -1, -1, -1});
28612 Amt0 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
28613 {0, 1, 1, 1, -1, -1, -1, -1});
28614 Amt1 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
28615 {2, 3, 3, 3, -1, -1, -1, -1});
28616 Amt2 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt23, Amt23,
28617 {0, 1, 1, 1, -1, -1, -1, -1});
28618 Amt3 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt23, Amt23,
28619 {2, 3, 3, 3, -1, -1, -1, -1});
28620 }
28621 }
28622
28623 unsigned ShOpc = ConstantAmt ? Opc : X86OpcV;
28624 SDValue R0 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt0));
28625 SDValue R1 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt1));
28626 SDValue R2 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt2));
28627 SDValue R3 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt3));
28628
28629 // Merge the shifted lane results optimally with/without PBLENDW.
28630 // TODO - ideally shuffle combining would handle this.
28631 if (Subtarget.hasSSE41()) {
28632 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
28633 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
28634 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
28635 }
28636 SDValue R01 = DAG.getVectorShuffle(VT, dl, R0, R1, {0, -1, -1, 5});
28637 SDValue R23 = DAG.getVectorShuffle(VT, dl, R2, R3, {2, -1, -1, 7});
28638 return DAG.getVectorShuffle(VT, dl, R01, R23, {0, 3, 4, 7});
28639 }
28640
28641 // It's worth extending once and using the vXi16/vXi32 shifts for smaller
28642 // types, but without AVX512 the extra overheads to get from vXi8 to vXi32
28643 // make the existing SSE solution better.
28644 // NOTE: We honor prefered vector width before promoting to 512-bits.
28645 if ((Subtarget.hasInt256() && VT == MVT::v8i16) ||
28646 (Subtarget.canExtendTo512DQ() && VT == MVT::v16i16) ||
28647 (Subtarget.canExtendTo512DQ() && VT == MVT::v16i8) ||
28648 (Subtarget.canExtendTo512BW() && VT == MVT::v32i8) ||
28649 (Subtarget.hasBWI() && Subtarget.hasVLX() && VT == MVT::v16i8)) {
28650 assert((!Subtarget.hasBWI() || VT == MVT::v32i8 || VT == MVT::v16i8) &&(static_cast <bool> ((!Subtarget.hasBWI() || VT == MVT::
v32i8 || VT == MVT::v16i8) && "Unexpected vector type"
) ? void (0) : __assert_fail ("(!Subtarget.hasBWI() || VT == MVT::v32i8 || VT == MVT::v16i8) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28651, __extension__ __PRETTY_FUNCTION__))
28651 "Unexpected vector type")(static_cast <bool> ((!Subtarget.hasBWI() || VT == MVT::
v32i8 || VT == MVT::v16i8) && "Unexpected vector type"
) ? void (0) : __assert_fail ("(!Subtarget.hasBWI() || VT == MVT::v32i8 || VT == MVT::v16i8) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28651, __extension__ __PRETTY_FUNCTION__))
;
28652 MVT EvtSVT = Subtarget.hasBWI() ? MVT::i16 : MVT::i32;
28653 MVT ExtVT = MVT::getVectorVT(EvtSVT, VT.getVectorNumElements());
28654 unsigned ExtOpc = Opc == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
28655 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
28656 Amt = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Amt);
28657 return DAG.getNode(ISD::TRUNCATE, dl, VT,
28658 DAG.getNode(Opc, dl, ExtVT, R, Amt));
28659 }
28660
28661 // Constant ISD::SRA/SRL can be performed efficiently on vXi8 vectors as we
28662 // extend to vXi16 to perform a MUL scale effectively as a MUL_LOHI.
28663 if (ConstantAmt && (Opc == ISD::SRA || Opc == ISD::SRL) &&
28664 (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) ||
28665 (VT == MVT::v64i8 && Subtarget.hasBWI())) &&
28666 !Subtarget.hasXOP()) {
28667 int NumElts = VT.getVectorNumElements();
28668 SDValue Cst8 = DAG.getTargetConstant(8, dl, MVT::i8);
28669
28670 // Extend constant shift amount to vXi16 (it doesn't matter if the type
28671 // isn't legal).
28672 MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
28673 Amt = DAG.getZExtOrTrunc(Amt, dl, ExVT);
28674 Amt = DAG.getNode(ISD::SUB, dl, ExVT, DAG.getConstant(8, dl, ExVT), Amt);
28675 Amt = DAG.getNode(ISD::SHL, dl, ExVT, DAG.getConstant(1, dl, ExVT), Amt);
28676 assert(ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()) &&(static_cast <bool> (ISD::isBuildVectorOfConstantSDNodes
(Amt.getNode()) && "Constant build vector expected") ?
void (0) : __assert_fail ("ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()) && \"Constant build vector expected\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28677, __extension__ __PRETTY_FUNCTION__))
28677 "Constant build vector expected")(static_cast <bool> (ISD::isBuildVectorOfConstantSDNodes
(Amt.getNode()) && "Constant build vector expected") ?
void (0) : __assert_fail ("ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()) && \"Constant build vector expected\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28677, __extension__ __PRETTY_FUNCTION__))
;
28678
28679 if (VT == MVT::v16i8 && Subtarget.hasInt256()) {
28680 R = Opc == ISD::SRA ? DAG.getSExtOrTrunc(R, dl, ExVT)
28681 : DAG.getZExtOrTrunc(R, dl, ExVT);
28682 R = DAG.getNode(ISD::MUL, dl, ExVT, R, Amt);
28683 R = DAG.getNode(X86ISD::VSRLI, dl, ExVT, R, Cst8);
28684 return DAG.getZExtOrTrunc(R, dl, VT);
28685 }
28686
28687 SmallVector<SDValue, 16> LoAmt, HiAmt;
28688 for (int i = 0; i != NumElts; i += 16) {
28689 for (int j = 0; j != 8; ++j) {
28690 LoAmt.push_back(Amt.getOperand(i + j));
28691 HiAmt.push_back(Amt.getOperand(i + j + 8));
28692 }
28693 }
28694
28695 MVT VT16 = MVT::getVectorVT(MVT::i16, NumElts / 2);
28696 SDValue LoA = DAG.getBuildVector(VT16, dl, LoAmt);
28697 SDValue HiA = DAG.getBuildVector(VT16, dl, HiAmt);
28698
28699 SDValue LoR = DAG.getBitcast(VT16, getUnpackl(DAG, dl, VT, R, R));
28700 SDValue HiR = DAG.getBitcast(VT16, getUnpackh(DAG, dl, VT, R, R));
28701 LoR = DAG.getNode(X86OpcI, dl, VT16, LoR, Cst8);
28702 HiR = DAG.getNode(X86OpcI, dl, VT16, HiR, Cst8);
28703 LoR = DAG.getNode(ISD::MUL, dl, VT16, LoR, LoA);
28704 HiR = DAG.getNode(ISD::MUL, dl, VT16, HiR, HiA);
28705 LoR = DAG.getNode(X86ISD::VSRLI, dl, VT16, LoR, Cst8);
28706 HiR = DAG.getNode(X86ISD::VSRLI, dl, VT16, HiR, Cst8);
28707 return DAG.getNode(X86ISD::PACKUS, dl, VT, LoR, HiR);
28708 }
28709
28710 if (VT == MVT::v16i8 ||
28711 (VT == MVT::v32i8 && Subtarget.hasInt256() && !Subtarget.hasXOP()) ||
28712 (VT == MVT::v64i8 && Subtarget.hasBWI())) {
28713 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
28714
28715 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
28716 if (VT.is512BitVector()) {
28717 // On AVX512BW targets we make use of the fact that VSELECT lowers
28718 // to a masked blend which selects bytes based just on the sign bit
28719 // extracted to a mask.
28720 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
28721 V0 = DAG.getBitcast(VT, V0);
28722 V1 = DAG.getBitcast(VT, V1);
28723 Sel = DAG.getBitcast(VT, Sel);
28724 Sel = DAG.getSetCC(dl, MaskVT, DAG.getConstant(0, dl, VT), Sel,
28725 ISD::SETGT);
28726 return DAG.getBitcast(SelVT, DAG.getSelect(dl, VT, Sel, V0, V1));
28727 } else if (Subtarget.hasSSE41()) {
28728 // On SSE41 targets we can use PBLENDVB which selects bytes based just
28729 // on the sign bit.
28730 V0 = DAG.getBitcast(VT, V0);
28731 V1 = DAG.getBitcast(VT, V1);
28732 Sel = DAG.getBitcast(VT, Sel);
28733 return DAG.getBitcast(SelVT,
28734 DAG.getNode(X86ISD::BLENDV, dl, VT, Sel, V0, V1));
28735 }
28736 // On pre-SSE41 targets we test for the sign bit by comparing to
28737 // zero - a negative value will set all bits of the lanes to true
28738 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
28739 SDValue Z = DAG.getConstant(0, dl, SelVT);
28740 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
28741 return DAG.getSelect(dl, SelVT, C, V0, V1);
28742 };
28743
28744 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
28745 // We can safely do this using i16 shifts as we're only interested in
28746 // the 3 lower bits of each byte.
28747 Amt = DAG.getBitcast(ExtVT, Amt);
28748 Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ExtVT, Amt, 5, DAG);
28749 Amt = DAG.getBitcast(VT, Amt);
28750
28751 if (Opc == ISD::SHL || Opc == ISD::SRL) {
28752 // r = VSELECT(r, shift(r, 4), a);
28753 SDValue M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(4, dl, VT));
28754 R = SignBitSelect(VT, Amt, M, R);
28755
28756 // a += a
28757 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
28758
28759 // r = VSELECT(r, shift(r, 2), a);
28760 M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(2, dl, VT));
28761 R = SignBitSelect(VT, Amt, M, R);
28762
28763 // a += a
28764 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
28765
28766 // return VSELECT(r, shift(r, 1), a);
28767 M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(1, dl, VT));
28768 R = SignBitSelect(VT, Amt, M, R);
28769 return R;
28770 }
28771
28772 if (Opc == ISD::SRA) {
28773 // For SRA we need to unpack each byte to the higher byte of a i16 vector
28774 // so we can correctly sign extend. We don't care what happens to the
28775 // lower byte.
28776 SDValue ALo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
28777 SDValue AHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
28778 SDValue RLo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), R);
28779 SDValue RHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), R);
28780 ALo = DAG.getBitcast(ExtVT, ALo);
28781 AHi = DAG.getBitcast(ExtVT, AHi);
28782 RLo = DAG.getBitcast(ExtVT, RLo);
28783 RHi = DAG.getBitcast(ExtVT, RHi);
28784
28785 // r = VSELECT(r, shift(r, 4), a);
28786 SDValue MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 4, DAG);
28787 SDValue MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 4, DAG);
28788 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
28789 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
28790
28791 // a += a
28792 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
28793 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
28794
28795 // r = VSELECT(r, shift(r, 2), a);
28796 MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 2, DAG);
28797 MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 2, DAG);
28798 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
28799 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
28800
28801 // a += a
28802 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
28803 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
28804
28805 // r = VSELECT(r, shift(r, 1), a);
28806 MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 1, DAG);
28807 MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 1, DAG);
28808 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
28809 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
28810
28811 // Logical shift the result back to the lower byte, leaving a zero upper
28812 // byte meaning that we can safely pack with PACKUSWB.
28813 RLo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RLo, 8, DAG);
28814 RHi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RHi, 8, DAG);
28815 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
28816 }
28817 }
28818
28819 if (Subtarget.hasInt256() && !Subtarget.hasXOP() && VT == MVT::v16i16) {
28820 MVT ExtVT = MVT::v8i32;
28821 SDValue Z = DAG.getConstant(0, dl, VT);
28822 SDValue ALo = getUnpackl(DAG, dl, VT, Amt, Z);
28823 SDValue AHi = getUnpackh(DAG, dl, VT, Amt, Z);
28824 SDValue RLo = getUnpackl(DAG, dl, VT, Z, R);
28825 SDValue RHi = getUnpackh(DAG, dl, VT, Z, R);
28826 ALo = DAG.getBitcast(ExtVT, ALo);
28827 AHi = DAG.getBitcast(ExtVT, AHi);
28828 RLo = DAG.getBitcast(ExtVT, RLo);
28829 RHi = DAG.getBitcast(ExtVT, RHi);
28830 SDValue Lo = DAG.getNode(Opc, dl, ExtVT, RLo, ALo);
28831 SDValue Hi = DAG.getNode(Opc, dl, ExtVT, RHi, AHi);
28832 Lo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Lo, 16, DAG);
28833 Hi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Hi, 16, DAG);
28834 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
28835 }
28836
28837 if (VT == MVT::v8i16) {
28838 // If we have a constant shift amount, the non-SSE41 path is best as
28839 // avoiding bitcasts make it easier to constant fold and reduce to PBLENDW.
28840 bool UseSSE41 = Subtarget.hasSSE41() &&
28841 !ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
28842
28843 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
28844 // On SSE41 targets we can use PBLENDVB which selects bytes based just on
28845 // the sign bit.
28846 if (UseSSE41) {
28847 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
28848 V0 = DAG.getBitcast(ExtVT, V0);
28849 V1 = DAG.getBitcast(ExtVT, V1);
28850 Sel = DAG.getBitcast(ExtVT, Sel);
28851 return DAG.getBitcast(
28852 VT, DAG.getNode(X86ISD::BLENDV, dl, ExtVT, Sel, V0, V1));
28853 }
28854 // On pre-SSE41 targets we splat the sign bit - a negative value will
28855 // set all bits of the lanes to true and VSELECT uses that in
28856 // its OR(AND(V0,C),AND(V1,~C)) lowering.
28857 SDValue C =
28858 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Sel, 15, DAG);
28859 return DAG.getSelect(dl, VT, C, V0, V1);
28860 };
28861
28862 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
28863 if (UseSSE41) {
28864 // On SSE41 targets we need to replicate the shift mask in both
28865 // bytes for PBLENDVB.
28866 Amt = DAG.getNode(
28867 ISD::OR, dl, VT,
28868 getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 4, DAG),
28869 getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG));
28870 } else {
28871 Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG);
28872 }
28873
28874 // r = VSELECT(r, shift(r, 8), a);
28875 SDValue M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 8, DAG);
28876 R = SignBitSelect(Amt, M, R);
28877
28878 // a += a
28879 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
28880
28881 // r = VSELECT(r, shift(r, 4), a);
28882 M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 4, DAG);
28883 R = SignBitSelect(Amt, M, R);
28884
28885 // a += a
28886 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
28887
28888 // r = VSELECT(r, shift(r, 2), a);
28889 M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 2, DAG);
28890 R = SignBitSelect(Amt, M, R);
28891
28892 // a += a
28893 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
28894
28895 // return VSELECT(r, shift(r, 1), a);
28896 M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 1, DAG);
28897 R = SignBitSelect(Amt, M, R);
28898 return R;
28899 }
28900
28901 // Decompose 256-bit shifts into 128-bit shifts.
28902 if (VT.is256BitVector())
28903 return splitVectorIntBinary(Op, DAG);
28904
28905 if (VT == MVT::v32i16 || VT == MVT::v64i8)
28906 return splitVectorIntBinary(Op, DAG);
28907
28908 return SDValue();
28909}
28910
28911static SDValue LowerRotate(SDValue Op, const X86Subtarget &Subtarget,
28912 SelectionDAG &DAG) {
28913 MVT VT = Op.getSimpleValueType();
28914 assert(VT.isVector() && "Custom lowering only for vector rotates!")(static_cast <bool> (VT.isVector() && "Custom lowering only for vector rotates!"
) ? void (0) : __assert_fail ("VT.isVector() && \"Custom lowering only for vector rotates!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28914, __extension__ __PRETTY_FUNCTION__))
;
28915
28916 SDLoc DL(Op);
28917 SDValue R = Op.getOperand(0);
28918 SDValue Amt = Op.getOperand(1);
28919 unsigned Opcode = Op.getOpcode();
28920 unsigned EltSizeInBits = VT.getScalarSizeInBits();
28921 int NumElts = VT.getVectorNumElements();
28922
28923 // Check for constant splat rotation amount.
28924 APInt CstSplatValue;
28925 bool IsCstSplat = X86::isConstantSplat(Amt, CstSplatValue);
28926
28927 // Check for splat rotate by zero.
28928 if (IsCstSplat && CstSplatValue.urem(EltSizeInBits) == 0)
28929 return R;
28930
28931 // AVX512 implicitly uses modulo rotation amounts.
28932 if (Subtarget.hasAVX512() && 32 <= EltSizeInBits) {
28933 // Attempt to rotate by immediate.
28934 if (IsCstSplat) {
28935 unsigned RotOpc = (Opcode == ISD::ROTL ? X86ISD::VROTLI : X86ISD::VROTRI);
28936 uint64_t RotAmt = CstSplatValue.urem(EltSizeInBits);
28937 return DAG.getNode(RotOpc, DL, VT, R,
28938 DAG.getTargetConstant(RotAmt, DL, MVT::i8));
28939 }
28940
28941 // Else, fall-back on VPROLV/VPRORV.
28942 return Op;
28943 }
28944
28945 // AVX512 VBMI2 vXi16 - lower to funnel shifts.
28946 if (Subtarget.hasVBMI2() && 16 == EltSizeInBits) {
28947 unsigned FunnelOpc = (Opcode == ISD::ROTL ? ISD::FSHL : ISD::FSHR);
28948 return DAG.getNode(FunnelOpc, DL, VT, R, R, Amt);
28949 }
28950
28951 assert((Opcode == ISD::ROTL) && "Only ROTL supported")(static_cast <bool> ((Opcode == ISD::ROTL) && "Only ROTL supported"
) ? void (0) : __assert_fail ("(Opcode == ISD::ROTL) && \"Only ROTL supported\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28951, __extension__ __PRETTY_FUNCTION__))
;
28952
28953 // XOP has 128-bit vector variable + immediate rotates.
28954 // +ve/-ve Amt = rotate left/right - just need to handle ISD::ROTL.
28955 // XOP implicitly uses modulo rotation amounts.
28956 if (Subtarget.hasXOP()) {
28957 if (VT.is256BitVector())
28958 return splitVectorIntBinary(Op, DAG);
28959 assert(VT.is128BitVector() && "Only rotate 128-bit vectors!")(static_cast <bool> (VT.is128BitVector() && "Only rotate 128-bit vectors!"
) ? void (0) : __assert_fail ("VT.is128BitVector() && \"Only rotate 128-bit vectors!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28959, __extension__ __PRETTY_FUNCTION__))
;
28960
28961 // Attempt to rotate by immediate.
28962 if (IsCstSplat) {
28963 uint64_t RotAmt = CstSplatValue.urem(EltSizeInBits);
28964 return DAG.getNode(X86ISD::VROTLI, DL, VT, R,
28965 DAG.getTargetConstant(RotAmt, DL, MVT::i8));
28966 }
28967
28968 // Use general rotate by variable (per-element).
28969 return Op;
28970 }
28971
28972 // Split 256-bit integers on pre-AVX2 targets.
28973 if (VT.is256BitVector() && !Subtarget.hasAVX2())
28974 return splitVectorIntBinary(Op, DAG);
28975
28976 assert((VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 ||(static_cast <bool> ((VT == MVT::v4i32 || VT == MVT::v8i16
|| VT == MVT::v16i8 || ((VT == MVT::v8i32 || VT == MVT::v16i16
|| VT == MVT::v32i8 || VT == MVT::v32i16) && Subtarget
.hasAVX2())) && "Only vXi32/vXi16/vXi8 vector rotates supported"
) ? void (0) : __assert_fail ("(VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 || ((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8 || VT == MVT::v32i16) && Subtarget.hasAVX2())) && \"Only vXi32/vXi16/vXi8 vector rotates supported\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28980, __extension__ __PRETTY_FUNCTION__))
28977 ((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8 ||(static_cast <bool> ((VT == MVT::v4i32 || VT == MVT::v8i16
|| VT == MVT::v16i8 || ((VT == MVT::v8i32 || VT == MVT::v16i16
|| VT == MVT::v32i8 || VT == MVT::v32i16) && Subtarget
.hasAVX2())) && "Only vXi32/vXi16/vXi8 vector rotates supported"
) ? void (0) : __assert_fail ("(VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 || ((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8 || VT == MVT::v32i16) && Subtarget.hasAVX2())) && \"Only vXi32/vXi16/vXi8 vector rotates supported\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28980, __extension__ __PRETTY_FUNCTION__))
28978 VT == MVT::v32i16) &&(static_cast <bool> ((VT == MVT::v4i32 || VT == MVT::v8i16
|| VT == MVT::v16i8 || ((VT == MVT::v8i32 || VT == MVT::v16i16
|| VT == MVT::v32i8 || VT == MVT::v32i16) && Subtarget
.hasAVX2())) && "Only vXi32/vXi16/vXi8 vector rotates supported"
) ? void (0) : __assert_fail ("(VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 || ((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8 || VT == MVT::v32i16) && Subtarget.hasAVX2())) && \"Only vXi32/vXi16/vXi8 vector rotates supported\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28980, __extension__ __PRETTY_FUNCTION__))
28979 Subtarget.hasAVX2())) &&(static_cast <bool> ((VT == MVT::v4i32 || VT == MVT::v8i16
|| VT == MVT::v16i8 || ((VT == MVT::v8i32 || VT == MVT::v16i16
|| VT == MVT::v32i8 || VT == MVT::v32i16) && Subtarget
.hasAVX2())) && "Only vXi32/vXi16/vXi8 vector rotates supported"
) ? void (0) : __assert_fail ("(VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 || ((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8 || VT == MVT::v32i16) && Subtarget.hasAVX2())) && \"Only vXi32/vXi16/vXi8 vector rotates supported\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28980, __extension__ __PRETTY_FUNCTION__))
28980 "Only vXi32/vXi16/vXi8 vector rotates supported")(static_cast <bool> ((VT == MVT::v4i32 || VT == MVT::v8i16
|| VT == MVT::v16i8 || ((VT == MVT::v8i32 || VT == MVT::v16i16
|| VT == MVT::v32i8 || VT == MVT::v32i16) && Subtarget
.hasAVX2())) && "Only vXi32/vXi16/vXi8 vector rotates supported"
) ? void (0) : __assert_fail ("(VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 || ((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8 || VT == MVT::v32i16) && Subtarget.hasAVX2())) && \"Only vXi32/vXi16/vXi8 vector rotates supported\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 28980, __extension__ __PRETTY_FUNCTION__))
;
28981
28982 // Rotate by an uniform constant - expand back to shifts.
28983 if (IsCstSplat)
28984 return SDValue();
28985
28986 bool IsSplatAmt = DAG.isSplatValue(Amt);
28987
28988 // v16i8/v32i8: Split rotation into rot4/rot2/rot1 stages and select by
28989 // the amount bit.
28990 if (EltSizeInBits == 8 && !IsSplatAmt) {
28991 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()))
28992 return SDValue();
28993
28994 // We don't need ModuloAmt here as we just peek at individual bits.
28995 MVT ExtVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
28996
28997 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
28998 if (Subtarget.hasSSE41()) {
28999 // On SSE41 targets we can use PBLENDVB which selects bytes based just
29000 // on the sign bit.
29001 V0 = DAG.getBitcast(VT, V0);
29002 V1 = DAG.getBitcast(VT, V1);
29003 Sel = DAG.getBitcast(VT, Sel);
29004 return DAG.getBitcast(SelVT,
29005 DAG.getNode(X86ISD::BLENDV, DL, VT, Sel, V0, V1));
29006 }
29007 // On pre-SSE41 targets we test for the sign bit by comparing to
29008 // zero - a negative value will set all bits of the lanes to true
29009 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
29010 SDValue Z = DAG.getConstant(0, DL, SelVT);
29011 SDValue C = DAG.getNode(X86ISD::PCMPGT, DL, SelVT, Z, Sel);
29012 return DAG.getSelect(DL, SelVT, C, V0, V1);
29013 };
29014
29015 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
29016 // We can safely do this using i16 shifts as we're only interested in
29017 // the 3 lower bits of each byte.
29018 Amt = DAG.getBitcast(ExtVT, Amt);
29019 Amt = DAG.getNode(ISD::SHL, DL, ExtVT, Amt, DAG.getConstant(5, DL, ExtVT));
29020 Amt = DAG.getBitcast(VT, Amt);
29021
29022 // r = VSELECT(r, rot(r, 4), a);
29023 SDValue M;
29024 M = DAG.getNode(
29025 ISD::OR, DL, VT,
29026 DAG.getNode(ISD::SHL, DL, VT, R, DAG.getConstant(4, DL, VT)),
29027 DAG.getNode(ISD::SRL, DL, VT, R, DAG.getConstant(4, DL, VT)));
29028 R = SignBitSelect(VT, Amt, M, R);
29029
29030 // a += a
29031 Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
29032
29033 // r = VSELECT(r, rot(r, 2), a);
29034 M = DAG.getNode(
29035 ISD::OR, DL, VT,
29036 DAG.getNode(ISD::SHL, DL, VT, R, DAG.getConstant(2, DL, VT)),
29037 DAG.getNode(ISD::SRL, DL, VT, R, DAG.getConstant(6, DL, VT)));
29038 R = SignBitSelect(VT, Amt, M, R);
29039
29040 // a += a
29041 Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
29042
29043 // return VSELECT(r, rot(r, 1), a);
29044 M = DAG.getNode(
29045 ISD::OR, DL, VT,
29046 DAG.getNode(ISD::SHL, DL, VT, R, DAG.getConstant(1, DL, VT)),
29047 DAG.getNode(ISD::SRL, DL, VT, R, DAG.getConstant(7, DL, VT)));
29048 return SignBitSelect(VT, Amt, M, R);
29049 }
29050
29051 // ISD::ROT* uses modulo rotate amounts.
29052 if (SDValue BaseRotAmt = DAG.getSplatValue(Amt)) {
29053 // If the amount is a splat, perform the modulo BEFORE the splat,
29054 // this helps LowerScalarVariableShift to remove the splat later.
29055 Amt = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, BaseRotAmt);
29056 Amt = DAG.getNode(ISD::AND, DL, VT, Amt,
29057 DAG.getConstant(EltSizeInBits - 1, DL, VT));
29058 Amt = DAG.getVectorShuffle(VT, DL, Amt, DAG.getUNDEF(VT),
29059 SmallVector<int>(NumElts, 0));
29060 } else {
29061 Amt = DAG.getNode(ISD::AND, DL, VT, Amt,
29062 DAG.getConstant(EltSizeInBits - 1, DL, VT));
29063 }
29064
29065 bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
29066 bool LegalVarShifts = SupportedVectorVarShift(VT, Subtarget, ISD::SHL) &&
29067 SupportedVectorVarShift(VT, Subtarget, ISD::SRL);
29068
29069 // Fallback for splats + all supported variable shifts.
29070 // Fallback for non-constants AVX2 vXi16 as well.
29071 if (IsSplatAmt || LegalVarShifts || (Subtarget.hasAVX2() && !ConstantAmt)) {
29072 SDValue AmtR = DAG.getConstant(EltSizeInBits, DL, VT);
29073 AmtR = DAG.getNode(ISD::SUB, DL, VT, AmtR, Amt);
29074 SDValue SHL = DAG.getNode(ISD::SHL, DL, VT, R, Amt);
29075 SDValue SRL = DAG.getNode(ISD::SRL, DL, VT, R, AmtR);
29076 return DAG.getNode(ISD::OR, DL, VT, SHL, SRL);
29077 }
29078
29079 // As with shifts, convert the rotation amount to a multiplication factor.
29080 SDValue Scale = convertShiftLeftToScale(Amt, DL, Subtarget, DAG);
29081 assert(Scale && "Failed to convert ROTL amount to scale")(static_cast <bool> (Scale && "Failed to convert ROTL amount to scale"
) ? void (0) : __assert_fail ("Scale && \"Failed to convert ROTL amount to scale\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29081, __extension__ __PRETTY_FUNCTION__))
;
29082
29083 // v8i16/v16i16: perform unsigned multiply hi/lo and OR the results.
29084 if (EltSizeInBits == 16) {
29085 SDValue Lo = DAG.getNode(ISD::MUL, DL, VT, R, Scale);
29086 SDValue Hi = DAG.getNode(ISD::MULHU, DL, VT, R, Scale);
29087 return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
29088 }
29089
29090 // v4i32: make use of the PMULUDQ instruction to multiply 2 lanes of v4i32
29091 // to v2i64 results at a time. The upper 32-bits contain the wrapped bits
29092 // that can then be OR'd with the lower 32-bits.
29093 assert(VT == MVT::v4i32 && "Only v4i32 vector rotate expected")(static_cast <bool> (VT == MVT::v4i32 && "Only v4i32 vector rotate expected"
) ? void (0) : __assert_fail ("VT == MVT::v4i32 && \"Only v4i32 vector rotate expected\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29093, __extension__ __PRETTY_FUNCTION__))
;
29094 static const int OddMask[] = {1, -1, 3, -1};
29095 SDValue R13 = DAG.getVectorShuffle(VT, DL, R, R, OddMask);
29096 SDValue Scale13 = DAG.getVectorShuffle(VT, DL, Scale, Scale, OddMask);
29097
29098 SDValue Res02 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
29099 DAG.getBitcast(MVT::v2i64, R),
29100 DAG.getBitcast(MVT::v2i64, Scale));
29101 SDValue Res13 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
29102 DAG.getBitcast(MVT::v2i64, R13),
29103 DAG.getBitcast(MVT::v2i64, Scale13));
29104 Res02 = DAG.getBitcast(VT, Res02);
29105 Res13 = DAG.getBitcast(VT, Res13);
29106
29107 return DAG.getNode(ISD::OR, DL, VT,
29108 DAG.getVectorShuffle(VT, DL, Res02, Res13, {0, 4, 2, 6}),
29109 DAG.getVectorShuffle(VT, DL, Res02, Res13, {1, 5, 3, 7}));
29110}
29111
29112/// Returns true if the operand type is exactly twice the native width, and
29113/// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
29114/// Used to know whether to use cmpxchg8/16b when expanding atomic operations
29115/// (otherwise we leave them alone to become __sync_fetch_and_... calls).
29116bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
29117 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
29118
29119 if (OpWidth == 64)
29120 return Subtarget.hasCmpxchg8b() && !Subtarget.is64Bit();
29121 if (OpWidth == 128)
29122 return Subtarget.hasCmpxchg16b();
29123
29124 return false;
29125}
29126
29127bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
29128 Type *MemType = SI->getValueOperand()->getType();
29129
29130 bool NoImplicitFloatOps =
29131 SI->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat);
29132 if (MemType->getPrimitiveSizeInBits() == 64 && !Subtarget.is64Bit() &&
29133 !Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
29134 (Subtarget.hasSSE1() || Subtarget.hasX87()))
29135 return false;
29136
29137 return needsCmpXchgNb(MemType);
29138}
29139
29140// Note: this turns large loads into lock cmpxchg8b/16b.
29141// TODO: In 32-bit mode, use MOVLPS when SSE1 is available?
29142TargetLowering::AtomicExpansionKind
29143X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
29144 Type *MemType = LI->getType();
29145
29146 // If this a 64 bit atomic load on a 32-bit target and SSE2 is enabled, we
29147 // can use movq to do the load. If we have X87 we can load into an 80-bit
29148 // X87 register and store it to a stack temporary.
29149 bool NoImplicitFloatOps =
29150 LI->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat);
29151 if (MemType->getPrimitiveSizeInBits() == 64 && !Subtarget.is64Bit() &&
29152 !Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
29153 (Subtarget.hasSSE1() || Subtarget.hasX87()))
29154 return AtomicExpansionKind::None;
29155
29156 return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
29157 : AtomicExpansionKind::None;
29158}
29159
29160TargetLowering::AtomicExpansionKind
29161X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
29162 unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
29163 Type *MemType = AI->getType();
29164
29165 // If the operand is too big, we must see if cmpxchg8/16b is available
29166 // and default to library calls otherwise.
29167 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
29168 return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
29169 : AtomicExpansionKind::None;
29170 }
29171
29172 AtomicRMWInst::BinOp Op = AI->getOperation();
29173 switch (Op) {
29174 default:
29175 llvm_unreachable("Unknown atomic operation")::llvm::llvm_unreachable_internal("Unknown atomic operation",
"/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29175)
;
29176 case AtomicRMWInst::Xchg:
29177 case AtomicRMWInst::Add:
29178 case AtomicRMWInst::Sub:
29179 // It's better to use xadd, xsub or xchg for these in all cases.
29180 return AtomicExpansionKind::None;
29181 case AtomicRMWInst::Or:
29182 case AtomicRMWInst::And:
29183 case AtomicRMWInst::Xor:
29184 // If the atomicrmw's result isn't actually used, we can just add a "lock"
29185 // prefix to a normal instruction for these operations.
29186 return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
29187 : AtomicExpansionKind::None;
29188 case AtomicRMWInst::Nand:
29189 case AtomicRMWInst::Max:
29190 case AtomicRMWInst::Min:
29191 case AtomicRMWInst::UMax:
29192 case AtomicRMWInst::UMin:
29193 case AtomicRMWInst::FAdd:
29194 case AtomicRMWInst::FSub:
29195 // These always require a non-trivial set of data operations on x86. We must
29196 // use a cmpxchg loop.
29197 return AtomicExpansionKind::CmpXChg;
29198 }
29199}
29200
29201LoadInst *
29202X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
29203 unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
29204 Type *MemType = AI->getType();
29205 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
29206 // there is no benefit in turning such RMWs into loads, and it is actually
29207 // harmful as it introduces a mfence.
29208 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
29209 return nullptr;
29210
29211 // If this is a canonical idempotent atomicrmw w/no uses, we have a better
29212 // lowering available in lowerAtomicArith.
29213 // TODO: push more cases through this path.
29214 if (auto *C = dyn_cast<ConstantInt>(AI->getValOperand()))
29215 if (AI->getOperation() == AtomicRMWInst::Or && C->isZero() &&
29216 AI->use_empty())
29217 return nullptr;
29218
29219 IRBuilder<> Builder(AI);
29220 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
29221 auto SSID = AI->getSyncScopeID();
29222 // We must restrict the ordering to avoid generating loads with Release or
29223 // ReleaseAcquire orderings.
29224 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
29225
29226 // Before the load we need a fence. Here is an example lifted from
29227 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
29228 // is required:
29229 // Thread 0:
29230 // x.store(1, relaxed);
29231 // r1 = y.fetch_add(0, release);
29232 // Thread 1:
29233 // y.fetch_add(42, acquire);
29234 // r2 = x.load(relaxed);
29235 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
29236 // lowered to just a load without a fence. A mfence flushes the store buffer,
29237 // making the optimization clearly correct.
29238 // FIXME: it is required if isReleaseOrStronger(Order) but it is not clear
29239 // otherwise, we might be able to be more aggressive on relaxed idempotent
29240 // rmw. In practice, they do not look useful, so we don't try to be
29241 // especially clever.
29242 if (SSID == SyncScope::SingleThread)
29243 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
29244 // the IR level, so we must wrap it in an intrinsic.
29245 return nullptr;
29246
29247 if (!Subtarget.hasMFence())
29248 // FIXME: it might make sense to use a locked operation here but on a
29249 // different cache-line to prevent cache-line bouncing. In practice it
29250 // is probably a small win, and x86 processors without mfence are rare
29251 // enough that we do not bother.
29252 return nullptr;
29253
29254 Function *MFence =
29255 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
29256 Builder.CreateCall(MFence, {});
29257
29258 // Finally we can emit the atomic load.
29259 LoadInst *Loaded = Builder.CreateAlignedLoad(
29260 AI->getType(), AI->getPointerOperand(), AI->getAlign());
29261 Loaded->setAtomic(Order, SSID);
29262 AI->replaceAllUsesWith(Loaded);
29263 AI->eraseFromParent();
29264 return Loaded;
29265}
29266
29267bool X86TargetLowering::lowerAtomicStoreAsStoreSDNode(const StoreInst &SI) const {
29268 if (!SI.isUnordered())
29269 return false;
29270 return ExperimentalUnorderedISEL;
29271}
29272bool X86TargetLowering::lowerAtomicLoadAsLoadSDNode(const LoadInst &LI) const {
29273 if (!LI.isUnordered())
29274 return false;
29275 return ExperimentalUnorderedISEL;
29276}
29277
29278
29279/// Emit a locked operation on a stack location which does not change any
29280/// memory location, but does involve a lock prefix. Location is chosen to be
29281/// a) very likely accessed only by a single thread to minimize cache traffic,
29282/// and b) definitely dereferenceable. Returns the new Chain result.
29283static SDValue emitLockedStackOp(SelectionDAG &DAG,
29284 const X86Subtarget &Subtarget, SDValue Chain,
29285 const SDLoc &DL) {
29286 // Implementation notes:
29287 // 1) LOCK prefix creates a full read/write reordering barrier for memory
29288 // operations issued by the current processor. As such, the location
29289 // referenced is not relevant for the ordering properties of the instruction.
29290 // See: Intel® 64 and IA-32 ArchitecturesSoftware Developer’s Manual,
29291 // 8.2.3.9 Loads and Stores Are Not Reordered with Locked Instructions
29292 // 2) Using an immediate operand appears to be the best encoding choice
29293 // here since it doesn't require an extra register.
29294 // 3) OR appears to be very slightly faster than ADD. (Though, the difference
29295 // is small enough it might just be measurement noise.)
29296 // 4) When choosing offsets, there are several contributing factors:
29297 // a) If there's no redzone, we default to TOS. (We could allocate a cache
29298 // line aligned stack object to improve this case.)
29299 // b) To minimize our chances of introducing a false dependence, we prefer
29300 // to offset the stack usage from TOS slightly.
29301 // c) To minimize concerns about cross thread stack usage - in particular,
29302 // the idiomatic MyThreadPool.run([&StackVars]() {...}) pattern which
29303 // captures state in the TOS frame and accesses it from many threads -
29304 // we want to use an offset such that the offset is in a distinct cache
29305 // line from the TOS frame.
29306 //
29307 // For a general discussion of the tradeoffs and benchmark results, see:
29308 // https://shipilev.net/blog/2014/on-the-fence-with-dependencies/
29309
29310 auto &MF = DAG.getMachineFunction();
29311 auto &TFL = *Subtarget.getFrameLowering();
29312 const unsigned SPOffset = TFL.has128ByteRedZone(MF) ? -64 : 0;
29313
29314 if (Subtarget.is64Bit()) {
29315 SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
29316 SDValue Ops[] = {
29317 DAG.getRegister(X86::RSP, MVT::i64), // Base
29318 DAG.getTargetConstant(1, DL, MVT::i8), // Scale
29319 DAG.getRegister(0, MVT::i64), // Index
29320 DAG.getTargetConstant(SPOffset, DL, MVT::i32), // Disp
29321 DAG.getRegister(0, MVT::i16), // Segment.
29322 Zero,
29323 Chain};
29324 SDNode *Res = DAG.getMachineNode(X86::OR32mi8Locked, DL, MVT::i32,
29325 MVT::Other, Ops);
29326 return SDValue(Res, 1);
29327 }
29328
29329 SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
29330 SDValue Ops[] = {
29331 DAG.getRegister(X86::ESP, MVT::i32), // Base
29332 DAG.getTargetConstant(1, DL, MVT::i8), // Scale
29333 DAG.getRegister(0, MVT::i32), // Index
29334 DAG.getTargetConstant(SPOffset, DL, MVT::i32), // Disp
29335 DAG.getRegister(0, MVT::i16), // Segment.
29336 Zero,
29337 Chain
29338 };
29339 SDNode *Res = DAG.getMachineNode(X86::OR32mi8Locked, DL, MVT::i32,
29340 MVT::Other, Ops);
29341 return SDValue(Res, 1);
29342}
29343
29344static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget &Subtarget,
29345 SelectionDAG &DAG) {
29346 SDLoc dl(Op);
29347 AtomicOrdering FenceOrdering =
29348 static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
29349 SyncScope::ID FenceSSID =
29350 static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
29351
29352 // The only fence that needs an instruction is a sequentially-consistent
29353 // cross-thread fence.
29354 if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
29355 FenceSSID == SyncScope::System) {
29356 if (Subtarget.hasMFence())
29357 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
29358
29359 SDValue Chain = Op.getOperand(0);
29360 return emitLockedStackOp(DAG, Subtarget, Chain, dl);
29361 }
29362
29363 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
29364 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
29365}
29366
29367static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget &Subtarget,
29368 SelectionDAG &DAG) {
29369 MVT T = Op.getSimpleValueType();
29370 SDLoc DL(Op);
29371 unsigned Reg = 0;
29372 unsigned size = 0;
29373 switch(T.SimpleTy) {
29374 default: llvm_unreachable("Invalid value type!")::llvm::llvm_unreachable_internal("Invalid value type!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29374)
;
29375 case MVT::i8: Reg = X86::AL; size = 1; break;
29376 case MVT::i16: Reg = X86::AX; size = 2; break;
29377 case MVT::i32: Reg = X86::EAX; size = 4; break;
29378 case MVT::i64:
29379 assert(Subtarget.is64Bit() && "Node not type legal!")(static_cast <bool> (Subtarget.is64Bit() && "Node not type legal!"
) ? void (0) : __assert_fail ("Subtarget.is64Bit() && \"Node not type legal!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29379, __extension__ __PRETTY_FUNCTION__))
;
29380 Reg = X86::RAX; size = 8;
29381 break;
29382 }
29383 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
29384 Op.getOperand(2), SDValue());
29385 SDValue Ops[] = { cpIn.getValue(0),
29386 Op.getOperand(1),
29387 Op.getOperand(3),
29388 DAG.getTargetConstant(size, DL, MVT::i8),
29389 cpIn.getValue(1) };
29390 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
29391 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
29392 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
29393 Ops, T, MMO);
29394
29395 SDValue cpOut =
29396 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
29397 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
29398 MVT::i32, cpOut.getValue(2));
29399 SDValue Success = getSETCC(X86::COND_E, EFLAGS, DL, DAG);
29400
29401 return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
29402 cpOut, Success, EFLAGS.getValue(1));
29403}
29404
29405// Create MOVMSKB, taking into account whether we need to split for AVX1.
29406static SDValue getPMOVMSKB(const SDLoc &DL, SDValue V, SelectionDAG &DAG,
29407 const X86Subtarget &Subtarget) {
29408 MVT InVT = V.getSimpleValueType();
29409
29410 if (InVT == MVT::v64i8) {
29411 SDValue Lo, Hi;
29412 std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
29413 Lo = getPMOVMSKB(DL, Lo, DAG, Subtarget);
29414 Hi = getPMOVMSKB(DL, Hi, DAG, Subtarget);
29415 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Lo);
29416 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Hi);
29417 Hi = DAG.getNode(ISD::SHL, DL, MVT::i64, Hi,
29418 DAG.getConstant(32, DL, MVT::i8));
29419 return DAG.getNode(ISD::OR, DL, MVT::i64, Lo, Hi);
29420 }
29421 if (InVT == MVT::v32i8 && !Subtarget.hasInt256()) {
29422 SDValue Lo, Hi;
29423 std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
29424 Lo = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Lo);
29425 Hi = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Hi);
29426 Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
29427 DAG.getConstant(16, DL, MVT::i8));
29428 return DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi);
29429 }
29430
29431 return DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
29432}
29433
29434static SDValue LowerBITCAST(SDValue Op, const X86Subtarget &Subtarget,
29435 SelectionDAG &DAG) {
29436 SDValue Src = Op.getOperand(0);
29437 MVT SrcVT = Src.getSimpleValueType();
29438 MVT DstVT = Op.getSimpleValueType();
29439
29440 // Legalize (v64i1 (bitcast i64 (X))) by splitting the i64, bitcasting each
29441 // half to v32i1 and concatenating the result.
29442 if (SrcVT == MVT::i64 && DstVT == MVT::v64i1) {
29443 assert(!Subtarget.is64Bit() && "Expected 32-bit mode")(static_cast <bool> (!Subtarget.is64Bit() && "Expected 32-bit mode"
) ? void (0) : __assert_fail ("!Subtarget.is64Bit() && \"Expected 32-bit mode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29443, __extension__ __PRETTY_FUNCTION__))
;
29444 assert(Subtarget.hasBWI() && "Expected BWI target")(static_cast <bool> (Subtarget.hasBWI() && "Expected BWI target"
) ? void (0) : __assert_fail ("Subtarget.hasBWI() && \"Expected BWI target\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29444, __extension__ __PRETTY_FUNCTION__))
;
29445 SDLoc dl(Op);
29446 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Src,
29447 DAG.getIntPtrConstant(0, dl));
29448 Lo = DAG.getBitcast(MVT::v32i1, Lo);
29449 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Src,
29450 DAG.getIntPtrConstant(1, dl));
29451 Hi = DAG.getBitcast(MVT::v32i1, Hi);
29452 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
29453 }
29454
29455 // Use MOVMSK for vector to scalar conversion to prevent scalarization.
29456 if ((SrcVT == MVT::v16i1 || SrcVT == MVT::v32i1) && DstVT.isScalarInteger()) {
29457 assert(!Subtarget.hasAVX512() && "Should use K-registers with AVX512")(static_cast <bool> (!Subtarget.hasAVX512() && "Should use K-registers with AVX512"
) ? void (0) : __assert_fail ("!Subtarget.hasAVX512() && \"Should use K-registers with AVX512\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29457, __extension__ __PRETTY_FUNCTION__))
;
29458 MVT SExtVT = SrcVT == MVT::v16i1 ? MVT::v16i8 : MVT::v32i8;
29459 SDLoc DL(Op);
29460 SDValue V = DAG.getSExtOrTrunc(Src, DL, SExtVT);
29461 V = getPMOVMSKB(DL, V, DAG, Subtarget);
29462 return DAG.getZExtOrTrunc(V, DL, DstVT);
29463 }
29464
29465 assert((SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8 ||(static_cast <bool> ((SrcVT == MVT::v2i32 || SrcVT == MVT
::v4i16 || SrcVT == MVT::v8i8 || SrcVT == MVT::i64) &&
"Unexpected VT!") ? void (0) : __assert_fail ("(SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8 || SrcVT == MVT::i64) && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29466, __extension__ __PRETTY_FUNCTION__))
29466 SrcVT == MVT::i64) && "Unexpected VT!")(static_cast <bool> ((SrcVT == MVT::v2i32 || SrcVT == MVT
::v4i16 || SrcVT == MVT::v8i8 || SrcVT == MVT::i64) &&
"Unexpected VT!") ? void (0) : __assert_fail ("(SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8 || SrcVT == MVT::i64) && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29466, __extension__ __PRETTY_FUNCTION__))
;
29467
29468 assert(Subtarget.hasSSE2() && "Requires at least SSE2!")(static_cast <bool> (Subtarget.hasSSE2() && "Requires at least SSE2!"
) ? void (0) : __assert_fail ("Subtarget.hasSSE2() && \"Requires at least SSE2!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29468, __extension__ __PRETTY_FUNCTION__))
;
29469 if (!(DstVT == MVT::f64 && SrcVT == MVT::i64) &&
29470 !(DstVT == MVT::x86mmx && SrcVT.isVector()))
29471 // This conversion needs to be expanded.
29472 return SDValue();
29473
29474 SDLoc dl(Op);
29475 if (SrcVT.isVector()) {
29476 // Widen the vector in input in the case of MVT::v2i32.
29477 // Example: from MVT::v2i32 to MVT::v4i32.
29478 MVT NewVT = MVT::getVectorVT(SrcVT.getVectorElementType(),
29479 SrcVT.getVectorNumElements() * 2);
29480 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewVT, Src,
29481 DAG.getUNDEF(SrcVT));
29482 } else {
29483 assert(SrcVT == MVT::i64 && !Subtarget.is64Bit() &&(static_cast <bool> (SrcVT == MVT::i64 && !Subtarget
.is64Bit() && "Unexpected source type in LowerBITCAST"
) ? void (0) : __assert_fail ("SrcVT == MVT::i64 && !Subtarget.is64Bit() && \"Unexpected source type in LowerBITCAST\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29484, __extension__ __PRETTY_FUNCTION__))
29484 "Unexpected source type in LowerBITCAST")(static_cast <bool> (SrcVT == MVT::i64 && !Subtarget
.is64Bit() && "Unexpected source type in LowerBITCAST"
) ? void (0) : __assert_fail ("SrcVT == MVT::i64 && !Subtarget.is64Bit() && \"Unexpected source type in LowerBITCAST\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29484, __extension__ __PRETTY_FUNCTION__))
;
29485 Src = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Src);
29486 }
29487
29488 MVT V2X64VT = DstVT == MVT::f64 ? MVT::v2f64 : MVT::v2i64;
29489 Src = DAG.getNode(ISD::BITCAST, dl, V2X64VT, Src);
29490
29491 if (DstVT == MVT::x86mmx)
29492 return DAG.getNode(X86ISD::MOVDQ2Q, dl, DstVT, Src);
29493
29494 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, DstVT, Src,
29495 DAG.getIntPtrConstant(0, dl));
29496}
29497
29498/// Compute the horizontal sum of bytes in V for the elements of VT.
29499///
29500/// Requires V to be a byte vector and VT to be an integer vector type with
29501/// wider elements than V's type. The width of the elements of VT determines
29502/// how many bytes of V are summed horizontally to produce each element of the
29503/// result.
29504static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
29505 const X86Subtarget &Subtarget,
29506 SelectionDAG &DAG) {
29507 SDLoc DL(V);
29508 MVT ByteVecVT = V.getSimpleValueType();
29509 MVT EltVT = VT.getVectorElementType();
29510 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&(static_cast <bool> (ByteVecVT.getVectorElementType() ==
MVT::i8 && "Expected value to have byte element type."
) ? void (0) : __assert_fail ("ByteVecVT.getVectorElementType() == MVT::i8 && \"Expected value to have byte element type.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29511, __extension__ __PRETTY_FUNCTION__))
29511 "Expected value to have byte element type.")(static_cast <bool> (ByteVecVT.getVectorElementType() ==
MVT::i8 && "Expected value to have byte element type."
) ? void (0) : __assert_fail ("ByteVecVT.getVectorElementType() == MVT::i8 && \"Expected value to have byte element type.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29511, __extension__ __PRETTY_FUNCTION__))
;
29512 assert(EltVT != MVT::i8 &&(static_cast <bool> (EltVT != MVT::i8 && "Horizontal byte sum only makes sense for wider elements!"
) ? void (0) : __assert_fail ("EltVT != MVT::i8 && \"Horizontal byte sum only makes sense for wider elements!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29513, __extension__ __PRETTY_FUNCTION__))
29513 "Horizontal byte sum only makes sense for wider elements!")(static_cast <bool> (EltVT != MVT::i8 && "Horizontal byte sum only makes sense for wider elements!"
) ? void (0) : __assert_fail ("EltVT != MVT::i8 && \"Horizontal byte sum only makes sense for wider elements!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29513, __extension__ __PRETTY_FUNCTION__))
;
29514 unsigned VecSize = VT.getSizeInBits();
29515 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!")(static_cast <bool> (ByteVecVT.getSizeInBits() == VecSize
&& "Cannot change vector size!") ? void (0) : __assert_fail
("ByteVecVT.getSizeInBits() == VecSize && \"Cannot change vector size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29515, __extension__ __PRETTY_FUNCTION__))
;
29516
29517 // PSADBW instruction horizontally add all bytes and leave the result in i64
29518 // chunks, thus directly computes the pop count for v2i64 and v4i64.
29519 if (EltVT == MVT::i64) {
29520 SDValue Zeros = DAG.getConstant(0, DL, ByteVecVT);
29521 MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
29522 V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
29523 return DAG.getBitcast(VT, V);
29524 }
29525
29526 if (EltVT == MVT::i32) {
29527 // We unpack the low half and high half into i32s interleaved with zeros so
29528 // that we can use PSADBW to horizontally sum them. The most useful part of
29529 // this is that it lines up the results of two PSADBW instructions to be
29530 // two v2i64 vectors which concatenated are the 4 population counts. We can
29531 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
29532 SDValue Zeros = DAG.getConstant(0, DL, VT);
29533 SDValue V32 = DAG.getBitcast(VT, V);
29534 SDValue Low = getUnpackl(DAG, DL, VT, V32, Zeros);
29535 SDValue High = getUnpackh(DAG, DL, VT, V32, Zeros);
29536
29537 // Do the horizontal sums into two v2i64s.
29538 Zeros = DAG.getConstant(0, DL, ByteVecVT);
29539 MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
29540 Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
29541 DAG.getBitcast(ByteVecVT, Low), Zeros);
29542 High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
29543 DAG.getBitcast(ByteVecVT, High), Zeros);
29544
29545 // Merge them together.
29546 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
29547 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
29548 DAG.getBitcast(ShortVecVT, Low),
29549 DAG.getBitcast(ShortVecVT, High));
29550
29551 return DAG.getBitcast(VT, V);
29552 }
29553
29554 // The only element type left is i16.
29555 assert(EltVT == MVT::i16 && "Unknown how to handle type")(static_cast <bool> (EltVT == MVT::i16 && "Unknown how to handle type"
) ? void (0) : __assert_fail ("EltVT == MVT::i16 && \"Unknown how to handle type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29555, __extension__ __PRETTY_FUNCTION__))
;
29556
29557 // To obtain pop count for each i16 element starting from the pop count for
29558 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
29559 // right by 8. It is important to shift as i16s as i8 vector shift isn't
29560 // directly supported.
29561 SDValue ShifterV = DAG.getConstant(8, DL, VT);
29562 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
29563 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
29564 DAG.getBitcast(ByteVecVT, V));
29565 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
29566}
29567
29568static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, const SDLoc &DL,
29569 const X86Subtarget &Subtarget,
29570 SelectionDAG &DAG) {
29571 MVT VT = Op.getSimpleValueType();
29572 MVT EltVT = VT.getVectorElementType();
29573 int NumElts = VT.getVectorNumElements();
29574 (void)EltVT;
29575 assert(EltVT == MVT::i8 && "Only vXi8 vector CTPOP lowering supported.")(static_cast <bool> (EltVT == MVT::i8 && "Only vXi8 vector CTPOP lowering supported."
) ? void (0) : __assert_fail ("EltVT == MVT::i8 && \"Only vXi8 vector CTPOP lowering supported.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29575, __extension__ __PRETTY_FUNCTION__))
;
29576
29577 // Implement a lookup table in register by using an algorithm based on:
29578 // http://wm.ite.pl/articles/sse-popcount.html
29579 //
29580 // The general idea is that every lower byte nibble in the input vector is an
29581 // index into a in-register pre-computed pop count table. We then split up the
29582 // input vector in two new ones: (1) a vector with only the shifted-right
29583 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
29584 // masked out higher ones) for each byte. PSHUFB is used separately with both
29585 // to index the in-register table. Next, both are added and the result is a
29586 // i8 vector where each element contains the pop count for input byte.
29587 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
29588 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
29589 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
29590 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
29591
29592 SmallVector<SDValue, 64> LUTVec;
29593 for (int i = 0; i < NumElts; ++i)
29594 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
29595 SDValue InRegLUT = DAG.getBuildVector(VT, DL, LUTVec);
29596 SDValue M0F = DAG.getConstant(0x0F, DL, VT);
29597
29598 // High nibbles
29599 SDValue FourV = DAG.getConstant(4, DL, VT);
29600 SDValue HiNibbles = DAG.getNode(ISD::SRL, DL, VT, Op, FourV);
29601
29602 // Low nibbles
29603 SDValue LoNibbles = DAG.getNode(ISD::AND, DL, VT, Op, M0F);
29604
29605 // The input vector is used as the shuffle mask that index elements into the
29606 // LUT. After counting low and high nibbles, add the vector to obtain the
29607 // final pop count per i8 element.
29608 SDValue HiPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, HiNibbles);
29609 SDValue LoPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, LoNibbles);
29610 return DAG.getNode(ISD::ADD, DL, VT, HiPopCnt, LoPopCnt);
29611}
29612
29613// Please ensure that any codegen change from LowerVectorCTPOP is reflected in
29614// updated cost models in X86TTIImpl::getIntrinsicInstrCost.
29615static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget &Subtarget,
29616 SelectionDAG &DAG) {
29617 MVT VT = Op.getSimpleValueType();
29618 assert((VT.is512BitVector() || VT.is256BitVector() || VT.is128BitVector()) &&(static_cast <bool> ((VT.is512BitVector() || VT.is256BitVector
() || VT.is128BitVector()) && "Unknown CTPOP type to handle"
) ? void (0) : __assert_fail ("(VT.is512BitVector() || VT.is256BitVector() || VT.is128BitVector()) && \"Unknown CTPOP type to handle\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29619, __extension__ __PRETTY_FUNCTION__))
29619 "Unknown CTPOP type to handle")(static_cast <bool> ((VT.is512BitVector() || VT.is256BitVector
() || VT.is128BitVector()) && "Unknown CTPOP type to handle"
) ? void (0) : __assert_fail ("(VT.is512BitVector() || VT.is256BitVector() || VT.is128BitVector()) && \"Unknown CTPOP type to handle\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29619, __extension__ __PRETTY_FUNCTION__))
;
29620 SDLoc DL(Op.getNode());
29621 SDValue Op0 = Op.getOperand(0);
29622
29623 // TRUNC(CTPOP(ZEXT(X))) to make use of vXi32/vXi64 VPOPCNT instructions.
29624 if (Subtarget.hasVPOPCNTDQ()) {
29625 unsigned NumElems = VT.getVectorNumElements();
29626 assert((VT.getVectorElementType() == MVT::i8 ||(static_cast <bool> ((VT.getVectorElementType() == MVT::
i8 || VT.getVectorElementType() == MVT::i16) && "Unexpected type"
) ? void (0) : __assert_fail ("(VT.getVectorElementType() == MVT::i8 || VT.getVectorElementType() == MVT::i16) && \"Unexpected type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29627, __extension__ __PRETTY_FUNCTION__))
29627 VT.getVectorElementType() == MVT::i16) && "Unexpected type")(static_cast <bool> ((VT.getVectorElementType() == MVT::
i8 || VT.getVectorElementType() == MVT::i16) && "Unexpected type"
) ? void (0) : __assert_fail ("(VT.getVectorElementType() == MVT::i8 || VT.getVectorElementType() == MVT::i16) && \"Unexpected type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29627, __extension__ __PRETTY_FUNCTION__))
;
29628 if (NumElems < 16 || (NumElems == 16 && Subtarget.canExtendTo512DQ())) {
29629 MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
29630 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, Op0);
29631 Op = DAG.getNode(ISD::CTPOP, DL, NewVT, Op);
29632 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
29633 }
29634 }
29635
29636 // Decompose 256-bit ops into smaller 128-bit ops.
29637 if (VT.is256BitVector() && !Subtarget.hasInt256())
29638 return splitVectorIntUnary(Op, DAG);
29639
29640 // Decompose 512-bit ops into smaller 256-bit ops.
29641 if (VT.is512BitVector() && !Subtarget.hasBWI())
29642 return splitVectorIntUnary(Op, DAG);
29643
29644 // For element types greater than i8, do vXi8 pop counts and a bytesum.
29645 if (VT.getScalarType() != MVT::i8) {
29646 MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
29647 SDValue ByteOp = DAG.getBitcast(ByteVT, Op0);
29648 SDValue PopCnt8 = DAG.getNode(ISD::CTPOP, DL, ByteVT, ByteOp);
29649 return LowerHorizontalByteSum(PopCnt8, VT, Subtarget, DAG);
29650 }
29651
29652 // We can't use the fast LUT approach, so fall back on LegalizeDAG.
29653 if (!Subtarget.hasSSSE3())
29654 return SDValue();
29655
29656 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
29657}
29658
29659static SDValue LowerCTPOP(SDValue Op, const X86Subtarget &Subtarget,
29660 SelectionDAG &DAG) {
29661 assert(Op.getSimpleValueType().isVector() &&(static_cast <bool> (Op.getSimpleValueType().isVector()
&& "We only do custom lowering for vector population count."
) ? void (0) : __assert_fail ("Op.getSimpleValueType().isVector() && \"We only do custom lowering for vector population count.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29662, __extension__ __PRETTY_FUNCTION__))
29662 "We only do custom lowering for vector population count.")(static_cast <bool> (Op.getSimpleValueType().isVector()
&& "We only do custom lowering for vector population count."
) ? void (0) : __assert_fail ("Op.getSimpleValueType().isVector() && \"We only do custom lowering for vector population count.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29662, __extension__ __PRETTY_FUNCTION__))
;
29663 return LowerVectorCTPOP(Op, Subtarget, DAG);
29664}
29665
29666static SDValue LowerBITREVERSE_XOP(SDValue Op, SelectionDAG &DAG) {
29667 MVT VT = Op.getSimpleValueType();
29668 SDValue In = Op.getOperand(0);
29669 SDLoc DL(Op);
29670
29671 // For scalars, its still beneficial to transfer to/from the SIMD unit to
29672 // perform the BITREVERSE.
29673 if (!VT.isVector()) {
29674 MVT VecVT = MVT::getVectorVT(VT, 128 / VT.getSizeInBits());
29675 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, In);
29676 Res = DAG.getNode(ISD::BITREVERSE, DL, VecVT, Res);
29677 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Res,
29678 DAG.getIntPtrConstant(0, DL));
29679 }
29680
29681 int NumElts = VT.getVectorNumElements();
29682 int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
29683
29684 // Decompose 256-bit ops into smaller 128-bit ops.
29685 if (VT.is256BitVector())
29686 return splitVectorIntUnary(Op, DAG);
29687
29688 assert(VT.is128BitVector() &&(static_cast <bool> (VT.is128BitVector() && "Only 128-bit vector bitreverse lowering supported."
) ? void (0) : __assert_fail ("VT.is128BitVector() && \"Only 128-bit vector bitreverse lowering supported.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29689, __extension__ __PRETTY_FUNCTION__))
29689 "Only 128-bit vector bitreverse lowering supported.")(static_cast <bool> (VT.is128BitVector() && "Only 128-bit vector bitreverse lowering supported."
) ? void (0) : __assert_fail ("VT.is128BitVector() && \"Only 128-bit vector bitreverse lowering supported.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29689, __extension__ __PRETTY_FUNCTION__))
;
29690
29691 // VPPERM reverses the bits of a byte with the permute Op (2 << 5), and we
29692 // perform the BSWAP in the shuffle.
29693 // Its best to shuffle using the second operand as this will implicitly allow
29694 // memory folding for multiple vectors.
29695 SmallVector<SDValue, 16> MaskElts;
29696 for (int i = 0; i != NumElts; ++i) {
29697 for (int j = ScalarSizeInBytes - 1; j >= 0; --j) {
29698 int SourceByte = 16 + (i * ScalarSizeInBytes) + j;
29699 int PermuteByte = SourceByte | (2 << 5);
29700 MaskElts.push_back(DAG.getConstant(PermuteByte, DL, MVT::i8));
29701 }
29702 }
29703
29704 SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, MaskElts);
29705 SDValue Res = DAG.getBitcast(MVT::v16i8, In);
29706 Res = DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, DAG.getUNDEF(MVT::v16i8),
29707 Res, Mask);
29708 return DAG.getBitcast(VT, Res);
29709}
29710
29711static SDValue LowerBITREVERSE(SDValue Op, const X86Subtarget &Subtarget,
29712 SelectionDAG &DAG) {
29713 MVT VT = Op.getSimpleValueType();
29714
29715 if (Subtarget.hasXOP() && !VT.is512BitVector())
29716 return LowerBITREVERSE_XOP(Op, DAG);
29717
29718 assert(Subtarget.hasSSSE3() && "SSSE3 required for BITREVERSE")(static_cast <bool> (Subtarget.hasSSSE3() && "SSSE3 required for BITREVERSE"
) ? void (0) : __assert_fail ("Subtarget.hasSSSE3() && \"SSSE3 required for BITREVERSE\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29718, __extension__ __PRETTY_FUNCTION__))
;
29719
29720 SDValue In = Op.getOperand(0);
29721 SDLoc DL(Op);
29722
29723 assert(VT.getScalarType() == MVT::i8 &&(static_cast <bool> (VT.getScalarType() == MVT::i8 &&
"Only byte vector BITREVERSE supported") ? void (0) : __assert_fail
("VT.getScalarType() == MVT::i8 && \"Only byte vector BITREVERSE supported\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29724, __extension__ __PRETTY_FUNCTION__))
29724 "Only byte vector BITREVERSE supported")(static_cast <bool> (VT.getScalarType() == MVT::i8 &&
"Only byte vector BITREVERSE supported") ? void (0) : __assert_fail
("VT.getScalarType() == MVT::i8 && \"Only byte vector BITREVERSE supported\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29724, __extension__ __PRETTY_FUNCTION__))
;
29725
29726 // Split v64i8 without BWI so that we can still use the PSHUFB lowering.
29727 if (VT == MVT::v64i8 && !Subtarget.hasBWI())
29728 return splitVectorIntUnary(Op, DAG);
29729
29730 // Decompose 256-bit ops into smaller 128-bit ops on pre-AVX2.
29731 if (VT == MVT::v32i8 && !Subtarget.hasInt256())
29732 return splitVectorIntUnary(Op, DAG);
29733
29734 unsigned NumElts = VT.getVectorNumElements();
29735
29736 // If we have GFNI, we can use GF2P8AFFINEQB to reverse the bits.
29737 if (Subtarget.hasGFNI()) {
29738 MVT MatrixVT = MVT::getVectorVT(MVT::i64, NumElts / 8);
29739 SDValue Matrix = DAG.getConstant(0x8040201008040201ULL, DL, MatrixVT);
29740 Matrix = DAG.getBitcast(VT, Matrix);
29741 return DAG.getNode(X86ISD::GF2P8AFFINEQB, DL, VT, In, Matrix,
29742 DAG.getTargetConstant(0, DL, MVT::i8));
29743 }
29744
29745 // Perform BITREVERSE using PSHUFB lookups. Each byte is split into
29746 // two nibbles and a PSHUFB lookup to find the bitreverse of each
29747 // 0-15 value (moved to the other nibble).
29748 SDValue NibbleMask = DAG.getConstant(0xF, DL, VT);
29749 SDValue Lo = DAG.getNode(ISD::AND, DL, VT, In, NibbleMask);
29750 SDValue Hi = DAG.getNode(ISD::SRL, DL, VT, In, DAG.getConstant(4, DL, VT));
29751
29752 const int LoLUT[16] = {
29753 /* 0 */ 0x00, /* 1 */ 0x80, /* 2 */ 0x40, /* 3 */ 0xC0,
29754 /* 4 */ 0x20, /* 5 */ 0xA0, /* 6 */ 0x60, /* 7 */ 0xE0,
29755 /* 8 */ 0x10, /* 9 */ 0x90, /* a */ 0x50, /* b */ 0xD0,
29756 /* c */ 0x30, /* d */ 0xB0, /* e */ 0x70, /* f */ 0xF0};
29757 const int HiLUT[16] = {
29758 /* 0 */ 0x00, /* 1 */ 0x08, /* 2 */ 0x04, /* 3 */ 0x0C,
29759 /* 4 */ 0x02, /* 5 */ 0x0A, /* 6 */ 0x06, /* 7 */ 0x0E,
29760 /* 8 */ 0x01, /* 9 */ 0x09, /* a */ 0x05, /* b */ 0x0D,
29761 /* c */ 0x03, /* d */ 0x0B, /* e */ 0x07, /* f */ 0x0F};
29762
29763 SmallVector<SDValue, 16> LoMaskElts, HiMaskElts;
29764 for (unsigned i = 0; i < NumElts; ++i) {
29765 LoMaskElts.push_back(DAG.getConstant(LoLUT[i % 16], DL, MVT::i8));
29766 HiMaskElts.push_back(DAG.getConstant(HiLUT[i % 16], DL, MVT::i8));
29767 }
29768
29769 SDValue LoMask = DAG.getBuildVector(VT, DL, LoMaskElts);
29770 SDValue HiMask = DAG.getBuildVector(VT, DL, HiMaskElts);
29771 Lo = DAG.getNode(X86ISD::PSHUFB, DL, VT, LoMask, Lo);
29772 Hi = DAG.getNode(X86ISD::PSHUFB, DL, VT, HiMask, Hi);
29773 return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
29774}
29775
29776static SDValue LowerPARITY(SDValue Op, const X86Subtarget &Subtarget,
29777 SelectionDAG &DAG) {
29778 SDLoc DL(Op);
29779 SDValue X = Op.getOperand(0);
29780 MVT VT = Op.getSimpleValueType();
29781
29782 // Special case. If the input fits in 8-bits we can use a single 8-bit TEST.
29783 if (VT == MVT::i8 ||
29784 DAG.MaskedValueIsZero(X, APInt::getBitsSetFrom(VT.getSizeInBits(), 8))) {
29785 X = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, X);
29786 SDValue Flags = DAG.getNode(X86ISD::CMP, DL, MVT::i32, X,
29787 DAG.getConstant(0, DL, MVT::i8));
29788 // Copy the inverse of the parity flag into a register with setcc.
29789 SDValue Setnp = getSETCC(X86::COND_NP, Flags, DL, DAG);
29790 // Extend to the original type.
29791 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Setnp);
29792 }
29793
29794 if (VT == MVT::i64) {
29795 // Xor the high and low 16-bits together using a 32-bit operation.
29796 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
29797 DAG.getNode(ISD::SRL, DL, MVT::i64, X,
29798 DAG.getConstant(32, DL, MVT::i8)));
29799 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, X);
29800 X = DAG.getNode(ISD::XOR, DL, MVT::i32, Lo, Hi);
29801 }
29802
29803 if (VT != MVT::i16) {
29804 // Xor the high and low 16-bits together using a 32-bit operation.
29805 SDValue Hi16 = DAG.getNode(ISD::SRL, DL, MVT::i32, X,
29806 DAG.getConstant(16, DL, MVT::i8));
29807 X = DAG.getNode(ISD::XOR, DL, MVT::i32, X, Hi16);
29808 } else {
29809 // If the input is 16-bits, we need to extend to use an i32 shift below.
29810 X = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, X);
29811 }
29812
29813 // Finally xor the low 2 bytes together and use a 8-bit flag setting xor.
29814 // This should allow an h-reg to be used to save a shift.
29815 SDValue Hi = DAG.getNode(
29816 ISD::TRUNCATE, DL, MVT::i8,
29817 DAG.getNode(ISD::SRL, DL, MVT::i32, X, DAG.getConstant(8, DL, MVT::i8)));
29818 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, X);
29819 SDVTList VTs = DAG.getVTList(MVT::i8, MVT::i32);
29820 SDValue Flags = DAG.getNode(X86ISD::XOR, DL, VTs, Lo, Hi).getValue(1);
29821
29822 // Copy the inverse of the parity flag into a register with setcc.
29823 SDValue Setnp = getSETCC(X86::COND_NP, Flags, DL, DAG);
29824 // Extend to the original type.
29825 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Setnp);
29826}
29827
29828static SDValue lowerAtomicArithWithLOCK(SDValue N, SelectionDAG &DAG,
29829 const X86Subtarget &Subtarget) {
29830 unsigned NewOpc = 0;
29831 switch (N->getOpcode()) {
29832 case ISD::ATOMIC_LOAD_ADD:
29833 NewOpc = X86ISD::LADD;
29834 break;
29835 case ISD::ATOMIC_LOAD_SUB:
29836 NewOpc = X86ISD::LSUB;
29837 break;
29838 case ISD::ATOMIC_LOAD_OR:
29839 NewOpc = X86ISD::LOR;
29840 break;
29841 case ISD::ATOMIC_LOAD_XOR:
29842 NewOpc = X86ISD::LXOR;
29843 break;
29844 case ISD::ATOMIC_LOAD_AND:
29845 NewOpc = X86ISD::LAND;
29846 break;
29847 default:
29848 llvm_unreachable("Unknown ATOMIC_LOAD_ opcode")::llvm::llvm_unreachable_internal("Unknown ATOMIC_LOAD_ opcode"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29848)
;
29849 }
29850
29851 MachineMemOperand *MMO = cast<MemSDNode>(N)->getMemOperand();
29852
29853 return DAG.getMemIntrinsicNode(
29854 NewOpc, SDLoc(N), DAG.getVTList(MVT::i32, MVT::Other),
29855 {N->getOperand(0), N->getOperand(1), N->getOperand(2)},
29856 /*MemVT=*/N->getSimpleValueType(0), MMO);
29857}
29858
29859/// Lower atomic_load_ops into LOCK-prefixed operations.
29860static SDValue lowerAtomicArith(SDValue N, SelectionDAG &DAG,
29861 const X86Subtarget &Subtarget) {
29862 AtomicSDNode *AN = cast<AtomicSDNode>(N.getNode());
29863 SDValue Chain = N->getOperand(0);
29864 SDValue LHS = N->getOperand(1);
29865 SDValue RHS = N->getOperand(2);
29866 unsigned Opc = N->getOpcode();
29867 MVT VT = N->getSimpleValueType(0);
29868 SDLoc DL(N);
29869
29870 // We can lower atomic_load_add into LXADD. However, any other atomicrmw op
29871 // can only be lowered when the result is unused. They should have already
29872 // been transformed into a cmpxchg loop in AtomicExpand.
29873 if (N->hasAnyUseOfValue(0)) {
29874 // Handle (atomic_load_sub p, v) as (atomic_load_add p, -v), to be able to
29875 // select LXADD if LOCK_SUB can't be selected.
29876 if (Opc == ISD::ATOMIC_LOAD_SUB) {
29877 RHS = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), RHS);
29878 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, VT, Chain, LHS,
29879 RHS, AN->getMemOperand());
29880 }
29881 assert(Opc == ISD::ATOMIC_LOAD_ADD &&(static_cast <bool> (Opc == ISD::ATOMIC_LOAD_ADD &&
"Used AtomicRMW ops other than Add should have been expanded!"
) ? void (0) : __assert_fail ("Opc == ISD::ATOMIC_LOAD_ADD && \"Used AtomicRMW ops other than Add should have been expanded!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29882, __extension__ __PRETTY_FUNCTION__))
29882 "Used AtomicRMW ops other than Add should have been expanded!")(static_cast <bool> (Opc == ISD::ATOMIC_LOAD_ADD &&
"Used AtomicRMW ops other than Add should have been expanded!"
) ? void (0) : __assert_fail ("Opc == ISD::ATOMIC_LOAD_ADD && \"Used AtomicRMW ops other than Add should have been expanded!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29882, __extension__ __PRETTY_FUNCTION__))
;
29883 return N;
29884 }
29885
29886 // Specialized lowering for the canonical form of an idemptotent atomicrmw.
29887 // The core idea here is that since the memory location isn't actually
29888 // changing, all we need is a lowering for the *ordering* impacts of the
29889 // atomicrmw. As such, we can chose a different operation and memory
29890 // location to minimize impact on other code.
29891 if (Opc == ISD::ATOMIC_LOAD_OR && isNullConstant(RHS)) {
29892 // On X86, the only ordering which actually requires an instruction is
29893 // seq_cst which isn't SingleThread, everything just needs to be preserved
29894 // during codegen and then dropped. Note that we expect (but don't assume),
29895 // that orderings other than seq_cst and acq_rel have been canonicalized to
29896 // a store or load.
29897 if (AN->getSuccessOrdering() == AtomicOrdering::SequentiallyConsistent &&
29898 AN->getSyncScopeID() == SyncScope::System) {
29899 // Prefer a locked operation against a stack location to minimize cache
29900 // traffic. This assumes that stack locations are very likely to be
29901 // accessed only by the owning thread.
29902 SDValue NewChain = emitLockedStackOp(DAG, Subtarget, Chain, DL);
29903 assert(!N->hasAnyUseOfValue(0))(static_cast <bool> (!N->hasAnyUseOfValue(0)) ? void
(0) : __assert_fail ("!N->hasAnyUseOfValue(0)", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29903, __extension__ __PRETTY_FUNCTION__))
;
29904 // NOTE: The getUNDEF is needed to give something for the unused result 0.
29905 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
29906 DAG.getUNDEF(VT), NewChain);
29907 }
29908 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
29909 SDValue NewChain = DAG.getNode(X86ISD::MEMBARRIER, DL, MVT::Other, Chain);
29910 assert(!N->hasAnyUseOfValue(0))(static_cast <bool> (!N->hasAnyUseOfValue(0)) ? void
(0) : __assert_fail ("!N->hasAnyUseOfValue(0)", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29910, __extension__ __PRETTY_FUNCTION__))
;
29911 // NOTE: The getUNDEF is needed to give something for the unused result 0.
29912 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
29913 DAG.getUNDEF(VT), NewChain);
29914 }
29915
29916 SDValue LockOp = lowerAtomicArithWithLOCK(N, DAG, Subtarget);
29917 // RAUW the chain, but don't worry about the result, as it's unused.
29918 assert(!N->hasAnyUseOfValue(0))(static_cast <bool> (!N->hasAnyUseOfValue(0)) ? void
(0) : __assert_fail ("!N->hasAnyUseOfValue(0)", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 29918, __extension__ __PRETTY_FUNCTION__))
;
29919 // NOTE: The getUNDEF is needed to give something for the unused result 0.
29920 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
29921 DAG.getUNDEF(VT), LockOp.getValue(1));
29922}
29923
29924static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG,
29925 const X86Subtarget &Subtarget) {
29926 auto *Node = cast<AtomicSDNode>(Op.getNode());
29927 SDLoc dl(Node);
29928 EVT VT = Node->getMemoryVT();
29929
29930 bool IsSeqCst =
29931 Node->getSuccessOrdering() == AtomicOrdering::SequentiallyConsistent;
29932 bool IsTypeLegal = DAG.getTargetLoweringInfo().isTypeLegal(VT);
29933
29934 // If this store is not sequentially consistent and the type is legal
29935 // we can just keep it.
29936 if (!IsSeqCst && IsTypeLegal)
29937 return Op;
29938
29939 if (VT == MVT::i64 && !IsTypeLegal) {
29940 // For illegal i64 atomic_stores, we can try to use MOVQ or MOVLPS if SSE
29941 // is enabled.
29942 bool NoImplicitFloatOps =
29943 DAG.getMachineFunction().getFunction().hasFnAttribute(
29944 Attribute::NoImplicitFloat);
29945 if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps) {
29946 SDValue Chain;
29947 if (Subtarget.hasSSE1()) {
29948 SDValue SclToVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
29949 Node->getOperand(2));
29950 MVT StVT = Subtarget.hasSSE2() ? MVT::v2i64 : MVT::v4f32;
29951 SclToVec = DAG.getBitcast(StVT, SclToVec);
29952 SDVTList Tys = DAG.getVTList(MVT::Other);
29953 SDValue Ops[] = {Node->getChain(), SclToVec, Node->getBasePtr()};
29954 Chain = DAG.getMemIntrinsicNode(X86ISD::VEXTRACT_STORE, dl, Tys, Ops,
29955 MVT::i64, Node->getMemOperand());
29956 } else if (Subtarget.hasX87()) {
29957 // First load this into an 80-bit X87 register using a stack temporary.
29958 // This will put the whole integer into the significand.
29959 SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
29960 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
29961 MachinePointerInfo MPI =
29962 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
29963 Chain =
29964 DAG.getStore(Node->getChain(), dl, Node->getOperand(2), StackPtr,
29965 MPI, MaybeAlign(), MachineMemOperand::MOStore);
29966 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
29967 SDValue LdOps[] = {Chain, StackPtr};
29968 SDValue Value =
29969 DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, LdOps, MVT::i64, MPI,
29970 /*Align*/ None, MachineMemOperand::MOLoad);
29971 Chain = Value.getValue(1);
29972
29973 // Now use an FIST to do the atomic store.
29974 SDValue StoreOps[] = {Chain, Value, Node->getBasePtr()};
29975 Chain =
29976 DAG.getMemIntrinsicNode(X86ISD::FIST, dl, DAG.getVTList(MVT::Other),
29977 StoreOps, MVT::i64, Node->getMemOperand());
29978 }
29979
29980 if (Chain) {
29981 // If this is a sequentially consistent store, also emit an appropriate
29982 // barrier.
29983 if (IsSeqCst)
29984 Chain = emitLockedStackOp(DAG, Subtarget, Chain, dl);
29985
29986 return Chain;
29987 }
29988 }
29989 }
29990
29991 // Convert seq_cst store -> xchg
29992 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
29993 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
29994 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
29995 Node->getMemoryVT(),
29996 Node->getOperand(0),
29997 Node->getOperand(1), Node->getOperand(2),
29998 Node->getMemOperand());
29999 return Swap.getValue(1);
30000}
30001
30002static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
30003 SDNode *N = Op.getNode();
30004 MVT VT = N->getSimpleValueType(0);
30005 unsigned Opc = Op.getOpcode();
30006
30007 // Let legalize expand this if it isn't a legal type yet.
30008 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
30009 return SDValue();
30010
30011 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
30012 SDLoc DL(N);
30013
30014 // Set the carry flag.
30015 SDValue Carry = Op.getOperand(2);
30016 EVT CarryVT = Carry.getValueType();
30017 Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
30018 Carry, DAG.getAllOnesConstant(DL, CarryVT));
30019
30020 bool IsAdd = Opc == ISD::ADDCARRY || Opc == ISD::SADDO_CARRY;
30021 SDValue Sum = DAG.getNode(IsAdd ? X86ISD::ADC : X86ISD::SBB, DL, VTs,
30022 Op.getOperand(0), Op.getOperand(1),
30023 Carry.getValue(1));
30024
30025 bool IsSigned = Opc == ISD::SADDO_CARRY || Opc == ISD::SSUBO_CARRY;
30026 SDValue SetCC = getSETCC(IsSigned ? X86::COND_O : X86::COND_B,
30027 Sum.getValue(1), DL, DAG);
30028 if (N->getValueType(1) == MVT::i1)
30029 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
30030
30031 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
30032}
30033
30034static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget &Subtarget,
30035 SelectionDAG &DAG) {
30036 assert(Subtarget.isTargetDarwin() && Subtarget.is64Bit())(static_cast <bool> (Subtarget.isTargetDarwin() &&
Subtarget.is64Bit()) ? void (0) : __assert_fail ("Subtarget.isTargetDarwin() && Subtarget.is64Bit()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30036, __extension__ __PRETTY_FUNCTION__))
;
30037
30038 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
30039 // which returns the values as { float, float } (in XMM0) or
30040 // { double, double } (which is returned in XMM0, XMM1).
30041 SDLoc dl(Op);
30042 SDValue Arg = Op.getOperand(0);
30043 EVT ArgVT = Arg.getValueType();
30044 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
30045
30046 TargetLowering::ArgListTy Args;
30047 TargetLowering::ArgListEntry Entry;
30048
30049 Entry.Node = Arg;
30050 Entry.Ty = ArgTy;
30051 Entry.IsSExt = false;
30052 Entry.IsZExt = false;
30053 Args.push_back(Entry);
30054
30055 bool isF64 = ArgVT == MVT::f64;
30056 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
30057 // the small struct {f32, f32} is returned in (eax, edx). For f64,
30058 // the results are returned via SRet in memory.
30059 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
30060 RTLIB::Libcall LC = isF64 ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
30061 const char *LibcallName = TLI.getLibcallName(LC);
30062 SDValue Callee =
30063 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
30064
30065 Type *RetTy = isF64 ? (Type *)StructType::get(ArgTy, ArgTy)
30066 : (Type *)FixedVectorType::get(ArgTy, 4);
30067
30068 TargetLowering::CallLoweringInfo CLI(DAG);
30069 CLI.setDebugLoc(dl)
30070 .setChain(DAG.getEntryNode())
30071 .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args));
30072
30073 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
30074
30075 if (isF64)
30076 // Returned in xmm0 and xmm1.
30077 return CallResult.first;
30078
30079 // Returned in bits 0:31 and 32:64 xmm0.
30080 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
30081 CallResult.first, DAG.getIntPtrConstant(0, dl));
30082 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
30083 CallResult.first, DAG.getIntPtrConstant(1, dl));
30084 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
30085 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
30086}
30087
30088/// Widen a vector input to a vector of NVT. The
30089/// input vector must have the same element type as NVT.
30090static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
30091 bool FillWithZeroes = false) {
30092 // Check if InOp already has the right width.
30093 MVT InVT = InOp.getSimpleValueType();
30094 if (InVT == NVT)
30095 return InOp;
30096
30097 if (InOp.isUndef())
30098 return DAG.getUNDEF(NVT);
30099
30100 assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&(static_cast <bool> (InVT.getVectorElementType() == NVT
.getVectorElementType() && "input and widen element type must match"
) ? void (0) : __assert_fail ("InVT.getVectorElementType() == NVT.getVectorElementType() && \"input and widen element type must match\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30101, __extension__ __PRETTY_FUNCTION__))
30101 "input and widen element type must match")(static_cast <bool> (InVT.getVectorElementType() == NVT
.getVectorElementType() && "input and widen element type must match"
) ? void (0) : __assert_fail ("InVT.getVectorElementType() == NVT.getVectorElementType() && \"input and widen element type must match\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30101, __extension__ __PRETTY_FUNCTION__))
;
30102
30103 unsigned InNumElts = InVT.getVectorNumElements();
30104 unsigned WidenNumElts = NVT.getVectorNumElements();
30105 assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&(static_cast <bool> (WidenNumElts > InNumElts &&
WidenNumElts % InNumElts == 0 && "Unexpected request for vector widening"
) ? void (0) : __assert_fail ("WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 && \"Unexpected request for vector widening\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30106, __extension__ __PRETTY_FUNCTION__))
30106 "Unexpected request for vector widening")(static_cast <bool> (WidenNumElts > InNumElts &&
WidenNumElts % InNumElts == 0 && "Unexpected request for vector widening"
) ? void (0) : __assert_fail ("WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 && \"Unexpected request for vector widening\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30106, __extension__ __PRETTY_FUNCTION__))
;
30107
30108 SDLoc dl(InOp);
30109 if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
30110 InOp.getNumOperands() == 2) {
30111 SDValue N1 = InOp.getOperand(1);
30112 if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
30113 N1.isUndef()) {
30114 InOp = InOp.getOperand(0);
30115 InVT = InOp.getSimpleValueType();
30116 InNumElts = InVT.getVectorNumElements();
30117 }
30118 }
30119 if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
30120 ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
30121 SmallVector<SDValue, 16> Ops;
30122 for (unsigned i = 0; i < InNumElts; ++i)
30123 Ops.push_back(InOp.getOperand(i));
30124
30125 EVT EltVT = InOp.getOperand(0).getValueType();
30126
30127 SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
30128 DAG.getUNDEF(EltVT);
30129 for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
30130 Ops.push_back(FillVal);
30131 return DAG.getBuildVector(NVT, dl, Ops);
30132 }
30133 SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
30134 DAG.getUNDEF(NVT);
30135 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
30136 InOp, DAG.getIntPtrConstant(0, dl));
30137}
30138
30139static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget &Subtarget,
30140 SelectionDAG &DAG) {
30141 assert(Subtarget.hasAVX512() &&(static_cast <bool> (Subtarget.hasAVX512() && "MGATHER/MSCATTER are supported on AVX-512 arch only"
) ? void (0) : __assert_fail ("Subtarget.hasAVX512() && \"MGATHER/MSCATTER are supported on AVX-512 arch only\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30142, __extension__ __PRETTY_FUNCTION__))
30142 "MGATHER/MSCATTER are supported on AVX-512 arch only")(static_cast <bool> (Subtarget.hasAVX512() && "MGATHER/MSCATTER are supported on AVX-512 arch only"
) ? void (0) : __assert_fail ("Subtarget.hasAVX512() && \"MGATHER/MSCATTER are supported on AVX-512 arch only\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30142, __extension__ __PRETTY_FUNCTION__))
;
30143
30144 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
30145 SDValue Src = N->getValue();
30146 MVT VT = Src.getSimpleValueType();
30147 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op")(static_cast <bool> (VT.getScalarSizeInBits() >= 32 &&
"Unsupported scatter op") ? void (0) : __assert_fail ("VT.getScalarSizeInBits() >= 32 && \"Unsupported scatter op\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30147, __extension__ __PRETTY_FUNCTION__))
;
30148 SDLoc dl(Op);
30149
30150 SDValue Scale = N->getScale();
30151 SDValue Index = N->getIndex();
30152 SDValue Mask = N->getMask();
30153 SDValue Chain = N->getChain();
30154 SDValue BasePtr = N->getBasePtr();
30155
30156 if (VT == MVT::v2f32 || VT == MVT::v2i32) {
30157 assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type")(static_cast <bool> (Mask.getValueType() == MVT::v2i1 &&
"Unexpected mask type") ? void (0) : __assert_fail ("Mask.getValueType() == MVT::v2i1 && \"Unexpected mask type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30157, __extension__ __PRETTY_FUNCTION__))
;
30158 // If the index is v2i64 and we have VLX we can use xmm for data and index.
30159 if (Index.getValueType() == MVT::v2i64 && Subtarget.hasVLX()) {
30160 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
30161 EVT WideVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
30162 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Src, DAG.getUNDEF(VT));
30163 SDVTList VTs = DAG.getVTList(MVT::Other);
30164 SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
30165 return DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
30166 N->getMemoryVT(), N->getMemOperand());
30167 }
30168 return SDValue();
30169 }
30170
30171 MVT IndexVT = Index.getSimpleValueType();
30172
30173 // If the index is v2i32, we're being called by type legalization and we
30174 // should just let the default handling take care of it.
30175 if (IndexVT == MVT::v2i32)
30176 return SDValue();
30177
30178 // If we don't have VLX and neither the passthru or index is 512-bits, we
30179 // need to widen until one is.
30180 if (!Subtarget.hasVLX() && !VT.is512BitVector() &&
30181 !Index.getSimpleValueType().is512BitVector()) {
30182 // Determine how much we need to widen by to get a 512-bit type.
30183 unsigned Factor = std::min(512/VT.getSizeInBits(),
30184 512/IndexVT.getSizeInBits());
30185 unsigned NumElts = VT.getVectorNumElements() * Factor;
30186
30187 VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
30188 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
30189 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
30190
30191 Src = ExtendToType(Src, VT, DAG);
30192 Index = ExtendToType(Index, IndexVT, DAG);
30193 Mask = ExtendToType(Mask, MaskVT, DAG, true);
30194 }
30195
30196 SDVTList VTs = DAG.getVTList(MVT::Other);
30197 SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
30198 return DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
30199 N->getMemoryVT(), N->getMemOperand());
30200}
30201
30202static SDValue LowerMLOAD(SDValue Op, const X86Subtarget &Subtarget,
30203 SelectionDAG &DAG) {
30204
30205 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
30206 MVT VT = Op.getSimpleValueType();
30207 MVT ScalarVT = VT.getScalarType();
30208 SDValue Mask = N->getMask();
30209 MVT MaskVT = Mask.getSimpleValueType();
30210 SDValue PassThru = N->getPassThru();
30211 SDLoc dl(Op);
30212
30213 // Handle AVX masked loads which don't support passthru other than 0.
30214 if (MaskVT.getVectorElementType() != MVT::i1) {
30215 // We also allow undef in the isel pattern.
30216 if (PassThru.isUndef() || ISD::isBuildVectorAllZeros(PassThru.getNode()))
30217 return Op;
30218
30219 SDValue NewLoad = DAG.getMaskedLoad(
30220 VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask,
30221 getZeroVector(VT, Subtarget, DAG, dl), N->getMemoryVT(),
30222 N->getMemOperand(), N->getAddressingMode(), N->getExtensionType(),
30223 N->isExpandingLoad());
30224 // Emit a blend.
30225 SDValue Select = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
30226 return DAG.getMergeValues({ Select, NewLoad.getValue(1) }, dl);
30227 }
30228
30229 assert((!N->isExpandingLoad() || Subtarget.hasAVX512()) &&(static_cast <bool> ((!N->isExpandingLoad() || Subtarget
.hasAVX512()) && "Expanding masked load is supported on AVX-512 target only!"
) ? void (0) : __assert_fail ("(!N->isExpandingLoad() || Subtarget.hasAVX512()) && \"Expanding masked load is supported on AVX-512 target only!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30230, __extension__ __PRETTY_FUNCTION__))
30230 "Expanding masked load is supported on AVX-512 target only!")(static_cast <bool> ((!N->isExpandingLoad() || Subtarget
.hasAVX512()) && "Expanding masked load is supported on AVX-512 target only!"
) ? void (0) : __assert_fail ("(!N->isExpandingLoad() || Subtarget.hasAVX512()) && \"Expanding masked load is supported on AVX-512 target only!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30230, __extension__ __PRETTY_FUNCTION__))
;
30231
30232 assert((!N->isExpandingLoad() || ScalarVT.getSizeInBits() >= 32) &&(static_cast <bool> ((!N->isExpandingLoad() || ScalarVT
.getSizeInBits() >= 32) && "Expanding masked load is supported for 32 and 64-bit types only!"
) ? void (0) : __assert_fail ("(!N->isExpandingLoad() || ScalarVT.getSizeInBits() >= 32) && \"Expanding masked load is supported for 32 and 64-bit types only!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30233, __extension__ __PRETTY_FUNCTION__))
30233 "Expanding masked load is supported for 32 and 64-bit types only!")(static_cast <bool> ((!N->isExpandingLoad() || ScalarVT
.getSizeInBits() >= 32) && "Expanding masked load is supported for 32 and 64-bit types only!"
) ? void (0) : __assert_fail ("(!N->isExpandingLoad() || ScalarVT.getSizeInBits() >= 32) && \"Expanding masked load is supported for 32 and 64-bit types only!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30233, __extension__ __PRETTY_FUNCTION__))
;
30234
30235 assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&(static_cast <bool> (Subtarget.hasAVX512() && !
Subtarget.hasVLX() && !VT.is512BitVector() &&
"Cannot lower masked load op.") ? void (0) : __assert_fail (
"Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() && \"Cannot lower masked load op.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30236, __extension__ __PRETTY_FUNCTION__))
30236 "Cannot lower masked load op.")(static_cast <bool> (Subtarget.hasAVX512() && !
Subtarget.hasVLX() && !VT.is512BitVector() &&
"Cannot lower masked load op.") ? void (0) : __assert_fail (
"Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() && \"Cannot lower masked load op.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30236, __extension__ __PRETTY_FUNCTION__))
;
30237
30238 assert((ScalarVT.getSizeInBits() >= 32 ||(static_cast <bool> ((ScalarVT.getSizeInBits() >= 32
|| (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT
== MVT::i16))) && "Unsupported masked load op.") ? void
(0) : __assert_fail ("(ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && \"Unsupported masked load op.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30241, __extension__ __PRETTY_FUNCTION__))
30239 (Subtarget.hasBWI() &&(static_cast <bool> ((ScalarVT.getSizeInBits() >= 32
|| (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT
== MVT::i16))) && "Unsupported masked load op.") ? void
(0) : __assert_fail ("(ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && \"Unsupported masked load op.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30241, __extension__ __PRETTY_FUNCTION__))
30240 (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&(static_cast <bool> ((ScalarVT.getSizeInBits() >= 32
|| (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT
== MVT::i16))) && "Unsupported masked load op.") ? void
(0) : __assert_fail ("(ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && \"Unsupported masked load op.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30241, __extension__ __PRETTY_FUNCTION__))
30241 "Unsupported masked load op.")(static_cast <bool> ((ScalarVT.getSizeInBits() >= 32
|| (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT
== MVT::i16))) && "Unsupported masked load op.") ? void
(0) : __assert_fail ("(ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && \"Unsupported masked load op.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30241, __extension__ __PRETTY_FUNCTION__))
;
30242
30243 // This operation is legal for targets with VLX, but without
30244 // VLX the vector should be widened to 512 bit
30245 unsigned NumEltsInWideVec = 512 / VT.getScalarSizeInBits();
30246 MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
30247 PassThru = ExtendToType(PassThru, WideDataVT, DAG);
30248
30249 // Mask element has to be i1.
30250 assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&(static_cast <bool> (Mask.getSimpleValueType().getScalarType
() == MVT::i1 && "Unexpected mask type") ? void (0) :
__assert_fail ("Mask.getSimpleValueType().getScalarType() == MVT::i1 && \"Unexpected mask type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30251, __extension__ __PRETTY_FUNCTION__))
30251 "Unexpected mask type")(static_cast <bool> (Mask.getSimpleValueType().getScalarType
() == MVT::i1 && "Unexpected mask type") ? void (0) :
__assert_fail ("Mask.getSimpleValueType().getScalarType() == MVT::i1 && \"Unexpected mask type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30251, __extension__ __PRETTY_FUNCTION__))
;
30252
30253 MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
30254
30255 Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
30256 SDValue NewLoad = DAG.getMaskedLoad(
30257 WideDataVT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask,
30258 PassThru, N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
30259 N->getExtensionType(), N->isExpandingLoad());
30260
30261 SDValue Extract =
30262 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, NewLoad.getValue(0),
30263 DAG.getIntPtrConstant(0, dl));
30264 SDValue RetOps[] = {Extract, NewLoad.getValue(1)};
30265 return DAG.getMergeValues(RetOps, dl);
30266}
30267
30268static SDValue LowerMSTORE(SDValue Op, const X86Subtarget &Subtarget,
30269 SelectionDAG &DAG) {
30270 MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
30271 SDValue DataToStore = N->getValue();
30272 MVT VT = DataToStore.getSimpleValueType();
30273 MVT ScalarVT = VT.getScalarType();
30274 SDValue Mask = N->getMask();
30275 SDLoc dl(Op);
30276
30277 assert((!N->isCompressingStore() || Subtarget.hasAVX512()) &&(static_cast <bool> ((!N->isCompressingStore() || Subtarget
.hasAVX512()) && "Expanding masked load is supported on AVX-512 target only!"
) ? void (0) : __assert_fail ("(!N->isCompressingStore() || Subtarget.hasAVX512()) && \"Expanding masked load is supported on AVX-512 target only!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30278, __extension__ __PRETTY_FUNCTION__))
30278 "Expanding masked load is supported on AVX-512 target only!")(static_cast <bool> ((!N->isCompressingStore() || Subtarget
.hasAVX512()) && "Expanding masked load is supported on AVX-512 target only!"
) ? void (0) : __assert_fail ("(!N->isCompressingStore() || Subtarget.hasAVX512()) && \"Expanding masked load is supported on AVX-512 target only!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30278, __extension__ __PRETTY_FUNCTION__))
;
30279
30280 assert((!N->isCompressingStore() || ScalarVT.getSizeInBits() >= 32) &&(static_cast <bool> ((!N->isCompressingStore() || ScalarVT
.getSizeInBits() >= 32) && "Expanding masked load is supported for 32 and 64-bit types only!"
) ? void (0) : __assert_fail ("(!N->isCompressingStore() || ScalarVT.getSizeInBits() >= 32) && \"Expanding masked load is supported for 32 and 64-bit types only!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30281, __extension__ __PRETTY_FUNCTION__))
30281 "Expanding masked load is supported for 32 and 64-bit types only!")(static_cast <bool> ((!N->isCompressingStore() || ScalarVT
.getSizeInBits() >= 32) && "Expanding masked load is supported for 32 and 64-bit types only!"
) ? void (0) : __assert_fail ("(!N->isCompressingStore() || ScalarVT.getSizeInBits() >= 32) && \"Expanding masked load is supported for 32 and 64-bit types only!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30281, __extension__ __PRETTY_FUNCTION__))
;
30282
30283 assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&(static_cast <bool> (Subtarget.hasAVX512() && !
Subtarget.hasVLX() && !VT.is512BitVector() &&
"Cannot lower masked store op.") ? void (0) : __assert_fail (
"Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() && \"Cannot lower masked store op.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30284, __extension__ __PRETTY_FUNCTION__))
30284 "Cannot lower masked store op.")(static_cast <bool> (Subtarget.hasAVX512() && !
Subtarget.hasVLX() && !VT.is512BitVector() &&
"Cannot lower masked store op.") ? void (0) : __assert_fail (
"Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() && \"Cannot lower masked store op.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30284, __extension__ __PRETTY_FUNCTION__))
;
30285
30286 assert((ScalarVT.getSizeInBits() >= 32 ||(static_cast <bool> ((ScalarVT.getSizeInBits() >= 32
|| (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT
== MVT::i16))) && "Unsupported masked store op.") ? void
(0) : __assert_fail ("(ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && \"Unsupported masked store op.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30289, __extension__ __PRETTY_FUNCTION__))
30287 (Subtarget.hasBWI() &&(static_cast <bool> ((ScalarVT.getSizeInBits() >= 32
|| (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT
== MVT::i16))) && "Unsupported masked store op.") ? void
(0) : __assert_fail ("(ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && \"Unsupported masked store op.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30289, __extension__ __PRETTY_FUNCTION__))
30288 (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&(static_cast <bool> ((ScalarVT.getSizeInBits() >= 32
|| (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT
== MVT::i16))) && "Unsupported masked store op.") ? void
(0) : __assert_fail ("(ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && \"Unsupported masked store op.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30289, __extension__ __PRETTY_FUNCTION__))
30289 "Unsupported masked store op.")(static_cast <bool> ((ScalarVT.getSizeInBits() >= 32
|| (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT
== MVT::i16))) && "Unsupported masked store op.") ? void
(0) : __assert_fail ("(ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && \"Unsupported masked store op.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30289, __extension__ __PRETTY_FUNCTION__))
;
30290
30291 // This operation is legal for targets with VLX, but without
30292 // VLX the vector should be widened to 512 bit
30293 unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
30294 MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
30295
30296 // Mask element has to be i1.
30297 assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&(static_cast <bool> (Mask.getSimpleValueType().getScalarType
() == MVT::i1 && "Unexpected mask type") ? void (0) :
__assert_fail ("Mask.getSimpleValueType().getScalarType() == MVT::i1 && \"Unexpected mask type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30298, __extension__ __PRETTY_FUNCTION__))
30298 "Unexpected mask type")(static_cast <bool> (Mask.getSimpleValueType().getScalarType
() == MVT::i1 && "Unexpected mask type") ? void (0) :
__assert_fail ("Mask.getSimpleValueType().getScalarType() == MVT::i1 && \"Unexpected mask type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30298, __extension__ __PRETTY_FUNCTION__))
;
30299
30300 MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
30301
30302 DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
30303 Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
30304 return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
30305 N->getOffset(), Mask, N->getMemoryVT(),
30306 N->getMemOperand(), N->getAddressingMode(),
30307 N->isTruncatingStore(), N->isCompressingStore());
30308}
30309
30310static SDValue LowerMGATHER(SDValue Op, const X86Subtarget &Subtarget,
30311 SelectionDAG &DAG) {
30312 assert(Subtarget.hasAVX2() &&(static_cast <bool> (Subtarget.hasAVX2() && "MGATHER/MSCATTER are supported on AVX-512/AVX-2 arch only"
) ? void (0) : __assert_fail ("Subtarget.hasAVX2() && \"MGATHER/MSCATTER are supported on AVX-512/AVX-2 arch only\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30313, __extension__ __PRETTY_FUNCTION__))
30313 "MGATHER/MSCATTER are supported on AVX-512/AVX-2 arch only")(static_cast <bool> (Subtarget.hasAVX2() && "MGATHER/MSCATTER are supported on AVX-512/AVX-2 arch only"
) ? void (0) : __assert_fail ("Subtarget.hasAVX2() && \"MGATHER/MSCATTER are supported on AVX-512/AVX-2 arch only\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30313, __extension__ __PRETTY_FUNCTION__))
;
30314
30315 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
30316 SDLoc dl(Op);
30317 MVT VT = Op.getSimpleValueType();
30318 SDValue Index = N->getIndex();
30319 SDValue Mask = N->getMask();
30320 SDValue PassThru = N->getPassThru();
30321 MVT IndexVT = Index.getSimpleValueType();
30322
30323 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op")(static_cast <bool> (VT.getScalarSizeInBits() >= 32 &&
"Unsupported gather op") ? void (0) : __assert_fail ("VT.getScalarSizeInBits() >= 32 && \"Unsupported gather op\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30323, __extension__ __PRETTY_FUNCTION__))
;
30324
30325 // If the index is v2i32, we're being called by type legalization.
30326 if (IndexVT == MVT::v2i32)
30327 return SDValue();
30328
30329 // If we don't have VLX and neither the passthru or index is 512-bits, we
30330 // need to widen until one is.
30331 MVT OrigVT = VT;
30332 if (Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
30333 !IndexVT.is512BitVector()) {
30334 // Determine how much we need to widen by to get a 512-bit type.
30335 unsigned Factor = std::min(512/VT.getSizeInBits(),
30336 512/IndexVT.getSizeInBits());
30337
30338 unsigned NumElts = VT.getVectorNumElements() * Factor;
30339
30340 VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
30341 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
30342 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
30343
30344 PassThru = ExtendToType(PassThru, VT, DAG);
30345 Index = ExtendToType(Index, IndexVT, DAG);
30346 Mask = ExtendToType(Mask, MaskVT, DAG, true);
30347 }
30348
30349 SDValue Ops[] = { N->getChain(), PassThru, Mask, N->getBasePtr(), Index,
30350 N->getScale() };
30351 SDValue NewGather = DAG.getMemIntrinsicNode(
30352 X86ISD::MGATHER, dl, DAG.getVTList(VT, MVT::Other), Ops, N->getMemoryVT(),
30353 N->getMemOperand());
30354 SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OrigVT,
30355 NewGather, DAG.getIntPtrConstant(0, dl));
30356 return DAG.getMergeValues({Extract, NewGather.getValue(1)}, dl);
30357}
30358
30359static SDValue LowerADDRSPACECAST(SDValue Op, SelectionDAG &DAG) {
30360 SDLoc dl(Op);
30361 SDValue Src = Op.getOperand(0);
30362 MVT DstVT = Op.getSimpleValueType();
30363
30364 AddrSpaceCastSDNode *N = cast<AddrSpaceCastSDNode>(Op.getNode());
30365 unsigned SrcAS = N->getSrcAddressSpace();
30366
30367 assert(SrcAS != N->getDestAddressSpace() &&(static_cast <bool> (SrcAS != N->getDestAddressSpace
() && "addrspacecast must be between different address spaces"
) ? void (0) : __assert_fail ("SrcAS != N->getDestAddressSpace() && \"addrspacecast must be between different address spaces\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30368, __extension__ __PRETTY_FUNCTION__))
30368 "addrspacecast must be between different address spaces")(static_cast <bool> (SrcAS != N->getDestAddressSpace
() && "addrspacecast must be between different address spaces"
) ? void (0) : __assert_fail ("SrcAS != N->getDestAddressSpace() && \"addrspacecast must be between different address spaces\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30368, __extension__ __PRETTY_FUNCTION__))
;
30369
30370 if (SrcAS == X86AS::PTR32_UPTR && DstVT == MVT::i64) {
30371 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Src);
30372 } else if (DstVT == MVT::i64) {
30373 Op = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Src);
30374 } else if (DstVT == MVT::i32) {
30375 Op = DAG.getNode(ISD::TRUNCATE, dl, DstVT, Src);
30376 } else {
30377 report_fatal_error("Bad address space in addrspacecast");
30378 }
30379 return Op;
30380}
30381
30382SDValue X86TargetLowering::LowerGC_TRANSITION(SDValue Op,
30383 SelectionDAG &DAG) const {
30384 // TODO: Eventually, the lowering of these nodes should be informed by or
30385 // deferred to the GC strategy for the function in which they appear. For
30386 // now, however, they must be lowered to something. Since they are logically
30387 // no-ops in the case of a null GC strategy (or a GC strategy which does not
30388 // require special handling for these nodes), lower them as literal NOOPs for
30389 // the time being.
30390 SmallVector<SDValue, 2> Ops;
30391
30392 Ops.push_back(Op.getOperand(0));
30393 if (Op->getGluedNode())
30394 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
30395
30396 SDLoc OpDL(Op);
30397 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
30398 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
30399
30400 return NOOP;
30401}
30402
30403// Custom split CVTPS2PH with wide types.
30404static SDValue LowerCVTPS2PH(SDValue Op, SelectionDAG &DAG) {
30405 SDLoc dl(Op);
30406 EVT VT = Op.getValueType();
30407 SDValue Lo, Hi;
30408 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
30409 EVT LoVT, HiVT;
30410 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
30411 SDValue RC = Op.getOperand(1);
30412 Lo = DAG.getNode(X86ISD::CVTPS2PH, dl, LoVT, Lo, RC);
30413 Hi = DAG.getNode(X86ISD::CVTPS2PH, dl, HiVT, Hi, RC);
30414 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
30415}
30416
30417/// Provide custom lowering hooks for some operations.
30418SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
30419 switch (Op.getOpcode()) {
30420 default: llvm_unreachable("Should not custom lower this!")::llvm::llvm_unreachable_internal("Should not custom lower this!"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30420)
;
30421 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
30422 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
30423 return LowerCMP_SWAP(Op, Subtarget, DAG);
30424 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
30425 case ISD::ATOMIC_LOAD_ADD:
30426 case ISD::ATOMIC_LOAD_SUB:
30427 case ISD::ATOMIC_LOAD_OR:
30428 case ISD::ATOMIC_LOAD_XOR:
30429 case ISD::ATOMIC_LOAD_AND: return lowerAtomicArith(Op, DAG, Subtarget);
30430 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op, DAG, Subtarget);
30431 case ISD::BITREVERSE: return LowerBITREVERSE(Op, Subtarget, DAG);
30432 case ISD::PARITY: return LowerPARITY(Op, Subtarget, DAG);
30433 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
30434 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
30435 case ISD::VECTOR_SHUFFLE: return lowerVECTOR_SHUFFLE(Op, Subtarget, DAG);
30436 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
30437 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
30438 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
30439 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
30440 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
30441 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, Subtarget,DAG);
30442 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
30443 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
30444 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
30445 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
30446 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
30447 case ISD::SHL_PARTS:
30448 case ISD::SRA_PARTS:
30449 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
30450 case ISD::FSHL:
30451 case ISD::FSHR: return LowerFunnelShift(Op, Subtarget, DAG);
30452 case ISD::STRICT_SINT_TO_FP:
30453 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
30454 case ISD::STRICT_UINT_TO_FP:
30455 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
30456 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
30457 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
30458 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
30459 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
30460 case ISD::ZERO_EXTEND_VECTOR_INREG:
30461 case ISD::SIGN_EXTEND_VECTOR_INREG:
30462 return LowerEXTEND_VECTOR_INREG(Op, Subtarget, DAG);
30463 case ISD::FP_TO_SINT:
30464 case ISD::STRICT_FP_TO_SINT:
30465 case ISD::FP_TO_UINT:
30466 case ISD::STRICT_FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
30467 case ISD::FP_TO_SINT_SAT:
30468 case ISD::FP_TO_UINT_SAT: return LowerFP_TO_INT_SAT(Op, DAG);
30469 case ISD::FP_EXTEND:
30470 case ISD::STRICT_FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
30471 case ISD::FP_ROUND:
30472 case ISD::STRICT_FP_ROUND: return LowerFP_ROUND(Op, DAG);
30473 case ISD::FP16_TO_FP:
30474 case ISD::STRICT_FP16_TO_FP: return LowerFP16_TO_FP(Op, DAG);
30475 case ISD::FP_TO_FP16:
30476 case ISD::STRICT_FP_TO_FP16: return LowerFP_TO_FP16(Op, DAG);
30477 case ISD::LOAD: return LowerLoad(Op, Subtarget, DAG);
30478 case ISD::STORE: return LowerStore(Op, Subtarget, DAG);
30479 case ISD::FADD:
30480 case ISD::FSUB: return lowerFaddFsub(Op, DAG);
30481 case ISD::FROUND: return LowerFROUND(Op, DAG);
30482 case ISD::FABS:
30483 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
30484 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
30485 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
30486 case ISD::LRINT:
30487 case ISD::LLRINT: return LowerLRINT_LLRINT(Op, DAG);
30488 case ISD::SETCC:
30489 case ISD::STRICT_FSETCC:
30490 case ISD::STRICT_FSETCCS: return LowerSETCC(Op, DAG);
30491 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
30492 case ISD::SELECT: return LowerSELECT(Op, DAG);
30493 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
30494 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
30495 case ISD::VASTART: return LowerVASTART(Op, DAG);
30496 case ISD::VAARG: return LowerVAARG(Op, DAG);
30497 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
30498 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
30499 case ISD::INTRINSIC_VOID:
30500 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
30501 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
30502 case ISD::ADDROFRETURNADDR: return LowerADDROFRETURNADDR(Op, DAG);
30503 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
30504 case ISD::FRAME_TO_ARGS_OFFSET:
30505 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
30506 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
30507 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
30508 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
30509 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
30510 case ISD::EH_SJLJ_SETUP_DISPATCH:
30511 return lowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
30512 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
30513 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
30514 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
30515 case ISD::SET_ROUNDING: return LowerSET_ROUNDING(Op, DAG);
30516 case ISD::CTLZ:
30517 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ(Op, Subtarget, DAG);
30518 case ISD::CTTZ:
30519 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op, Subtarget, DAG);
30520 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
30521 case ISD::MULHS:
30522 case ISD::MULHU: return LowerMULH(Op, Subtarget, DAG);
30523 case ISD::ROTL:
30524 case ISD::ROTR: return LowerRotate(Op, Subtarget, DAG);
30525 case ISD::SRA:
30526 case ISD::SRL:
30527 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
30528 case ISD::SADDO:
30529 case ISD::UADDO:
30530 case ISD::SSUBO:
30531 case ISD::USUBO: return LowerXALUO(Op, DAG);
30532 case ISD::SMULO:
30533 case ISD::UMULO: return LowerMULO(Op, Subtarget, DAG);
30534 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
30535 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
30536 case ISD::SADDO_CARRY:
30537 case ISD::SSUBO_CARRY:
30538 case ISD::ADDCARRY:
30539 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG);
30540 case ISD::ADD:
30541 case ISD::SUB: return lowerAddSub(Op, DAG, Subtarget);
30542 case ISD::UADDSAT:
30543 case ISD::SADDSAT:
30544 case ISD::USUBSAT:
30545 case ISD::SSUBSAT: return LowerADDSAT_SUBSAT(Op, DAG, Subtarget);
30546 case ISD::SMAX:
30547 case ISD::SMIN:
30548 case ISD::UMAX:
30549 case ISD::UMIN: return LowerMINMAX(Op, DAG);
30550 case ISD::ABS: return LowerABS(Op, Subtarget, DAG);
30551 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
30552 case ISD::MLOAD: return LowerMLOAD(Op, Subtarget, DAG);
30553 case ISD::MSTORE: return LowerMSTORE(Op, Subtarget, DAG);
30554 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
30555 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
30556 case ISD::GC_TRANSITION_START:
30557 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION(Op, DAG);
30558 case ISD::ADDRSPACECAST: return LowerADDRSPACECAST(Op, DAG);
30559 case X86ISD::CVTPS2PH: return LowerCVTPS2PH(Op, DAG);
30560 }
30561}
30562
30563/// Replace a node with an illegal result type with a new node built out of
30564/// custom code.
30565void X86TargetLowering::ReplaceNodeResults(SDNode *N,
30566 SmallVectorImpl<SDValue>&Results,
30567 SelectionDAG &DAG) const {
30568 SDLoc dl(N);
30569 switch (N->getOpcode()) {
30570 default:
30571#ifndef NDEBUG
30572 dbgs() << "ReplaceNodeResults: ";
30573 N->dump(&DAG);
30574#endif
30575 llvm_unreachable("Do not know how to custom type legalize this operation!")::llvm::llvm_unreachable_internal("Do not know how to custom type legalize this operation!"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30575)
;
30576 case X86ISD::CVTPH2PS: {
30577 EVT VT = N->getValueType(0);
30578 SDValue Lo, Hi;
30579 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
30580 EVT LoVT, HiVT;
30581 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
30582 Lo = DAG.getNode(X86ISD::CVTPH2PS, dl, LoVT, Lo);
30583 Hi = DAG.getNode(X86ISD::CVTPH2PS, dl, HiVT, Hi);
30584 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
30585 Results.push_back(Res);
30586 return;
30587 }
30588 case X86ISD::STRICT_CVTPH2PS: {
30589 EVT VT = N->getValueType(0);
30590 SDValue Lo, Hi;
30591 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 1);
30592 EVT LoVT, HiVT;
30593 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
30594 Lo = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {LoVT, MVT::Other},
30595 {N->getOperand(0), Lo});
30596 Hi = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {HiVT, MVT::Other},
30597 {N->getOperand(0), Hi});
30598 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
30599 Lo.getValue(1), Hi.getValue(1));
30600 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
30601 Results.push_back(Res);
30602 Results.push_back(Chain);
30603 return;
30604 }
30605 case X86ISD::CVTPS2PH:
30606 Results.push_back(LowerCVTPS2PH(SDValue(N, 0), DAG));
30607 return;
30608 case ISD::CTPOP: {
30609 assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!")(static_cast <bool> (N->getValueType(0) == MVT::i64 &&
"Unexpected VT!") ? void (0) : __assert_fail ("N->getValueType(0) == MVT::i64 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30609, __extension__ __PRETTY_FUNCTION__))
;
30610 // Use a v2i64 if possible.
30611 bool NoImplicitFloatOps =
30612 DAG.getMachineFunction().getFunction().hasFnAttribute(
30613 Attribute::NoImplicitFloat);
30614 if (isTypeLegal(MVT::v2i64) && !NoImplicitFloatOps) {
30615 SDValue Wide =
30616 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, N->getOperand(0));
30617 Wide = DAG.getNode(ISD::CTPOP, dl, MVT::v2i64, Wide);
30618 // Bit count should fit in 32-bits, extract it as that and then zero
30619 // extend to i64. Otherwise we end up extracting bits 63:32 separately.
30620 Wide = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Wide);
30621 Wide = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Wide,
30622 DAG.getIntPtrConstant(0, dl));
30623 Wide = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Wide);
30624 Results.push_back(Wide);
30625 }
30626 return;
30627 }
30628 case ISD::MUL: {
30629 EVT VT = N->getValueType(0);
30630 assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&(static_cast <bool> (getTypeAction(*DAG.getContext(), VT
) == TypeWidenVector && VT.getVectorElementType() == MVT
::i8 && "Unexpected VT!") ? void (0) : __assert_fail (
"getTypeAction(*DAG.getContext(), VT) == TypeWidenVector && VT.getVectorElementType() == MVT::i8 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30631, __extension__ __PRETTY_FUNCTION__))
30631 VT.getVectorElementType() == MVT::i8 && "Unexpected VT!")(static_cast <bool> (getTypeAction(*DAG.getContext(), VT
) == TypeWidenVector && VT.getVectorElementType() == MVT
::i8 && "Unexpected VT!") ? void (0) : __assert_fail (
"getTypeAction(*DAG.getContext(), VT) == TypeWidenVector && VT.getVectorElementType() == MVT::i8 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30631, __extension__ __PRETTY_FUNCTION__))
;
30632 // Pre-promote these to vXi16 to avoid op legalization thinking all 16
30633 // elements are needed.
30634 MVT MulVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
30635 SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(0));
30636 SDValue Op1 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(1));
30637 SDValue Res = DAG.getNode(ISD::MUL, dl, MulVT, Op0, Op1);
30638 Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
30639 unsigned NumConcats = 16 / VT.getVectorNumElements();
30640 SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
30641 ConcatOps[0] = Res;
30642 Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i8, ConcatOps);
30643 Results.push_back(Res);
30644 return;
30645 }
30646 case X86ISD::VPMADDWD:
30647 case X86ISD::AVG: {
30648 // Legalize types for X86ISD::AVG/VPMADDWD by widening.
30649 assert(Subtarget.hasSSE2() && "Requires at least SSE2!")(static_cast <bool> (Subtarget.hasSSE2() && "Requires at least SSE2!"
) ? void (0) : __assert_fail ("Subtarget.hasSSE2() && \"Requires at least SSE2!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30649, __extension__ __PRETTY_FUNCTION__))
;
30650
30651 EVT VT = N->getValueType(0);
30652 EVT InVT = N->getOperand(0).getValueType();
30653 assert(VT.getSizeInBits() < 128 && 128 % VT.getSizeInBits() == 0 &&(static_cast <bool> (VT.getSizeInBits() < 128 &&
128 % VT.getSizeInBits() == 0 && "Expected a VT that divides into 128 bits."
) ? void (0) : __assert_fail ("VT.getSizeInBits() < 128 && 128 % VT.getSizeInBits() == 0 && \"Expected a VT that divides into 128 bits.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30654, __extension__ __PRETTY_FUNCTION__))
30654 "Expected a VT that divides into 128 bits.")(static_cast <bool> (VT.getSizeInBits() < 128 &&
128 % VT.getSizeInBits() == 0 && "Expected a VT that divides into 128 bits."
) ? void (0) : __assert_fail ("VT.getSizeInBits() < 128 && 128 % VT.getSizeInBits() == 0 && \"Expected a VT that divides into 128 bits.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30654, __extension__ __PRETTY_FUNCTION__))
;
30655 assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&(static_cast <bool> (getTypeAction(*DAG.getContext(), VT
) == TypeWidenVector && "Unexpected type action!") ? void
(0) : __assert_fail ("getTypeAction(*DAG.getContext(), VT) == TypeWidenVector && \"Unexpected type action!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30656, __extension__ __PRETTY_FUNCTION__))
30656 "Unexpected type action!")(static_cast <bool> (getTypeAction(*DAG.getContext(), VT
) == TypeWidenVector && "Unexpected type action!") ? void
(0) : __assert_fail ("getTypeAction(*DAG.getContext(), VT) == TypeWidenVector && \"Unexpected type action!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30656, __extension__ __PRETTY_FUNCTION__))
;
30657 unsigned NumConcat = 128 / InVT.getSizeInBits();
30658
30659 EVT InWideVT = EVT::getVectorVT(*DAG.getContext(),
30660 InVT.getVectorElementType(),
30661 NumConcat * InVT.getVectorNumElements());
30662 EVT WideVT = EVT::getVectorVT(*DAG.getContext(),
30663 VT.getVectorElementType(),
30664 NumConcat * VT.getVectorNumElements());
30665
30666 SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
30667 Ops[0] = N->getOperand(0);
30668 SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
30669 Ops[0] = N->getOperand(1);
30670 SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
30671
30672 SDValue Res = DAG.getNode(N->getOpcode(), dl, WideVT, InVec0, InVec1);
30673 Results.push_back(Res);
30674 return;
30675 }
30676 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
30677 case X86ISD::FMINC:
30678 case X86ISD::FMIN:
30679 case X86ISD::FMAXC:
30680 case X86ISD::FMAX: {
30681 EVT VT = N->getValueType(0);
30682 assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.")(static_cast <bool> (VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX."
) ? void (0) : __assert_fail ("VT == MVT::v2f32 && \"Unexpected type (!= v2f32) on FMIN/FMAX.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30682, __extension__ __PRETTY_FUNCTION__))
;
30683 SDValue UNDEF = DAG.getUNDEF(VT);
30684 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
30685 N->getOperand(0), UNDEF);
30686 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
30687 N->getOperand(1), UNDEF);
30688 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
30689 return;
30690 }
30691 case ISD::SDIV:
30692 case ISD::UDIV:
30693 case ISD::SREM:
30694 case ISD::UREM: {
30695 EVT VT = N->getValueType(0);
30696 if (VT.isVector()) {
30697 assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&(static_cast <bool> (getTypeAction(*DAG.getContext(), VT
) == TypeWidenVector && "Unexpected type action!") ? void
(0) : __assert_fail ("getTypeAction(*DAG.getContext(), VT) == TypeWidenVector && \"Unexpected type action!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30698, __extension__ __PRETTY_FUNCTION__))
30698 "Unexpected type action!")(static_cast <bool> (getTypeAction(*DAG.getContext(), VT
) == TypeWidenVector && "Unexpected type action!") ? void
(0) : __assert_fail ("getTypeAction(*DAG.getContext(), VT) == TypeWidenVector && \"Unexpected type action!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30698, __extension__ __PRETTY_FUNCTION__))
;
30699 // If this RHS is a constant splat vector we can widen this and let
30700 // division/remainder by constant optimize it.
30701 // TODO: Can we do something for non-splat?
30702 APInt SplatVal;
30703 if (ISD::isConstantSplatVector(N->getOperand(1).getNode(), SplatVal)) {
30704 unsigned NumConcats = 128 / VT.getSizeInBits();
30705 SmallVector<SDValue, 8> Ops0(NumConcats, DAG.getUNDEF(VT));
30706 Ops0[0] = N->getOperand(0);
30707 EVT ResVT = getTypeToTransformTo(*DAG.getContext(), VT);
30708 SDValue N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Ops0);
30709 SDValue N1 = DAG.getConstant(SplatVal, dl, ResVT);
30710 SDValue Res = DAG.getNode(N->getOpcode(), dl, ResVT, N0, N1);
30711 Results.push_back(Res);
30712 }
30713 return;
30714 }
30715
30716 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
30717 Results.push_back(V);
30718 return;
30719 }
30720 case ISD::TRUNCATE: {
30721 MVT VT = N->getSimpleValueType(0);
30722 if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector)
30723 return;
30724
30725 // The generic legalizer will try to widen the input type to the same
30726 // number of elements as the widened result type. But this isn't always
30727 // the best thing so do some custom legalization to avoid some cases.
30728 MVT WidenVT = getTypeToTransformTo(*DAG.getContext(), VT).getSimpleVT();
30729 SDValue In = N->getOperand(0);
30730 EVT InVT = In.getValueType();
30731
30732 unsigned InBits = InVT.getSizeInBits();
30733 if (128 % InBits == 0) {
30734 // 128 bit and smaller inputs should avoid truncate all together and
30735 // just use a build_vector that will become a shuffle.
30736 // TODO: Widen and use a shuffle directly?
30737 MVT InEltVT = InVT.getSimpleVT().getVectorElementType();
30738 EVT EltVT = VT.getVectorElementType();
30739 unsigned WidenNumElts = WidenVT.getVectorNumElements();
30740 SmallVector<SDValue, 16> Ops(WidenNumElts, DAG.getUNDEF(EltVT));
30741 // Use the original element count so we don't do more scalar opts than
30742 // necessary.
30743 unsigned MinElts = VT.getVectorNumElements();
30744 for (unsigned i=0; i < MinElts; ++i) {
30745 SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, In,
30746 DAG.getIntPtrConstant(i, dl));
30747 Ops[i] = DAG.getNode(ISD::TRUNCATE, dl, EltVT, Val);
30748 }
30749 Results.push_back(DAG.getBuildVector(WidenVT, dl, Ops));
30750 return;
30751 }
30752 // With AVX512 there are some cases that can use a target specific
30753 // truncate node to go from 256/512 to less than 128 with zeros in the
30754 // upper elements of the 128 bit result.
30755 if (Subtarget.hasAVX512() && isTypeLegal(InVT)) {
30756 // We can use VTRUNC directly if for 256 bits with VLX or for any 512.
30757 if ((InBits == 256 && Subtarget.hasVLX()) || InBits == 512) {
30758 Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
30759 return;
30760 }
30761 // There's one case we can widen to 512 bits and use VTRUNC.
30762 if (InVT == MVT::v4i64 && VT == MVT::v4i8 && isTypeLegal(MVT::v8i64)) {
30763 In = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i64, In,
30764 DAG.getUNDEF(MVT::v4i64));
30765 Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
30766 return;
30767 }
30768 }
30769 if (Subtarget.hasVLX() && InVT == MVT::v8i64 && VT == MVT::v8i8 &&
30770 getTypeAction(*DAG.getContext(), InVT) == TypeSplitVector &&
30771 isTypeLegal(MVT::v4i64)) {
30772 // Input needs to be split and output needs to widened. Let's use two
30773 // VTRUNCs, and shuffle their results together into the wider type.
30774 SDValue Lo, Hi;
30775 std::tie(Lo, Hi) = DAG.SplitVector(In, dl);
30776
30777 Lo = DAG.getNode(X86ISD::VTRUNC, dl, MVT::v16i8, Lo);
30778 Hi = DAG.getNode(X86ISD::VTRUNC, dl, MVT::v16i8, Hi);
30779 SDValue Res = DAG.getVectorShuffle(MVT::v16i8, dl, Lo, Hi,
30780 { 0, 1, 2, 3, 16, 17, 18, 19,
30781 -1, -1, -1, -1, -1, -1, -1, -1 });
30782 Results.push_back(Res);
30783 return;
30784 }
30785
30786 return;
30787 }
30788 case ISD::ANY_EXTEND:
30789 // Right now, only MVT::v8i8 has Custom action for an illegal type.
30790 // It's intended to custom handle the input type.
30791 assert(N->getValueType(0) == MVT::v8i8 &&(static_cast <bool> (N->getValueType(0) == MVT::v8i8
&& "Do not know how to legalize this Node") ? void (
0) : __assert_fail ("N->getValueType(0) == MVT::v8i8 && \"Do not know how to legalize this Node\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30792, __extension__ __PRETTY_FUNCTION__))
30792 "Do not know how to legalize this Node")(static_cast <bool> (N->getValueType(0) == MVT::v8i8
&& "Do not know how to legalize this Node") ? void (
0) : __assert_fail ("N->getValueType(0) == MVT::v8i8 && \"Do not know how to legalize this Node\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30792, __extension__ __PRETTY_FUNCTION__))
;
30793 return;
30794 case ISD::SIGN_EXTEND:
30795 case ISD::ZERO_EXTEND: {
30796 EVT VT = N->getValueType(0);
30797 SDValue In = N->getOperand(0);
30798 EVT InVT = In.getValueType();
30799 if (!Subtarget.hasSSE41() && VT == MVT::v4i64 &&
30800 (InVT == MVT::v4i16 || InVT == MVT::v4i8)){
30801 assert(getTypeAction(*DAG.getContext(), InVT) == TypeWidenVector &&(static_cast <bool> (getTypeAction(*DAG.getContext(), InVT
) == TypeWidenVector && "Unexpected type action!") ? void
(0) : __assert_fail ("getTypeAction(*DAG.getContext(), InVT) == TypeWidenVector && \"Unexpected type action!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30802, __extension__ __PRETTY_FUNCTION__))
30802 "Unexpected type action!")(static_cast <bool> (getTypeAction(*DAG.getContext(), InVT
) == TypeWidenVector && "Unexpected type action!") ? void
(0) : __assert_fail ("getTypeAction(*DAG.getContext(), InVT) == TypeWidenVector && \"Unexpected type action!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30802, __extension__ __PRETTY_FUNCTION__))
;
30803 assert(N->getOpcode() == ISD::SIGN_EXTEND && "Unexpected opcode")(static_cast <bool> (N->getOpcode() == ISD::SIGN_EXTEND
&& "Unexpected opcode") ? void (0) : __assert_fail (
"N->getOpcode() == ISD::SIGN_EXTEND && \"Unexpected opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30803, __extension__ __PRETTY_FUNCTION__))
;
30804 // Custom split this so we can extend i8/i16->i32 invec. This is better
30805 // since sign_extend_inreg i8/i16->i64 requires an extend to i32 using
30806 // sra. Then extending from i32 to i64 using pcmpgt. By custom splitting
30807 // we allow the sra from the extend to i32 to be shared by the split.
30808 In = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, In);
30809
30810 // Fill a vector with sign bits for each element.
30811 SDValue Zero = DAG.getConstant(0, dl, MVT::v4i32);
30812 SDValue SignBits = DAG.getSetCC(dl, MVT::v4i32, Zero, In, ISD::SETGT);
30813
30814 // Create an unpackl and unpackh to interleave the sign bits then bitcast
30815 // to v2i64.
30816 SDValue Lo = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
30817 {0, 4, 1, 5});
30818 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Lo);
30819 SDValue Hi = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
30820 {2, 6, 3, 7});
30821 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Hi);
30822
30823 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
30824 Results.push_back(Res);
30825 return;
30826 }
30827
30828 if (VT == MVT::v16i32 || VT == MVT::v8i64) {
30829 if (!InVT.is128BitVector()) {
30830 // Not a 128 bit vector, but maybe type legalization will promote
30831 // it to 128 bits.
30832 if (getTypeAction(*DAG.getContext(), InVT) != TypePromoteInteger)
30833 return;
30834 InVT = getTypeToTransformTo(*DAG.getContext(), InVT);
30835 if (!InVT.is128BitVector())
30836 return;
30837
30838 // Promote the input to 128 bits. Type legalization will turn this into
30839 // zext_inreg/sext_inreg.
30840 In = DAG.getNode(N->getOpcode(), dl, InVT, In);
30841 }
30842
30843 // Perform custom splitting instead of the two stage extend we would get
30844 // by default.
30845 EVT LoVT, HiVT;
30846 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
30847 assert(isTypeLegal(LoVT) && "Split VT not legal?")(static_cast <bool> (isTypeLegal(LoVT) && "Split VT not legal?"
) ? void (0) : __assert_fail ("isTypeLegal(LoVT) && \"Split VT not legal?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30847, __extension__ __PRETTY_FUNCTION__))
;
30848
30849 SDValue Lo = getEXTEND_VECTOR_INREG(N->getOpcode(), dl, LoVT, In, DAG);
30850
30851 // We need to shift the input over by half the number of elements.
30852 unsigned NumElts = InVT.getVectorNumElements();
30853 unsigned HalfNumElts = NumElts / 2;
30854 SmallVector<int, 16> ShufMask(NumElts, SM_SentinelUndef);
30855 for (unsigned i = 0; i != HalfNumElts; ++i)
30856 ShufMask[i] = i + HalfNumElts;
30857
30858 SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
30859 Hi = getEXTEND_VECTOR_INREG(N->getOpcode(), dl, HiVT, Hi, DAG);
30860
30861 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
30862 Results.push_back(Res);
30863 }
30864 return;
30865 }
30866 case ISD::FP_TO_SINT:
30867 case ISD::STRICT_FP_TO_SINT:
30868 case ISD::FP_TO_UINT:
30869 case ISD::STRICT_FP_TO_UINT: {
30870 bool IsStrict = N->isStrictFPOpcode();
30871 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
30872 N->getOpcode() == ISD::STRICT_FP_TO_SINT;
30873 EVT VT = N->getValueType(0);
30874 SDValue Src = N->getOperand(IsStrict ? 1 : 0);
30875 EVT SrcVT = Src.getValueType();
30876
30877 if (VT.isVector() && VT.getScalarSizeInBits() < 32) {
30878 assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&(static_cast <bool> (getTypeAction(*DAG.getContext(), VT
) == TypeWidenVector && "Unexpected type action!") ? void
(0) : __assert_fail ("getTypeAction(*DAG.getContext(), VT) == TypeWidenVector && \"Unexpected type action!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30879, __extension__ __PRETTY_FUNCTION__))
30879 "Unexpected type action!")(static_cast <bool> (getTypeAction(*DAG.getContext(), VT
) == TypeWidenVector && "Unexpected type action!") ? void
(0) : __assert_fail ("getTypeAction(*DAG.getContext(), VT) == TypeWidenVector && \"Unexpected type action!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30879, __extension__ __PRETTY_FUNCTION__))
;
30880
30881 // Try to create a 128 bit vector, but don't exceed a 32 bit element.
30882 unsigned NewEltWidth = std::min(128 / VT.getVectorNumElements(), 32U);
30883 MVT PromoteVT = MVT::getVectorVT(MVT::getIntegerVT(NewEltWidth),
30884 VT.getVectorNumElements());
30885 SDValue Res;
30886 SDValue Chain;
30887 if (IsStrict) {
30888 Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, {PromoteVT, MVT::Other},
30889 {N->getOperand(0), Src});
30890 Chain = Res.getValue(1);
30891 } else
30892 Res = DAG.getNode(ISD::FP_TO_SINT, dl, PromoteVT, Src);
30893
30894 // Preserve what we know about the size of the original result. If the
30895 // result is v2i32, we have to manually widen the assert.
30896 if (PromoteVT == MVT::v2i32)
30897 Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Res,
30898 DAG.getUNDEF(MVT::v2i32));
30899
30900 Res = DAG.getNode(!IsSigned ? ISD::AssertZext : ISD::AssertSext, dl,
30901 Res.getValueType(), Res,
30902 DAG.getValueType(VT.getVectorElementType()));
30903
30904 if (PromoteVT == MVT::v2i32)
30905 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i32, Res,
30906 DAG.getIntPtrConstant(0, dl));
30907
30908 // Truncate back to the original width.
30909 Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
30910
30911 // Now widen to 128 bits.
30912 unsigned NumConcats = 128 / VT.getSizeInBits();
30913 MVT ConcatVT = MVT::getVectorVT(VT.getSimpleVT().getVectorElementType(),
30914 VT.getVectorNumElements() * NumConcats);
30915 SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
30916 ConcatOps[0] = Res;
30917 Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatVT, ConcatOps);
30918 Results.push_back(Res);
30919 if (IsStrict)
30920 Results.push_back(Chain);
30921 return;
30922 }
30923
30924
30925 if (VT == MVT::v2i32) {
30926 assert((!IsStrict || IsSigned || Subtarget.hasAVX512()) &&(static_cast <bool> ((!IsStrict || IsSigned || Subtarget
.hasAVX512()) && "Strict unsigned conversion requires AVX512"
) ? void (0) : __assert_fail ("(!IsStrict || IsSigned || Subtarget.hasAVX512()) && \"Strict unsigned conversion requires AVX512\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30927, __extension__ __PRETTY_FUNCTION__))
30927 "Strict unsigned conversion requires AVX512")(static_cast <bool> ((!IsStrict || IsSigned || Subtarget
.hasAVX512()) && "Strict unsigned conversion requires AVX512"
) ? void (0) : __assert_fail ("(!IsStrict || IsSigned || Subtarget.hasAVX512()) && \"Strict unsigned conversion requires AVX512\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30927, __extension__ __PRETTY_FUNCTION__))
;
30928 assert(Subtarget.hasSSE2() && "Requires at least SSE2!")(static_cast <bool> (Subtarget.hasSSE2() && "Requires at least SSE2!"
) ? void (0) : __assert_fail ("Subtarget.hasSSE2() && \"Requires at least SSE2!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30928, __extension__ __PRETTY_FUNCTION__))
;
30929 assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&(static_cast <bool> (getTypeAction(*DAG.getContext(), VT
) == TypeWidenVector && "Unexpected type action!") ? void
(0) : __assert_fail ("getTypeAction(*DAG.getContext(), VT) == TypeWidenVector && \"Unexpected type action!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30930, __extension__ __PRETTY_FUNCTION__))
30930 "Unexpected type action!")(static_cast <bool> (getTypeAction(*DAG.getContext(), VT
) == TypeWidenVector && "Unexpected type action!") ? void
(0) : __assert_fail ("getTypeAction(*DAG.getContext(), VT) == TypeWidenVector && \"Unexpected type action!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30930, __extension__ __PRETTY_FUNCTION__))
;
30931 if (Src.getValueType() == MVT::v2f64) {
30932 if (!IsSigned && !Subtarget.hasAVX512()) {
30933 SDValue Res =
30934 expandFP_TO_UINT_SSE(MVT::v4i32, Src, dl, DAG, Subtarget);
30935 Results.push_back(Res);
30936 return;
30937 }
30938
30939 unsigned Opc;
30940 if (IsStrict)
30941 Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
30942 else
30943 Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
30944
30945 // If we have VLX we can emit a target specific FP_TO_UINT node,.
30946 if (!IsSigned && !Subtarget.hasVLX()) {
30947 // Otherwise we can defer to the generic legalizer which will widen
30948 // the input as well. This will be further widened during op
30949 // legalization to v8i32<-v8f64.
30950 // For strict nodes we'll need to widen ourselves.
30951 // FIXME: Fix the type legalizer to safely widen strict nodes?
30952 if (!IsStrict)
30953 return;
30954 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f64, Src,
30955 DAG.getConstantFP(0.0, dl, MVT::v2f64));
30956 Opc = N->getOpcode();
30957 }
30958 SDValue Res;
30959 SDValue Chain;
30960 if (IsStrict) {
30961 Res = DAG.getNode(Opc, dl, {MVT::v4i32, MVT::Other},
30962 {N->getOperand(0), Src});
30963 Chain = Res.getValue(1);
30964 } else {
30965 Res = DAG.getNode(Opc, dl, MVT::v4i32, Src);
30966 }
30967 Results.push_back(Res);
30968 if (IsStrict)
30969 Results.push_back(Chain);
30970 return;
30971 }
30972
30973 // Custom widen strict v2f32->v2i32 by padding with zeros.
30974 // FIXME: Should generic type legalizer do this?
30975 if (Src.getValueType() == MVT::v2f32 && IsStrict) {
30976 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
30977 DAG.getConstantFP(0.0, dl, MVT::v2f32));
30978 SDValue Res = DAG.getNode(N->getOpcode(), dl, {MVT::v4i32, MVT::Other},
30979 {N->getOperand(0), Src});
30980 Results.push_back(Res);
30981 Results.push_back(Res.getValue(1));
30982 return;
30983 }
30984
30985 // The FP_TO_INTHelper below only handles f32/f64/f80 scalar inputs,
30986 // so early out here.
30987 return;
30988 }
30989
30990 assert(!VT.isVector() && "Vectors should have been handled above!")(static_cast <bool> (!VT.isVector() && "Vectors should have been handled above!"
) ? void (0) : __assert_fail ("!VT.isVector() && \"Vectors should have been handled above!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30990, __extension__ __PRETTY_FUNCTION__))
;
30991
30992 if (Subtarget.hasDQI() && VT == MVT::i64 &&
30993 (SrcVT == MVT::f32 || SrcVT == MVT::f64)) {
30994 assert(!Subtarget.is64Bit() && "i64 should be legal")(static_cast <bool> (!Subtarget.is64Bit() && "i64 should be legal"
) ? void (0) : __assert_fail ("!Subtarget.is64Bit() && \"i64 should be legal\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 30994, __extension__ __PRETTY_FUNCTION__))
;
30995 unsigned NumElts = Subtarget.hasVLX() ? 2 : 8;
30996 // If we use a 128-bit result we might need to use a target specific node.
30997 unsigned SrcElts =
30998 std::max(NumElts, 128U / (unsigned)SrcVT.getSizeInBits());
30999 MVT VecVT = MVT::getVectorVT(MVT::i64, NumElts);
31000 MVT VecInVT = MVT::getVectorVT(SrcVT.getSimpleVT(), SrcElts);
31001 unsigned Opc = N->getOpcode();
31002 if (NumElts != SrcElts) {
31003 if (IsStrict)
31004 Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
31005 else
31006 Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
31007 }
31008
31009 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
31010 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecInVT,
31011 DAG.getConstantFP(0.0, dl, VecInVT), Src,
31012 ZeroIdx);
31013 SDValue Chain;
31014 if (IsStrict) {
31015 SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
31016 Res = DAG.getNode(Opc, SDLoc(N), Tys, N->getOperand(0), Res);
31017 Chain = Res.getValue(1);
31018 } else
31019 Res = DAG.getNode(Opc, SDLoc(N), VecVT, Res);
31020 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Res, ZeroIdx);
31021 Results.push_back(Res);
31022 if (IsStrict)
31023 Results.push_back(Chain);
31024 return;
31025 }
31026
31027 SDValue Chain;
31028 if (SDValue V = FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, Chain)) {
31029 Results.push_back(V);
31030 if (IsStrict)
31031 Results.push_back(Chain);
31032 }
31033 return;
31034 }
31035 case ISD::LRINT:
31036 case ISD::LLRINT: {
31037 if (SDValue V = LRINT_LLRINTHelper(N, DAG))
31038 Results.push_back(V);
31039 return;
31040 }
31041
31042 case ISD::SINT_TO_FP:
31043 case ISD::STRICT_SINT_TO_FP:
31044 case ISD::UINT_TO_FP:
31045 case ISD::STRICT_UINT_TO_FP: {
31046 bool IsStrict = N->isStrictFPOpcode();
31047 bool IsSigned = N->getOpcode() == ISD::SINT_TO_FP ||
31048 N->getOpcode() == ISD::STRICT_SINT_TO_FP;
31049 EVT VT = N->getValueType(0);
31050 if (VT != MVT::v2f32)
31051 return;
31052 SDValue Src = N->getOperand(IsStrict ? 1 : 0);
31053 EVT SrcVT = Src.getValueType();
31054 if (Subtarget.hasDQI() && Subtarget.hasVLX() && SrcVT == MVT::v2i64) {
31055 if (IsStrict) {
31056 unsigned Opc = IsSigned ? X86ISD::STRICT_CVTSI2P
31057 : X86ISD::STRICT_CVTUI2P;
31058 SDValue Res = DAG.getNode(Opc, dl, {MVT::v4f32, MVT::Other},
31059 {N->getOperand(0), Src});
31060 Results.push_back(Res);
31061 Results.push_back(Res.getValue(1));
31062 } else {
31063 unsigned Opc = IsSigned ? X86ISD::CVTSI2P : X86ISD::CVTUI2P;
31064 Results.push_back(DAG.getNode(Opc, dl, MVT::v4f32, Src));
31065 }
31066 return;
31067 }
31068 if (SrcVT == MVT::v2i64 && !IsSigned && Subtarget.is64Bit() &&
31069 Subtarget.hasSSE41() && !Subtarget.hasAVX512()) {
31070 SDValue Zero = DAG.getConstant(0, dl, SrcVT);
31071 SDValue One = DAG.getConstant(1, dl, SrcVT);
31072 SDValue Sign = DAG.getNode(ISD::OR, dl, SrcVT,
31073 DAG.getNode(ISD::SRL, dl, SrcVT, Src, One),
31074 DAG.getNode(ISD::AND, dl, SrcVT, Src, One));
31075 SDValue IsNeg = DAG.getSetCC(dl, MVT::v2i64, Src, Zero, ISD::SETLT);
31076 SDValue SignSrc = DAG.getSelect(dl, SrcVT, IsNeg, Sign, Src);
31077 SmallVector<SDValue, 4> SignCvts(4, DAG.getConstantFP(0.0, dl, MVT::f32));
31078 for (int i = 0; i != 2; ++i) {
31079 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
31080 SignSrc, DAG.getIntPtrConstant(i, dl));
31081 if (IsStrict)
31082 SignCvts[i] =
31083 DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {MVT::f32, MVT::Other},
31084 {N->getOperand(0), Elt});
31085 else
31086 SignCvts[i] = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Elt);
31087 };
31088 SDValue SignCvt = DAG.getBuildVector(MVT::v4f32, dl, SignCvts);
31089 SDValue Slow, Chain;
31090 if (IsStrict) {
31091 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
31092 SignCvts[0].getValue(1), SignCvts[1].getValue(1));
31093 Slow = DAG.getNode(ISD::STRICT_FADD, dl, {MVT::v4f32, MVT::Other},
31094 {Chain, SignCvt, SignCvt});
31095 Chain = Slow.getValue(1);
31096 } else {
31097 Slow = DAG.getNode(ISD::FADD, dl, MVT::v4f32, SignCvt, SignCvt);
31098 }
31099 IsNeg = DAG.getBitcast(MVT::v4i32, IsNeg);
31100 IsNeg =
31101 DAG.getVectorShuffle(MVT::v4i32, dl, IsNeg, IsNeg, {1, 3, -1, -1});
31102 SDValue Cvt = DAG.getSelect(dl, MVT::v4f32, IsNeg, Slow, SignCvt);
31103 Results.push_back(Cvt);
31104 if (IsStrict)
31105 Results.push_back(Chain);
31106 return;
31107 }
31108
31109 if (SrcVT != MVT::v2i32)
31110 return;
31111
31112 if (IsSigned || Subtarget.hasAVX512()) {
31113 if (!IsStrict)
31114 return;
31115
31116 // Custom widen strict v2i32->v2f32 to avoid scalarization.
31117 // FIXME: Should generic type legalizer do this?
31118 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
31119 DAG.getConstant(0, dl, MVT::v2i32));
31120 SDValue Res = DAG.getNode(N->getOpcode(), dl, {MVT::v4f32, MVT::Other},
31121 {N->getOperand(0), Src});
31122 Results.push_back(Res);
31123 Results.push_back(Res.getValue(1));
31124 return;
31125 }
31126
31127 assert(Subtarget.hasSSE2() && "Requires at least SSE2!")(static_cast <bool> (Subtarget.hasSSE2() && "Requires at least SSE2!"
) ? void (0) : __assert_fail ("Subtarget.hasSSE2() && \"Requires at least SSE2!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31127, __extension__ __PRETTY_FUNCTION__))
;
31128 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64, Src);
31129 SDValue VBias =
31130 DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl, MVT::v2f64);
31131 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
31132 DAG.getBitcast(MVT::v2i64, VBias));
31133 Or = DAG.getBitcast(MVT::v2f64, Or);
31134 if (IsStrict) {
31135 SDValue Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::v2f64, MVT::Other},
31136 {N->getOperand(0), Or, VBias});
31137 SDValue Res = DAG.getNode(X86ISD::STRICT_VFPROUND, dl,
31138 {MVT::v4f32, MVT::Other},
31139 {Sub.getValue(1), Sub});
31140 Results.push_back(Res);
31141 Results.push_back(Res.getValue(1));
31142 } else {
31143 // TODO: Are there any fast-math-flags to propagate here?
31144 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
31145 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
31146 }
31147 return;
31148 }
31149 case ISD::STRICT_FP_ROUND:
31150 case ISD::FP_ROUND: {
31151 bool IsStrict = N->isStrictFPOpcode();
31152 SDValue Src = N->getOperand(IsStrict ? 1 : 0);
31153 if (!isTypeLegal(Src.getValueType()))
31154 return;
31155 SDValue V;
31156 if (IsStrict)
31157 V = DAG.getNode(X86ISD::STRICT_VFPROUND, dl, {MVT::v4f32, MVT::Other},
31158 {N->getOperand(0), N->getOperand(1)});
31159 else
31160 V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
31161 Results.push_back(V);
31162 if (IsStrict)
31163 Results.push_back(V.getValue(1));
31164 return;
31165 }
31166 case ISD::FP_EXTEND:
31167 case ISD::STRICT_FP_EXTEND: {
31168 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
31169 // No other ValueType for FP_EXTEND should reach this point.
31170 assert(N->getValueType(0) == MVT::v2f32 &&(static_cast <bool> (N->getValueType(0) == MVT::v2f32
&& "Do not know how to legalize this Node") ? void (
0) : __assert_fail ("N->getValueType(0) == MVT::v2f32 && \"Do not know how to legalize this Node\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31171, __extension__ __PRETTY_FUNCTION__))
31171 "Do not know how to legalize this Node")(static_cast <bool> (N->getValueType(0) == MVT::v2f32
&& "Do not know how to legalize this Node") ? void (
0) : __assert_fail ("N->getValueType(0) == MVT::v2f32 && \"Do not know how to legalize this Node\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31171, __extension__ __PRETTY_FUNCTION__))
;
31172 return;
31173 }
31174 case ISD::INTRINSIC_W_CHAIN: {
31175 unsigned IntNo = N->getConstantOperandVal(1);
31176 switch (IntNo) {
31177 default : llvm_unreachable("Do not know how to custom type "::llvm::llvm_unreachable_internal("Do not know how to custom type "
"legalize this intrinsic operation!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31178)
31178 "legalize this intrinsic operation!")::llvm::llvm_unreachable_internal("Do not know how to custom type "
"legalize this intrinsic operation!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31178)
;
31179 case Intrinsic::x86_rdtsc:
31180 return getReadTimeStampCounter(N, dl, X86::RDTSC, DAG, Subtarget,
31181 Results);
31182 case Intrinsic::x86_rdtscp:
31183 return getReadTimeStampCounter(N, dl, X86::RDTSCP, DAG, Subtarget,
31184 Results);
31185 case Intrinsic::x86_rdpmc:
31186 expandIntrinsicWChainHelper(N, dl, DAG, X86::RDPMC, X86::ECX, Subtarget,
31187 Results);
31188 return;
31189 case Intrinsic::x86_xgetbv:
31190 expandIntrinsicWChainHelper(N, dl, DAG, X86::XGETBV, X86::ECX, Subtarget,
31191 Results);
31192 return;
31193 }
31194 }
31195 case ISD::READCYCLECOUNTER: {
31196 return getReadTimeStampCounter(N, dl, X86::RDTSC, DAG, Subtarget, Results);
31197 }
31198 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
31199 EVT T = N->getValueType(0);
31200 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair")(static_cast <bool> ((T == MVT::i64 || T == MVT::i128) &&
"can only expand cmpxchg pair") ? void (0) : __assert_fail (
"(T == MVT::i64 || T == MVT::i128) && \"can only expand cmpxchg pair\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31200, __extension__ __PRETTY_FUNCTION__))
;
31201 bool Regs64bit = T == MVT::i128;
31202 assert((!Regs64bit || Subtarget.hasCmpxchg16b()) &&(static_cast <bool> ((!Regs64bit || Subtarget.hasCmpxchg16b
()) && "64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS requires CMPXCHG16B"
) ? void (0) : __assert_fail ("(!Regs64bit || Subtarget.hasCmpxchg16b()) && \"64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS requires CMPXCHG16B\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31203, __extension__ __PRETTY_FUNCTION__))
31203 "64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS requires CMPXCHG16B")(static_cast <bool> ((!Regs64bit || Subtarget.hasCmpxchg16b
()) && "64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS requires CMPXCHG16B"
) ? void (0) : __assert_fail ("(!Regs64bit || Subtarget.hasCmpxchg16b()) && \"64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS requires CMPXCHG16B\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31203, __extension__ __PRETTY_FUNCTION__))
;
31204 MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
31205 SDValue cpInL, cpInH;
31206 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
31207 DAG.getConstant(0, dl, HalfT));
31208 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
31209 DAG.getConstant(1, dl, HalfT));
31210 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
31211 Regs64bit ? X86::RAX : X86::EAX,
31212 cpInL, SDValue());
31213 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
31214 Regs64bit ? X86::RDX : X86::EDX,
31215 cpInH, cpInL.getValue(1));
31216 SDValue swapInL, swapInH;
31217 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
31218 DAG.getConstant(0, dl, HalfT));
31219 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
31220 DAG.getConstant(1, dl, HalfT));
31221 swapInH =
31222 DAG.getCopyToReg(cpInH.getValue(0), dl, Regs64bit ? X86::RCX : X86::ECX,
31223 swapInH, cpInH.getValue(1));
31224
31225 // In 64-bit mode we might need the base pointer in RBX, but we can't know
31226 // until later. So we keep the RBX input in a vreg and use a custom
31227 // inserter.
31228 // Since RBX will be a reserved register the register allocator will not
31229 // make sure its value will be properly saved and restored around this
31230 // live-range.
31231 SDValue Result;
31232 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
31233 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
31234 if (Regs64bit) {
31235 SDValue Ops[] = {swapInH.getValue(0), N->getOperand(1), swapInL,
31236 swapInH.getValue(1)};
31237 Result =
31238 DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG16_DAG, dl, Tys, Ops, T, MMO);
31239 } else {
31240 swapInL = DAG.getCopyToReg(swapInH.getValue(0), dl, X86::EBX, swapInL,
31241 swapInH.getValue(1));
31242 SDValue Ops[] = {swapInL.getValue(0), N->getOperand(1),
31243 swapInL.getValue(1)};
31244 Result =
31245 DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, T, MMO);
31246 }
31247
31248 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
31249 Regs64bit ? X86::RAX : X86::EAX,
31250 HalfT, Result.getValue(1));
31251 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
31252 Regs64bit ? X86::RDX : X86::EDX,
31253 HalfT, cpOutL.getValue(2));
31254 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
31255
31256 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
31257 MVT::i32, cpOutH.getValue(2));
31258 SDValue Success = getSETCC(X86::COND_E, EFLAGS, dl, DAG);
31259 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
31260
31261 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
31262 Results.push_back(Success);
31263 Results.push_back(EFLAGS.getValue(1));
31264 return;
31265 }
31266 case ISD::ATOMIC_LOAD: {
31267 assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!")(static_cast <bool> (N->getValueType(0) == MVT::i64 &&
"Unexpected VT!") ? void (0) : __assert_fail ("N->getValueType(0) == MVT::i64 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31267, __extension__ __PRETTY_FUNCTION__))
;
31268 bool NoImplicitFloatOps =
31269 DAG.getMachineFunction().getFunction().hasFnAttribute(
31270 Attribute::NoImplicitFloat);
31271 if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps) {
31272 auto *Node = cast<AtomicSDNode>(N);
31273 if (Subtarget.hasSSE1()) {
31274 // Use a VZEXT_LOAD which will be selected as MOVQ or XORPS+MOVLPS.
31275 // Then extract the lower 64-bits.
31276 MVT LdVT = Subtarget.hasSSE2() ? MVT::v2i64 : MVT::v4f32;
31277 SDVTList Tys = DAG.getVTList(LdVT, MVT::Other);
31278 SDValue Ops[] = { Node->getChain(), Node->getBasePtr() };
31279 SDValue Ld = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
31280 MVT::i64, Node->getMemOperand());
31281 if (Subtarget.hasSSE2()) {
31282 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Ld,
31283 DAG.getIntPtrConstant(0, dl));
31284 Results.push_back(Res);
31285 Results.push_back(Ld.getValue(1));
31286 return;
31287 }
31288 // We use an alternative sequence for SSE1 that extracts as v2f32 and
31289 // then casts to i64. This avoids a 128-bit stack temporary being
31290 // created by type legalization if we were to cast v4f32->v2i64.
31291 SDValue Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2f32, Ld,
31292 DAG.getIntPtrConstant(0, dl));
31293 Res = DAG.getBitcast(MVT::i64, Res);
31294 Results.push_back(Res);
31295 Results.push_back(Ld.getValue(1));
31296 return;
31297 }
31298 if (Subtarget.hasX87()) {
31299 // First load this into an 80-bit X87 register. This will put the whole
31300 // integer into the significand.
31301 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
31302 SDValue Ops[] = { Node->getChain(), Node->getBasePtr() };
31303 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::FILD,
31304 dl, Tys, Ops, MVT::i64,
31305 Node->getMemOperand());
31306 SDValue Chain = Result.getValue(1);
31307
31308 // Now store the X87 register to a stack temporary and convert to i64.
31309 // This store is not atomic and doesn't need to be.
31310 // FIXME: We don't need a stack temporary if the result of the load
31311 // is already being stored. We could just directly store there.
31312 SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
31313 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
31314 MachinePointerInfo MPI =
31315 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
31316 SDValue StoreOps[] = { Chain, Result, StackPtr };
31317 Chain = DAG.getMemIntrinsicNode(
31318 X86ISD::FIST, dl, DAG.getVTList(MVT::Other), StoreOps, MVT::i64,
31319 MPI, None /*Align*/, MachineMemOperand::MOStore);
31320
31321 // Finally load the value back from the stack temporary and return it.
31322 // This load is not atomic and doesn't need to be.
31323 // This load will be further type legalized.
31324 Result = DAG.getLoad(MVT::i64, dl, Chain, StackPtr, MPI);
31325 Results.push_back(Result);
31326 Results.push_back(Result.getValue(1));
31327 return;
31328 }
31329 }
31330 // TODO: Use MOVLPS when SSE1 is available?
31331 // Delegate to generic TypeLegalization. Situations we can really handle
31332 // should have already been dealt with by AtomicExpandPass.cpp.
31333 break;
31334 }
31335 case ISD::ATOMIC_SWAP:
31336 case ISD::ATOMIC_LOAD_ADD:
31337 case ISD::ATOMIC_LOAD_SUB:
31338 case ISD::ATOMIC_LOAD_AND:
31339 case ISD::ATOMIC_LOAD_OR:
31340 case ISD::ATOMIC_LOAD_XOR:
31341 case ISD::ATOMIC_LOAD_NAND:
31342 case ISD::ATOMIC_LOAD_MIN:
31343 case ISD::ATOMIC_LOAD_MAX:
31344 case ISD::ATOMIC_LOAD_UMIN:
31345 case ISD::ATOMIC_LOAD_UMAX:
31346 // Delegate to generic TypeLegalization. Situations we can really handle
31347 // should have already been dealt with by AtomicExpandPass.cpp.
31348 break;
31349
31350 case ISD::BITCAST: {
31351 assert(Subtarget.hasSSE2() && "Requires at least SSE2!")(static_cast <bool> (Subtarget.hasSSE2() && "Requires at least SSE2!"
) ? void (0) : __assert_fail ("Subtarget.hasSSE2() && \"Requires at least SSE2!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31351, __extension__ __PRETTY_FUNCTION__))
;
31352 EVT DstVT = N->getValueType(0);
31353 EVT SrcVT = N->getOperand(0).getValueType();
31354
31355 // If this is a bitcast from a v64i1 k-register to a i64 on a 32-bit target
31356 // we can split using the k-register rather than memory.
31357 if (SrcVT == MVT::v64i1 && DstVT == MVT::i64 && Subtarget.hasBWI()) {
31358 assert(!Subtarget.is64Bit() && "Expected 32-bit mode")(static_cast <bool> (!Subtarget.is64Bit() && "Expected 32-bit mode"
) ? void (0) : __assert_fail ("!Subtarget.is64Bit() && \"Expected 32-bit mode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31358, __extension__ __PRETTY_FUNCTION__))
;
31359 SDValue Lo, Hi;
31360 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
31361 Lo = DAG.getBitcast(MVT::i32, Lo);
31362 Hi = DAG.getBitcast(MVT::i32, Hi);
31363 SDValue Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
31364 Results.push_back(Res);
31365 return;
31366 }
31367
31368 if (DstVT.isVector() && SrcVT == MVT::x86mmx) {
31369 // FIXME: Use v4f32 for SSE1?
31370 assert(Subtarget.hasSSE2() && "Requires SSE2")(static_cast <bool> (Subtarget.hasSSE2() && "Requires SSE2"
) ? void (0) : __assert_fail ("Subtarget.hasSSE2() && \"Requires SSE2\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31370, __extension__ __PRETTY_FUNCTION__))
;
31371 assert(getTypeAction(*DAG.getContext(), DstVT) == TypeWidenVector &&(static_cast <bool> (getTypeAction(*DAG.getContext(), DstVT
) == TypeWidenVector && "Unexpected type action!") ? void
(0) : __assert_fail ("getTypeAction(*DAG.getContext(), DstVT) == TypeWidenVector && \"Unexpected type action!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31372, __extension__ __PRETTY_FUNCTION__))
31372 "Unexpected type action!")(static_cast <bool> (getTypeAction(*DAG.getContext(), DstVT
) == TypeWidenVector && "Unexpected type action!") ? void
(0) : __assert_fail ("getTypeAction(*DAG.getContext(), DstVT) == TypeWidenVector && \"Unexpected type action!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31372, __extension__ __PRETTY_FUNCTION__))
;
31373 EVT WideVT = getTypeToTransformTo(*DAG.getContext(), DstVT);
31374 SDValue Res = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64,
31375 N->getOperand(0));
31376 Res = DAG.getBitcast(WideVT, Res);
31377 Results.push_back(Res);
31378 return;
31379 }
31380
31381 return;
31382 }
31383 case ISD::MGATHER: {
31384 EVT VT = N->getValueType(0);
31385 if ((VT == MVT::v2f32 || VT == MVT::v2i32) &&
31386 (Subtarget.hasVLX() || !Subtarget.hasAVX512())) {
31387 auto *Gather = cast<MaskedGatherSDNode>(N);
31388 SDValue Index = Gather->getIndex();
31389 if (Index.getValueType() != MVT::v2i64)
31390 return;
31391 assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&(static_cast <bool> (getTypeAction(*DAG.getContext(), VT
) == TypeWidenVector && "Unexpected type action!") ? void
(0) : __assert_fail ("getTypeAction(*DAG.getContext(), VT) == TypeWidenVector && \"Unexpected type action!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31392, __extension__ __PRETTY_FUNCTION__))
31392 "Unexpected type action!")(static_cast <bool> (getTypeAction(*DAG.getContext(), VT
) == TypeWidenVector && "Unexpected type action!") ? void
(0) : __assert_fail ("getTypeAction(*DAG.getContext(), VT) == TypeWidenVector && \"Unexpected type action!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31392, __extension__ __PRETTY_FUNCTION__))
;
31393 EVT WideVT = getTypeToTransformTo(*DAG.getContext(), VT);
31394 SDValue Mask = Gather->getMask();
31395 assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type")(static_cast <bool> (Mask.getValueType() == MVT::v2i1 &&
"Unexpected mask type") ? void (0) : __assert_fail ("Mask.getValueType() == MVT::v2i1 && \"Unexpected mask type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31395, __extension__ __PRETTY_FUNCTION__))
;
31396 SDValue PassThru = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT,
31397 Gather->getPassThru(),
31398 DAG.getUNDEF(VT));
31399 if (!Subtarget.hasVLX()) {
31400 // We need to widen the mask, but the instruction will only use 2
31401 // of its elements. So we can use undef.
31402 Mask = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i1, Mask,
31403 DAG.getUNDEF(MVT::v2i1));
31404 Mask = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Mask);
31405 }
31406 SDValue Ops[] = { Gather->getChain(), PassThru, Mask,
31407 Gather->getBasePtr(), Index, Gather->getScale() };
31408 SDValue Res = DAG.getMemIntrinsicNode(
31409 X86ISD::MGATHER, dl, DAG.getVTList(WideVT, MVT::Other), Ops,
31410 Gather->getMemoryVT(), Gather->getMemOperand());
31411 Results.push_back(Res);
31412 Results.push_back(Res.getValue(1));
31413 return;
31414 }
31415 return;
31416 }
31417 case ISD::LOAD: {
31418 // Use an f64/i64 load and a scalar_to_vector for v2f32/v2i32 loads. This
31419 // avoids scalarizing in 32-bit mode. In 64-bit mode this avoids a int->fp
31420 // cast since type legalization will try to use an i64 load.
31421 MVT VT = N->getSimpleValueType(0);
31422 assert(VT.isVector() && VT.getSizeInBits() == 64 && "Unexpected VT")(static_cast <bool> (VT.isVector() && VT.getSizeInBits
() == 64 && "Unexpected VT") ? void (0) : __assert_fail
("VT.isVector() && VT.getSizeInBits() == 64 && \"Unexpected VT\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31422, __extension__ __PRETTY_FUNCTION__))
;
31423 assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&(static_cast <bool> (getTypeAction(*DAG.getContext(), VT
) == TypeWidenVector && "Unexpected type action!") ? void
(0) : __assert_fail ("getTypeAction(*DAG.getContext(), VT) == TypeWidenVector && \"Unexpected type action!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31424, __extension__ __PRETTY_FUNCTION__))
31424 "Unexpected type action!")(static_cast <bool> (getTypeAction(*DAG.getContext(), VT
) == TypeWidenVector && "Unexpected type action!") ? void
(0) : __assert_fail ("getTypeAction(*DAG.getContext(), VT) == TypeWidenVector && \"Unexpected type action!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31424, __extension__ __PRETTY_FUNCTION__))
;
31425 if (!ISD::isNON_EXTLoad(N))
31426 return;
31427 auto *Ld = cast<LoadSDNode>(N);
31428 if (Subtarget.hasSSE2()) {
31429 MVT LdVT = Subtarget.is64Bit() && VT.isInteger() ? MVT::i64 : MVT::f64;
31430 SDValue Res = DAG.getLoad(LdVT, dl, Ld->getChain(), Ld->getBasePtr(),
31431 Ld->getPointerInfo(), Ld->getOriginalAlign(),
31432 Ld->getMemOperand()->getFlags());
31433 SDValue Chain = Res.getValue(1);
31434 MVT VecVT = MVT::getVectorVT(LdVT, 2);
31435 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Res);
31436 EVT WideVT = getTypeToTransformTo(*DAG.getContext(), VT);
31437 Res = DAG.getBitcast(WideVT, Res);
31438 Results.push_back(Res);
31439 Results.push_back(Chain);
31440 return;
31441 }
31442 assert(Subtarget.hasSSE1() && "Expected SSE")(static_cast <bool> (Subtarget.hasSSE1() && "Expected SSE"
) ? void (0) : __assert_fail ("Subtarget.hasSSE1() && \"Expected SSE\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31442, __extension__ __PRETTY_FUNCTION__))
;
31443 SDVTList Tys = DAG.getVTList(MVT::v4f32, MVT::Other);
31444 SDValue Ops[] = {Ld->getChain(), Ld->getBasePtr()};
31445 SDValue Res = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
31446 MVT::i64, Ld->getMemOperand());
31447 Results.push_back(Res);
31448 Results.push_back(Res.getValue(1));
31449 return;
31450 }
31451 case ISD::ADDRSPACECAST: {
31452 SDValue V = LowerADDRSPACECAST(SDValue(N,0), DAG);
31453 Results.push_back(V);
31454 return;
31455 }
31456 case ISD::BITREVERSE:
31457 assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!")(static_cast <bool> (N->getValueType(0) == MVT::i64 &&
"Unexpected VT!") ? void (0) : __assert_fail ("N->getValueType(0) == MVT::i64 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31457, __extension__ __PRETTY_FUNCTION__))
;
31458 assert(Subtarget.hasXOP() && "Expected XOP")(static_cast <bool> (Subtarget.hasXOP() && "Expected XOP"
) ? void (0) : __assert_fail ("Subtarget.hasXOP() && \"Expected XOP\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31458, __extension__ __PRETTY_FUNCTION__))
;
31459 // We can use VPPERM by copying to a vector register and back. We'll need
31460 // to move the scalar in two i32 pieces.
31461 Results.push_back(LowerBITREVERSE(SDValue(N, 0), Subtarget, DAG));
31462 return;
31463 }
31464}
31465
31466const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
31467 switch ((X86ISD::NodeType)Opcode) {
31468 case X86ISD::FIRST_NUMBER: break;
31469#define NODE_NAME_CASE(NODE) case X86ISD::NODE: return "X86ISD::" #NODE;
31470 NODE_NAME_CASE(BSF)
31471 NODE_NAME_CASE(BSR)
31472 NODE_NAME_CASE(FSHL)
31473 NODE_NAME_CASE(FSHR)
31474 NODE_NAME_CASE(FAND)
31475 NODE_NAME_CASE(FANDN)
31476 NODE_NAME_CASE(FOR)
31477 NODE_NAME_CASE(FXOR)
31478 NODE_NAME_CASE(FILD)
31479 NODE_NAME_CASE(FIST)
31480 NODE_NAME_CASE(FP_TO_INT_IN_MEM)
31481 NODE_NAME_CASE(FLD)
31482 NODE_NAME_CASE(FST)
31483 NODE_NAME_CASE(CALL)
31484 NODE_NAME_CASE(CALL_RVMARKER)
31485 NODE_NAME_CASE(BT)
31486 NODE_NAME_CASE(CMP)
31487 NODE_NAME_CASE(FCMP)
31488 NODE_NAME_CASE(STRICT_FCMP)
31489 NODE_NAME_CASE(STRICT_FCMPS)
31490 NODE_NAME_CASE(COMI)
31491 NODE_NAME_CASE(UCOMI)
31492 NODE_NAME_CASE(CMPM)
31493 NODE_NAME_CASE(CMPMM)
31494 NODE_NAME_CASE(STRICT_CMPM)
31495 NODE_NAME_CASE(CMPMM_SAE)
31496 NODE_NAME_CASE(SETCC)
31497 NODE_NAME_CASE(SETCC_CARRY)
31498 NODE_NAME_CASE(FSETCC)
31499 NODE_NAME_CASE(FSETCCM)
31500 NODE_NAME_CASE(FSETCCM_SAE)
31501 NODE_NAME_CASE(CMOV)
31502 NODE_NAME_CASE(BRCOND)
31503 NODE_NAME_CASE(RET_FLAG)
31504 NODE_NAME_CASE(IRET)
31505 NODE_NAME_CASE(REP_STOS)
31506 NODE_NAME_CASE(REP_MOVS)
31507 NODE_NAME_CASE(GlobalBaseReg)
31508 NODE_NAME_CASE(Wrapper)
31509 NODE_NAME_CASE(WrapperRIP)
31510 NODE_NAME_CASE(MOVQ2DQ)
31511 NODE_NAME_CASE(MOVDQ2Q)
31512 NODE_NAME_CASE(MMX_MOVD2W)
31513 NODE_NAME_CASE(MMX_MOVW2D)
31514 NODE_NAME_CASE(PEXTRB)
31515 NODE_NAME_CASE(PEXTRW)
31516 NODE_NAME_CASE(INSERTPS)
31517 NODE_NAME_CASE(PINSRB)
31518 NODE_NAME_CASE(PINSRW)
31519 NODE_NAME_CASE(PSHUFB)
31520 NODE_NAME_CASE(ANDNP)
31521 NODE_NAME_CASE(BLENDI)
31522 NODE_NAME_CASE(BLENDV)
31523 NODE_NAME_CASE(HADD)
31524 NODE_NAME_CASE(HSUB)
31525 NODE_NAME_CASE(FHADD)
31526 NODE_NAME_CASE(FHSUB)
31527 NODE_NAME_CASE(CONFLICT)
31528 NODE_NAME_CASE(FMAX)
31529 NODE_NAME_CASE(FMAXS)
31530 NODE_NAME_CASE(FMAX_SAE)
31531 NODE_NAME_CASE(FMAXS_SAE)
31532 NODE_NAME_CASE(FMIN)
31533 NODE_NAME_CASE(FMINS)
31534 NODE_NAME_CASE(FMIN_SAE)
31535 NODE_NAME_CASE(FMINS_SAE)
31536 NODE_NAME_CASE(FMAXC)
31537 NODE_NAME_CASE(FMINC)
31538 NODE_NAME_CASE(FRSQRT)
31539 NODE_NAME_CASE(FRCP)
31540 NODE_NAME_CASE(EXTRQI)
31541 NODE_NAME_CASE(INSERTQI)
31542 NODE_NAME_CASE(TLSADDR)
31543 NODE_NAME_CASE(TLSBASEADDR)
31544 NODE_NAME_CASE(TLSCALL)
31545 NODE_NAME_CASE(EH_SJLJ_SETJMP)
31546 NODE_NAME_CASE(EH_SJLJ_LONGJMP)
31547 NODE_NAME_CASE(EH_SJLJ_SETUP_DISPATCH)
31548 NODE_NAME_CASE(EH_RETURN)
31549 NODE_NAME_CASE(TC_RETURN)
31550 NODE_NAME_CASE(FNSTCW16m)
31551 NODE_NAME_CASE(FLDCW16m)
31552 NODE_NAME_CASE(LCMPXCHG_DAG)
31553 NODE_NAME_CASE(LCMPXCHG8_DAG)
31554 NODE_NAME_CASE(LCMPXCHG16_DAG)
31555 NODE_NAME_CASE(LCMPXCHG16_SAVE_RBX_DAG)
31556 NODE_NAME_CASE(LADD)
31557 NODE_NAME_CASE(LSUB)
31558 NODE_NAME_CASE(LOR)
31559 NODE_NAME_CASE(LXOR)
31560 NODE_NAME_CASE(LAND)
31561 NODE_NAME_CASE(VZEXT_MOVL)
31562 NODE_NAME_CASE(VZEXT_LOAD)
31563 NODE_NAME_CASE(VEXTRACT_STORE)
31564 NODE_NAME_CASE(VTRUNC)
31565 NODE_NAME_CASE(VTRUNCS)
31566 NODE_NAME_CASE(VTRUNCUS)
31567 NODE_NAME_CASE(VMTRUNC)
31568 NODE_NAME_CASE(VMTRUNCS)
31569 NODE_NAME_CASE(VMTRUNCUS)
31570 NODE_NAME_CASE(VTRUNCSTORES)
31571 NODE_NAME_CASE(VTRUNCSTOREUS)
31572 NODE_NAME_CASE(VMTRUNCSTORES)
31573 NODE_NAME_CASE(VMTRUNCSTOREUS)
31574 NODE_NAME_CASE(VFPEXT)
31575 NODE_NAME_CASE(STRICT_VFPEXT)
31576 NODE_NAME_CASE(VFPEXT_SAE)
31577 NODE_NAME_CASE(VFPEXTS)
31578 NODE_NAME_CASE(VFPEXTS_SAE)
31579 NODE_NAME_CASE(VFPROUND)
31580 NODE_NAME_CASE(STRICT_VFPROUND)
31581 NODE_NAME_CASE(VMFPROUND)
31582 NODE_NAME_CASE(VFPROUND_RND)
31583 NODE_NAME_CASE(VFPROUNDS)
31584 NODE_NAME_CASE(VFPROUNDS_RND)
31585 NODE_NAME_CASE(VSHLDQ)
31586 NODE_NAME_CASE(VSRLDQ)
31587 NODE_NAME_CASE(VSHL)
31588 NODE_NAME_CASE(VSRL)
31589 NODE_NAME_CASE(VSRA)
31590 NODE_NAME_CASE(VSHLI)
31591 NODE_NAME_CASE(VSRLI)
31592 NODE_NAME_CASE(VSRAI)
31593 NODE_NAME_CASE(VSHLV)
31594 NODE_NAME_CASE(VSRLV)
31595 NODE_NAME_CASE(VSRAV)
31596 NODE_NAME_CASE(VROTLI)
31597 NODE_NAME_CASE(VROTRI)
31598 NODE_NAME_CASE(VPPERM)
31599 NODE_NAME_CASE(CMPP)
31600 NODE_NAME_CASE(STRICT_CMPP)
31601 NODE_NAME_CASE(PCMPEQ)
31602 NODE_NAME_CASE(PCMPGT)
31603 NODE_NAME_CASE(PHMINPOS)
31604 NODE_NAME_CASE(ADD)
31605 NODE_NAME_CASE(SUB)
31606 NODE_NAME_CASE(ADC)
31607 NODE_NAME_CASE(SBB)
31608 NODE_NAME_CASE(SMUL)
31609 NODE_NAME_CASE(UMUL)
31610 NODE_NAME_CASE(OR)
31611 NODE_NAME_CASE(XOR)
31612 NODE_NAME_CASE(AND)
31613 NODE_NAME_CASE(BEXTR)
31614 NODE_NAME_CASE(BEXTRI)
31615 NODE_NAME_CASE(BZHI)
31616 NODE_NAME_CASE(PDEP)
31617 NODE_NAME_CASE(PEXT)
31618 NODE_NAME_CASE(MUL_IMM)
31619 NODE_NAME_CASE(MOVMSK)
31620 NODE_NAME_CASE(PTEST)
31621 NODE_NAME_CASE(TESTP)
31622 NODE_NAME_CASE(KORTEST)
31623 NODE_NAME_CASE(KTEST)
31624 NODE_NAME_CASE(KADD)
31625 NODE_NAME_CASE(KSHIFTL)
31626 NODE_NAME_CASE(KSHIFTR)
31627 NODE_NAME_CASE(PACKSS)
31628 NODE_NAME_CASE(PACKUS)
31629 NODE_NAME_CASE(PALIGNR)
31630 NODE_NAME_CASE(VALIGN)
31631 NODE_NAME_CASE(VSHLD)
31632 NODE_NAME_CASE(VSHRD)
31633 NODE_NAME_CASE(VSHLDV)
31634 NODE_NAME_CASE(VSHRDV)
31635 NODE_NAME_CASE(PSHUFD)
31636 NODE_NAME_CASE(PSHUFHW)
31637 NODE_NAME_CASE(PSHUFLW)
31638 NODE_NAME_CASE(SHUFP)
31639 NODE_NAME_CASE(SHUF128)
31640 NODE_NAME_CASE(MOVLHPS)
31641 NODE_NAME_CASE(MOVHLPS)
31642 NODE_NAME_CASE(MOVDDUP)
31643 NODE_NAME_CASE(MOVSHDUP)
31644 NODE_NAME_CASE(MOVSLDUP)
31645 NODE_NAME_CASE(MOVSD)
31646 NODE_NAME_CASE(MOVSS)
31647 NODE_NAME_CASE(UNPCKL)
31648 NODE_NAME_CASE(UNPCKH)
31649 NODE_NAME_CASE(VBROADCAST)
31650 NODE_NAME_CASE(VBROADCAST_LOAD)
31651 NODE_NAME_CASE(VBROADCASTM)
31652 NODE_NAME_CASE(SUBV_BROADCAST_LOAD)
31653 NODE_NAME_CASE(VPERMILPV)
31654 NODE_NAME_CASE(VPERMILPI)
31655 NODE_NAME_CASE(VPERM2X128)
31656 NODE_NAME_CASE(VPERMV)
31657 NODE_NAME_CASE(VPERMV3)
31658 NODE_NAME_CASE(VPERMI)
31659 NODE_NAME_CASE(VPTERNLOG)
31660 NODE_NAME_CASE(VFIXUPIMM)
31661 NODE_NAME_CASE(VFIXUPIMM_SAE)
31662 NODE_NAME_CASE(VFIXUPIMMS)
31663 NODE_NAME_CASE(VFIXUPIMMS_SAE)
31664 NODE_NAME_CASE(VRANGE)
31665 NODE_NAME_CASE(VRANGE_SAE)
31666 NODE_NAME_CASE(VRANGES)
31667 NODE_NAME_CASE(VRANGES_SAE)
31668 NODE_NAME_CASE(PMULUDQ)
31669 NODE_NAME_CASE(PMULDQ)
31670 NODE_NAME_CASE(PSADBW)
31671 NODE_NAME_CASE(DBPSADBW)
31672 NODE_NAME_CASE(VASTART_SAVE_XMM_REGS)
31673 NODE_NAME_CASE(VAARG_64)
31674 NODE_NAME_CASE(VAARG_X32)
31675 NODE_NAME_CASE(WIN_ALLOCA)
31676 NODE_NAME_CASE(MEMBARRIER)
31677 NODE_NAME_CASE(MFENCE)
31678 NODE_NAME_CASE(SEG_ALLOCA)
31679 NODE_NAME_CASE(PROBED_ALLOCA)
31680 NODE_NAME_CASE(RDRAND)
31681 NODE_NAME_CASE(RDSEED)
31682 NODE_NAME_CASE(RDPKRU)
31683 NODE_NAME_CASE(WRPKRU)
31684 NODE_NAME_CASE(VPMADDUBSW)
31685 NODE_NAME_CASE(VPMADDWD)
31686 NODE_NAME_CASE(VPSHA)
31687 NODE_NAME_CASE(VPSHL)
31688 NODE_NAME_CASE(VPCOM)
31689 NODE_NAME_CASE(VPCOMU)
31690 NODE_NAME_CASE(VPERMIL2)
31691 NODE_NAME_CASE(FMSUB)
31692 NODE_NAME_CASE(STRICT_FMSUB)
31693 NODE_NAME_CASE(FNMADD)
31694 NODE_NAME_CASE(STRICT_FNMADD)
31695 NODE_NAME_CASE(FNMSUB)
31696 NODE_NAME_CASE(STRICT_FNMSUB)
31697 NODE_NAME_CASE(FMADDSUB)
31698 NODE_NAME_CASE(FMSUBADD)
31699 NODE_NAME_CASE(FMADD_RND)
31700 NODE_NAME_CASE(FNMADD_RND)
31701 NODE_NAME_CASE(FMSUB_RND)
31702 NODE_NAME_CASE(FNMSUB_RND)
31703 NODE_NAME_CASE(FMADDSUB_RND)
31704 NODE_NAME_CASE(FMSUBADD_RND)
31705 NODE_NAME_CASE(VPMADD52H)
31706 NODE_NAME_CASE(VPMADD52L)
31707 NODE_NAME_CASE(VRNDSCALE)
31708 NODE_NAME_CASE(STRICT_VRNDSCALE)
31709 NODE_NAME_CASE(VRNDSCALE_SAE)
31710 NODE_NAME_CASE(VRNDSCALES)
31711 NODE_NAME_CASE(VRNDSCALES_SAE)
31712 NODE_NAME_CASE(VREDUCE)
31713 NODE_NAME_CASE(VREDUCE_SAE)
31714 NODE_NAME_CASE(VREDUCES)
31715 NODE_NAME_CASE(VREDUCES_SAE)
31716 NODE_NAME_CASE(VGETMANT)
31717 NODE_NAME_CASE(VGETMANT_SAE)
31718 NODE_NAME_CASE(VGETMANTS)
31719 NODE_NAME_CASE(VGETMANTS_SAE)
31720 NODE_NAME_CASE(PCMPESTR)
31721 NODE_NAME_CASE(PCMPISTR)
31722 NODE_NAME_CASE(XTEST)
31723 NODE_NAME_CASE(COMPRESS)
31724 NODE_NAME_CASE(EXPAND)
31725 NODE_NAME_CASE(SELECTS)
31726 NODE_NAME_CASE(ADDSUB)
31727 NODE_NAME_CASE(RCP14)
31728 NODE_NAME_CASE(RCP14S)
31729 NODE_NAME_CASE(RCP28)
31730 NODE_NAME_CASE(RCP28_SAE)
31731 NODE_NAME_CASE(RCP28S)
31732 NODE_NAME_CASE(RCP28S_SAE)
31733 NODE_NAME_CASE(EXP2)
31734 NODE_NAME_CASE(EXP2_SAE)
31735 NODE_NAME_CASE(RSQRT14)
31736 NODE_NAME_CASE(RSQRT14S)
31737 NODE_NAME_CASE(RSQRT28)
31738 NODE_NAME_CASE(RSQRT28_SAE)
31739 NODE_NAME_CASE(RSQRT28S)
31740 NODE_NAME_CASE(RSQRT28S_SAE)
31741 NODE_NAME_CASE(FADD_RND)
31742 NODE_NAME_CASE(FADDS)
31743 NODE_NAME_CASE(FADDS_RND)
31744 NODE_NAME_CASE(FSUB_RND)
31745 NODE_NAME_CASE(FSUBS)
31746 NODE_NAME_CASE(FSUBS_RND)
31747 NODE_NAME_CASE(FMUL_RND)
31748 NODE_NAME_CASE(FMULS)
31749 NODE_NAME_CASE(FMULS_RND)
31750 NODE_NAME_CASE(FDIV_RND)
31751 NODE_NAME_CASE(FDIVS)
31752 NODE_NAME_CASE(FDIVS_RND)
31753 NODE_NAME_CASE(FSQRT_RND)
31754 NODE_NAME_CASE(FSQRTS)
31755 NODE_NAME_CASE(FSQRTS_RND)
31756 NODE_NAME_CASE(FGETEXP)
31757 NODE_NAME_CASE(FGETEXP_SAE)
31758 NODE_NAME_CASE(FGETEXPS)
31759 NODE_NAME_CASE(FGETEXPS_SAE)
31760 NODE_NAME_CASE(SCALEF)
31761 NODE_NAME_CASE(SCALEF_RND)
31762 NODE_NAME_CASE(SCALEFS)
31763 NODE_NAME_CASE(SCALEFS_RND)
31764 NODE_NAME_CASE(AVG)
31765 NODE_NAME_CASE(MULHRS)
31766 NODE_NAME_CASE(SINT_TO_FP_RND)
31767 NODE_NAME_CASE(UINT_TO_FP_RND)
31768 NODE_NAME_CASE(CVTTP2SI)
31769 NODE_NAME_CASE(CVTTP2UI)
31770 NODE_NAME_CASE(STRICT_CVTTP2SI)
31771 NODE_NAME_CASE(STRICT_CVTTP2UI)
31772 NODE_NAME_CASE(MCVTTP2SI)
31773 NODE_NAME_CASE(MCVTTP2UI)
31774 NODE_NAME_CASE(CVTTP2SI_SAE)
31775 NODE_NAME_CASE(CVTTP2UI_SAE)
31776 NODE_NAME_CASE(CVTTS2SI)
31777 NODE_NAME_CASE(CVTTS2UI)
31778 NODE_NAME_CASE(CVTTS2SI_SAE)
31779 NODE_NAME_CASE(CVTTS2UI_SAE)
31780 NODE_NAME_CASE(CVTSI2P)
31781 NODE_NAME_CASE(CVTUI2P)
31782 NODE_NAME_CASE(STRICT_CVTSI2P)
31783 NODE_NAME_CASE(STRICT_CVTUI2P)
31784 NODE_NAME_CASE(MCVTSI2P)
31785 NODE_NAME_CASE(MCVTUI2P)
31786 NODE_NAME_CASE(VFPCLASS)
31787 NODE_NAME_CASE(VFPCLASSS)
31788 NODE_NAME_CASE(MULTISHIFT)
31789 NODE_NAME_CASE(SCALAR_SINT_TO_FP)
31790 NODE_NAME_CASE(SCALAR_SINT_TO_FP_RND)
31791 NODE_NAME_CASE(SCALAR_UINT_TO_FP)
31792 NODE_NAME_CASE(SCALAR_UINT_TO_FP_RND)
31793 NODE_NAME_CASE(CVTPS2PH)
31794 NODE_NAME_CASE(STRICT_CVTPS2PH)
31795 NODE_NAME_CASE(MCVTPS2PH)
31796 NODE_NAME_CASE(CVTPH2PS)
31797 NODE_NAME_CASE(STRICT_CVTPH2PS)
31798 NODE_NAME_CASE(CVTPH2PS_SAE)
31799 NODE_NAME_CASE(CVTP2SI)
31800 NODE_NAME_CASE(CVTP2UI)
31801 NODE_NAME_CASE(MCVTP2SI)
31802 NODE_NAME_CASE(MCVTP2UI)
31803 NODE_NAME_CASE(CVTP2SI_RND)
31804 NODE_NAME_CASE(CVTP2UI_RND)
31805 NODE_NAME_CASE(CVTS2SI)
31806 NODE_NAME_CASE(CVTS2UI)
31807 NODE_NAME_CASE(CVTS2SI_RND)
31808 NODE_NAME_CASE(CVTS2UI_RND)
31809 NODE_NAME_CASE(CVTNE2PS2BF16)
31810 NODE_NAME_CASE(CVTNEPS2BF16)
31811 NODE_NAME_CASE(MCVTNEPS2BF16)
31812 NODE_NAME_CASE(DPBF16PS)
31813 NODE_NAME_CASE(LWPINS)
31814 NODE_NAME_CASE(MGATHER)
31815 NODE_NAME_CASE(MSCATTER)
31816 NODE_NAME_CASE(VPDPBUSD)
31817 NODE_NAME_CASE(VPDPBUSDS)
31818 NODE_NAME_CASE(VPDPWSSD)
31819 NODE_NAME_CASE(VPDPWSSDS)
31820 NODE_NAME_CASE(VPSHUFBITQMB)
31821 NODE_NAME_CASE(GF2P8MULB)
31822 NODE_NAME_CASE(GF2P8AFFINEQB)
31823 NODE_NAME_CASE(GF2P8AFFINEINVQB)
31824 NODE_NAME_CASE(NT_CALL)
31825 NODE_NAME_CASE(NT_BRIND)
31826 NODE_NAME_CASE(UMWAIT)
31827 NODE_NAME_CASE(TPAUSE)
31828 NODE_NAME_CASE(ENQCMD)
31829 NODE_NAME_CASE(ENQCMDS)
31830 NODE_NAME_CASE(VP2INTERSECT)
31831 NODE_NAME_CASE(AESENC128KL)
31832 NODE_NAME_CASE(AESDEC128KL)
31833 NODE_NAME_CASE(AESENC256KL)
31834 NODE_NAME_CASE(AESDEC256KL)
31835 NODE_NAME_CASE(AESENCWIDE128KL)
31836 NODE_NAME_CASE(AESDECWIDE128KL)
31837 NODE_NAME_CASE(AESENCWIDE256KL)
31838 NODE_NAME_CASE(AESDECWIDE256KL)
31839 NODE_NAME_CASE(TESTUI)
31840 }
31841 return nullptr;
31842#undef NODE_NAME_CASE
31843}
31844
31845/// Return true if the addressing mode represented by AM is legal for this
31846/// target, for a load/store of the specified type.
31847bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
31848 const AddrMode &AM, Type *Ty,
31849 unsigned AS,
31850 Instruction *I) const {
31851 // X86 supports extremely general addressing modes.
31852 CodeModel::Model M = getTargetMachine().getCodeModel();
31853
31854 // X86 allows a sign-extended 32-bit immediate field as a displacement.
31855 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
31856 return false;
31857
31858 if (AM.BaseGV) {
31859 unsigned GVFlags = Subtarget.classifyGlobalReference(AM.BaseGV);
31860
31861 // If a reference to this global requires an extra load, we can't fold it.
31862 if (isGlobalStubReference(GVFlags))
31863 return false;
31864
31865 // If BaseGV requires a register for the PIC base, we cannot also have a
31866 // BaseReg specified.
31867 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
31868 return false;
31869
31870 // If lower 4G is not available, then we must use rip-relative addressing.
31871 if ((M != CodeModel::Small || isPositionIndependent()) &&
31872 Subtarget.is64Bit() && (AM.BaseOffs || AM.Scale > 1))
31873 return false;
31874 }
31875
31876 switch (AM.Scale) {
31877 case 0:
31878 case 1:
31879 case 2:
31880 case 4:
31881 case 8:
31882 // These scales always work.
31883 break;
31884 case 3:
31885 case 5:
31886 case 9:
31887 // These scales are formed with basereg+scalereg. Only accept if there is
31888 // no basereg yet.
31889 if (AM.HasBaseReg)
31890 return false;
31891 break;
31892 default: // Other stuff never works.
31893 return false;
31894 }
31895
31896 return true;
31897}
31898
31899bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
31900 unsigned Bits = Ty->getScalarSizeInBits();
31901
31902 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
31903 // particularly cheaper than those without.
31904 if (Bits == 8)
31905 return false;
31906
31907 // XOP has v16i8/v8i16/v4i32/v2i64 variable vector shifts.
31908 // Splitting for v32i8/v16i16 on XOP+AVX2 targets is still preferred.
31909 if (Subtarget.hasXOP() &&
31910 (Bits == 8 || Bits == 16 || Bits == 32 || Bits == 64))
31911 return false;
31912
31913 // AVX2 has vpsllv[dq] instructions (and other shifts) that make variable
31914 // shifts just as cheap as scalar ones.
31915 if (Subtarget.hasAVX2() && (Bits == 32 || Bits == 64))
31916 return false;
31917
31918 // AVX512BW has shifts such as vpsllvw.
31919 if (Subtarget.hasBWI() && Bits == 16)
31920 return false;
31921
31922 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
31923 // fully general vector.
31924 return true;
31925}
31926
31927bool X86TargetLowering::isBinOp(unsigned Opcode) const {
31928 switch (Opcode) {
31929 // These are non-commutative binops.
31930 // TODO: Add more X86ISD opcodes once we have test coverage.
31931 case X86ISD::ANDNP:
31932 case X86ISD::PCMPGT:
31933 case X86ISD::FMAX:
31934 case X86ISD::FMIN:
31935 case X86ISD::FANDN:
31936 return true;
31937 }
31938
31939 return TargetLoweringBase::isBinOp(Opcode);
31940}
31941
31942bool X86TargetLowering::isCommutativeBinOp(unsigned Opcode) const {
31943 switch (Opcode) {
31944 // TODO: Add more X86ISD opcodes once we have test coverage.
31945 case X86ISD::PCMPEQ:
31946 case X86ISD::PMULDQ:
31947 case X86ISD::PMULUDQ:
31948 case X86ISD::FMAXC:
31949 case X86ISD::FMINC:
31950 case X86ISD::FAND:
31951 case X86ISD::FOR:
31952 case X86ISD::FXOR:
31953 return true;
31954 }
31955
31956 return TargetLoweringBase::isCommutativeBinOp(Opcode);
31957}
31958
31959bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
31960 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
31961 return false;
31962 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
31963 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
31964 return NumBits1 > NumBits2;
31965}
31966
31967bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
31968 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
31969 return false;
31970
31971 if (!isTypeLegal(EVT::getEVT(Ty1)))
31972 return false;
31973
31974 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-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 31974, __extension__ __PRETTY_FUNCTION__))
;
31975
31976 // Assuming the caller doesn't have a zeroext or signext return parameter,
31977 // truncation all the way down to i1 is valid.
31978 return true;
31979}
31980
31981bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
31982 return isInt<32>(Imm);
31983}
31984
31985bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
31986 // Can also use sub to handle negated immediates.
31987 return isInt<32>(Imm);
31988}
31989
31990bool X86TargetLowering::isLegalStoreImmediate(int64_t Imm) const {
31991 return isInt<32>(Imm);
31992}
31993
31994bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
31995 if (!VT1.isScalarInteger() || !VT2.isScalarInteger())
31996 return false;
31997 unsigned NumBits1 = VT1.getSizeInBits();
31998 unsigned NumBits2 = VT2.getSizeInBits();
31999 return NumBits1 > NumBits2;
32000}
32001
32002bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
32003 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
32004 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget.is64Bit();
32005}
32006
32007bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
32008 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
32009 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget.is64Bit();
32010}
32011
32012bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
32013 EVT VT1 = Val.getValueType();
32014 if (isZExtFree(VT1, VT2))
32015 return true;
32016
32017 if (Val.getOpcode() != ISD::LOAD)
32018 return false;
32019
32020 if (!VT1.isSimple() || !VT1.isInteger() ||
32021 !VT2.isSimple() || !VT2.isInteger())
32022 return false;
32023
32024 switch (VT1.getSimpleVT().SimpleTy) {
32025 default: break;
32026 case MVT::i8:
32027 case MVT::i16:
32028 case MVT::i32:
32029 // X86 has 8, 16, and 32-bit zero-extending loads.
32030 return true;
32031 }
32032
32033 return false;
32034}
32035
32036bool X86TargetLowering::shouldSinkOperands(Instruction *I,
32037 SmallVectorImpl<Use *> &Ops) const {
32038 // A uniform shift amount in a vector shift or funnel shift may be much
32039 // cheaper than a generic variable vector shift, so make that pattern visible
32040 // to SDAG by sinking the shuffle instruction next to the shift.
32041 int ShiftAmountOpNum = -1;
32042 if (I->isShift())
32043 ShiftAmountOpNum = 1;
32044 else if (auto *II = dyn_cast<IntrinsicInst>(I)) {
32045 if (II->getIntrinsicID() == Intrinsic::fshl ||
32046 II->getIntrinsicID() == Intrinsic::fshr)
32047 ShiftAmountOpNum = 2;
32048 }
32049
32050 if (ShiftAmountOpNum == -1)
32051 return false;
32052
32053 auto *Shuf = dyn_cast<ShuffleVectorInst>(I->getOperand(ShiftAmountOpNum));
32054 if (Shuf && getSplatIndex(Shuf->getShuffleMask()) >= 0 &&
32055 isVectorShiftByScalarCheap(I->getType())) {
32056 Ops.push_back(&I->getOperandUse(ShiftAmountOpNum));
32057 return true;
32058 }
32059
32060 return false;
32061}
32062
32063bool X86TargetLowering::shouldConvertPhiType(Type *From, Type *To) const {
32064 if (!Subtarget.is64Bit())
32065 return false;
32066 return TargetLowering::shouldConvertPhiType(From, To);
32067}
32068
32069bool X86TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
32070 if (isa<MaskedLoadSDNode>(ExtVal.getOperand(0)))
32071 return false;
32072
32073 EVT SrcVT = ExtVal.getOperand(0).getValueType();
32074
32075 // There is no extending load for vXi1.
32076 if (SrcVT.getScalarType() == MVT::i1)
32077 return false;
32078
32079 return true;
32080}
32081
32082bool X86TargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
32083 EVT VT) const {
32084 if (!Subtarget.hasAnyFMA())
32085 return false;
32086
32087 VT = VT.getScalarType();
32088
32089 if (!VT.isSimple())
32090 return false;
32091
32092 switch (VT.getSimpleVT().SimpleTy) {
32093 case MVT::f32:
32094 case MVT::f64:
32095 return true;
32096 default:
32097 break;
32098 }
32099
32100 return false;
32101}
32102
32103bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
32104 // i16 instructions are longer (0x66 prefix) and potentially slower.
32105 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
32106}
32107
32108/// Targets can use this to indicate that they only support *some*
32109/// VECTOR_SHUFFLE operations, those with specific masks.
32110/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
32111/// are assumed to be legal.
32112bool X86TargetLowering::isShuffleMaskLegal(ArrayRef<int> Mask, EVT VT) const {
32113 if (!VT.isSimple())
32114 return false;
32115
32116 // Not for i1 vectors
32117 if (VT.getSimpleVT().getScalarType() == MVT::i1)
32118 return false;
32119
32120 // Very little shuffling can be done for 64-bit vectors right now.
32121 if (VT.getSimpleVT().getSizeInBits() == 64)
32122 return false;
32123
32124 // We only care that the types being shuffled are legal. The lowering can
32125 // handle any possible shuffle mask that results.
32126 return isTypeLegal(VT.getSimpleVT());
32127}
32128
32129bool X86TargetLowering::isVectorClearMaskLegal(ArrayRef<int> Mask,
32130 EVT VT) const {
32131 // Don't convert an 'and' into a shuffle that we don't directly support.
32132 // vpblendw and vpshufb for 256-bit vectors are not available on AVX1.
32133 if (!Subtarget.hasAVX2())
32134 if (VT == MVT::v32i8 || VT == MVT::v16i16)
32135 return false;
32136
32137 // Just delegate to the generic legality, clear masks aren't special.
32138 return isShuffleMaskLegal(Mask, VT);
32139}
32140
32141bool X86TargetLowering::areJTsAllowed(const Function *Fn) const {
32142 // If the subtarget is using thunks, we need to not generate jump tables.
32143 if (Subtarget.useIndirectThunkBranches())
32144 return false;
32145
32146 // Otherwise, fallback on the generic logic.
32147 return TargetLowering::areJTsAllowed(Fn);
32148}
32149
32150//===----------------------------------------------------------------------===//
32151// X86 Scheduler Hooks
32152//===----------------------------------------------------------------------===//
32153
32154// Returns true if EFLAG is consumed after this iterator in the rest of the
32155// basic block or any successors of the basic block.
32156static bool isEFLAGSLiveAfter(MachineBasicBlock::iterator Itr,
32157 MachineBasicBlock *BB) {
32158 // Scan forward through BB for a use/def of EFLAGS.
32159 for (MachineBasicBlock::iterator miI = std::next(Itr), miE = BB->end();
32160 miI != miE; ++miI) {
32161 const MachineInstr& mi = *miI;
32162 if (mi.readsRegister(X86::EFLAGS))
32163 return true;
32164 // If we found a def, we can stop searching.
32165 if (mi.definesRegister(X86::EFLAGS))
32166 return false;
32167 }
32168
32169 // If we hit the end of the block, check whether EFLAGS is live into a
32170 // successor.
32171 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
32172 sEnd = BB->succ_end();
32173 sItr != sEnd; ++sItr) {
32174 MachineBasicBlock* succ = *sItr;
32175 if (succ->isLiveIn(X86::EFLAGS))
32176 return true;
32177 }
32178
32179 return false;
32180}
32181
32182/// Utility function to emit xbegin specifying the start of an RTM region.
32183static MachineBasicBlock *emitXBegin(MachineInstr &MI, MachineBasicBlock *MBB,
32184 const TargetInstrInfo *TII) {
32185 const DebugLoc &DL = MI.getDebugLoc();
32186
32187 const BasicBlock *BB = MBB->getBasicBlock();
32188 MachineFunction::iterator I = ++MBB->getIterator();
32189
32190 // For the v = xbegin(), we generate
32191 //
32192 // thisMBB:
32193 // xbegin sinkMBB
32194 //
32195 // mainMBB:
32196 // s0 = -1
32197 //
32198 // fallBB:
32199 // eax = # XABORT_DEF
32200 // s1 = eax
32201 //
32202 // sinkMBB:
32203 // v = phi(s0/mainBB, s1/fallBB)
32204
32205 MachineBasicBlock *thisMBB = MBB;
32206 MachineFunction *MF = MBB->getParent();
32207 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
32208 MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
32209 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
32210 MF->insert(I, mainMBB);
32211 MF->insert(I, fallMBB);
32212 MF->insert(I, sinkMBB);
32213
32214 if (isEFLAGSLiveAfter(MI, MBB)) {
32215 mainMBB->addLiveIn(X86::EFLAGS);
32216 fallMBB->addLiveIn(X86::EFLAGS);
32217 sinkMBB->addLiveIn(X86::EFLAGS);
32218 }
32219
32220 // Transfer the remainder of BB and its successor edges to sinkMBB.
32221 sinkMBB->splice(sinkMBB->begin(), MBB,
32222 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
32223 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
32224
32225 MachineRegisterInfo &MRI = MF->getRegInfo();
32226 Register DstReg = MI.getOperand(0).getReg();
32227 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
32228 Register mainDstReg = MRI.createVirtualRegister(RC);
32229 Register fallDstReg = MRI.createVirtualRegister(RC);
32230
32231 // thisMBB:
32232 // xbegin fallMBB
32233 // # fallthrough to mainMBB
32234 // # abortion to fallMBB
32235 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(fallMBB);
32236 thisMBB->addSuccessor(mainMBB);
32237 thisMBB->addSuccessor(fallMBB);
32238
32239 // mainMBB:
32240 // mainDstReg := -1
32241 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), mainDstReg).addImm(-1);
32242 BuildMI(mainMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
32243 mainMBB->addSuccessor(sinkMBB);
32244
32245 // fallMBB:
32246 // ; pseudo instruction to model hardware's definition from XABORT
32247 // EAX := XABORT_DEF
32248 // fallDstReg := EAX
32249 BuildMI(fallMBB, DL, TII->get(X86::XABORT_DEF));
32250 BuildMI(fallMBB, DL, TII->get(TargetOpcode::COPY), fallDstReg)
32251 .addReg(X86::EAX);
32252 fallMBB->addSuccessor(sinkMBB);
32253
32254 // sinkMBB:
32255 // DstReg := phi(mainDstReg/mainBB, fallDstReg/fallBB)
32256 BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI), DstReg)
32257 .addReg(mainDstReg).addMBB(mainMBB)
32258 .addReg(fallDstReg).addMBB(fallMBB);
32259
32260 MI.eraseFromParent();
32261 return sinkMBB;
32262}
32263
32264MachineBasicBlock *
32265X86TargetLowering::EmitVAARGWithCustomInserter(MachineInstr &MI,
32266 MachineBasicBlock *MBB) const {
32267 // Emit va_arg instruction on X86-64.
32268
32269 // Operands to this pseudo-instruction:
32270 // 0 ) Output : destination address (reg)
32271 // 1-5) Input : va_list address (addr, i64mem)
32272 // 6 ) ArgSize : Size (in bytes) of vararg type
32273 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
32274 // 8 ) Align : Alignment of type
32275 // 9 ) EFLAGS (implicit-def)
32276
32277 assert(MI.getNumOperands() == 10 && "VAARG should have 10 operands!")(static_cast <bool> (MI.getNumOperands() == 10 &&
"VAARG should have 10 operands!") ? void (0) : __assert_fail
("MI.getNumOperands() == 10 && \"VAARG should have 10 operands!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 32277, __extension__ __PRETTY_FUNCTION__))
;
32278 static_assert(X86::AddrNumOperands == 5, "VAARG assumes 5 address operands");
32279
32280 Register DestReg = MI.getOperand(0).getReg();
32281 MachineOperand &Base = MI.getOperand(1);
32282 MachineOperand &Scale = MI.getOperand(2);
32283 MachineOperand &Index = MI.getOperand(3);
32284 MachineOperand &Disp = MI.getOperand(4);
32285 MachineOperand &Segment = MI.getOperand(5);
32286 unsigned ArgSize = MI.getOperand(6).getImm();
32287 unsigned ArgMode = MI.getOperand(7).getImm();
32288 Align Alignment = Align(MI.getOperand(8).getImm());
32289
32290 MachineFunction *MF = MBB->getParent();
32291
32292 // Memory Reference
32293 assert(MI.hasOneMemOperand() && "Expected VAARG to have one memoperand")(static_cast <bool> (MI.hasOneMemOperand() && "Expected VAARG to have one memoperand"
) ? void (0) : __assert_fail ("MI.hasOneMemOperand() && \"Expected VAARG to have one memoperand\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 32293, __extension__ __PRETTY_FUNCTION__))
;
32294
32295 MachineMemOperand *OldMMO = MI.memoperands().front();
32296
32297 // Clone the MMO into two separate MMOs for loading and storing
32298 MachineMemOperand *LoadOnlyMMO = MF->getMachineMemOperand(
32299 OldMMO, OldMMO->getFlags() & ~MachineMemOperand::MOStore);
32300 MachineMemOperand *StoreOnlyMMO = MF->getMachineMemOperand(
32301 OldMMO, OldMMO->getFlags() & ~MachineMemOperand::MOLoad);
32302
32303 // Machine Information
32304 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
32305 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
32306 const TargetRegisterClass *AddrRegClass =
32307 getRegClassFor(getPointerTy(MBB->getParent()->getDataLayout()));
32308 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
32309 const DebugLoc &DL = MI.getDebugLoc();
32310
32311 // struct va_list {
32312 // i32 gp_offset
32313 // i32 fp_offset
32314 // i64 overflow_area (address)
32315 // i64 reg_save_area (address)
32316 // }
32317 // sizeof(va_list) = 24
32318 // alignment(va_list) = 8
32319
32320 unsigned TotalNumIntRegs = 6;
32321 unsigned TotalNumXMMRegs = 8;
32322 bool UseGPOffset = (ArgMode == 1);
32323 bool UseFPOffset = (ArgMode == 2);
32324 unsigned MaxOffset = TotalNumIntRegs * 8 +
32325 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
32326
32327 /* Align ArgSize to a multiple of 8 */
32328 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
32329 bool NeedsAlign = (Alignment > 8);
32330
32331 MachineBasicBlock *thisMBB = MBB;
32332 MachineBasicBlock *overflowMBB;
32333 MachineBasicBlock *offsetMBB;
32334 MachineBasicBlock *endMBB;
32335
32336 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
32337 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
32338 unsigned OffsetReg = 0;
32339
32340 if (!UseGPOffset && !UseFPOffset) {
32341 // If we only pull from the overflow region, we don't create a branch.
32342 // We don't need to alter control flow.
32343 OffsetDestReg = 0; // unused
32344 OverflowDestReg = DestReg;
32345
32346 offsetMBB = nullptr;
32347 overflowMBB = thisMBB;
32348 endMBB = thisMBB;
32349 } else {
32350 // First emit code to check if gp_offset (or fp_offset) is below the bound.
32351 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
32352 // If not, pull from overflow_area. (branch to overflowMBB)
32353 //
32354 // thisMBB
32355 // | .
32356 // | .
32357 // offsetMBB overflowMBB
32358 // | .
32359 // | .
32360 // endMBB
32361
32362 // Registers for the PHI in endMBB
32363 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
32364 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
32365
32366 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
32367 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
32368 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
32369 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
32370
32371 MachineFunction::iterator MBBIter = ++MBB->getIterator();
32372
32373 // Insert the new basic blocks
32374 MF->insert(MBBIter, offsetMBB);
32375 MF->insert(MBBIter, overflowMBB);
32376 MF->insert(MBBIter, endMBB);
32377
32378 // Transfer the remainder of MBB and its successor edges to endMBB.
32379 endMBB->splice(endMBB->begin(), thisMBB,
32380 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
32381 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
32382
32383 // Make offsetMBB and overflowMBB successors of thisMBB
32384 thisMBB->addSuccessor(offsetMBB);
32385 thisMBB->addSuccessor(overflowMBB);
32386
32387 // endMBB is a successor of both offsetMBB and overflowMBB
32388 offsetMBB->addSuccessor(endMBB);
32389 overflowMBB->addSuccessor(endMBB);
32390
32391 // Load the offset value into a register
32392 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
32393 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
32394 .add(Base)
32395 .add(Scale)
32396 .add(Index)
32397 .addDisp(Disp, UseFPOffset ? 4 : 0)
32398 .add(Segment)
32399 .setMemRefs(LoadOnlyMMO);
32400
32401 // Check if there is enough room left to pull this argument.
32402 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
32403 .addReg(OffsetReg)
32404 .addImm(MaxOffset + 8 - ArgSizeA8);
32405
32406 // Branch to "overflowMBB" if offset >= max
32407 // Fall through to "offsetMBB" otherwise
32408 BuildMI(thisMBB, DL, TII->get(X86::JCC_1))
32409 .addMBB(overflowMBB).addImm(X86::COND_AE);
32410 }
32411
32412 // In offsetMBB, emit code to use the reg_save_area.
32413 if (offsetMBB) {
32414 assert(OffsetReg != 0)(static_cast <bool> (OffsetReg != 0) ? void (0) : __assert_fail
("OffsetReg != 0", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 32414, __extension__ __PRETTY_FUNCTION__))
;
32415
32416 // Read the reg_save_area address.
32417 Register RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
32418 BuildMI(
32419 offsetMBB, DL,
32420 TII->get(Subtarget.isTarget64BitLP64() ? X86::MOV64rm : X86::MOV32rm),
32421 RegSaveReg)
32422 .add(Base)
32423 .add(Scale)
32424 .add(Index)
32425 .addDisp(Disp, Subtarget.isTarget64BitLP64() ? 16 : 12)
32426 .add(Segment)
32427 .setMemRefs(LoadOnlyMMO);
32428
32429 if (Subtarget.isTarget64BitLP64()) {
32430 // Zero-extend the offset
32431 Register OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
32432 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
32433 .addImm(0)
32434 .addReg(OffsetReg)
32435 .addImm(X86::sub_32bit);
32436
32437 // Add the offset to the reg_save_area to get the final address.
32438 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
32439 .addReg(OffsetReg64)
32440 .addReg(RegSaveReg);
32441 } else {
32442 // Add the offset to the reg_save_area to get the final address.
32443 BuildMI(offsetMBB, DL, TII->get(X86::ADD32rr), OffsetDestReg)
32444 .addReg(OffsetReg)
32445 .addReg(RegSaveReg);
32446 }
32447
32448 // Compute the offset for the next argument
32449 Register NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
32450 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
32451 .addReg(OffsetReg)
32452 .addImm(UseFPOffset ? 16 : 8);
32453
32454 // Store it back into the va_list.
32455 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
32456 .add(Base)
32457 .add(Scale)
32458 .add(Index)
32459 .addDisp(Disp, UseFPOffset ? 4 : 0)
32460 .add(Segment)
32461 .addReg(NextOffsetReg)
32462 .setMemRefs(StoreOnlyMMO);
32463
32464 // Jump to endMBB
32465 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
32466 .addMBB(endMBB);
32467 }
32468
32469 //
32470 // Emit code to use overflow area
32471 //
32472
32473 // Load the overflow_area address into a register.
32474 Register OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
32475 BuildMI(overflowMBB, DL,
32476 TII->get(Subtarget.isTarget64BitLP64() ? X86::MOV64rm : X86::MOV32rm),
32477 OverflowAddrReg)
32478 .add(Base)
32479 .add(Scale)
32480 .add(Index)
32481 .addDisp(Disp, 8)
32482 .add(Segment)
32483 .setMemRefs(LoadOnlyMMO);
32484
32485 // If we need to align it, do so. Otherwise, just copy the address
32486 // to OverflowDestReg.
32487 if (NeedsAlign) {
32488 // Align the overflow address
32489 Register TmpReg = MRI.createVirtualRegister(AddrRegClass);
32490
32491 // aligned_addr = (addr + (align-1)) & ~(align-1)
32492 BuildMI(
32493 overflowMBB, DL,
32494 TII->get(Subtarget.isTarget64BitLP64() ? X86::ADD64ri32 : X86::ADD32ri),
32495 TmpReg)
32496 .addReg(OverflowAddrReg)
32497 .addImm(Alignment.value() - 1);
32498
32499 BuildMI(
32500 overflowMBB, DL,
32501 TII->get(Subtarget.isTarget64BitLP64() ? X86::AND64ri32 : X86::AND32ri),
32502 OverflowDestReg)
32503 .addReg(TmpReg)
32504 .addImm(~(uint64_t)(Alignment.value() - 1));
32505 } else {
32506 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
32507 .addReg(OverflowAddrReg);
32508 }
32509
32510 // Compute the next overflow address after this argument.
32511 // (the overflow address should be kept 8-byte aligned)
32512 Register NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
32513 BuildMI(
32514 overflowMBB, DL,
32515 TII->get(Subtarget.isTarget64BitLP64() ? X86::ADD64ri32 : X86::ADD32ri),
32516 NextAddrReg)
32517 .addReg(OverflowDestReg)
32518 .addImm(ArgSizeA8);
32519
32520 // Store the new overflow address.
32521 BuildMI(overflowMBB, DL,
32522 TII->get(Subtarget.isTarget64BitLP64() ? X86::MOV64mr : X86::MOV32mr))
32523 .add(Base)
32524 .add(Scale)
32525 .add(Index)
32526 .addDisp(Disp, 8)
32527 .add(Segment)
32528 .addReg(NextAddrReg)
32529 .setMemRefs(StoreOnlyMMO);
32530
32531 // If we branched, emit the PHI to the front of endMBB.
32532 if (offsetMBB) {
32533 BuildMI(*endMBB, endMBB->begin(), DL,
32534 TII->get(X86::PHI), DestReg)
32535 .addReg(OffsetDestReg).addMBB(offsetMBB)
32536 .addReg(OverflowDestReg).addMBB(overflowMBB);
32537 }
32538
32539 // Erase the pseudo instruction
32540 MI.eraseFromParent();
32541
32542 return endMBB;
32543}
32544
32545// The EFLAGS operand of SelectItr might be missing a kill marker
32546// because there were multiple uses of EFLAGS, and ISel didn't know
32547// which to mark. Figure out whether SelectItr should have had a
32548// kill marker, and set it if it should. Returns the correct kill
32549// marker value.
32550static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
32551 MachineBasicBlock* BB,
32552 const TargetRegisterInfo* TRI) {
32553 if (isEFLAGSLiveAfter(SelectItr, BB))
32554 return false;
32555
32556 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
32557 // out. SelectMI should have a kill flag on EFLAGS.
32558 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
32559 return true;
32560}
32561
32562// Return true if it is OK for this CMOV pseudo-opcode to be cascaded
32563// together with other CMOV pseudo-opcodes into a single basic-block with
32564// conditional jump around it.
32565static bool isCMOVPseudo(MachineInstr &MI) {
32566 switch (MI.getOpcode()) {
32567 case X86::CMOV_FR32:
32568 case X86::CMOV_FR32X:
32569 case X86::CMOV_FR64:
32570 case X86::CMOV_FR64X:
32571 case X86::CMOV_GR8:
32572 case X86::CMOV_GR16:
32573 case X86::CMOV_GR32:
32574 case X86::CMOV_RFP32:
32575 case X86::CMOV_RFP64:
32576 case X86::CMOV_RFP80:
32577 case X86::CMOV_VR64:
32578 case X86::CMOV_VR128:
32579 case X86::CMOV_VR128X:
32580 case X86::CMOV_VR256:
32581 case X86::CMOV_VR256X:
32582 case X86::CMOV_VR512:
32583 case X86::CMOV_VK1:
32584 case X86::CMOV_VK2:
32585 case X86::CMOV_VK4:
32586 case X86::CMOV_VK8:
32587 case X86::CMOV_VK16:
32588 case X86::CMOV_VK32:
32589 case X86::CMOV_VK64:
32590 return true;
32591
32592 default:
32593 return false;
32594 }
32595}
32596
32597// Helper function, which inserts PHI functions into SinkMBB:
32598// %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ],
32599// where %FalseValue(i) and %TrueValue(i) are taken from the consequent CMOVs
32600// in [MIItBegin, MIItEnd) range. It returns the last MachineInstrBuilder for
32601// the last PHI function inserted.
32602static MachineInstrBuilder createPHIsForCMOVsInSinkBB(
32603 MachineBasicBlock::iterator MIItBegin, MachineBasicBlock::iterator MIItEnd,
32604 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
32605 MachineBasicBlock *SinkMBB) {
32606 MachineFunction *MF = TrueMBB->getParent();
32607 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
32608 const DebugLoc &DL = MIItBegin->getDebugLoc();
32609
32610 X86::CondCode CC = X86::CondCode(MIItBegin->getOperand(3).getImm());
32611 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
32612
32613 MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
32614
32615 // As we are creating the PHIs, we have to be careful if there is more than
32616 // one. Later CMOVs may reference the results of earlier CMOVs, but later
32617 // PHIs have to reference the individual true/false inputs from earlier PHIs.
32618 // That also means that PHI construction must work forward from earlier to
32619 // later, and that the code must maintain a mapping from earlier PHI's
32620 // destination registers, and the registers that went into the PHI.
32621 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
32622 MachineInstrBuilder MIB;
32623
32624 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
32625 Register DestReg = MIIt->getOperand(0).getReg();
32626 Register Op1Reg = MIIt->getOperand(1).getReg();
32627 Register Op2Reg = MIIt->getOperand(2).getReg();
32628
32629 // If this CMOV we are generating is the opposite condition from
32630 // the jump we generated, then we have to swap the operands for the
32631 // PHI that is going to be generated.
32632 if (MIIt->getOperand(3).getImm() == OppCC)
32633 std::swap(Op1Reg, Op2Reg);
32634
32635 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
32636 Op1Reg = RegRewriteTable[Op1Reg].first;
32637
32638 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
32639 Op2Reg = RegRewriteTable[Op2Reg].second;
32640
32641 MIB = BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(X86::PHI), DestReg)
32642 .addReg(Op1Reg)
32643 .addMBB(FalseMBB)
32644 .addReg(Op2Reg)
32645 .addMBB(TrueMBB);
32646
32647 // Add this PHI to the rewrite table.
32648 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
32649 }
32650
32651 return MIB;
32652}
32653
32654// Lower cascaded selects in form of (SecondCmov (FirstCMOV F, T, cc1), T, cc2).
32655MachineBasicBlock *
32656X86TargetLowering::EmitLoweredCascadedSelect(MachineInstr &FirstCMOV,
32657 MachineInstr &SecondCascadedCMOV,
32658 MachineBasicBlock *ThisMBB) const {
32659 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
32660 const DebugLoc &DL = FirstCMOV.getDebugLoc();
32661
32662 // We lower cascaded CMOVs such as
32663 //
32664 // (SecondCascadedCMOV (FirstCMOV F, T, cc1), T, cc2)
32665 //
32666 // to two successive branches.
32667 //
32668 // Without this, we would add a PHI between the two jumps, which ends up
32669 // creating a few copies all around. For instance, for
32670 //
32671 // (sitofp (zext (fcmp une)))
32672 //
32673 // we would generate:
32674 //
32675 // ucomiss %xmm1, %xmm0
32676 // movss <1.0f>, %xmm0
32677 // movaps %xmm0, %xmm1
32678 // jne .LBB5_2
32679 // xorps %xmm1, %xmm1
32680 // .LBB5_2:
32681 // jp .LBB5_4
32682 // movaps %xmm1, %xmm0
32683 // .LBB5_4:
32684 // retq
32685 //
32686 // because this custom-inserter would have generated:
32687 //
32688 // A
32689 // | \
32690 // | B
32691 // | /
32692 // C
32693 // | \
32694 // | D
32695 // | /
32696 // E
32697 //
32698 // A: X = ...; Y = ...
32699 // B: empty
32700 // C: Z = PHI [X, A], [Y, B]
32701 // D: empty
32702 // E: PHI [X, C], [Z, D]
32703 //
32704 // If we lower both CMOVs in a single step, we can instead generate:
32705 //
32706 // A
32707 // | \
32708 // | C
32709 // | /|
32710 // |/ |
32711 // | |
32712 // | D
32713 // | /
32714 // E
32715 //
32716 // A: X = ...; Y = ...
32717 // D: empty
32718 // E: PHI [X, A], [X, C], [Y, D]
32719 //
32720 // Which, in our sitofp/fcmp example, gives us something like:
32721 //
32722 // ucomiss %xmm1, %xmm0
32723 // movss <1.0f>, %xmm0
32724 // jne .LBB5_4
32725 // jp .LBB5_4
32726 // xorps %xmm0, %xmm0
32727 // .LBB5_4:
32728 // retq
32729 //
32730
32731 // We lower cascaded CMOV into two successive branches to the same block.
32732 // EFLAGS is used by both, so mark it as live in the second.
32733 const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
32734 MachineFunction *F = ThisMBB->getParent();
32735 MachineBasicBlock *FirstInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
32736 MachineBasicBlock *SecondInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
32737 MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
32738
32739 MachineFunction::iterator It = ++ThisMBB->getIterator();
32740 F->insert(It, FirstInsertedMBB);
32741 F->insert(It, SecondInsertedMBB);
32742 F->insert(It, SinkMBB);
32743
32744 // For a cascaded CMOV, we lower it to two successive branches to
32745 // the same block (SinkMBB). EFLAGS is used by both, so mark it as live in
32746 // the FirstInsertedMBB.
32747 FirstInsertedMBB->addLiveIn(X86::EFLAGS);
32748
32749 // If the EFLAGS register isn't dead in the terminator, then claim that it's
32750 // live into the sink and copy blocks.
32751 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
32752 if (!SecondCascadedCMOV.killsRegister(X86::EFLAGS) &&
32753 !checkAndUpdateEFLAGSKill(SecondCascadedCMOV, ThisMBB, TRI)) {
32754 SecondInsertedMBB->addLiveIn(X86::EFLAGS);
32755 SinkMBB->addLiveIn(X86::EFLAGS);
32756 }
32757
32758 // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
32759 SinkMBB->splice(SinkMBB->begin(), ThisMBB,
32760 std::next(MachineBasicBlock::iterator(FirstCMOV)),
32761 ThisMBB->end());
32762 SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
32763
32764 // Fallthrough block for ThisMBB.
32765 ThisMBB->addSuccessor(FirstInsertedMBB);
32766 // The true block target of the first branch is always SinkMBB.
32767 ThisMBB->addSuccessor(SinkMBB);
32768 // Fallthrough block for FirstInsertedMBB.
32769 FirstInsertedMBB->addSuccessor(SecondInsertedMBB);
32770 // The true block for the branch of FirstInsertedMBB.
32771 FirstInsertedMBB->addSuccessor(SinkMBB);
32772 // This is fallthrough.
32773 SecondInsertedMBB->addSuccessor(SinkMBB);
32774
32775 // Create the conditional branch instructions.
32776 X86::CondCode FirstCC = X86::CondCode(FirstCMOV.getOperand(3).getImm());
32777 BuildMI(ThisMBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(FirstCC);
32778
32779 X86::CondCode SecondCC =
32780 X86::CondCode(SecondCascadedCMOV.getOperand(3).getImm());
32781 BuildMI(FirstInsertedMBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(SecondCC);
32782
32783 // SinkMBB:
32784 // %Result = phi [ %FalseValue, SecondInsertedMBB ], [ %TrueValue, ThisMBB ]
32785 Register DestReg = FirstCMOV.getOperand(0).getReg();
32786 Register Op1Reg = FirstCMOV.getOperand(1).getReg();
32787 Register Op2Reg = FirstCMOV.getOperand(2).getReg();
32788 MachineInstrBuilder MIB =
32789 BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII->get(X86::PHI), DestReg)
32790 .addReg(Op1Reg)
32791 .addMBB(SecondInsertedMBB)
32792 .addReg(Op2Reg)
32793 .addMBB(ThisMBB);
32794
32795 // The second SecondInsertedMBB provides the same incoming value as the
32796 // FirstInsertedMBB (the True operand of the SELECT_CC/CMOV nodes).
32797 MIB.addReg(FirstCMOV.getOperand(2).getReg()).addMBB(FirstInsertedMBB);
32798 // Copy the PHI result to the register defined by the second CMOV.
32799 BuildMI(*SinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())), DL,
32800 TII->get(TargetOpcode::COPY),
32801 SecondCascadedCMOV.getOperand(0).getReg())
32802 .addReg(FirstCMOV.getOperand(0).getReg());
32803
32804 // Now remove the CMOVs.
32805 FirstCMOV.eraseFromParent();
32806 SecondCascadedCMOV.eraseFromParent();
32807
32808 return SinkMBB;
32809}
32810
32811MachineBasicBlock *
32812X86TargetLowering::EmitLoweredSelect(MachineInstr &MI,
32813 MachineBasicBlock *ThisMBB) const {
32814 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
32815 const DebugLoc &DL = MI.getDebugLoc();
32816
32817 // To "insert" a SELECT_CC instruction, we actually have to insert the
32818 // diamond control-flow pattern. The incoming instruction knows the
32819 // destination vreg to set, the condition code register to branch on, the
32820 // true/false values to select between and a branch opcode to use.
32821
32822 // ThisMBB:
32823 // ...
32824 // TrueVal = ...
32825 // cmpTY ccX, r1, r2
32826 // bCC copy1MBB
32827 // fallthrough --> FalseMBB
32828
32829 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
32830 // as described above, by inserting a BB, and then making a PHI at the join
32831 // point to select the true and false operands of the CMOV in the PHI.
32832 //
32833 // The code also handles two different cases of multiple CMOV opcodes
32834 // in a row.
32835 //
32836 // Case 1:
32837 // In this case, there are multiple CMOVs in a row, all which are based on
32838 // the same condition setting (or the exact opposite condition setting).
32839 // In this case we can lower all the CMOVs using a single inserted BB, and
32840 // then make a number of PHIs at the join point to model the CMOVs. The only
32841 // trickiness here, is that in a case like:
32842 //
32843 // t2 = CMOV cond1 t1, f1
32844 // t3 = CMOV cond1 t2, f2
32845 //
32846 // when rewriting this into PHIs, we have to perform some renaming on the
32847 // temps since you cannot have a PHI operand refer to a PHI result earlier
32848 // in the same block. The "simple" but wrong lowering would be:
32849 //
32850 // t2 = PHI t1(BB1), f1(BB2)
32851 // t3 = PHI t2(BB1), f2(BB2)
32852 //
32853 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
32854 // renaming is to note that on the path through BB1, t2 is really just a
32855 // copy of t1, and do that renaming, properly generating:
32856 //
32857 // t2 = PHI t1(BB1), f1(BB2)
32858 // t3 = PHI t1(BB1), f2(BB2)
32859 //
32860 // Case 2:
32861 // CMOV ((CMOV F, T, cc1), T, cc2) is checked here and handled by a separate
32862 // function - EmitLoweredCascadedSelect.
32863
32864 X86::CondCode CC = X86::CondCode(MI.getOperand(3).getImm());
32865 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
32866 MachineInstr *LastCMOV = &MI;
32867 MachineBasicBlock::iterator NextMIIt = MachineBasicBlock::iterator(MI);
32868
32869 // Check for case 1, where there are multiple CMOVs with the same condition
32870 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
32871 // number of jumps the most.
32872
32873 if (isCMOVPseudo(MI)) {
32874 // See if we have a string of CMOVS with the same condition. Skip over
32875 // intervening debug insts.
32876 while (NextMIIt != ThisMBB->end() && isCMOVPseudo(*NextMIIt) &&
32877 (NextMIIt->getOperand(3).getImm() == CC ||
32878 NextMIIt->getOperand(3).getImm() == OppCC)) {
32879 LastCMOV = &*NextMIIt;
32880 NextMIIt = next_nodbg(NextMIIt, ThisMBB->end());
32881 }
32882 }
32883
32884 // This checks for case 2, but only do this if we didn't already find
32885 // case 1, as indicated by LastCMOV == MI.
32886 if (LastCMOV == &MI && NextMIIt != ThisMBB->end() &&
32887 NextMIIt->getOpcode() == MI.getOpcode() &&
32888 NextMIIt->getOperand(2).getReg() == MI.getOperand(2).getReg() &&
32889 NextMIIt->getOperand(1).getReg() == MI.getOperand(0).getReg() &&
32890 NextMIIt->getOperand(1).isKill()) {
32891 return EmitLoweredCascadedSelect(MI, *NextMIIt, ThisMBB);
32892 }
32893
32894 const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
32895 MachineFunction *F = ThisMBB->getParent();
32896 MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
32897 MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
32898
32899 MachineFunction::iterator It = ++ThisMBB->getIterator();
32900 F->insert(It, FalseMBB);
32901 F->insert(It, SinkMBB);
32902
32903 // If the EFLAGS register isn't dead in the terminator, then claim that it's
32904 // live into the sink and copy blocks.
32905 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
32906 if (!LastCMOV->killsRegister(X86::EFLAGS) &&
32907 !checkAndUpdateEFLAGSKill(LastCMOV, ThisMBB, TRI)) {
32908 FalseMBB->addLiveIn(X86::EFLAGS);
32909 SinkMBB->addLiveIn(X86::EFLAGS);
32910 }
32911
32912 // Transfer any debug instructions inside the CMOV sequence to the sunk block.
32913 auto DbgEnd = MachineBasicBlock::iterator(LastCMOV);
32914 auto DbgIt = MachineBasicBlock::iterator(MI);
32915 while (DbgIt != DbgEnd) {
32916 auto Next = std::next(DbgIt);
32917 if (DbgIt->isDebugInstr())
32918 SinkMBB->push_back(DbgIt->removeFromParent());
32919 DbgIt = Next;
32920 }
32921
32922 // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
32923 SinkMBB->splice(SinkMBB->end(), ThisMBB,
32924 std::next(MachineBasicBlock::iterator(LastCMOV)),
32925 ThisMBB->end());
32926 SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
32927
32928 // Fallthrough block for ThisMBB.
32929 ThisMBB->addSuccessor(FalseMBB);
32930 // The true block target of the first (or only) branch is always a SinkMBB.
32931 ThisMBB->addSuccessor(SinkMBB);
32932 // Fallthrough block for FalseMBB.
32933 FalseMBB->addSuccessor(SinkMBB);
32934
32935 // Create the conditional branch instruction.
32936 BuildMI(ThisMBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(CC);
32937
32938 // SinkMBB:
32939 // %Result = phi [ %FalseValue, FalseMBB ], [ %TrueValue, ThisMBB ]
32940 // ...
32941 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
32942 MachineBasicBlock::iterator MIItEnd =
32943 std::next(MachineBasicBlock::iterator(LastCMOV));
32944 createPHIsForCMOVsInSinkBB(MIItBegin, MIItEnd, ThisMBB, FalseMBB, SinkMBB);
32945
32946 // Now remove the CMOV(s).
32947 ThisMBB->erase(MIItBegin, MIItEnd);
32948
32949 return SinkMBB;
32950}
32951
32952static unsigned getSUBriOpcode(bool IsLP64, int64_t Imm) {
32953 if (IsLP64) {
32954 if (isInt<8>(Imm))
32955 return X86::SUB64ri8;
32956 return X86::SUB64ri32;
32957 } else {
32958 if (isInt<8>(Imm))
32959 return X86::SUB32ri8;
32960 return X86::SUB32ri;
32961 }
32962}
32963
32964MachineBasicBlock *
32965X86TargetLowering::EmitLoweredProbedAlloca(MachineInstr &MI,
32966 MachineBasicBlock *MBB) const {
32967 MachineFunction *MF = MBB->getParent();
32968 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
32969 const X86FrameLowering &TFI = *Subtarget.getFrameLowering();
32970 const DebugLoc &DL = MI.getDebugLoc();
32971 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
32972
32973 const unsigned ProbeSize = getStackProbeSize(*MF);
32974
32975 MachineRegisterInfo &MRI = MF->getRegInfo();
32976 MachineBasicBlock *testMBB = MF->CreateMachineBasicBlock(LLVM_BB);
32977 MachineBasicBlock *tailMBB = MF->CreateMachineBasicBlock(LLVM_BB);
32978 MachineBasicBlock *blockMBB = MF->CreateMachineBasicBlock(LLVM_BB);
32979
32980 MachineFunction::iterator MBBIter = ++MBB->getIterator();
32981 MF->insert(MBBIter, testMBB);
32982 MF->insert(MBBIter, blockMBB);
32983 MF->insert(MBBIter, tailMBB);
32984
32985 Register sizeVReg = MI.getOperand(1).getReg();
32986
32987 Register physSPReg = TFI.Uses64BitFramePtr ? X86::RSP : X86::ESP;
32988
32989 Register TmpStackPtr = MRI.createVirtualRegister(
32990 TFI.Uses64BitFramePtr ? &X86::GR64RegClass : &X86::GR32RegClass);
32991 Register FinalStackPtr = MRI.createVirtualRegister(
32992 TFI.Uses64BitFramePtr ? &X86::GR64RegClass : &X86::GR32RegClass);
32993
32994 BuildMI(*MBB, {MI}, DL, TII->get(TargetOpcode::COPY), TmpStackPtr)
32995 .addReg(physSPReg);
32996 {
32997 const unsigned Opc = TFI.Uses64BitFramePtr ? X86::SUB64rr : X86::SUB32rr;
32998 BuildMI(*MBB, {MI}, DL, TII->get(Opc), FinalStackPtr)
32999 .addReg(TmpStackPtr)
33000 .addReg(sizeVReg);
33001 }
33002
33003 // test rsp size
33004
33005 BuildMI(testMBB, DL,
33006 TII->get(TFI.Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
33007 .addReg(FinalStackPtr)
33008 .addReg(physSPReg);
33009
33010 BuildMI(testMBB, DL, TII->get(X86::JCC_1))
33011 .addMBB(tailMBB)
33012 .addImm(X86::COND_GE);
33013 testMBB->addSuccessor(blockMBB);
33014 testMBB->addSuccessor(tailMBB);
33015
33016 // Touch the block then extend it. This is done on the opposite side of
33017 // static probe where we allocate then touch, to avoid the need of probing the
33018 // tail of the static alloca. Possible scenarios are:
33019 //
33020 // + ---- <- ------------ <- ------------- <- ------------ +
33021 // | |
33022 // [free probe] -> [page alloc] -> [alloc probe] -> [tail alloc] + -> [dyn probe] -> [page alloc] -> [dyn probe] -> [tail alloc] +
33023 // | |
33024 // + <- ----------- <- ------------ <- ----------- <- ------------ +
33025 //
33026 // The property we want to enforce is to never have more than [page alloc] between two probes.
33027
33028 const unsigned XORMIOpc =
33029 TFI.Uses64BitFramePtr ? X86::XOR64mi8 : X86::XOR32mi8;
33030 addRegOffset(BuildMI(blockMBB, DL, TII->get(XORMIOpc)), physSPReg, false, 0)
33031 .addImm(0);
33032
33033 BuildMI(blockMBB, DL,
33034 TII->get(getSUBriOpcode(TFI.Uses64BitFramePtr, ProbeSize)), physSPReg)
33035 .addReg(physSPReg)
33036 .addImm(ProbeSize);
33037
33038
33039 BuildMI(blockMBB, DL, TII->get(X86::JMP_1)).addMBB(testMBB);
33040 blockMBB->addSuccessor(testMBB);
33041
33042 // Replace original instruction by the expected stack ptr
33043 BuildMI(tailMBB, DL, TII->get(TargetOpcode::COPY), MI.getOperand(0).getReg())
33044 .addReg(FinalStackPtr);
33045
33046 tailMBB->splice(tailMBB->end(), MBB,
33047 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
33048 tailMBB->transferSuccessorsAndUpdatePHIs(MBB);
33049 MBB->addSuccessor(testMBB);
33050
33051 // Delete the original pseudo instruction.
33052 MI.eraseFromParent();
33053
33054 // And we're done.
33055 return tailMBB;
33056}
33057
33058MachineBasicBlock *
33059X86TargetLowering::EmitLoweredSegAlloca(MachineInstr &MI,
33060 MachineBasicBlock *BB) const {
33061 MachineFunction *MF = BB->getParent();
33062 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
33063 const DebugLoc &DL = MI.getDebugLoc();
33064 const BasicBlock *LLVM_BB = BB->getBasicBlock();
33065
33066 assert(MF->shouldSplitStack())(static_cast <bool> (MF->shouldSplitStack()) ? void (
0) : __assert_fail ("MF->shouldSplitStack()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33066, __extension__ __PRETTY_FUNCTION__))
;
33067
33068 const bool Is64Bit = Subtarget.is64Bit();
33069 const bool IsLP64 = Subtarget.isTarget64BitLP64();
33070
33071 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
33072 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
33073
33074 // BB:
33075 // ... [Till the alloca]
33076 // If stacklet is not large enough, jump to mallocMBB
33077 //
33078 // bumpMBB:
33079 // Allocate by subtracting from RSP
33080 // Jump to continueMBB
33081 //
33082 // mallocMBB:
33083 // Allocate by call to runtime
33084 //
33085 // continueMBB:
33086 // ...
33087 // [rest of original BB]
33088 //
33089
33090 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
33091 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
33092 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
33093
33094 MachineRegisterInfo &MRI = MF->getRegInfo();
33095 const TargetRegisterClass *AddrRegClass =
33096 getRegClassFor(getPointerTy(MF->getDataLayout()));
33097
33098 Register mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
33099 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
33100 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
33101 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
33102 sizeVReg = MI.getOperand(1).getReg(),
33103 physSPReg =
33104 IsLP64 || Subtarget.isTargetNaCl64() ? X86::RSP : X86::ESP;
33105
33106 MachineFunction::iterator MBBIter = ++BB->getIterator();
33107
33108 MF->insert(MBBIter, bumpMBB);
33109 MF->insert(MBBIter, mallocMBB);
33110 MF->insert(MBBIter, continueMBB);
33111
33112 continueMBB->splice(continueMBB->begin(), BB,
33113 std::next(MachineBasicBlock::iterator(MI)), BB->end());
33114 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
33115
33116 // Add code to the main basic block to check if the stack limit has been hit,
33117 // and if so, jump to mallocMBB otherwise to bumpMBB.
33118 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
33119 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
33120 .addReg(tmpSPVReg).addReg(sizeVReg);
33121 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
33122 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
33123 .addReg(SPLimitVReg);
33124 BuildMI(BB, DL, TII->get(X86::JCC_1)).addMBB(mallocMBB).addImm(X86::COND_G);
33125
33126 // bumpMBB simply decreases the stack pointer, since we know the current
33127 // stacklet has enough space.
33128 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
33129 .addReg(SPLimitVReg);
33130 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
33131 .addReg(SPLimitVReg);
33132 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
33133
33134 // Calls into a routine in libgcc to allocate more space from the heap.
33135 const uint32_t *RegMask =
33136 Subtarget.getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
33137 if (IsLP64) {
33138 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
33139 .addReg(sizeVReg);
33140 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
33141 .addExternalSymbol("__morestack_allocate_stack_space")
33142 .addRegMask(RegMask)
33143 .addReg(X86::RDI, RegState::Implicit)
33144 .addReg(X86::RAX, RegState::ImplicitDefine);
33145 } else if (Is64Bit) {
33146 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
33147 .addReg(sizeVReg);
33148 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
33149 .addExternalSymbol("__morestack_allocate_stack_space")
33150 .addRegMask(RegMask)
33151 .addReg(X86::EDI, RegState::Implicit)
33152 .addReg(X86::EAX, RegState::ImplicitDefine);
33153 } else {
33154 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
33155 .addImm(12);
33156 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
33157 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
33158 .addExternalSymbol("__morestack_allocate_stack_space")
33159 .addRegMask(RegMask)
33160 .addReg(X86::EAX, RegState::ImplicitDefine);
33161 }
33162
33163 if (!Is64Bit)
33164 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
33165 .addImm(16);
33166
33167 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
33168 .addReg(IsLP64 ? X86::RAX : X86::EAX);
33169 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
33170
33171 // Set up the CFG correctly.
33172 BB->addSuccessor(bumpMBB);
33173 BB->addSuccessor(mallocMBB);
33174 mallocMBB->addSuccessor(continueMBB);
33175 bumpMBB->addSuccessor(continueMBB);
33176
33177 // Take care of the PHI nodes.
33178 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
33179 MI.getOperand(0).getReg())
33180 .addReg(mallocPtrVReg)
33181 .addMBB(mallocMBB)
33182 .addReg(bumpSPPtrVReg)
33183 .addMBB(bumpMBB);
33184
33185 // Delete the original pseudo instruction.
33186 MI.eraseFromParent();
33187
33188 // And we're done.
33189 return continueMBB;
33190}
33191
33192MachineBasicBlock *
33193X86TargetLowering::EmitLoweredCatchRet(MachineInstr &MI,
33194 MachineBasicBlock *BB) const {
33195 MachineFunction *MF = BB->getParent();
33196 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
33197 MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB();
33198 const DebugLoc &DL = MI.getDebugLoc();
33199
33200 assert(!isAsynchronousEHPersonality((static_cast <bool> (!isAsynchronousEHPersonality( classifyEHPersonality
(MF->getFunction().getPersonalityFn())) && "SEH does not use catchret!"
) ? void (0) : __assert_fail ("!isAsynchronousEHPersonality( classifyEHPersonality(MF->getFunction().getPersonalityFn())) && \"SEH does not use catchret!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33202, __extension__ __PRETTY_FUNCTION__))
33201 classifyEHPersonality(MF->getFunction().getPersonalityFn())) &&(static_cast <bool> (!isAsynchronousEHPersonality( classifyEHPersonality
(MF->getFunction().getPersonalityFn())) && "SEH does not use catchret!"
) ? void (0) : __assert_fail ("!isAsynchronousEHPersonality( classifyEHPersonality(MF->getFunction().getPersonalityFn())) && \"SEH does not use catchret!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33202, __extension__ __PRETTY_FUNCTION__))
33202 "SEH does not use catchret!")(static_cast <bool> (!isAsynchronousEHPersonality( classifyEHPersonality
(MF->getFunction().getPersonalityFn())) && "SEH does not use catchret!"
) ? void (0) : __assert_fail ("!isAsynchronousEHPersonality( classifyEHPersonality(MF->getFunction().getPersonalityFn())) && \"SEH does not use catchret!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33202, __extension__ __PRETTY_FUNCTION__))
;
33203
33204 // Only 32-bit EH needs to worry about manually restoring stack pointers.
33205 if (!Subtarget.is32Bit())
33206 return BB;
33207
33208 // C++ EH creates a new target block to hold the restore code, and wires up
33209 // the new block to the return destination with a normal JMP_4.
33210 MachineBasicBlock *RestoreMBB =
33211 MF->CreateMachineBasicBlock(BB->getBasicBlock());
33212 assert(BB->succ_size() == 1)(static_cast <bool> (BB->succ_size() == 1) ? void (0
) : __assert_fail ("BB->succ_size() == 1", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33212, __extension__ __PRETTY_FUNCTION__))
;
33213 MF->insert(std::next(BB->getIterator()), RestoreMBB);
33214 RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
33215 BB->addSuccessor(RestoreMBB);
33216 MI.getOperand(0).setMBB(RestoreMBB);
33217
33218 // Marking this as an EH pad but not a funclet entry block causes PEI to
33219 // restore stack pointers in the block.
33220 RestoreMBB->setIsEHPad(true);
33221
33222 auto RestoreMBBI = RestoreMBB->begin();
33223 BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
33224 return BB;
33225}
33226
33227MachineBasicBlock *
33228X86TargetLowering::EmitLoweredTLSAddr(MachineInstr &MI,
33229 MachineBasicBlock *BB) const {
33230 // So, here we replace TLSADDR with the sequence:
33231 // adjust_stackdown -> TLSADDR -> adjust_stackup.
33232 // We need this because TLSADDR is lowered into calls
33233 // inside MC, therefore without the two markers shrink-wrapping
33234 // may push the prologue/epilogue pass them.
33235 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
33236 const DebugLoc &DL = MI.getDebugLoc();
33237 MachineFunction &MF = *BB->getParent();
33238
33239 // Emit CALLSEQ_START right before the instruction.
33240 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
33241 MachineInstrBuilder CallseqStart =
33242 BuildMI(MF, DL, TII.get(AdjStackDown)).addImm(0).addImm(0).addImm(0);
33243 BB->insert(MachineBasicBlock::iterator(MI), CallseqStart);
33244
33245 // Emit CALLSEQ_END right after the instruction.
33246 // We don't call erase from parent because we want to keep the
33247 // original instruction around.
33248 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
33249 MachineInstrBuilder CallseqEnd =
33250 BuildMI(MF, DL, TII.get(AdjStackUp)).addImm(0).addImm(0);
33251 BB->insertAfter(MachineBasicBlock::iterator(MI), CallseqEnd);
33252
33253 return BB;
33254}
33255
33256MachineBasicBlock *
33257X86TargetLowering::EmitLoweredTLSCall(MachineInstr &MI,
33258 MachineBasicBlock *BB) const {
33259 // This is pretty easy. We're taking the value that we received from
33260 // our load from the relocation, sticking it in either RDI (x86-64)
33261 // or EAX and doing an indirect call. The return value will then
33262 // be in the normal return register.
33263 MachineFunction *F = BB->getParent();
33264 const X86InstrInfo *TII = Subtarget.getInstrInfo();
33265 const DebugLoc &DL = MI.getDebugLoc();
33266
33267 assert(Subtarget.isTargetDarwin() && "Darwin only instr emitted?")(static_cast <bool> (Subtarget.isTargetDarwin() &&
"Darwin only instr emitted?") ? void (0) : __assert_fail ("Subtarget.isTargetDarwin() && \"Darwin only instr emitted?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33267, __extension__ __PRETTY_FUNCTION__))
;
33268 assert(MI.getOperand(3).isGlobal() && "This should be a global")(static_cast <bool> (MI.getOperand(3).isGlobal() &&
"This should be a global") ? void (0) : __assert_fail ("MI.getOperand(3).isGlobal() && \"This should be a global\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33268, __extension__ __PRETTY_FUNCTION__))
;
33269
33270 // Get a register mask for the lowered call.
33271 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
33272 // proper register mask.
33273 const uint32_t *RegMask =
33274 Subtarget.is64Bit() ?
33275 Subtarget.getRegisterInfo()->getDarwinTLSCallPreservedMask() :
33276 Subtarget.getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
33277 if (Subtarget.is64Bit()) {
33278 MachineInstrBuilder MIB =
33279 BuildMI(*BB, MI, DL, TII->get(X86::MOV64rm), X86::RDI)
33280 .addReg(X86::RIP)
33281 .addImm(0)
33282 .addReg(0)
33283 .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
33284 MI.getOperand(3).getTargetFlags())
33285 .addReg(0);
33286 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
33287 addDirectMem(MIB, X86::RDI);
33288 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
33289 } else if (!isPositionIndependent()) {
33290 MachineInstrBuilder MIB =
33291 BuildMI(*BB, MI, DL, TII->get(X86::MOV32rm), X86::EAX)
33292 .addReg(0)
33293 .addImm(0)
33294 .addReg(0)
33295 .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
33296 MI.getOperand(3).getTargetFlags())
33297 .addReg(0);
33298 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
33299 addDirectMem(MIB, X86::EAX);
33300 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
33301 } else {
33302 MachineInstrBuilder MIB =
33303 BuildMI(*BB, MI, DL, TII->get(X86::MOV32rm), X86::EAX)
33304 .addReg(TII->getGlobalBaseReg(F))
33305 .addImm(0)
33306 .addReg(0)
33307 .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
33308 MI.getOperand(3).getTargetFlags())
33309 .addReg(0);
33310 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
33311 addDirectMem(MIB, X86::EAX);
33312 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
33313 }
33314
33315 MI.eraseFromParent(); // The pseudo instruction is gone now.
33316 return BB;
33317}
33318
33319static unsigned getOpcodeForIndirectThunk(unsigned RPOpc) {
33320 switch (RPOpc) {
33321 case X86::INDIRECT_THUNK_CALL32:
33322 return X86::CALLpcrel32;
33323 case X86::INDIRECT_THUNK_CALL64:
33324 return X86::CALL64pcrel32;
33325 case X86::INDIRECT_THUNK_TCRETURN32:
33326 return X86::TCRETURNdi;
33327 case X86::INDIRECT_THUNK_TCRETURN64:
33328 return X86::TCRETURNdi64;
33329 }
33330 llvm_unreachable("not indirect thunk opcode")::llvm::llvm_unreachable_internal("not indirect thunk opcode"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33330)
;
33331}
33332
33333static const char *getIndirectThunkSymbol(const X86Subtarget &Subtarget,
33334 unsigned Reg) {
33335 if (Subtarget.useRetpolineExternalThunk()) {
33336 // When using an external thunk for retpolines, we pick names that match the
33337 // names GCC happens to use as well. This helps simplify the implementation
33338 // of the thunks for kernels where they have no easy ability to create
33339 // aliases and are doing non-trivial configuration of the thunk's body. For
33340 // example, the Linux kernel will do boot-time hot patching of the thunk
33341 // bodies and cannot easily export aliases of these to loaded modules.
33342 //
33343 // Note that at any point in the future, we may need to change the semantics
33344 // of how we implement retpolines and at that time will likely change the
33345 // name of the called thunk. Essentially, there is no hard guarantee that
33346 // LLVM will generate calls to specific thunks, we merely make a best-effort
33347 // attempt to help out kernels and other systems where duplicating the
33348 // thunks is costly.
33349 switch (Reg) {
33350 case X86::EAX:
33351 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!")(static_cast <bool> (!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!"
) ? void (0) : __assert_fail ("!Subtarget.is64Bit() && \"Should not be using a 32-bit thunk!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33351, __extension__ __PRETTY_FUNCTION__))
;
33352 return "__x86_indirect_thunk_eax";
33353 case X86::ECX:
33354 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!")(static_cast <bool> (!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!"
) ? void (0) : __assert_fail ("!Subtarget.is64Bit() && \"Should not be using a 32-bit thunk!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33354, __extension__ __PRETTY_FUNCTION__))
;
33355 return "__x86_indirect_thunk_ecx";
33356 case X86::EDX:
33357 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!")(static_cast <bool> (!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!"
) ? void (0) : __assert_fail ("!Subtarget.is64Bit() && \"Should not be using a 32-bit thunk!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33357, __extension__ __PRETTY_FUNCTION__))
;
33358 return "__x86_indirect_thunk_edx";
33359 case X86::EDI:
33360 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!")(static_cast <bool> (!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!"
) ? void (0) : __assert_fail ("!Subtarget.is64Bit() && \"Should not be using a 32-bit thunk!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33360, __extension__ __PRETTY_FUNCTION__))
;
33361 return "__x86_indirect_thunk_edi";
33362 case X86::R11:
33363 assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!")(static_cast <bool> (Subtarget.is64Bit() && "Should not be using a 64-bit thunk!"
) ? void (0) : __assert_fail ("Subtarget.is64Bit() && \"Should not be using a 64-bit thunk!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33363, __extension__ __PRETTY_FUNCTION__))
;
33364 return "__x86_indirect_thunk_r11";
33365 }
33366 llvm_unreachable("unexpected reg for external indirect thunk")::llvm::llvm_unreachable_internal("unexpected reg for external indirect thunk"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33366)
;
33367 }
33368
33369 if (Subtarget.useRetpolineIndirectCalls() ||
33370 Subtarget.useRetpolineIndirectBranches()) {
33371 // When targeting an internal COMDAT thunk use an LLVM-specific name.
33372 switch (Reg) {
33373 case X86::EAX:
33374 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!")(static_cast <bool> (!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!"
) ? void (0) : __assert_fail ("!Subtarget.is64Bit() && \"Should not be using a 32-bit thunk!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33374, __extension__ __PRETTY_FUNCTION__))
;
33375 return "__llvm_retpoline_eax";
33376 case X86::ECX:
33377 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!")(static_cast <bool> (!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!"
) ? void (0) : __assert_fail ("!Subtarget.is64Bit() && \"Should not be using a 32-bit thunk!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33377, __extension__ __PRETTY_FUNCTION__))
;
33378 return "__llvm_retpoline_ecx";
33379 case X86::EDX:
33380 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!")(static_cast <bool> (!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!"
) ? void (0) : __assert_fail ("!Subtarget.is64Bit() && \"Should not be using a 32-bit thunk!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33380, __extension__ __PRETTY_FUNCTION__))
;
33381 return "__llvm_retpoline_edx";
33382 case X86::EDI:
33383 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!")(static_cast <bool> (!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!"
) ? void (0) : __assert_fail ("!Subtarget.is64Bit() && \"Should not be using a 32-bit thunk!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33383, __extension__ __PRETTY_FUNCTION__))
;
33384 return "__llvm_retpoline_edi";
33385 case X86::R11:
33386 assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!")(static_cast <bool> (Subtarget.is64Bit() && "Should not be using a 64-bit thunk!"
) ? void (0) : __assert_fail ("Subtarget.is64Bit() && \"Should not be using a 64-bit thunk!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33386, __extension__ __PRETTY_FUNCTION__))
;
33387 return "__llvm_retpoline_r11";
33388 }
33389 llvm_unreachable("unexpected reg for retpoline")::llvm::llvm_unreachable_internal("unexpected reg for retpoline"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33389)
;
33390 }
33391
33392 if (Subtarget.useLVIControlFlowIntegrity()) {
33393 assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!")(static_cast <bool> (Subtarget.is64Bit() && "Should not be using a 64-bit thunk!"
) ? void (0) : __assert_fail ("Subtarget.is64Bit() && \"Should not be using a 64-bit thunk!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33393, __extension__ __PRETTY_FUNCTION__))
;
33394 return "__llvm_lvi_thunk_r11";
33395 }
33396 llvm_unreachable("getIndirectThunkSymbol() invoked without thunk feature")::llvm::llvm_unreachable_internal("getIndirectThunkSymbol() invoked without thunk feature"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33396)
;
33397}
33398
33399MachineBasicBlock *
33400X86TargetLowering::EmitLoweredIndirectThunk(MachineInstr &MI,
33401 MachineBasicBlock *BB) const {
33402 // Copy the virtual register into the R11 physical register and
33403 // call the retpoline thunk.
33404 const DebugLoc &DL = MI.getDebugLoc();
33405 const X86InstrInfo *TII = Subtarget.getInstrInfo();
33406 Register CalleeVReg = MI.getOperand(0).getReg();
33407 unsigned Opc = getOpcodeForIndirectThunk(MI.getOpcode());
33408
33409 // Find an available scratch register to hold the callee. On 64-bit, we can
33410 // just use R11, but we scan for uses anyway to ensure we don't generate
33411 // incorrect code. On 32-bit, we use one of EAX, ECX, or EDX that isn't
33412 // already a register use operand to the call to hold the callee. If none
33413 // are available, use EDI instead. EDI is chosen because EBX is the PIC base
33414 // register and ESI is the base pointer to realigned stack frames with VLAs.
33415 SmallVector<unsigned, 3> AvailableRegs;
33416 if (Subtarget.is64Bit())
33417 AvailableRegs.push_back(X86::R11);
33418 else
33419 AvailableRegs.append({X86::EAX, X86::ECX, X86::EDX, X86::EDI});
33420
33421 // Zero out any registers that are already used.
33422 for (const auto &MO : MI.operands()) {
33423 if (MO.isReg() && MO.isUse())
33424 for (unsigned &Reg : AvailableRegs)
33425 if (Reg == MO.getReg())
33426 Reg = 0;
33427 }
33428
33429 // Choose the first remaining non-zero available register.
33430 unsigned AvailableReg = 0;
33431 for (unsigned MaybeReg : AvailableRegs) {
33432 if (MaybeReg) {
33433 AvailableReg = MaybeReg;
33434 break;
33435 }
33436 }
33437 if (!AvailableReg)
33438 report_fatal_error("calling convention incompatible with retpoline, no "
33439 "available registers");
33440
33441 const char *Symbol = getIndirectThunkSymbol(Subtarget, AvailableReg);
33442
33443 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), AvailableReg)
33444 .addReg(CalleeVReg);
33445 MI.getOperand(0).ChangeToES(Symbol);
33446 MI.setDesc(TII->get(Opc));
33447 MachineInstrBuilder(*BB->getParent(), &MI)
33448 .addReg(AvailableReg, RegState::Implicit | RegState::Kill);
33449 return BB;
33450}
33451
33452/// SetJmp implies future control flow change upon calling the corresponding
33453/// LongJmp.
33454/// Instead of using the 'return' instruction, the long jump fixes the stack and
33455/// performs an indirect branch. To do so it uses the registers that were stored
33456/// in the jump buffer (when calling SetJmp).
33457/// In case the shadow stack is enabled we need to fix it as well, because some
33458/// return addresses will be skipped.
33459/// The function will save the SSP for future fixing in the function
33460/// emitLongJmpShadowStackFix.
33461/// \sa emitLongJmpShadowStackFix
33462/// \param [in] MI The temporary Machine Instruction for the builtin.
33463/// \param [in] MBB The Machine Basic Block that will be modified.
33464void X86TargetLowering::emitSetJmpShadowStackFix(MachineInstr &MI,
33465 MachineBasicBlock *MBB) const {
33466 const DebugLoc &DL = MI.getDebugLoc();
33467 MachineFunction *MF = MBB->getParent();
33468 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
33469 MachineRegisterInfo &MRI = MF->getRegInfo();
33470 MachineInstrBuilder MIB;
33471
33472 // Memory Reference.
33473 SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
33474 MI.memoperands_end());
33475
33476 // Initialize a register with zero.
33477 MVT PVT = getPointerTy(MF->getDataLayout());
33478 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
33479 Register ZReg = MRI.createVirtualRegister(PtrRC);
33480 unsigned XorRROpc = (PVT == MVT::i64) ? X86::XOR64rr : X86::XOR32rr;
33481 BuildMI(*MBB, MI, DL, TII->get(XorRROpc))
33482 .addDef(ZReg)
33483 .addReg(ZReg, RegState::Undef)
33484 .addReg(ZReg, RegState::Undef);
33485
33486 // Read the current SSP Register value to the zeroed register.
33487 Register SSPCopyReg = MRI.createVirtualRegister(PtrRC);
33488 unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
33489 BuildMI(*MBB, MI, DL, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
33490
33491 // Write the SSP register value to offset 3 in input memory buffer.
33492 unsigned PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
33493 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrStoreOpc));
33494 const int64_t SSPOffset = 3 * PVT.getStoreSize();
33495 const unsigned MemOpndSlot = 1;
33496 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
33497 if (i == X86::AddrDisp)
33498 MIB.addDisp(MI.getOperand(MemOpndSlot + i), SSPOffset);
33499 else
33500 MIB.add(MI.getOperand(MemOpndSlot + i));
33501 }
33502 MIB.addReg(SSPCopyReg);
33503 MIB.setMemRefs(MMOs);
33504}
33505
33506MachineBasicBlock *
33507X86TargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
33508 MachineBasicBlock *MBB) const {
33509 const DebugLoc &DL = MI.getDebugLoc();
33510 MachineFunction *MF = MBB->getParent();
33511 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
33512 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
33513 MachineRegisterInfo &MRI = MF->getRegInfo();
33514
33515 const BasicBlock *BB = MBB->getBasicBlock();
33516 MachineFunction::iterator I = ++MBB->getIterator();
33517
33518 // Memory Reference
33519 SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
33520 MI.memoperands_end());
33521
33522 unsigned DstReg;
33523 unsigned MemOpndSlot = 0;
33524
33525 unsigned CurOp = 0;
33526
33527 DstReg = MI.getOperand(CurOp++).getReg();
33528 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
33529 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!")(static_cast <bool> (TRI->isTypeLegalForClass(*RC, MVT
::i32) && "Invalid destination!") ? void (0) : __assert_fail
("TRI->isTypeLegalForClass(*RC, MVT::i32) && \"Invalid destination!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33529, __extension__ __PRETTY_FUNCTION__))
;
33530 (void)TRI;
33531 Register mainDstReg = MRI.createVirtualRegister(RC);
33532 Register restoreDstReg = MRI.createVirtualRegister(RC);
33533
33534 MemOpndSlot = CurOp;
33535
33536 MVT PVT = getPointerTy(MF->getDataLayout());
33537 assert((PVT == MVT::i64 || PVT == MVT::i32) &&(static_cast <bool> ((PVT == MVT::i64 || PVT == MVT::i32
) && "Invalid Pointer Size!") ? void (0) : __assert_fail
("(PVT == MVT::i64 || PVT == MVT::i32) && \"Invalid Pointer Size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33538, __extension__ __PRETTY_FUNCTION__))
33538 "Invalid Pointer Size!")(static_cast <bool> ((PVT == MVT::i64 || PVT == MVT::i32
) && "Invalid Pointer Size!") ? void (0) : __assert_fail
("(PVT == MVT::i64 || PVT == MVT::i32) && \"Invalid Pointer Size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33538, __extension__ __PRETTY_FUNCTION__))
;
33539
33540 // For v = setjmp(buf), we generate
33541 //
33542 // thisMBB:
33543 // buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
33544 // SjLjSetup restoreMBB
33545 //
33546 // mainMBB:
33547 // v_main = 0
33548 //
33549 // sinkMBB:
33550 // v = phi(main, restore)
33551 //
33552 // restoreMBB:
33553 // if base pointer being used, load it from frame
33554 // v_restore = 1
33555
33556 MachineBasicBlock *thisMBB = MBB;
33557 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
33558 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
33559 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
33560 MF->insert(I, mainMBB);
33561 MF->insert(I, sinkMBB);
33562 MF->push_back(restoreMBB);
33563 restoreMBB->setHasAddressTaken();
33564
33565 MachineInstrBuilder MIB;
33566
33567 // Transfer the remainder of BB and its successor edges to sinkMBB.
33568 sinkMBB->splice(sinkMBB->begin(), MBB,
33569 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
33570 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
33571
33572 // thisMBB:
33573 unsigned PtrStoreOpc = 0;
33574 unsigned LabelReg = 0;
33575 const int64_t LabelOffset = 1 * PVT.getStoreSize();
33576 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
33577 !isPositionIndependent();
33578
33579 // Prepare IP either in reg or imm.
33580 if (!UseImmLabel) {
33581 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
33582 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
33583 LabelReg = MRI.createVirtualRegister(PtrRC);
33584 if (Subtarget.is64Bit()) {
33585 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
33586 .addReg(X86::RIP)
33587 .addImm(0)
33588 .addReg(0)
33589 .addMBB(restoreMBB)
33590 .addReg(0);
33591 } else {
33592 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
33593 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
33594 .addReg(XII->getGlobalBaseReg(MF))
33595 .addImm(0)
33596 .addReg(0)
33597 .addMBB(restoreMBB, Subtarget.classifyBlockAddressReference())
33598 .addReg(0);
33599 }
33600 } else
33601 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
33602 // Store IP
33603 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
33604 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
33605 if (i == X86::AddrDisp)
33606 MIB.addDisp(MI.getOperand(MemOpndSlot + i), LabelOffset);
33607 else
33608 MIB.add(MI.getOperand(MemOpndSlot + i));
33609 }
33610 if (!UseImmLabel)
33611 MIB.addReg(LabelReg);
33612 else
33613 MIB.addMBB(restoreMBB);
33614 MIB.setMemRefs(MMOs);
33615
33616 if (MF->getMMI().getModule()->getModuleFlag("cf-protection-return")) {
33617 emitSetJmpShadowStackFix(MI, thisMBB);
33618 }
33619
33620 // Setup
33621 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
33622 .addMBB(restoreMBB);
33623
33624 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
33625 MIB.addRegMask(RegInfo->getNoPreservedMask());
33626 thisMBB->addSuccessor(mainMBB);
33627 thisMBB->addSuccessor(restoreMBB);
33628
33629 // mainMBB:
33630 // EAX = 0
33631 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
33632 mainMBB->addSuccessor(sinkMBB);
33633
33634 // sinkMBB:
33635 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
33636 TII->get(X86::PHI), DstReg)
33637 .addReg(mainDstReg).addMBB(mainMBB)
33638 .addReg(restoreDstReg).addMBB(restoreMBB);
33639
33640 // restoreMBB:
33641 if (RegInfo->hasBasePointer(*MF)) {
33642 const bool Uses64BitFramePtr =
33643 Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
33644 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
33645 X86FI->setRestoreBasePointer(MF);
33646 Register FramePtr = RegInfo->getFrameRegister(*MF);
33647 Register BasePtr = RegInfo->getBaseRegister();
33648 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
33649 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
33650 FramePtr, true, X86FI->getRestoreBasePointerOffset())
33651 .setMIFlag(MachineInstr::FrameSetup);
33652 }
33653 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
33654 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
33655 restoreMBB->addSuccessor(sinkMBB);
33656
33657 MI.eraseFromParent();
33658 return sinkMBB;
33659}
33660
33661/// Fix the shadow stack using the previously saved SSP pointer.
33662/// \sa emitSetJmpShadowStackFix
33663/// \param [in] MI The temporary Machine Instruction for the builtin.
33664/// \param [in] MBB The Machine Basic Block that will be modified.
33665/// \return The sink MBB that will perform the future indirect branch.
33666MachineBasicBlock *
33667X86TargetLowering::emitLongJmpShadowStackFix(MachineInstr &MI,
33668 MachineBasicBlock *MBB) const {
33669 const DebugLoc &DL = MI.getDebugLoc();
33670 MachineFunction *MF = MBB->getParent();
33671 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
33672 MachineRegisterInfo &MRI = MF->getRegInfo();
33673
33674 // Memory Reference
33675 SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
33676 MI.memoperands_end());
33677
33678 MVT PVT = getPointerTy(MF->getDataLayout());
33679 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
33680
33681 // checkSspMBB:
33682 // xor vreg1, vreg1
33683 // rdssp vreg1
33684 // test vreg1, vreg1
33685 // je sinkMBB # Jump if Shadow Stack is not supported
33686 // fallMBB:
33687 // mov buf+24/12(%rip), vreg2
33688 // sub vreg1, vreg2
33689 // jbe sinkMBB # No need to fix the Shadow Stack
33690 // fixShadowMBB:
33691 // shr 3/2, vreg2
33692 // incssp vreg2 # fix the SSP according to the lower 8 bits
33693 // shr 8, vreg2
33694 // je sinkMBB
33695 // fixShadowLoopPrepareMBB:
33696 // shl vreg2
33697 // mov 128, vreg3
33698 // fixShadowLoopMBB:
33699 // incssp vreg3
33700 // dec vreg2
33701 // jne fixShadowLoopMBB # Iterate until you finish fixing
33702 // # the Shadow Stack
33703 // sinkMBB:
33704
33705 MachineFunction::iterator I = ++MBB->getIterator();
33706 const BasicBlock *BB = MBB->getBasicBlock();
33707
33708 MachineBasicBlock *checkSspMBB = MF->CreateMachineBasicBlock(BB);
33709 MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
33710 MachineBasicBlock *fixShadowMBB = MF->CreateMachineBasicBlock(BB);
33711 MachineBasicBlock *fixShadowLoopPrepareMBB = MF->CreateMachineBasicBlock(BB);
33712 MachineBasicBlock *fixShadowLoopMBB = MF->CreateMachineBasicBlock(BB);
33713 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
33714 MF->insert(I, checkSspMBB);
33715 MF->insert(I, fallMBB);
33716 MF->insert(I, fixShadowMBB);
33717 MF->insert(I, fixShadowLoopPrepareMBB);
33718 MF->insert(I, fixShadowLoopMBB);
33719 MF->insert(I, sinkMBB);
33720
33721 // Transfer the remainder of BB and its successor edges to sinkMBB.
33722 sinkMBB->splice(sinkMBB->begin(), MBB, MachineBasicBlock::iterator(MI),
33723 MBB->end());
33724 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
33725
33726 MBB->addSuccessor(checkSspMBB);
33727
33728 // Initialize a register with zero.
33729 Register ZReg = MRI.createVirtualRegister(&X86::GR32RegClass);
33730 BuildMI(checkSspMBB, DL, TII->get(X86::MOV32r0), ZReg);
33731
33732 if (PVT == MVT::i64) {
33733 Register TmpZReg = MRI.createVirtualRegister(PtrRC);
33734 BuildMI(checkSspMBB, DL, TII->get(X86::SUBREG_TO_REG), TmpZReg)
33735 .addImm(0)
33736 .addReg(ZReg)
33737 .addImm(X86::sub_32bit);
33738 ZReg = TmpZReg;
33739 }
33740
33741 // Read the current SSP Register value to the zeroed register.
33742 Register SSPCopyReg = MRI.createVirtualRegister(PtrRC);
33743 unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
33744 BuildMI(checkSspMBB, DL, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
33745
33746 // Check whether the result of the SSP register is zero and jump directly
33747 // to the sink.
33748 unsigned TestRROpc = (PVT == MVT::i64) ? X86::TEST64rr : X86::TEST32rr;
33749 BuildMI(checkSspMBB, DL, TII->get(TestRROpc))
33750 .addReg(SSPCopyReg)
33751 .addReg(SSPCopyReg);
33752 BuildMI(checkSspMBB, DL, TII->get(X86::JCC_1)).addMBB(sinkMBB).addImm(X86::COND_E);
33753 checkSspMBB->addSuccessor(sinkMBB);
33754 checkSspMBB->addSuccessor(fallMBB);
33755
33756 // Reload the previously saved SSP register value.
33757 Register PrevSSPReg = MRI.createVirtualRegister(PtrRC);
33758 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
33759 const int64_t SPPOffset = 3 * PVT.getStoreSize();
33760 MachineInstrBuilder MIB =
33761 BuildMI(fallMBB, DL, TII->get(PtrLoadOpc), PrevSSPReg);
33762 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
33763 const MachineOperand &MO = MI.getOperand(i);
33764 if (i == X86::AddrDisp)
33765 MIB.addDisp(MO, SPPOffset);
33766 else if (MO.isReg()) // Don't add the whole operand, we don't want to
33767 // preserve kill flags.
33768 MIB.addReg(MO.getReg());
33769 else
33770 MIB.add(MO);
33771 }
33772 MIB.setMemRefs(MMOs);
33773
33774 // Subtract the current SSP from the previous SSP.
33775 Register SspSubReg = MRI.createVirtualRegister(PtrRC);
33776 unsigned SubRROpc = (PVT == MVT::i64) ? X86::SUB64rr : X86::SUB32rr;
33777 BuildMI(fallMBB, DL, TII->get(SubRROpc), SspSubReg)
33778 .addReg(PrevSSPReg)
33779 .addReg(SSPCopyReg);
33780
33781 // Jump to sink in case PrevSSPReg <= SSPCopyReg.
33782 BuildMI(fallMBB, DL, TII->get(X86::JCC_1)).addMBB(sinkMBB).addImm(X86::COND_BE);
33783 fallMBB->addSuccessor(sinkMBB);
33784 fallMBB->addSuccessor(fixShadowMBB);
33785
33786 // Shift right by 2/3 for 32/64 because incssp multiplies the argument by 4/8.
33787 unsigned ShrRIOpc = (PVT == MVT::i64) ? X86::SHR64ri : X86::SHR32ri;
33788 unsigned Offset = (PVT == MVT::i64) ? 3 : 2;
33789 Register SspFirstShrReg = MRI.createVirtualRegister(PtrRC);
33790 BuildMI(fixShadowMBB, DL, TII->get(ShrRIOpc), SspFirstShrReg)
33791 .addReg(SspSubReg)
33792 .addImm(Offset);
33793
33794 // Increase SSP when looking only on the lower 8 bits of the delta.
33795 unsigned IncsspOpc = (PVT == MVT::i64) ? X86::INCSSPQ : X86::INCSSPD;
33796 BuildMI(fixShadowMBB, DL, TII->get(IncsspOpc)).addReg(SspFirstShrReg);
33797
33798 // Reset the lower 8 bits.
33799 Register SspSecondShrReg = MRI.createVirtualRegister(PtrRC);
33800 BuildMI(fixShadowMBB, DL, TII->get(ShrRIOpc), SspSecondShrReg)
33801 .addReg(SspFirstShrReg)
33802 .addImm(8);
33803
33804 // Jump if the result of the shift is zero.
33805 BuildMI(fixShadowMBB, DL, TII->get(X86::JCC_1)).addMBB(sinkMBB).addImm(X86::COND_E);
33806 fixShadowMBB->addSuccessor(sinkMBB);
33807 fixShadowMBB->addSuccessor(fixShadowLoopPrepareMBB);
33808
33809 // Do a single shift left.
33810 unsigned ShlR1Opc = (PVT == MVT::i64) ? X86::SHL64r1 : X86::SHL32r1;
33811 Register SspAfterShlReg = MRI.createVirtualRegister(PtrRC);
33812 BuildMI(fixShadowLoopPrepareMBB, DL, TII->get(ShlR1Opc), SspAfterShlReg)
33813 .addReg(SspSecondShrReg);
33814
33815 // Save the value 128 to a register (will be used next with incssp).
33816 Register Value128InReg = MRI.createVirtualRegister(PtrRC);
33817 unsigned MovRIOpc = (PVT == MVT::i64) ? X86::MOV64ri32 : X86::MOV32ri;
33818 BuildMI(fixShadowLoopPrepareMBB, DL, TII->get(MovRIOpc), Value128InReg)
33819 .addImm(128);
33820 fixShadowLoopPrepareMBB->addSuccessor(fixShadowLoopMBB);
33821
33822 // Since incssp only looks at the lower 8 bits, we might need to do several
33823 // iterations of incssp until we finish fixing the shadow stack.
33824 Register DecReg = MRI.createVirtualRegister(PtrRC);
33825 Register CounterReg = MRI.createVirtualRegister(PtrRC);
33826 BuildMI(fixShadowLoopMBB, DL, TII->get(X86::PHI), CounterReg)
33827 .addReg(SspAfterShlReg)
33828 .addMBB(fixShadowLoopPrepareMBB)
33829 .addReg(DecReg)
33830 .addMBB(fixShadowLoopMBB);
33831
33832 // Every iteration we increase the SSP by 128.
33833 BuildMI(fixShadowLoopMBB, DL, TII->get(IncsspOpc)).addReg(Value128InReg);
33834
33835 // Every iteration we decrement the counter by 1.
33836 unsigned DecROpc = (PVT == MVT::i64) ? X86::DEC64r : X86::DEC32r;
33837 BuildMI(fixShadowLoopMBB, DL, TII->get(DecROpc), DecReg).addReg(CounterReg);
33838
33839 // Jump if the counter is not zero yet.
33840 BuildMI(fixShadowLoopMBB, DL, TII->get(X86::JCC_1)).addMBB(fixShadowLoopMBB).addImm(X86::COND_NE);
33841 fixShadowLoopMBB->addSuccessor(sinkMBB);
33842 fixShadowLoopMBB->addSuccessor(fixShadowLoopMBB);
33843
33844 return sinkMBB;
33845}
33846
33847MachineBasicBlock *
33848X86TargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
33849 MachineBasicBlock *MBB) const {
33850 const DebugLoc &DL = MI.getDebugLoc();
33851 MachineFunction *MF = MBB->getParent();
33852 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
33853 MachineRegisterInfo &MRI = MF->getRegInfo();
33854
33855 // Memory Reference
33856 SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
33857 MI.memoperands_end());
33858
33859 MVT PVT = getPointerTy(MF->getDataLayout());
33860 assert((PVT == MVT::i64 || PVT == MVT::i32) &&(static_cast <bool> ((PVT == MVT::i64 || PVT == MVT::i32
) && "Invalid Pointer Size!") ? void (0) : __assert_fail
("(PVT == MVT::i64 || PVT == MVT::i32) && \"Invalid Pointer Size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33861, __extension__ __PRETTY_FUNCTION__))
33861 "Invalid Pointer Size!")(static_cast <bool> ((PVT == MVT::i64 || PVT == MVT::i32
) && "Invalid Pointer Size!") ? void (0) : __assert_fail
("(PVT == MVT::i64 || PVT == MVT::i32) && \"Invalid Pointer Size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33861, __extension__ __PRETTY_FUNCTION__))
;
33862
33863 const TargetRegisterClass *RC =
33864 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
33865 Register Tmp = MRI.createVirtualRegister(RC);
33866 // Since FP is only updated here but NOT referenced, it's treated as GPR.
33867 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
33868 Register FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
33869 Register SP = RegInfo->getStackRegister();
33870
33871 MachineInstrBuilder MIB;
33872
33873 const int64_t LabelOffset = 1 * PVT.getStoreSize();
33874 const int64_t SPOffset = 2 * PVT.getStoreSize();
33875
33876 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
33877 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
33878
33879 MachineBasicBlock *thisMBB = MBB;
33880
33881 // When CET and shadow stack is enabled, we need to fix the Shadow Stack.
33882 if (MF->getMMI().getModule()->getModuleFlag("cf-protection-return")) {
33883 thisMBB = emitLongJmpShadowStackFix(MI, thisMBB);
33884 }
33885
33886 // Reload FP
33887 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), FP);
33888 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
33889 const MachineOperand &MO = MI.getOperand(i);
33890 if (MO.isReg()) // Don't add the whole operand, we don't want to
33891 // preserve kill flags.
33892 MIB.addReg(MO.getReg());
33893 else
33894 MIB.add(MO);
33895 }
33896 MIB.setMemRefs(MMOs);
33897
33898 // Reload IP
33899 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
33900 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
33901 const MachineOperand &MO = MI.getOperand(i);
33902 if (i == X86::AddrDisp)
33903 MIB.addDisp(MO, LabelOffset);
33904 else if (MO.isReg()) // Don't add the whole operand, we don't want to
33905 // preserve kill flags.
33906 MIB.addReg(MO.getReg());
33907 else
33908 MIB.add(MO);
33909 }
33910 MIB.setMemRefs(MMOs);
33911
33912 // Reload SP
33913 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), SP);
33914 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
33915 if (i == X86::AddrDisp)
33916 MIB.addDisp(MI.getOperand(i), SPOffset);
33917 else
33918 MIB.add(MI.getOperand(i)); // We can preserve the kill flags here, it's
33919 // the last instruction of the expansion.
33920 }
33921 MIB.setMemRefs(MMOs);
33922
33923 // Jump
33924 BuildMI(*thisMBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
33925
33926 MI.eraseFromParent();
33927 return thisMBB;
33928}
33929
33930void X86TargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
33931 MachineBasicBlock *MBB,
33932 MachineBasicBlock *DispatchBB,
33933 int FI) const {
33934 const DebugLoc &DL = MI.getDebugLoc();
33935 MachineFunction *MF = MBB->getParent();
33936 MachineRegisterInfo *MRI = &MF->getRegInfo();
33937 const X86InstrInfo *TII = Subtarget.getInstrInfo();
33938
33939 MVT PVT = getPointerTy(MF->getDataLayout());
33940 assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!")(static_cast <bool> ((PVT == MVT::i64 || PVT == MVT::i32
) && "Invalid Pointer Size!") ? void (0) : __assert_fail
("(PVT == MVT::i64 || PVT == MVT::i32) && \"Invalid Pointer Size!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 33940, __extension__ __PRETTY_FUNCTION__))
;
33941
33942 unsigned Op = 0;
33943 unsigned VR = 0;
33944
33945 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
33946 !isPositionIndependent();
33947
33948 if (UseImmLabel) {
33949 Op = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
33950 } else {
33951 const TargetRegisterClass *TRC =
33952 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
33953 VR = MRI->createVirtualRegister(TRC);
33954 Op = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
33955
33956 if (Subtarget.is64Bit())
33957 BuildMI(*MBB, MI, DL, TII->get(X86::LEA64r), VR)
33958 .addReg(X86::RIP)
33959 .addImm(1)
33960 .addReg(0)
33961 .addMBB(DispatchBB)
33962 .addReg(0);
33963 else
33964 BuildMI(*MBB, MI, DL, TII->get(X86::LEA32r), VR)
33965 .addReg(0) /* TII->getGlobalBaseReg(MF) */
33966 .addImm(1)
33967 .addReg(0)
33968 .addMBB(DispatchBB, Subtarget.classifyBlockAddressReference())
33969 .addReg(0);
33970 }
33971
33972 MachineInstrBuilder MIB = BuildMI(*MBB, MI, DL, TII->get(Op));
33973 addFrameReference(MIB, FI, Subtarget.is64Bit() ? 56 : 36);
33974 if (UseImmLabel)
33975 MIB.addMBB(DispatchBB);
33976 else
33977 MIB.addReg(VR);
33978}
33979
33980MachineBasicBlock *
33981X86TargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
33982 MachineBasicBlock *BB) const {
33983 const DebugLoc &DL = MI.getDebugLoc();
33984 MachineFunction *MF = BB->getParent();
33985 MachineRegisterInfo *MRI = &MF->getRegInfo();
33986 const X86InstrInfo *TII = Subtarget.getInstrInfo();
33987 int FI = MF->getFrameInfo().getFunctionContextIndex();
33988
33989 // Get a mapping of the call site numbers to all of the landing pads they're
33990 // associated with.
33991 DenseMap<unsigned, SmallVector<MachineBasicBlock *, 2>> CallSiteNumToLPad;
33992 unsigned MaxCSNum = 0;
33993 for (auto &MBB : *MF) {
33994 if (!MBB.isEHPad())
33995 continue;
33996
33997 MCSymbol *Sym = nullptr;
33998 for (const auto &MI : MBB) {
33999 if (MI.isDebugInstr())
34000 continue;
34001
34002 assert(MI.isEHLabel() && "expected EH_LABEL")(static_cast <bool> (MI.isEHLabel() && "expected EH_LABEL"
) ? void (0) : __assert_fail ("MI.isEHLabel() && \"expected EH_LABEL\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34002, __extension__ __PRETTY_FUNCTION__))
;
34003 Sym = MI.getOperand(0).getMCSymbol();
34004 break;
34005 }
34006
34007 if (!MF->hasCallSiteLandingPad(Sym))
34008 continue;
34009
34010 for (unsigned CSI : MF->getCallSiteLandingPad(Sym)) {
34011 CallSiteNumToLPad[CSI].push_back(&MBB);
34012 MaxCSNum = std::max(MaxCSNum, CSI);
34013 }
34014 }
34015
34016 // Get an ordered list of the machine basic blocks for the jump table.
34017 std::vector<MachineBasicBlock *> LPadList;
34018 SmallPtrSet<MachineBasicBlock *, 32> InvokeBBs;
34019 LPadList.reserve(CallSiteNumToLPad.size());
34020
34021 for (unsigned CSI = 1; CSI <= MaxCSNum; ++CSI) {
34022 for (auto &LP : CallSiteNumToLPad[CSI]) {
34023 LPadList.push_back(LP);
34024 InvokeBBs.insert(LP->pred_begin(), LP->pred_end());
34025 }
34026 }
34027
34028 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-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34029, __extension__ __PRETTY_FUNCTION__))
34029 "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-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34029, __extension__ __PRETTY_FUNCTION__))
;
34030
34031 // Create the MBBs for the dispatch code.
34032
34033 // Shove the dispatch's address into the return slot in the function context.
34034 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
34035 DispatchBB->setIsEHPad(true);
34036
34037 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
34038 BuildMI(TrapBB, DL, TII->get(X86::TRAP));
34039 DispatchBB->addSuccessor(TrapBB);
34040
34041 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
34042 DispatchBB->addSuccessor(DispContBB);
34043
34044 // Insert MBBs.
34045 MF->push_back(DispatchBB);
34046 MF->push_back(DispContBB);
34047 MF->push_back(TrapBB);
34048
34049 // Insert code into the entry block that creates and registers the function
34050 // context.
34051 SetupEntryBlockForSjLj(MI, BB, DispatchBB, FI);
34052
34053 // Create the jump table and associated information
34054 unsigned JTE = getJumpTableEncoding();
34055 MachineJumpTableInfo *JTI = MF->getOrCreateJumpTableInfo(JTE);
34056 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
34057
34058 const X86RegisterInfo &RI = TII->getRegisterInfo();
34059 // Add a register mask with no preserved registers. This results in all
34060 // registers being marked as clobbered.
34061 if (RI.hasBasePointer(*MF)) {
34062 const bool FPIs64Bit =
34063 Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
34064 X86MachineFunctionInfo *MFI = MF->getInfo<X86MachineFunctionInfo>();
34065 MFI->setRestoreBasePointer(MF);
34066
34067 Register FP = RI.getFrameRegister(*MF);
34068 Register BP = RI.getBaseRegister();
34069 unsigned Op = FPIs64Bit ? X86::MOV64rm : X86::MOV32rm;
34070 addRegOffset(BuildMI(DispatchBB, DL, TII->get(Op), BP), FP, true,
34071 MFI->getRestoreBasePointerOffset())
34072 .addRegMask(RI.getNoPreservedMask());
34073 } else {
34074 BuildMI(DispatchBB, DL, TII->get(X86::NOOP))
34075 .addRegMask(RI.getNoPreservedMask());
34076 }
34077
34078 // IReg is used as an index in a memory operand and therefore can't be SP
34079 Register IReg = MRI->createVirtualRegister(&X86::GR32_NOSPRegClass);
34080 addFrameReference(BuildMI(DispatchBB, DL, TII->get(X86::MOV32rm), IReg), FI,
34081 Subtarget.is64Bit() ? 8 : 4);
34082 BuildMI(DispatchBB, DL, TII->get(X86::CMP32ri))
34083 .addReg(IReg)
34084 .addImm(LPadList.size());
34085 BuildMI(DispatchBB, DL, TII->get(X86::JCC_1)).addMBB(TrapBB).addImm(X86::COND_AE);
34086
34087 if (Subtarget.is64Bit()) {
34088 Register BReg = MRI->createVirtualRegister(&X86::GR64RegClass);
34089 Register IReg64 = MRI->createVirtualRegister(&X86::GR64_NOSPRegClass);
34090
34091 // leaq .LJTI0_0(%rip), BReg
34092 BuildMI(DispContBB, DL, TII->get(X86::LEA64r), BReg)
34093 .addReg(X86::RIP)
34094 .addImm(1)
34095 .addReg(0)
34096 .addJumpTableIndex(MJTI)
34097 .addReg(0);
34098 // movzx IReg64, IReg
34099 BuildMI(DispContBB, DL, TII->get(TargetOpcode::SUBREG_TO_REG), IReg64)
34100 .addImm(0)
34101 .addReg(IReg)
34102 .addImm(X86::sub_32bit);
34103
34104 switch (JTE) {
34105 case MachineJumpTableInfo::EK_BlockAddress:
34106 // jmpq *(BReg,IReg64,8)
34107 BuildMI(DispContBB, DL, TII->get(X86::JMP64m))
34108 .addReg(BReg)
34109 .addImm(8)
34110 .addReg(IReg64)
34111 .addImm(0)
34112 .addReg(0);
34113 break;
34114 case MachineJumpTableInfo::EK_LabelDifference32: {
34115 Register OReg = MRI->createVirtualRegister(&X86::GR32RegClass);
34116 Register OReg64 = MRI->createVirtualRegister(&X86::GR64RegClass);
34117 Register TReg = MRI->createVirtualRegister(&X86::GR64RegClass);
34118
34119 // movl (BReg,IReg64,4), OReg
34120 BuildMI(DispContBB, DL, TII->get(X86::MOV32rm), OReg)
34121 .addReg(BReg)
34122 .addImm(4)
34123 .addReg(IReg64)
34124 .addImm(0)
34125 .addReg(0);
34126 // movsx OReg64, OReg
34127 BuildMI(DispContBB, DL, TII->get(X86::MOVSX64rr32), OReg64).addReg(OReg);
34128 // addq BReg, OReg64, TReg
34129 BuildMI(DispContBB, DL, TII->get(X86::ADD64rr), TReg)
34130 .addReg(OReg64)
34131 .addReg(BReg);
34132 // jmpq *TReg
34133 BuildMI(DispContBB, DL, TII->get(X86::JMP64r)).addReg(TReg);
34134 break;
34135 }
34136 default:
34137 llvm_unreachable("Unexpected jump table encoding")::llvm::llvm_unreachable_internal("Unexpected jump table encoding"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34137)
;
34138 }
34139 } else {
34140 // jmpl *.LJTI0_0(,IReg,4)
34141 BuildMI(DispContBB, DL, TII->get(X86::JMP32m))
34142 .addReg(0)
34143 .addImm(4)
34144 .addReg(IReg)
34145 .addJumpTableIndex(MJTI)
34146 .addReg(0);
34147 }
34148
34149 // Add the jump table entries as successors to the MBB.
34150 SmallPtrSet<MachineBasicBlock *, 8> SeenMBBs;
34151 for (auto &LP : LPadList)
34152 if (SeenMBBs.insert(LP).second)
34153 DispContBB->addSuccessor(LP);
34154
34155 // N.B. the order the invoke BBs are processed in doesn't matter here.
34156 SmallVector<MachineBasicBlock *, 64> MBBLPads;
34157 const MCPhysReg *SavedRegs = MF->getRegInfo().getCalleeSavedRegs();
34158 for (MachineBasicBlock *MBB : InvokeBBs) {
34159 // Remove the landing pad successor from the invoke block and replace it
34160 // with the new dispatch block.
34161 // Keep a copy of Successors since it's modified inside the loop.
34162 SmallVector<MachineBasicBlock *, 8> Successors(MBB->succ_rbegin(),
34163 MBB->succ_rend());
34164 // FIXME: Avoid quadratic complexity.
34165 for (auto MBBS : Successors) {
34166 if (MBBS->isEHPad()) {
34167 MBB->removeSuccessor(MBBS);
34168 MBBLPads.push_back(MBBS);
34169 }
34170 }
34171
34172 MBB->addSuccessor(DispatchBB);
34173
34174 // Find the invoke call and mark all of the callee-saved registers as
34175 // 'implicit defined' so that they're spilled. This prevents code from
34176 // moving instructions to before the EH block, where they will never be
34177 // executed.
34178 for (auto &II : reverse(*MBB)) {
34179 if (!II.isCall())
34180 continue;
34181
34182 DenseMap<unsigned, bool> DefRegs;
34183 for (auto &MOp : II.operands())
34184 if (MOp.isReg())
34185 DefRegs[MOp.getReg()] = true;
34186
34187 MachineInstrBuilder MIB(*MF, &II);
34188 for (unsigned RegIdx = 0; SavedRegs[RegIdx]; ++RegIdx) {
34189 unsigned Reg = SavedRegs[RegIdx];
34190 if (!DefRegs[Reg])
34191 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
34192 }
34193
34194 break;
34195 }
34196 }
34197
34198 // Mark all former landing pads as non-landing pads. The dispatch is the only
34199 // landing pad now.
34200 for (auto &LP : MBBLPads)
34201 LP->setIsEHPad(false);
34202
34203 // The instruction is gone now.
34204 MI.eraseFromParent();
34205 return BB;
34206}
34207
34208MachineBasicBlock *
34209X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
34210 MachineBasicBlock *BB) const {
34211 MachineFunction *MF = BB->getParent();
34212 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
34213 const DebugLoc &DL = MI.getDebugLoc();
34214
34215 auto TMMImmToTMMReg = [](unsigned Imm) {
34216 assert (Imm < 8 && "Illegal tmm index")(static_cast <bool> (Imm < 8 && "Illegal tmm index"
) ? void (0) : __assert_fail ("Imm < 8 && \"Illegal tmm index\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34216, __extension__ __PRETTY_FUNCTION__))
;
34217 return X86::TMM0 + Imm;
34218 };
34219 switch (MI.getOpcode()) {
34220 default: llvm_unreachable("Unexpected instr type to insert")::llvm::llvm_unreachable_internal("Unexpected instr type to insert"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34220)
;
34221 case X86::TLS_addr32:
34222 case X86::TLS_addr64:
34223 case X86::TLS_addrX32:
34224 case X86::TLS_base_addr32:
34225 case X86::TLS_base_addr64:
34226 case X86::TLS_base_addrX32:
34227 return EmitLoweredTLSAddr(MI, BB);
34228 case X86::INDIRECT_THUNK_CALL32:
34229 case X86::INDIRECT_THUNK_CALL64:
34230 case X86::INDIRECT_THUNK_TCRETURN32:
34231 case X86::INDIRECT_THUNK_TCRETURN64:
34232 return EmitLoweredIndirectThunk(MI, BB);
34233 case X86::CATCHRET:
34234 return EmitLoweredCatchRet(MI, BB);
34235 case X86::SEG_ALLOCA_32:
34236 case X86::SEG_ALLOCA_64:
34237 return EmitLoweredSegAlloca(MI, BB);
34238 case X86::PROBED_ALLOCA_32:
34239 case X86::PROBED_ALLOCA_64:
34240 return EmitLoweredProbedAlloca(MI, BB);
34241 case X86::TLSCall_32:
34242 case X86::TLSCall_64:
34243 return EmitLoweredTLSCall(MI, BB);
34244 case X86::CMOV_FR32:
34245 case X86::CMOV_FR32X:
34246 case X86::CMOV_FR64:
34247 case X86::CMOV_FR64X:
34248 case X86::CMOV_GR8:
34249 case X86::CMOV_GR16:
34250 case X86::CMOV_GR32:
34251 case X86::CMOV_RFP32:
34252 case X86::CMOV_RFP64:
34253 case X86::CMOV_RFP80:
34254 case X86::CMOV_VR64:
34255 case X86::CMOV_VR128:
34256 case X86::CMOV_VR128X:
34257 case X86::CMOV_VR256:
34258 case X86::CMOV_VR256X:
34259 case X86::CMOV_VR512:
34260 case X86::CMOV_VK1:
34261 case X86::CMOV_VK2:
34262 case X86::CMOV_VK4:
34263 case X86::CMOV_VK8:
34264 case X86::CMOV_VK16:
34265 case X86::CMOV_VK32:
34266 case X86::CMOV_VK64:
34267 return EmitLoweredSelect(MI, BB);
34268
34269 case X86::RDFLAGS32:
34270 case X86::RDFLAGS64: {
34271 unsigned PushF =
34272 MI.getOpcode() == X86::RDFLAGS32 ? X86::PUSHF32 : X86::PUSHF64;
34273 unsigned Pop = MI.getOpcode() == X86::RDFLAGS32 ? X86::POP32r : X86::POP64r;
34274 MachineInstr *Push = BuildMI(*BB, MI, DL, TII->get(PushF));
34275 // Permit reads of the EFLAGS and DF registers without them being defined.
34276 // This intrinsic exists to read external processor state in flags, such as
34277 // the trap flag, interrupt flag, and direction flag, none of which are
34278 // modeled by the backend.
34279 assert(Push->getOperand(2).getReg() == X86::EFLAGS &&(static_cast <bool> (Push->getOperand(2).getReg() ==
X86::EFLAGS && "Unexpected register in operand!") ? void
(0) : __assert_fail ("Push->getOperand(2).getReg() == X86::EFLAGS && \"Unexpected register in operand!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34280, __extension__ __PRETTY_FUNCTION__))
34280 "Unexpected register in operand!")(static_cast <bool> (Push->getOperand(2).getReg() ==
X86::EFLAGS && "Unexpected register in operand!") ? void
(0) : __assert_fail ("Push->getOperand(2).getReg() == X86::EFLAGS && \"Unexpected register in operand!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34280, __extension__ __PRETTY_FUNCTION__))
;
34281 Push->getOperand(2).setIsUndef();
34282 assert(Push->getOperand(3).getReg() == X86::DF &&(static_cast <bool> (Push->getOperand(3).getReg() ==
X86::DF && "Unexpected register in operand!") ? void
(0) : __assert_fail ("Push->getOperand(3).getReg() == X86::DF && \"Unexpected register in operand!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34283, __extension__ __PRETTY_FUNCTION__))
34283 "Unexpected register in operand!")(static_cast <bool> (Push->getOperand(3).getReg() ==
X86::DF && "Unexpected register in operand!") ? void
(0) : __assert_fail ("Push->getOperand(3).getReg() == X86::DF && \"Unexpected register in operand!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34283, __extension__ __PRETTY_FUNCTION__))
;
34284 Push->getOperand(3).setIsUndef();
34285 BuildMI(*BB, MI, DL, TII->get(Pop), MI.getOperand(0).getReg());
34286
34287 MI.eraseFromParent(); // The pseudo is gone now.
34288 return BB;
34289 }
34290
34291 case X86::WRFLAGS32:
34292 case X86::WRFLAGS64: {
34293 unsigned Push =
34294 MI.getOpcode() == X86::WRFLAGS32 ? X86::PUSH32r : X86::PUSH64r;
34295 unsigned PopF =
34296 MI.getOpcode() == X86::WRFLAGS32 ? X86::POPF32 : X86::POPF64;
34297 BuildMI(*BB, MI, DL, TII->get(Push)).addReg(MI.getOperand(0).getReg());
34298 BuildMI(*BB, MI, DL, TII->get(PopF));
34299
34300 MI.eraseFromParent(); // The pseudo is gone now.
34301 return BB;
34302 }
34303
34304 case X86::FP32_TO_INT16_IN_MEM:
34305 case X86::FP32_TO_INT32_IN_MEM:
34306 case X86::FP32_TO_INT64_IN_MEM:
34307 case X86::FP64_TO_INT16_IN_MEM:
34308 case X86::FP64_TO_INT32_IN_MEM:
34309 case X86::FP64_TO_INT64_IN_MEM:
34310 case X86::FP80_TO_INT16_IN_MEM:
34311 case X86::FP80_TO_INT32_IN_MEM:
34312 case X86::FP80_TO_INT64_IN_MEM: {
34313 // Change the floating point control register to use "round towards zero"
34314 // mode when truncating to an integer value.
34315 int OrigCWFrameIdx =
34316 MF->getFrameInfo().CreateStackObject(2, Align(2), false);
34317 addFrameReference(BuildMI(*BB, MI, DL,
34318 TII->get(X86::FNSTCW16m)), OrigCWFrameIdx);
34319
34320 // Load the old value of the control word...
34321 Register OldCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
34322 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOVZX32rm16), OldCW),
34323 OrigCWFrameIdx);
34324
34325 // OR 0b11 into bit 10 and 11. 0b11 is the encoding for round toward zero.
34326 Register NewCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
34327 BuildMI(*BB, MI, DL, TII->get(X86::OR32ri), NewCW)
34328 .addReg(OldCW, RegState::Kill).addImm(0xC00);
34329
34330 // Extract to 16 bits.
34331 Register NewCW16 =
34332 MF->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
34333 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), NewCW16)
34334 .addReg(NewCW, RegState::Kill, X86::sub_16bit);
34335
34336 // Prepare memory for FLDCW.
34337 int NewCWFrameIdx =
34338 MF->getFrameInfo().CreateStackObject(2, Align(2), false);
34339 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)),
34340 NewCWFrameIdx)
34341 .addReg(NewCW16, RegState::Kill);
34342
34343 // Reload the modified control word now...
34344 addFrameReference(BuildMI(*BB, MI, DL,
34345 TII->get(X86::FLDCW16m)), NewCWFrameIdx);
34346
34347 // Get the X86 opcode to use.
34348 unsigned Opc;
34349 switch (MI.getOpcode()) {
34350 default: llvm_unreachable("illegal opcode!")::llvm::llvm_unreachable_internal("illegal opcode!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34350)
;
34351 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
34352 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
34353 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
34354 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
34355 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
34356 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
34357 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
34358 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
34359 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
34360 }
34361
34362 X86AddressMode AM = getAddressFromInstr(&MI, 0);
34363 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
34364 .addReg(MI.getOperand(X86::AddrNumOperands).getReg());
34365
34366 // Reload the original control word now.
34367 addFrameReference(BuildMI(*BB, MI, DL,
34368 TII->get(X86::FLDCW16m)), OrigCWFrameIdx);
34369
34370 MI.eraseFromParent(); // The pseudo instruction is gone now.
34371 return BB;
34372 }
34373
34374 // xbegin
34375 case X86::XBEGIN:
34376 return emitXBegin(MI, BB, Subtarget.getInstrInfo());
34377
34378 case X86::VAARG_64:
34379 case X86::VAARG_X32:
34380 return EmitVAARGWithCustomInserter(MI, BB);
34381
34382 case X86::EH_SjLj_SetJmp32:
34383 case X86::EH_SjLj_SetJmp64:
34384 return emitEHSjLjSetJmp(MI, BB);
34385
34386 case X86::EH_SjLj_LongJmp32:
34387 case X86::EH_SjLj_LongJmp64:
34388 return emitEHSjLjLongJmp(MI, BB);
34389
34390 case X86::Int_eh_sjlj_setup_dispatch:
34391 return EmitSjLjDispatchBlock(MI, BB);
34392
34393 case TargetOpcode::STATEPOINT:
34394 // As an implementation detail, STATEPOINT shares the STACKMAP format at
34395 // this point in the process. We diverge later.
34396 return emitPatchPoint(MI, BB);
34397
34398 case TargetOpcode::STACKMAP:
34399 case TargetOpcode::PATCHPOINT:
34400 return emitPatchPoint(MI, BB);
34401
34402 case TargetOpcode::PATCHABLE_EVENT_CALL:
34403 case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
34404 return BB;
34405
34406 case X86::LCMPXCHG8B: {
34407 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
34408 // In addition to 4 E[ABCD] registers implied by encoding, CMPXCHG8B
34409 // requires a memory operand. If it happens that current architecture is
34410 // i686 and for current function we need a base pointer
34411 // - which is ESI for i686 - register allocator would not be able to
34412 // allocate registers for an address in form of X(%reg, %reg, Y)
34413 // - there never would be enough unreserved registers during regalloc
34414 // (without the need for base ptr the only option would be X(%edi, %esi, Y).
34415 // We are giving a hand to register allocator by precomputing the address in
34416 // a new vreg using LEA.
34417
34418 // If it is not i686 or there is no base pointer - nothing to do here.
34419 if (!Subtarget.is32Bit() || !TRI->hasBasePointer(*MF))
34420 return BB;
34421
34422 // Even though this code does not necessarily needs the base pointer to
34423 // be ESI, we check for that. The reason: if this assert fails, there are
34424 // some changes happened in the compiler base pointer handling, which most
34425 // probably have to be addressed somehow here.
34426 assert(TRI->getBaseRegister() == X86::ESI &&(static_cast <bool> (TRI->getBaseRegister() == X86::
ESI && "LCMPXCHG8B custom insertion for i686 is written with X86::ESI as a "
"base pointer in mind") ? void (0) : __assert_fail ("TRI->getBaseRegister() == X86::ESI && \"LCMPXCHG8B custom insertion for i686 is written with X86::ESI as a \" \"base pointer in mind\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34428, __extension__ __PRETTY_FUNCTION__))
34427 "LCMPXCHG8B custom insertion for i686 is written with X86::ESI as a "(static_cast <bool> (TRI->getBaseRegister() == X86::
ESI && "LCMPXCHG8B custom insertion for i686 is written with X86::ESI as a "
"base pointer in mind") ? void (0) : __assert_fail ("TRI->getBaseRegister() == X86::ESI && \"LCMPXCHG8B custom insertion for i686 is written with X86::ESI as a \" \"base pointer in mind\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34428, __extension__ __PRETTY_FUNCTION__))
34428 "base pointer in mind")(static_cast <bool> (TRI->getBaseRegister() == X86::
ESI && "LCMPXCHG8B custom insertion for i686 is written with X86::ESI as a "
"base pointer in mind") ? void (0) : __assert_fail ("TRI->getBaseRegister() == X86::ESI && \"LCMPXCHG8B custom insertion for i686 is written with X86::ESI as a \" \"base pointer in mind\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34428, __extension__ __PRETTY_FUNCTION__))
;
34429
34430 MachineRegisterInfo &MRI = MF->getRegInfo();
34431 MVT SPTy = getPointerTy(MF->getDataLayout());
34432 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
34433 Register computedAddrVReg = MRI.createVirtualRegister(AddrRegClass);
34434
34435 X86AddressMode AM = getAddressFromInstr(&MI, 0);
34436 // Regalloc does not need any help when the memory operand of CMPXCHG8B
34437 // does not use index register.
34438 if (AM.IndexReg == X86::NoRegister)
34439 return BB;
34440
34441 // After X86TargetLowering::ReplaceNodeResults CMPXCHG8B is glued to its
34442 // four operand definitions that are E[ABCD] registers. We skip them and
34443 // then insert the LEA.
34444 MachineBasicBlock::reverse_iterator RMBBI(MI.getReverseIterator());
34445 while (RMBBI != BB->rend() && (RMBBI->definesRegister(X86::EAX) ||
34446 RMBBI->definesRegister(X86::EBX) ||
34447 RMBBI->definesRegister(X86::ECX) ||
34448 RMBBI->definesRegister(X86::EDX))) {
34449 ++RMBBI;
34450 }
34451 MachineBasicBlock::iterator MBBI(RMBBI);
34452 addFullAddress(
34453 BuildMI(*BB, *MBBI, DL, TII->get(X86::LEA32r), computedAddrVReg), AM);
34454
34455 setDirectAddressInInstr(&MI, 0, computedAddrVReg);
34456
34457 return BB;
34458 }
34459 case X86::LCMPXCHG16B_NO_RBX: {
34460 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
34461 Register BasePtr = TRI->getBaseRegister();
34462 if (TRI->hasBasePointer(*MF) &&
34463 (BasePtr == X86::RBX || BasePtr == X86::EBX)) {
34464 if (!BB->isLiveIn(BasePtr))
34465 BB->addLiveIn(BasePtr);
34466 // Save RBX into a virtual register.
34467 Register SaveRBX =
34468 MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
34469 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), SaveRBX)
34470 .addReg(X86::RBX);
34471 Register Dst = MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
34472 MachineInstrBuilder MIB =
34473 BuildMI(*BB, MI, DL, TII->get(X86::LCMPXCHG16B_SAVE_RBX), Dst);
34474 for (unsigned Idx = 0; Idx < X86::AddrNumOperands; ++Idx)
34475 MIB.add(MI.getOperand(Idx));
34476 MIB.add(MI.getOperand(X86::AddrNumOperands));
34477 MIB.addReg(SaveRBX);
34478 } else {
34479 // Simple case, just copy the virtual register to RBX.
34480 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::RBX)
34481 .add(MI.getOperand(X86::AddrNumOperands));
34482 MachineInstrBuilder MIB =
34483 BuildMI(*BB, MI, DL, TII->get(X86::LCMPXCHG16B));
34484 for (unsigned Idx = 0; Idx < X86::AddrNumOperands; ++Idx)
34485 MIB.add(MI.getOperand(Idx));
34486 }
34487 MI.eraseFromParent();
34488 return BB;
34489 }
34490 case X86::MWAITX: {
34491 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
34492 Register BasePtr = TRI->getBaseRegister();
34493 bool IsRBX = (BasePtr == X86::RBX || BasePtr == X86::EBX);
34494 // If no need to save the base pointer, we generate MWAITXrrr,
34495 // else we generate pseudo MWAITX_SAVE_RBX.
34496 if (!IsRBX || !TRI->hasBasePointer(*MF)) {
34497 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::ECX)
34498 .addReg(MI.getOperand(0).getReg());
34499 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::EAX)
34500 .addReg(MI.getOperand(1).getReg());
34501 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::EBX)
34502 .addReg(MI.getOperand(2).getReg());
34503 BuildMI(*BB, MI, DL, TII->get(X86::MWAITXrrr));
34504 MI.eraseFromParent();
34505 } else {
34506 if (!BB->isLiveIn(BasePtr)) {
34507 BB->addLiveIn(BasePtr);
34508 }
34509 // Parameters can be copied into ECX and EAX but not EBX yet.
34510 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::ECX)
34511 .addReg(MI.getOperand(0).getReg());
34512 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::EAX)
34513 .addReg(MI.getOperand(1).getReg());
34514 assert(Subtarget.is64Bit() && "Expected 64-bit mode!")(static_cast <bool> (Subtarget.is64Bit() && "Expected 64-bit mode!"
) ? void (0) : __assert_fail ("Subtarget.is64Bit() && \"Expected 64-bit mode!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34514, __extension__ __PRETTY_FUNCTION__))
;
34515 // Save RBX into a virtual register.
34516 Register SaveRBX =
34517 MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
34518 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), SaveRBX)
34519 .addReg(X86::RBX);
34520 // Generate mwaitx pseudo.
34521 Register Dst = MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
34522 BuildMI(*BB, MI, DL, TII->get(X86::MWAITX_SAVE_RBX))
34523 .addDef(Dst) // Destination tied in with SaveRBX.
34524 .addReg(MI.getOperand(2).getReg()) // input value of EBX.
34525 .addUse(SaveRBX); // Save of base pointer.
34526 MI.eraseFromParent();
34527 }
34528 return BB;
34529 }
34530 case TargetOpcode::PREALLOCATED_SETUP: {
34531 assert(Subtarget.is32Bit() && "preallocated only used in 32-bit")(static_cast <bool> (Subtarget.is32Bit() && "preallocated only used in 32-bit"
) ? void (0) : __assert_fail ("Subtarget.is32Bit() && \"preallocated only used in 32-bit\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34531, __extension__ __PRETTY_FUNCTION__))
;
34532 auto MFI = MF->getInfo<X86MachineFunctionInfo>();
34533 MFI->setHasPreallocatedCall(true);
34534 int64_t PreallocatedId = MI.getOperand(0).getImm();
34535 size_t StackAdjustment = MFI->getPreallocatedStackSize(PreallocatedId);
34536 assert(StackAdjustment != 0 && "0 stack adjustment")(static_cast <bool> (StackAdjustment != 0 && "0 stack adjustment"
) ? void (0) : __assert_fail ("StackAdjustment != 0 && \"0 stack adjustment\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34536, __extension__ __PRETTY_FUNCTION__))
;
34537 LLVM_DEBUG(dbgs() << "PREALLOCATED_SETUP stack adjustment "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("x86-isel")) { dbgs() << "PREALLOCATED_SETUP stack adjustment "
<< StackAdjustment << "\n"; } } while (false)
34538 << StackAdjustment << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("x86-isel")) { dbgs() << "PREALLOCATED_SETUP stack adjustment "
<< StackAdjustment << "\n"; } } while (false)
;
34539 BuildMI(*BB, MI, DL, TII->get(X86::SUB32ri), X86::ESP)
34540 .addReg(X86::ESP)
34541 .addImm(StackAdjustment);
34542 MI.eraseFromParent();
34543 return BB;
34544 }
34545 case TargetOpcode::PREALLOCATED_ARG: {
34546 assert(Subtarget.is32Bit() && "preallocated calls only used in 32-bit")(static_cast <bool> (Subtarget.is32Bit() && "preallocated calls only used in 32-bit"
) ? void (0) : __assert_fail ("Subtarget.is32Bit() && \"preallocated calls only used in 32-bit\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34546, __extension__ __PRETTY_FUNCTION__))
;
34547 int64_t PreallocatedId = MI.getOperand(1).getImm();
34548 int64_t ArgIdx = MI.getOperand(2).getImm();
34549 auto MFI = MF->getInfo<X86MachineFunctionInfo>();
34550 size_t ArgOffset = MFI->getPreallocatedArgOffsets(PreallocatedId)[ArgIdx];
34551 LLVM_DEBUG(dbgs() << "PREALLOCATED_ARG arg index " << ArgIdxdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("x86-isel")) { dbgs() << "PREALLOCATED_ARG arg index "
<< ArgIdx << ", arg offset " << ArgOffset <<
"\n"; } } while (false)
34552 << ", arg offset " << ArgOffset << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("x86-isel")) { dbgs() << "PREALLOCATED_ARG arg index "
<< ArgIdx << ", arg offset " << ArgOffset <<
"\n"; } } while (false)
;
34553 // stack pointer + offset
34554 addRegOffset(
34555 BuildMI(*BB, MI, DL, TII->get(X86::LEA32r), MI.getOperand(0).getReg()),
34556 X86::ESP, false, ArgOffset);
34557 MI.eraseFromParent();
34558 return BB;
34559 }
34560 case X86::PTDPBSSD:
34561 case X86::PTDPBSUD:
34562 case X86::PTDPBUSD:
34563 case X86::PTDPBUUD:
34564 case X86::PTDPBF16PS: {
34565 unsigned Opc;
34566 switch (MI.getOpcode()) {
34567 case X86::PTDPBSSD: Opc = X86::TDPBSSD; break;
34568 case X86::PTDPBSUD: Opc = X86::TDPBSUD; break;
34569 case X86::PTDPBUSD: Opc = X86::TDPBUSD; break;
34570 case X86::PTDPBUUD: Opc = X86::TDPBUUD; break;
34571 case X86::PTDPBF16PS: Opc = X86::TDPBF16PS; break;
34572 }
34573
34574 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, TII->get(Opc));
34575 MIB.addReg(TMMImmToTMMReg(MI.getOperand(0).getImm()), RegState::Define);
34576 MIB.addReg(TMMImmToTMMReg(MI.getOperand(0).getImm()), RegState::Undef);
34577 MIB.addReg(TMMImmToTMMReg(MI.getOperand(1).getImm()), RegState::Undef);
34578 MIB.addReg(TMMImmToTMMReg(MI.getOperand(2).getImm()), RegState::Undef);
34579
34580 MI.eraseFromParent(); // The pseudo is gone now.
34581 return BB;
34582 }
34583 case X86::PTILEZERO: {
34584 unsigned Imm = MI.getOperand(0).getImm();
34585 BuildMI(*BB, MI, DL, TII->get(X86::TILEZERO), TMMImmToTMMReg(Imm));
34586 MI.eraseFromParent(); // The pseudo is gone now.
34587 return BB;
34588 }
34589 case X86::PTILELOADD:
34590 case X86::PTILELOADDT1:
34591 case X86::PTILESTORED: {
34592 unsigned Opc;
34593 switch (MI.getOpcode()) {
34594 case X86::PTILELOADD: Opc = X86::TILELOADD; break;
34595 case X86::PTILELOADDT1: Opc = X86::TILELOADDT1; break;
34596 case X86::PTILESTORED: Opc = X86::TILESTORED; break;
34597 }
34598
34599 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, TII->get(Opc));
34600 unsigned CurOp = 0;
34601 if (Opc != X86::TILESTORED)
34602 MIB.addReg(TMMImmToTMMReg(MI.getOperand(CurOp++).getImm()),
34603 RegState::Define);
34604
34605 MIB.add(MI.getOperand(CurOp++)); // base
34606 MIB.add(MI.getOperand(CurOp++)); // scale
34607 MIB.add(MI.getOperand(CurOp++)); // index -- stride
34608 MIB.add(MI.getOperand(CurOp++)); // displacement
34609 MIB.add(MI.getOperand(CurOp++)); // segment
34610
34611 if (Opc == X86::TILESTORED)
34612 MIB.addReg(TMMImmToTMMReg(MI.getOperand(CurOp++).getImm()),
34613 RegState::Undef);
34614
34615 MI.eraseFromParent(); // The pseudo is gone now.
34616 return BB;
34617 }
34618 }
34619}
34620
34621//===----------------------------------------------------------------------===//
34622// X86 Optimization Hooks
34623//===----------------------------------------------------------------------===//
34624
34625bool
34626X86TargetLowering::targetShrinkDemandedConstant(SDValue Op,
34627 const APInt &DemandedBits,
34628 const APInt &DemandedElts,
34629 TargetLoweringOpt &TLO) const {
34630 EVT VT = Op.getValueType();
34631 unsigned Opcode = Op.getOpcode();
34632 unsigned EltSize = VT.getScalarSizeInBits();
34633
34634 if (VT.isVector()) {
34635 // If the constant is only all signbits in the active bits, then we should
34636 // extend it to the entire constant to allow it act as a boolean constant
34637 // vector.
34638 auto NeedsSignExtension = [&](SDValue V, unsigned ActiveBits) {
34639 if (!ISD::isBuildVectorOfConstantSDNodes(V.getNode()))
34640 return false;
34641 for (unsigned i = 0, e = V.getNumOperands(); i != e; ++i) {
34642 if (!DemandedElts[i] || V.getOperand(i).isUndef())
34643 continue;
34644 const APInt &Val = V.getConstantOperandAPInt(i);
34645 if (Val.getBitWidth() > Val.getNumSignBits() &&
34646 Val.trunc(ActiveBits).getNumSignBits() == ActiveBits)
34647 return true;
34648 }
34649 return false;
34650 };
34651 // For vectors - if we have a constant, then try to sign extend.
34652 // TODO: Handle AND/ANDN cases.
34653 unsigned ActiveBits = DemandedBits.getActiveBits();
34654 if (EltSize > ActiveBits && EltSize > 1 && isTypeLegal(VT) &&
34655 (Opcode == ISD::OR || Opcode == ISD::XOR) &&
34656 NeedsSignExtension(Op.getOperand(1), ActiveBits)) {
34657 EVT ExtSVT = EVT::getIntegerVT(*TLO.DAG.getContext(), ActiveBits);
34658 EVT ExtVT = EVT::getVectorVT(*TLO.DAG.getContext(), ExtSVT,
34659 VT.getVectorNumElements());
34660 SDValue NewC =
34661 TLO.DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(Op), VT,
34662 Op.getOperand(1), TLO.DAG.getValueType(ExtVT));
34663 SDValue NewOp =
34664 TLO.DAG.getNode(Opcode, SDLoc(Op), VT, Op.getOperand(0), NewC);
34665 return TLO.CombineTo(Op, NewOp);
34666 }
34667 return false;
34668 }
34669
34670 // Only optimize Ands to prevent shrinking a constant that could be
34671 // matched by movzx.
34672 if (Opcode != ISD::AND)
34673 return false;
34674
34675 // Make sure the RHS really is a constant.
34676 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
34677 if (!C)
34678 return false;
34679
34680 const APInt &Mask = C->getAPIntValue();
34681
34682 // Clear all non-demanded bits initially.
34683 APInt ShrunkMask = Mask & DemandedBits;
34684
34685 // Find the width of the shrunk mask.
34686 unsigned Width = ShrunkMask.getActiveBits();
34687
34688 // If the mask is all 0s there's nothing to do here.
34689 if (Width == 0)
34690 return false;
34691
34692 // Find the next power of 2 width, rounding up to a byte.
34693 Width = PowerOf2Ceil(std::max(Width, 8U));
34694 // Truncate the width to size to handle illegal types.
34695 Width = std::min(Width, EltSize);
34696
34697 // Calculate a possible zero extend mask for this constant.
34698 APInt ZeroExtendMask = APInt::getLowBitsSet(EltSize, Width);
34699
34700 // If we aren't changing the mask, just return true to keep it and prevent
34701 // the caller from optimizing.
34702 if (ZeroExtendMask == Mask)
34703 return true;
34704
34705 // Make sure the new mask can be represented by a combination of mask bits
34706 // and non-demanded bits.
34707 if (!ZeroExtendMask.isSubsetOf(Mask | ~DemandedBits))
34708 return false;
34709
34710 // Replace the constant with the zero extend mask.
34711 SDLoc DL(Op);
34712 SDValue NewC = TLO.DAG.getConstant(ZeroExtendMask, DL, VT);
34713 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
34714 return TLO.CombineTo(Op, NewOp);
34715}
34716
34717void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
34718 KnownBits &Known,
34719 const APInt &DemandedElts,
34720 const SelectionDAG &DAG,
34721 unsigned Depth) const {
34722 unsigned BitWidth = Known.getBitWidth();
34723 unsigned NumElts = DemandedElts.getBitWidth();
34724 unsigned Opc = Op.getOpcode();
34725 EVT VT = Op.getValueType();
34726 assert((Opc >= ISD::BUILTIN_OP_END ||(static_cast <bool> ((Opc >= ISD::BUILTIN_OP_END || Opc
== ISD::INTRINSIC_WO_CHAIN || Opc == ISD::INTRINSIC_W_CHAIN ||
Opc == ISD::INTRINSIC_VOID) && "Should use MaskedValueIsZero if you don't know whether Op"
" is a target node!") ? void (0) : __assert_fail ("(Opc >= ISD::BUILTIN_OP_END || Opc == ISD::INTRINSIC_WO_CHAIN || Opc == ISD::INTRINSIC_W_CHAIN || Opc == ISD::INTRINSIC_VOID) && \"Should use MaskedValueIsZero if you don't know whether Op\" \" is a target node!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34731, __extension__ __PRETTY_FUNCTION__))
34727 Opc == ISD::INTRINSIC_WO_CHAIN ||(static_cast <bool> ((Opc >= ISD::BUILTIN_OP_END || Opc
== ISD::INTRINSIC_WO_CHAIN || Opc == ISD::INTRINSIC_W_CHAIN ||
Opc == ISD::INTRINSIC_VOID) && "Should use MaskedValueIsZero if you don't know whether Op"
" is a target node!") ? void (0) : __assert_fail ("(Opc >= ISD::BUILTIN_OP_END || Opc == ISD::INTRINSIC_WO_CHAIN || Opc == ISD::INTRINSIC_W_CHAIN || Opc == ISD::INTRINSIC_VOID) && \"Should use MaskedValueIsZero if you don't know whether Op\" \" is a target node!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34731, __extension__ __PRETTY_FUNCTION__))
34728 Opc == ISD::INTRINSIC_W_CHAIN ||(static_cast <bool> ((Opc >= ISD::BUILTIN_OP_END || Opc
== ISD::INTRINSIC_WO_CHAIN || Opc == ISD::INTRINSIC_W_CHAIN ||
Opc == ISD::INTRINSIC_VOID) && "Should use MaskedValueIsZero if you don't know whether Op"
" is a target node!") ? void (0) : __assert_fail ("(Opc >= ISD::BUILTIN_OP_END || Opc == ISD::INTRINSIC_WO_CHAIN || Opc == ISD::INTRINSIC_W_CHAIN || Opc == ISD::INTRINSIC_VOID) && \"Should use MaskedValueIsZero if you don't know whether Op\" \" is a target node!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34731, __extension__ __PRETTY_FUNCTION__))
34729 Opc == ISD::INTRINSIC_VOID) &&(static_cast <bool> ((Opc >= ISD::BUILTIN_OP_END || Opc
== ISD::INTRINSIC_WO_CHAIN || Opc == ISD::INTRINSIC_W_CHAIN ||
Opc == ISD::INTRINSIC_VOID) && "Should use MaskedValueIsZero if you don't know whether Op"
" is a target node!") ? void (0) : __assert_fail ("(Opc >= ISD::BUILTIN_OP_END || Opc == ISD::INTRINSIC_WO_CHAIN || Opc == ISD::INTRINSIC_W_CHAIN || Opc == ISD::INTRINSIC_VOID) && \"Should use MaskedValueIsZero if you don't know whether Op\" \" is a target node!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34731, __extension__ __PRETTY_FUNCTION__))
34730 "Should use MaskedValueIsZero if you don't know whether Op"(static_cast <bool> ((Opc >= ISD::BUILTIN_OP_END || Opc
== ISD::INTRINSIC_WO_CHAIN || Opc == ISD::INTRINSIC_W_CHAIN ||
Opc == ISD::INTRINSIC_VOID) && "Should use MaskedValueIsZero if you don't know whether Op"
" is a target node!") ? void (0) : __assert_fail ("(Opc >= ISD::BUILTIN_OP_END || Opc == ISD::INTRINSIC_WO_CHAIN || Opc == ISD::INTRINSIC_W_CHAIN || Opc == ISD::INTRINSIC_VOID) && \"Should use MaskedValueIsZero if you don't know whether Op\" \" is a target node!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34731, __extension__ __PRETTY_FUNCTION__))
34731 " is a target node!")(static_cast <bool> ((Opc >= ISD::BUILTIN_OP_END || Opc
== ISD::INTRINSIC_WO_CHAIN || Opc == ISD::INTRINSIC_W_CHAIN ||
Opc == ISD::INTRINSIC_VOID) && "Should use MaskedValueIsZero if you don't know whether Op"
" is a target node!") ? void (0) : __assert_fail ("(Opc >= ISD::BUILTIN_OP_END || Opc == ISD::INTRINSIC_WO_CHAIN || Opc == ISD::INTRINSIC_W_CHAIN || Opc == ISD::INTRINSIC_VOID) && \"Should use MaskedValueIsZero if you don't know whether Op\" \" is a target node!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34731, __extension__ __PRETTY_FUNCTION__))
;
34732
34733 Known.resetAll();
34734 switch (Opc) {
34735 default: break;
34736 case X86ISD::SETCC:
34737 Known.Zero.setBitsFrom(1);
34738 break;
34739 case X86ISD::MOVMSK: {
34740 unsigned NumLoBits = Op.getOperand(0).getValueType().getVectorNumElements();
34741 Known.Zero.setBitsFrom(NumLoBits);
34742 break;
34743 }
34744 case X86ISD::PEXTRB:
34745 case X86ISD::PEXTRW: {
34746 SDValue Src = Op.getOperand(0);
34747 EVT SrcVT = Src.getValueType();
34748 APInt DemandedElt = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
34749 Op.getConstantOperandVal(1));
34750 Known = DAG.computeKnownBits(Src, DemandedElt, Depth + 1);
34751 Known = Known.anyextOrTrunc(BitWidth);
34752 Known.Zero.setBitsFrom(SrcVT.getScalarSizeInBits());
34753 break;
34754 }
34755 case X86ISD::VSRAI:
34756 case X86ISD::VSHLI:
34757 case X86ISD::VSRLI: {
34758 unsigned ShAmt = Op.getConstantOperandVal(1);
34759 if (ShAmt >= VT.getScalarSizeInBits()) {
34760 Known.setAllZero();
34761 break;
34762 }
34763
34764 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
34765 if (Opc == X86ISD::VSHLI) {
34766 Known.Zero <<= ShAmt;
34767 Known.One <<= ShAmt;
34768 // Low bits are known zero.
34769 Known.Zero.setLowBits(ShAmt);
34770 } else if (Opc == X86ISD::VSRLI) {
34771 Known.Zero.lshrInPlace(ShAmt);
34772 Known.One.lshrInPlace(ShAmt);
34773 // High bits are known zero.
34774 Known.Zero.setHighBits(ShAmt);
34775 } else {
34776 Known.Zero.ashrInPlace(ShAmt);
34777 Known.One.ashrInPlace(ShAmt);
34778 }
34779 break;
34780 }
34781 case X86ISD::PACKUS: {
34782 // PACKUS is just a truncation if the upper half is zero.
34783 APInt DemandedLHS, DemandedRHS;
34784 getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
34785
34786 Known.One = APInt::getAllOnesValue(BitWidth * 2);
34787 Known.Zero = APInt::getAllOnesValue(BitWidth * 2);
34788
34789 KnownBits Known2;
34790 if (!!DemandedLHS) {
34791 Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedLHS, Depth + 1);
34792 Known = KnownBits::commonBits(Known, Known2);
34793 }
34794 if (!!DemandedRHS) {
34795 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedRHS, Depth + 1);
34796 Known = KnownBits::commonBits(Known, Known2);
34797 }
34798
34799 if (Known.countMinLeadingZeros() < BitWidth)
34800 Known.resetAll();
34801 Known = Known.trunc(BitWidth);
34802 break;
34803 }
34804 case X86ISD::VBROADCAST: {
34805 SDValue Src = Op.getOperand(0);
34806 if (!Src.getSimpleValueType().isVector()) {
34807 Known = DAG.computeKnownBits(Src, Depth + 1);
34808 return;
34809 }
34810 break;
34811 }
34812 case X86ISD::ANDNP: {
34813 KnownBits Known2;
34814 Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
34815 Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
34816
34817 // ANDNP = (~X & Y);
34818 Known.One &= Known2.Zero;
34819 Known.Zero |= Known2.One;
34820 break;
34821 }
34822 case X86ISD::FOR: {
34823 KnownBits Known2;
34824 Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
34825 Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
34826
34827 Known |= Known2;
34828 break;
34829 }
34830 case X86ISD::PSADBW: {
34831 assert(VT.getScalarType() == MVT::i64 &&(static_cast <bool> (VT.getScalarType() == MVT::i64 &&
Op.getOperand(0).getValueType().getScalarType() == MVT::i8 &&
"Unexpected PSADBW types") ? void (0) : __assert_fail ("VT.getScalarType() == MVT::i64 && Op.getOperand(0).getValueType().getScalarType() == MVT::i8 && \"Unexpected PSADBW types\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34833, __extension__ __PRETTY_FUNCTION__))
34832 Op.getOperand(0).getValueType().getScalarType() == MVT::i8 &&(static_cast <bool> (VT.getScalarType() == MVT::i64 &&
Op.getOperand(0).getValueType().getScalarType() == MVT::i8 &&
"Unexpected PSADBW types") ? void (0) : __assert_fail ("VT.getScalarType() == MVT::i64 && Op.getOperand(0).getValueType().getScalarType() == MVT::i8 && \"Unexpected PSADBW types\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34833, __extension__ __PRETTY_FUNCTION__))
34833 "Unexpected PSADBW types")(static_cast <bool> (VT.getScalarType() == MVT::i64 &&
Op.getOperand(0).getValueType().getScalarType() == MVT::i8 &&
"Unexpected PSADBW types") ? void (0) : __assert_fail ("VT.getScalarType() == MVT::i64 && Op.getOperand(0).getValueType().getScalarType() == MVT::i8 && \"Unexpected PSADBW types\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34833, __extension__ __PRETTY_FUNCTION__))
;
34834
34835 // PSADBW - fills low 16 bits and zeros upper 48 bits of each i64 result.
34836 Known.Zero.setBitsFrom(16);
34837 break;
34838 }
34839 case X86ISD::PMULUDQ: {
34840 KnownBits Known2;
34841 Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
34842 Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
34843
34844 Known = Known.trunc(BitWidth / 2).zext(BitWidth);
34845 Known2 = Known2.trunc(BitWidth / 2).zext(BitWidth);
34846 Known = KnownBits::mul(Known, Known2);
34847 break;
34848 }
34849 case X86ISD::CMOV: {
34850 Known = DAG.computeKnownBits(Op.getOperand(1), Depth + 1);
34851 // If we don't know any bits, early out.
34852 if (Known.isUnknown())
34853 break;
34854 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
34855
34856 // Only known if known in both the LHS and RHS.
34857 Known = KnownBits::commonBits(Known, Known2);
34858 break;
34859 }
34860 case X86ISD::BEXTR:
34861 case X86ISD::BEXTRI: {
34862 SDValue Op0 = Op.getOperand(0);
34863 SDValue Op1 = Op.getOperand(1);
34864
34865 if (auto* Cst1 = dyn_cast<ConstantSDNode>(Op1)) {
34866 unsigned Shift = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 0);
34867 unsigned Length = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 8);
34868
34869 // If the length is 0, the result is 0.
34870 if (Length == 0) {
34871 Known.setAllZero();
34872 break;
34873 }
34874
34875 if ((Shift + Length) <= BitWidth) {
34876 Known = DAG.computeKnownBits(Op0, Depth + 1);
34877 Known = Known.extractBits(Length, Shift);
34878 Known = Known.zextOrTrunc(BitWidth);
34879 }
34880 }
34881 break;
34882 }
34883 case X86ISD::PDEP: {
34884 KnownBits Known2;
34885 Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
34886 Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
34887 // Zeros are retained from the mask operand. But not ones.
34888 Known.One.clearAllBits();
34889 // The result will have at least as many trailing zeros as the non-mask
34890 // operand since bits can only map to the same or higher bit position.
34891 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
34892 break;
34893 }
34894 case X86ISD::PEXT: {
34895 Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
34896 // The result has as many leading zeros as the number of zeroes in the mask.
34897 unsigned Count = Known.Zero.countPopulation();
34898 Known.Zero = APInt::getHighBitsSet(BitWidth, Count);
34899 Known.One.clearAllBits();
34900 break;
34901 }
34902 case X86ISD::VTRUNC:
34903 case X86ISD::VTRUNCS:
34904 case X86ISD::VTRUNCUS:
34905 case X86ISD::CVTSI2P:
34906 case X86ISD::CVTUI2P:
34907 case X86ISD::CVTP2SI:
34908 case X86ISD::CVTP2UI:
34909 case X86ISD::MCVTP2SI:
34910 case X86ISD::MCVTP2UI:
34911 case X86ISD::CVTTP2SI:
34912 case X86ISD::CVTTP2UI:
34913 case X86ISD::MCVTTP2SI:
34914 case X86ISD::MCVTTP2UI:
34915 case X86ISD::MCVTSI2P:
34916 case X86ISD::MCVTUI2P:
34917 case X86ISD::VFPROUND:
34918 case X86ISD::VMFPROUND:
34919 case X86ISD::CVTPS2PH:
34920 case X86ISD::MCVTPS2PH: {
34921 // Truncations/Conversions - upper elements are known zero.
34922 EVT SrcVT = Op.getOperand(0).getValueType();
34923 if (SrcVT.isVector()) {
34924 unsigned NumSrcElts = SrcVT.getVectorNumElements();
34925 if (NumElts > NumSrcElts &&
34926 DemandedElts.countTrailingZeros() >= NumSrcElts)
34927 Known.setAllZero();
34928 }
34929 break;
34930 }
34931 case X86ISD::STRICT_CVTTP2SI:
34932 case X86ISD::STRICT_CVTTP2UI:
34933 case X86ISD::STRICT_CVTSI2P:
34934 case X86ISD::STRICT_CVTUI2P:
34935 case X86ISD::STRICT_VFPROUND:
34936 case X86ISD::STRICT_CVTPS2PH: {
34937 // Strict Conversions - upper elements are known zero.
34938 EVT SrcVT = Op.getOperand(1).getValueType();
34939 if (SrcVT.isVector()) {
34940 unsigned NumSrcElts = SrcVT.getVectorNumElements();
34941 if (NumElts > NumSrcElts &&
34942 DemandedElts.countTrailingZeros() >= NumSrcElts)
34943 Known.setAllZero();
34944 }
34945 break;
34946 }
34947 case X86ISD::MOVQ2DQ: {
34948 // Move from MMX to XMM. Upper half of XMM should be 0.
34949 if (DemandedElts.countTrailingZeros() >= (NumElts / 2))
34950 Known.setAllZero();
34951 break;
34952 }
34953 }
34954
34955 // Handle target shuffles.
34956 // TODO - use resolveTargetShuffleInputs once we can limit recursive depth.
34957 if (isTargetShuffle(Opc)) {
34958 SmallVector<int, 64> Mask;
34959 SmallVector<SDValue, 2> Ops;
34960 if (getTargetShuffleMask(Op.getNode(), VT.getSimpleVT(), true, Ops, Mask)) {
34961 unsigned NumOps = Ops.size();
34962 unsigned NumElts = VT.getVectorNumElements();
34963 if (Mask.size() == NumElts) {
34964 SmallVector<APInt, 2> DemandedOps(NumOps, APInt(NumElts, 0));
34965 Known.Zero.setAllBits(); Known.One.setAllBits();
34966 for (unsigned i = 0; i != NumElts; ++i) {
34967 if (!DemandedElts[i])
34968 continue;
34969 int M = Mask[i];
34970 if (M == SM_SentinelUndef) {
34971 // For UNDEF elements, we don't know anything about the common state
34972 // of the shuffle result.
34973 Known.resetAll();
34974 break;
34975 }
34976 if (M == SM_SentinelZero) {
34977 Known.One.clearAllBits();
34978 continue;
34979 }
34980 assert(0 <= M && (unsigned)M < (NumOps * NumElts) &&(static_cast <bool> (0 <= M && (unsigned)M <
(NumOps * NumElts) && "Shuffle index out of range") ?
void (0) : __assert_fail ("0 <= M && (unsigned)M < (NumOps * NumElts) && \"Shuffle index out of range\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34981, __extension__ __PRETTY_FUNCTION__))
34981 "Shuffle index out of range")(static_cast <bool> (0 <= M && (unsigned)M <
(NumOps * NumElts) && "Shuffle index out of range") ?
void (0) : __assert_fail ("0 <= M && (unsigned)M < (NumOps * NumElts) && \"Shuffle index out of range\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 34981, __extension__ __PRETTY_FUNCTION__))
;
34982
34983 unsigned OpIdx = (unsigned)M / NumElts;
34984 unsigned EltIdx = (unsigned)M % NumElts;
34985 if (Ops[OpIdx].getValueType() != VT) {
34986 // TODO - handle target shuffle ops with different value types.
34987 Known.resetAll();
34988 break;
34989 }
34990 DemandedOps[OpIdx].setBit(EltIdx);
34991 }
34992 // Known bits are the values that are shared by every demanded element.
34993 for (unsigned i = 0; i != NumOps && !Known.isUnknown(); ++i) {
34994 if (!DemandedOps[i])
34995 continue;
34996 KnownBits Known2 =
34997 DAG.computeKnownBits(Ops[i], DemandedOps[i], Depth + 1);
34998 Known = KnownBits::commonBits(Known, Known2);
34999 }
35000 }
35001 }
35002 }
35003}
35004
35005unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
35006 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
35007 unsigned Depth) const {
35008 EVT VT = Op.getValueType();
35009 unsigned VTBits = VT.getScalarSizeInBits();
35010 unsigned Opcode = Op.getOpcode();
35011 switch (Opcode) {
35012 case X86ISD::SETCC_CARRY:
35013 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
35014 return VTBits;
35015
35016 case X86ISD::VTRUNC: {
35017 SDValue Src = Op.getOperand(0);
35018 MVT SrcVT = Src.getSimpleValueType();
35019 unsigned NumSrcBits = SrcVT.getScalarSizeInBits();
35020 assert(VTBits < NumSrcBits && "Illegal truncation input type")(static_cast <bool> (VTBits < NumSrcBits && "Illegal truncation input type"
) ? void (0) : __assert_fail ("VTBits < NumSrcBits && \"Illegal truncation input type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35020, __extension__ __PRETTY_FUNCTION__))
;
35021 APInt DemandedSrc = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
35022 unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
35023 if (Tmp > (NumSrcBits - VTBits))
35024 return Tmp - (NumSrcBits - VTBits);
35025 return 1;
35026 }
35027
35028 case X86ISD::PACKSS: {
35029 // PACKSS is just a truncation if the sign bits extend to the packed size.
35030 APInt DemandedLHS, DemandedRHS;
35031 getPackDemandedElts(Op.getValueType(), DemandedElts, DemandedLHS,
35032 DemandedRHS);
35033
35034 unsigned SrcBits = Op.getOperand(0).getScalarValueSizeInBits();
35035 unsigned Tmp0 = SrcBits, Tmp1 = SrcBits;
35036 if (!!DemandedLHS)
35037 Tmp0 = DAG.ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
35038 if (!!DemandedRHS)
35039 Tmp1 = DAG.ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
35040 unsigned Tmp = std::min(Tmp0, Tmp1);
35041 if (Tmp > (SrcBits - VTBits))
35042 return Tmp - (SrcBits - VTBits);
35043 return 1;
35044 }
35045
35046 case X86ISD::VBROADCAST: {
35047 SDValue Src = Op.getOperand(0);
35048 if (!Src.getSimpleValueType().isVector())
35049 return DAG.ComputeNumSignBits(Src, Depth + 1);
35050 break;
35051 }
35052
35053 case X86ISD::VSHLI: {
35054 SDValue Src = Op.getOperand(0);
35055 const APInt &ShiftVal = Op.getConstantOperandAPInt(1);
35056 if (ShiftVal.uge(VTBits))
35057 return VTBits; // Shifted all bits out --> zero.
35058 unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
35059 if (ShiftVal.uge(Tmp))
35060 return 1; // Shifted all sign bits out --> unknown.
35061 return Tmp - ShiftVal.getZExtValue();
35062 }
35063
35064 case X86ISD::VSRAI: {
35065 SDValue Src = Op.getOperand(0);
35066 APInt ShiftVal = Op.getConstantOperandAPInt(1);
35067 if (ShiftVal.uge(VTBits - 1))
35068 return VTBits; // Sign splat.
35069 unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
35070 ShiftVal += Tmp;
35071 return ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
35072 }
35073
35074 case X86ISD::FSETCC:
35075 // cmpss/cmpsd return zero/all-bits result values in the bottom element.
35076 if (VT == MVT::f32 || VT == MVT::f64 ||
35077 ((VT == MVT::v4f32 || VT == MVT::v2f64) && DemandedElts == 1))
35078 return VTBits;
35079 break;
35080
35081 case X86ISD::PCMPGT:
35082 case X86ISD::PCMPEQ:
35083 case X86ISD::CMPP:
35084 case X86ISD::VPCOM:
35085 case X86ISD::VPCOMU:
35086 // Vector compares return zero/all-bits result values.
35087 return VTBits;
35088
35089 case X86ISD::ANDNP: {
35090 unsigned Tmp0 =
35091 DAG.ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
35092 if (Tmp0 == 1) return 1; // Early out.
35093 unsigned Tmp1 =
35094 DAG.ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
35095 return std::min(Tmp0, Tmp1);
35096 }
35097
35098 case X86ISD::CMOV: {
35099 unsigned Tmp0 = DAG.ComputeNumSignBits(Op.getOperand(0), Depth+1);
35100 if (Tmp0 == 1) return 1; // Early out.
35101 unsigned Tmp1 = DAG.ComputeNumSignBits(Op.getOperand(1), Depth+1);
35102 return std::min(Tmp0, Tmp1);
35103 }
35104 }
35105
35106 // Handle target shuffles.
35107 // TODO - use resolveTargetShuffleInputs once we can limit recursive depth.
35108 if (isTargetShuffle(Opcode)) {
35109 SmallVector<int, 64> Mask;
35110 SmallVector<SDValue, 2> Ops;
35111 if (getTargetShuffleMask(Op.getNode(), VT.getSimpleVT(), true, Ops, Mask)) {
35112 unsigned NumOps = Ops.size();
35113 unsigned NumElts = VT.getVectorNumElements();
35114 if (Mask.size() == NumElts) {
35115 SmallVector<APInt, 2> DemandedOps(NumOps, APInt(NumElts, 0));
35116 for (unsigned i = 0; i != NumElts; ++i) {
35117 if (!DemandedElts[i])
35118 continue;
35119 int M = Mask[i];
35120 if (M == SM_SentinelUndef) {
35121 // For UNDEF elements, we don't know anything about the common state
35122 // of the shuffle result.
35123 return 1;
35124 } else if (M == SM_SentinelZero) {
35125 // Zero = all sign bits.
35126 continue;
35127 }
35128 assert(0 <= M && (unsigned)M < (NumOps * NumElts) &&(static_cast <bool> (0 <= M && (unsigned)M <
(NumOps * NumElts) && "Shuffle index out of range") ?
void (0) : __assert_fail ("0 <= M && (unsigned)M < (NumOps * NumElts) && \"Shuffle index out of range\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35129, __extension__ __PRETTY_FUNCTION__))
35129 "Shuffle index out of range")(static_cast <bool> (0 <= M && (unsigned)M <
(NumOps * NumElts) && "Shuffle index out of range") ?
void (0) : __assert_fail ("0 <= M && (unsigned)M < (NumOps * NumElts) && \"Shuffle index out of range\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35129, __extension__ __PRETTY_FUNCTION__))
;
35130
35131 unsigned OpIdx = (unsigned)M / NumElts;
35132 unsigned EltIdx = (unsigned)M % NumElts;
35133 if (Ops[OpIdx].getValueType() != VT) {
35134 // TODO - handle target shuffle ops with different value types.
35135 return 1;
35136 }
35137 DemandedOps[OpIdx].setBit(EltIdx);
35138 }
35139 unsigned Tmp0 = VTBits;
35140 for (unsigned i = 0; i != NumOps && Tmp0 > 1; ++i) {
35141 if (!DemandedOps[i])
35142 continue;
35143 unsigned Tmp1 =
35144 DAG.ComputeNumSignBits(Ops[i], DemandedOps[i], Depth + 1);
35145 Tmp0 = std::min(Tmp0, Tmp1);
35146 }
35147 return Tmp0;
35148 }
35149 }
35150 }
35151
35152 // Fallback case.
35153 return 1;
35154}
35155
35156SDValue X86TargetLowering::unwrapAddress(SDValue N) const {
35157 if (N->getOpcode() == X86ISD::Wrapper || N->getOpcode() == X86ISD::WrapperRIP)
35158 return N->getOperand(0);
35159 return N;
35160}
35161
35162// Helper to look for a normal load that can be narrowed into a vzload with the
35163// specified VT and memory VT. Returns SDValue() on failure.
35164static SDValue narrowLoadToVZLoad(LoadSDNode *LN, MVT MemVT, MVT VT,
35165 SelectionDAG &DAG) {
35166 // Can't if the load is volatile or atomic.
35167 if (!LN->isSimple())
35168 return SDValue();
35169
35170 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
35171 SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
35172 return DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, SDLoc(LN), Tys, Ops, MemVT,
35173 LN->getPointerInfo(), LN->getOriginalAlign(),
35174 LN->getMemOperand()->getFlags());
35175}
35176
35177// Attempt to match a combined shuffle mask against supported unary shuffle
35178// instructions.
35179// TODO: Investigate sharing more of this with shuffle lowering.
35180static bool matchUnaryShuffle(MVT MaskVT, ArrayRef<int> Mask,
35181 bool AllowFloatDomain, bool AllowIntDomain,
35182 SDValue &V1, const SDLoc &DL, SelectionDAG &DAG,
35183 const X86Subtarget &Subtarget, unsigned &Shuffle,
35184 MVT &SrcVT, MVT &DstVT) {
35185 unsigned NumMaskElts = Mask.size();
35186 unsigned MaskEltSize = MaskVT.getScalarSizeInBits();
35187
35188 // Match against a VZEXT_MOVL vXi32 zero-extending instruction.
35189 if (MaskEltSize == 32 && Mask[0] == 0) {
35190 if (isUndefOrZero(Mask[1]) && isUndefInRange(Mask, 2, NumMaskElts - 2)) {
35191 Shuffle = X86ISD::VZEXT_MOVL;
35192 SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
35193 return true;
35194 }
35195 if (V1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
35196 isUndefOrZeroInRange(Mask, 1, NumMaskElts - 1)) {
35197 Shuffle = X86ISD::VZEXT_MOVL;
35198 SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
35199 return true;
35200 }
35201 }
35202
35203 // Match against a ANY/ZERO_EXTEND_VECTOR_INREG instruction.
35204 // TODO: Add 512-bit vector support (split AVX512F and AVX512BW).
35205 if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSE41()) ||
35206 (MaskVT.is256BitVector() && Subtarget.hasInt256()))) {
35207 unsigned MaxScale = 64 / MaskEltSize;
35208 for (unsigned Scale = 2; Scale <= MaxScale; Scale *= 2) {
35209 bool MatchAny = true;
35210 bool MatchZero = true;
35211 unsigned NumDstElts = NumMaskElts / Scale;
35212 for (unsigned i = 0; i != NumDstElts && (MatchAny || MatchZero); ++i) {
35213 if (!isUndefOrEqual(Mask[i * Scale], (int)i)) {
35214 MatchAny = MatchZero = false;
35215 break;
35216 }
35217 MatchAny &= isUndefInRange(Mask, (i * Scale) + 1, Scale - 1);
35218 MatchZero &= isUndefOrZeroInRange(Mask, (i * Scale) + 1, Scale - 1);
35219 }
35220 if (MatchAny || MatchZero) {
35221 assert(MatchZero && "Failed to match zext but matched aext?")(static_cast <bool> (MatchZero && "Failed to match zext but matched aext?"
) ? void (0) : __assert_fail ("MatchZero && \"Failed to match zext but matched aext?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35221, __extension__ __PRETTY_FUNCTION__))
;
35222 unsigned SrcSize = std::max(128u, NumDstElts * MaskEltSize);
35223 MVT ScalarTy = MaskVT.isInteger() ? MaskVT.getScalarType() :
35224 MVT::getIntegerVT(MaskEltSize);
35225 SrcVT = MVT::getVectorVT(ScalarTy, SrcSize / MaskEltSize);
35226
35227 if (SrcVT.getSizeInBits() != MaskVT.getSizeInBits())
35228 V1 = extractSubVector(V1, 0, DAG, DL, SrcSize);
35229
35230 Shuffle = unsigned(MatchAny ? ISD::ANY_EXTEND : ISD::ZERO_EXTEND);
35231 if (SrcVT.getVectorNumElements() != NumDstElts)
35232 Shuffle = getOpcode_EXTEND_VECTOR_INREG(Shuffle);
35233
35234 DstVT = MVT::getIntegerVT(Scale * MaskEltSize);
35235 DstVT = MVT::getVectorVT(DstVT, NumDstElts);
35236 return true;
35237 }
35238 }
35239 }
35240
35241 // Match against a VZEXT_MOVL instruction, SSE1 only supports 32-bits (MOVSS).
35242 if (((MaskEltSize == 32) || (MaskEltSize == 64 && Subtarget.hasSSE2())) &&
35243 isUndefOrEqual(Mask[0], 0) &&
35244 isUndefOrZeroInRange(Mask, 1, NumMaskElts - 1)) {
35245 Shuffle = X86ISD::VZEXT_MOVL;
35246 SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
35247 return true;
35248 }
35249
35250 // Check if we have SSE3 which will let us use MOVDDUP etc. The
35251 // instructions are no slower than UNPCKLPD but has the option to
35252 // fold the input operand into even an unaligned memory load.
35253 if (MaskVT.is128BitVector() && Subtarget.hasSSE3() && AllowFloatDomain) {
35254 if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0}, V1)) {
35255 Shuffle = X86ISD::MOVDDUP;
35256 SrcVT = DstVT = MVT::v2f64;
35257 return true;
35258 }
35259 if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2}, V1)) {
35260 Shuffle = X86ISD::MOVSLDUP;
35261 SrcVT = DstVT = MVT::v4f32;
35262 return true;
35263 }
35264 if (isTargetShuffleEquivalent(MaskVT, Mask, {1, 1, 3, 3}, V1)) {
35265 Shuffle = X86ISD::MOVSHDUP;
35266 SrcVT = DstVT = MVT::v4f32;
35267 return true;
35268 }
35269 }
35270
35271 if (MaskVT.is256BitVector() && AllowFloatDomain) {
35272 assert(Subtarget.hasAVX() && "AVX required for 256-bit vector shuffles")(static_cast <bool> (Subtarget.hasAVX() && "AVX required for 256-bit vector shuffles"
) ? void (0) : __assert_fail ("Subtarget.hasAVX() && \"AVX required for 256-bit vector shuffles\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35272, __extension__ __PRETTY_FUNCTION__))
;
35273 if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2}, V1)) {
35274 Shuffle = X86ISD::MOVDDUP;
35275 SrcVT = DstVT = MVT::v4f64;
35276 return true;
35277 }
35278 if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2, 4, 4, 6, 6}, V1)) {
35279 Shuffle = X86ISD::MOVSLDUP;
35280 SrcVT = DstVT = MVT::v8f32;
35281 return true;
35282 }
35283 if (isTargetShuffleEquivalent(MaskVT, Mask, {1, 1, 3, 3, 5, 5, 7, 7}, V1)) {
35284 Shuffle = X86ISD::MOVSHDUP;
35285 SrcVT = DstVT = MVT::v8f32;
35286 return true;
35287 }
35288 }
35289
35290 if (MaskVT.is512BitVector() && AllowFloatDomain) {
35291 assert(Subtarget.hasAVX512() &&(static_cast <bool> (Subtarget.hasAVX512() && "AVX512 required for 512-bit vector shuffles"
) ? void (0) : __assert_fail ("Subtarget.hasAVX512() && \"AVX512 required for 512-bit vector shuffles\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35292, __extension__ __PRETTY_FUNCTION__))
35292 "AVX512 required for 512-bit vector shuffles")(static_cast <bool> (Subtarget.hasAVX512() && "AVX512 required for 512-bit vector shuffles"
) ? void (0) : __assert_fail ("Subtarget.hasAVX512() && \"AVX512 required for 512-bit vector shuffles\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35292, __extension__ __PRETTY_FUNCTION__))
;
35293 if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2, 4, 4, 6, 6}, V1)) {
35294 Shuffle = X86ISD::MOVDDUP;
35295 SrcVT = DstVT = MVT::v8f64;
35296 return true;
35297 }
35298 if (isTargetShuffleEquivalent(
35299 MaskVT, Mask,
35300 {0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14}, V1)) {
35301 Shuffle = X86ISD::MOVSLDUP;
35302 SrcVT = DstVT = MVT::v16f32;
35303 return true;
35304 }
35305 if (isTargetShuffleEquivalent(
35306 MaskVT, Mask,
35307 {1, 1, 3, 3, 5, 5, 7, 7, 9, 9, 11, 11, 13, 13, 15, 15}, V1)) {
35308 Shuffle = X86ISD::MOVSHDUP;
35309 SrcVT = DstVT = MVT::v16f32;
35310 return true;
35311 }
35312 }
35313
35314 return false;
35315}
35316
35317// Attempt to match a combined shuffle mask against supported unary immediate
35318// permute instructions.
35319// TODO: Investigate sharing more of this with shuffle lowering.
35320static bool matchUnaryPermuteShuffle(MVT MaskVT, ArrayRef<int> Mask,
35321 const APInt &Zeroable,
35322 bool AllowFloatDomain, bool AllowIntDomain,
35323 const X86Subtarget &Subtarget,
35324 unsigned &Shuffle, MVT &ShuffleVT,
35325 unsigned &PermuteImm) {
35326 unsigned NumMaskElts = Mask.size();
35327 unsigned InputSizeInBits = MaskVT.getSizeInBits();
35328 unsigned MaskScalarSizeInBits = InputSizeInBits / NumMaskElts;
35329 MVT MaskEltVT = MVT::getIntegerVT(MaskScalarSizeInBits);
35330 bool ContainsZeros = isAnyZero(Mask);
35331
35332 // Handle VPERMI/VPERMILPD vXi64/vXi64 patterns.
35333 if (!ContainsZeros && MaskScalarSizeInBits == 64) {
35334 // Check for lane crossing permutes.
35335 if (is128BitLaneCrossingShuffleMask(MaskEltVT, Mask)) {
35336 // PERMPD/PERMQ permutes within a 256-bit vector (AVX2+).
35337 if (Subtarget.hasAVX2() && MaskVT.is256BitVector()) {
35338 Shuffle = X86ISD::VPERMI;
35339 ShuffleVT = (AllowFloatDomain ? MVT::v4f64 : MVT::v4i64);
35340 PermuteImm = getV4X86ShuffleImm(Mask);
35341 return true;
35342 }
35343 if (Subtarget.hasAVX512() && MaskVT.is512BitVector()) {
35344 SmallVector<int, 4> RepeatedMask;
35345 if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask)) {
35346 Shuffle = X86ISD::VPERMI;
35347 ShuffleVT = (AllowFloatDomain ? MVT::v8f64 : MVT::v8i64);
35348 PermuteImm = getV4X86ShuffleImm(RepeatedMask);
35349 return true;
35350 }
35351 }
35352 } else if (AllowFloatDomain && Subtarget.hasAVX()) {
35353 // VPERMILPD can permute with a non-repeating shuffle.
35354 Shuffle = X86ISD::VPERMILPI;
35355 ShuffleVT = MVT::getVectorVT(MVT::f64, Mask.size());
35356 PermuteImm = 0;
35357 for (int i = 0, e = Mask.size(); i != e; ++i) {
35358 int M = Mask[i];
35359 if (M == SM_SentinelUndef)
35360 continue;
35361 assert(((M / 2) == (i / 2)) && "Out of range shuffle mask index")(static_cast <bool> (((M / 2) == (i / 2)) && "Out of range shuffle mask index"
) ? void (0) : __assert_fail ("((M / 2) == (i / 2)) && \"Out of range shuffle mask index\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35361, __extension__ __PRETTY_FUNCTION__))
;
35362 PermuteImm |= (M & 1) << i;
35363 }
35364 return true;
35365 }
35366 }
35367
35368 // Handle PSHUFD/VPERMILPI vXi32/vXf32 repeated patterns.
35369 // AVX introduced the VPERMILPD/VPERMILPS float permutes, before then we
35370 // had to use 2-input SHUFPD/SHUFPS shuffles (not handled here).
35371 if ((MaskScalarSizeInBits == 64 || MaskScalarSizeInBits == 32) &&
35372 !ContainsZeros && (AllowIntDomain || Subtarget.hasAVX())) {
35373 SmallVector<int, 4> RepeatedMask;
35374 if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
35375 // Narrow the repeated mask to create 32-bit element permutes.
35376 SmallVector<int, 4> WordMask = RepeatedMask;
35377 if (MaskScalarSizeInBits == 64)
35378 narrowShuffleMaskElts(2, RepeatedMask, WordMask);
35379
35380 Shuffle = (AllowIntDomain ? X86ISD::PSHUFD : X86ISD::VPERMILPI);
35381 ShuffleVT = (AllowIntDomain ? MVT::i32 : MVT::f32);
35382 ShuffleVT = MVT::getVectorVT(ShuffleVT, InputSizeInBits / 32);
35383 PermuteImm = getV4X86ShuffleImm(WordMask);
35384 return true;
35385 }
35386 }
35387
35388 // Handle PSHUFLW/PSHUFHW vXi16 repeated patterns.
35389 if (!ContainsZeros && AllowIntDomain && MaskScalarSizeInBits == 16 &&
35390 ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
35391 (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
35392 (MaskVT.is512BitVector() && Subtarget.hasBWI()))) {
35393 SmallVector<int, 4> RepeatedMask;
35394 if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
35395 ArrayRef<int> LoMask(RepeatedMask.data() + 0, 4);
35396 ArrayRef<int> HiMask(RepeatedMask.data() + 4, 4);
35397
35398 // PSHUFLW: permute lower 4 elements only.
35399 if (isUndefOrInRange(LoMask, 0, 4) &&
35400 isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
35401 Shuffle = X86ISD::PSHUFLW;
35402 ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
35403 PermuteImm = getV4X86ShuffleImm(LoMask);
35404 return true;
35405 }
35406
35407 // PSHUFHW: permute upper 4 elements only.
35408 if (isUndefOrInRange(HiMask, 4, 8) &&
35409 isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
35410 // Offset the HiMask so that we can create the shuffle immediate.
35411 int OffsetHiMask[4];
35412 for (int i = 0; i != 4; ++i)
35413 OffsetHiMask[i] = (HiMask[i] < 0 ? HiMask[i] : HiMask[i] - 4);
35414
35415 Shuffle = X86ISD::PSHUFHW;
35416 ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
35417 PermuteImm = getV4X86ShuffleImm(OffsetHiMask);
35418 return true;
35419 }
35420 }
35421 }
35422
35423 // Attempt to match against byte/bit shifts.
35424 if (AllowIntDomain &&
35425 ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
35426 (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
35427 (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
35428 int ShiftAmt = matchShuffleAsShift(ShuffleVT, Shuffle, MaskScalarSizeInBits,
35429 Mask, 0, Zeroable, Subtarget);
35430 if (0 < ShiftAmt && (!ShuffleVT.is512BitVector() || Subtarget.hasBWI() ||
35431 32 <= ShuffleVT.getScalarSizeInBits())) {
35432 PermuteImm = (unsigned)ShiftAmt;
35433 return true;
35434 }
35435 }
35436
35437 // Attempt to match against bit rotates.
35438 if (!ContainsZeros && AllowIntDomain && MaskScalarSizeInBits < 64 &&
35439 ((MaskVT.is128BitVector() && Subtarget.hasXOP()) ||
35440 Subtarget.hasAVX512())) {
35441 int RotateAmt = matchShuffleAsBitRotate(ShuffleVT, MaskScalarSizeInBits,
35442 Subtarget, Mask);
35443 if (0 < RotateAmt) {
35444 Shuffle = X86ISD::VROTLI;
35445 PermuteImm = (unsigned)RotateAmt;
35446 return true;
35447 }
35448 }
35449
35450 return false;
35451}
35452
35453// Attempt to match a combined unary shuffle mask against supported binary
35454// shuffle instructions.
35455// TODO: Investigate sharing more of this with shuffle lowering.
35456static bool matchBinaryShuffle(MVT MaskVT, ArrayRef<int> Mask,
35457 bool AllowFloatDomain, bool AllowIntDomain,
35458 SDValue &V1, SDValue &V2, const SDLoc &DL,
35459 SelectionDAG &DAG, const X86Subtarget &Subtarget,
35460 unsigned &Shuffle, MVT &SrcVT, MVT &DstVT,
35461 bool IsUnary) {
35462 unsigned NumMaskElts = Mask.size();
35463 unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
35464
35465 if (MaskVT.is128BitVector()) {
35466 if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0}) && AllowFloatDomain) {
35467 V2 = V1;
35468 V1 = (SM_SentinelUndef == Mask[0] ? DAG.getUNDEF(MVT::v4f32) : V1);
35469 Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKL : X86ISD::MOVLHPS;
35470 SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
35471 return true;
35472 }
35473 if (isTargetShuffleEquivalent(MaskVT, Mask, {1, 1}) && AllowFloatDomain) {
35474 V2 = V1;
35475 Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKH : X86ISD::MOVHLPS;
35476 SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
35477 return true;
35478 }
35479 if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 3}) &&
35480 Subtarget.hasSSE2() && (AllowFloatDomain || !Subtarget.hasSSE41())) {
35481 std::swap(V1, V2);
35482 Shuffle = X86ISD::MOVSD;
35483 SrcVT = DstVT = MVT::v2f64;
35484 return true;
35485 }
35486 if (isTargetShuffleEquivalent(MaskVT, Mask, {4, 1, 2, 3}) &&
35487 (AllowFloatDomain || !Subtarget.hasSSE41())) {
35488 Shuffle = X86ISD::MOVSS;
35489 SrcVT = DstVT = MVT::v4f32;
35490 return true;
35491 }
35492 }
35493
35494 // Attempt to match against either an unary or binary PACKSS/PACKUS shuffle.
35495 if (((MaskVT == MVT::v8i16 || MaskVT == MVT::v16i8) && Subtarget.hasSSE2()) ||
35496 ((MaskVT == MVT::v16i16 || MaskVT == MVT::v32i8) && Subtarget.hasInt256()) ||
35497 ((MaskVT == MVT::v32i16 || MaskVT == MVT::v64i8) && Subtarget.hasBWI())) {
35498 if (matchShuffleWithPACK(MaskVT, SrcVT, V1, V2, Shuffle, Mask, DAG,
35499 Subtarget)) {
35500 DstVT = MaskVT;
35501 return true;
35502 }
35503 }
35504
35505 // Attempt to match against either a unary or binary UNPCKL/UNPCKH shuffle.
35506 if ((MaskVT == MVT::v4f32 && Subtarget.hasSSE1()) ||
35507 (MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
35508 (MaskVT.is256BitVector() && 32 <= EltSizeInBits && Subtarget.hasAVX()) ||
35509 (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
35510 (MaskVT.is512BitVector() && Subtarget.hasAVX512())) {
35511 if (matchShuffleWithUNPCK(MaskVT, V1, V2, Shuffle, IsUnary, Mask, DL, DAG,
35512 Subtarget)) {
35513 SrcVT = DstVT = MaskVT;
35514 if (MaskVT.is256BitVector() && !Subtarget.hasAVX2())
35515 SrcVT = DstVT = (32 == EltSizeInBits ? MVT::v8f32 : MVT::v4f64);
35516 return true;
35517 }
35518 }
35519
35520 // Attempt to match against a OR if we're performing a blend shuffle and the
35521 // non-blended source element is zero in each case.
35522 if ((EltSizeInBits % V1.getScalarValueSizeInBits()) == 0 &&
35523 (EltSizeInBits % V2.getScalarValueSizeInBits()) == 0) {
35524 bool IsBlend = true;
35525 unsigned NumV1Elts = V1.getValueType().getVectorNumElements();
35526 unsigned NumV2Elts = V2.getValueType().getVectorNumElements();
35527 unsigned Scale1 = NumV1Elts / NumMaskElts;
35528 unsigned Scale2 = NumV2Elts / NumMaskElts;
35529 APInt DemandedZeroV1 = APInt::getNullValue(NumV1Elts);
35530 APInt DemandedZeroV2 = APInt::getNullValue(NumV2Elts);
35531 for (unsigned i = 0; i != NumMaskElts; ++i) {
35532 int M = Mask[i];
35533 if (M == SM_SentinelUndef)
35534 continue;
35535 if (M == SM_SentinelZero) {
35536 DemandedZeroV1.setBits(i * Scale1, (i + 1) * Scale1);
35537 DemandedZeroV2.setBits(i * Scale2, (i + 1) * Scale2);
35538 continue;
35539 }
35540 if (M == (int)i) {
35541 DemandedZeroV2.setBits(i * Scale2, (i + 1) * Scale2);
35542 continue;
35543 }
35544 if (M == (int)(i + NumMaskElts)) {
35545 DemandedZeroV1.setBits(i * Scale1, (i + 1) * Scale1);
35546 continue;
35547 }
35548 IsBlend = false;
35549 break;
35550 }
35551 if (IsBlend &&
35552 DAG.computeKnownBits(V1, DemandedZeroV1).isZero() &&
35553 DAG.computeKnownBits(V2, DemandedZeroV2).isZero()) {
35554 Shuffle = ISD::OR;
35555 SrcVT = DstVT = MaskVT.changeTypeToInteger();
35556 return true;
35557 }
35558 }
35559
35560 return false;
35561}
35562
35563static bool matchBinaryPermuteShuffle(
35564 MVT MaskVT, ArrayRef<int> Mask, const APInt &Zeroable,
35565 bool AllowFloatDomain, bool AllowIntDomain, SDValue &V1, SDValue &V2,
35566 const SDLoc &DL, SelectionDAG &DAG, const X86Subtarget &Subtarget,
35567 unsigned &Shuffle, MVT &ShuffleVT, unsigned &PermuteImm) {
35568 unsigned NumMaskElts = Mask.size();
35569 unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
35570
35571 // Attempt to match against VALIGND/VALIGNQ rotate.
35572 if (AllowIntDomain && (EltSizeInBits == 64 || EltSizeInBits == 32) &&
35573 ((MaskVT.is128BitVector() && Subtarget.hasVLX()) ||
35574 (MaskVT.is256BitVector() && Subtarget.hasVLX()) ||
35575 (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
35576 if (!isAnyZero(Mask)) {
35577 int Rotation = matchShuffleAsElementRotate(V1, V2, Mask);
35578 if (0 < Rotation) {
35579 Shuffle = X86ISD::VALIGN;
35580 if (EltSizeInBits == 64)
35581 ShuffleVT = MVT::getVectorVT(MVT::i64, MaskVT.getSizeInBits() / 64);
35582 else
35583 ShuffleVT = MVT::getVectorVT(MVT::i32, MaskVT.getSizeInBits() / 32);
35584 PermuteImm = Rotation;
35585 return true;
35586 }
35587 }
35588 }
35589
35590 // Attempt to match against PALIGNR byte rotate.
35591 if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSSE3()) ||
35592 (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
35593 (MaskVT.is512BitVector() && Subtarget.hasBWI()))) {
35594 int ByteRotation = matchShuffleAsByteRotate(MaskVT, V1, V2, Mask);
35595 if (0 < ByteRotation) {
35596 Shuffle = X86ISD::PALIGNR;
35597 ShuffleVT = MVT::getVectorVT(MVT::i8, MaskVT.getSizeInBits() / 8);
35598 PermuteImm = ByteRotation;
35599 return true;
35600 }
35601 }
35602
35603 // Attempt to combine to X86ISD::BLENDI.
35604 if ((NumMaskElts <= 8 && ((Subtarget.hasSSE41() && MaskVT.is128BitVector()) ||
35605 (Subtarget.hasAVX() && MaskVT.is256BitVector()))) ||
35606 (MaskVT == MVT::v16i16 && Subtarget.hasAVX2())) {
35607 uint64_t BlendMask = 0;
35608 bool ForceV1Zero = false, ForceV2Zero = false;
35609 SmallVector<int, 8> TargetMask(Mask.begin(), Mask.end());
35610 if (matchShuffleAsBlend(V1, V2, TargetMask, Zeroable, ForceV1Zero,
35611 ForceV2Zero, BlendMask)) {
35612 if (MaskVT == MVT::v16i16) {
35613 // We can only use v16i16 PBLENDW if the lanes are repeated.
35614 SmallVector<int, 8> RepeatedMask;
35615 if (isRepeatedTargetShuffleMask(128, MaskVT, TargetMask,
35616 RepeatedMask)) {
35617 assert(RepeatedMask.size() == 8 &&(static_cast <bool> (RepeatedMask.size() == 8 &&
"Repeated mask size doesn't match!") ? void (0) : __assert_fail
("RepeatedMask.size() == 8 && \"Repeated mask size doesn't match!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35618, __extension__ __PRETTY_FUNCTION__))
35618 "Repeated mask size doesn't match!")(static_cast <bool> (RepeatedMask.size() == 8 &&
"Repeated mask size doesn't match!") ? void (0) : __assert_fail
("RepeatedMask.size() == 8 && \"Repeated mask size doesn't match!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35618, __extension__ __PRETTY_FUNCTION__))
;
35619 PermuteImm = 0;
35620 for (int i = 0; i < 8; ++i)
35621 if (RepeatedMask[i] >= 8)
35622 PermuteImm |= 1 << i;
35623 V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
35624 V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
35625 Shuffle = X86ISD::BLENDI;
35626 ShuffleVT = MaskVT;
35627 return true;
35628 }
35629 } else {
35630 V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
35631 V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
35632 PermuteImm = (unsigned)BlendMask;
35633 Shuffle = X86ISD::BLENDI;
35634 ShuffleVT = MaskVT;
35635 return true;
35636 }
35637 }
35638 }
35639
35640 // Attempt to combine to INSERTPS, but only if it has elements that need to
35641 // be set to zero.
35642 if (AllowFloatDomain && EltSizeInBits == 32 && Subtarget.hasSSE41() &&
35643 MaskVT.is128BitVector() && isAnyZero(Mask) &&
35644 matchShuffleAsInsertPS(V1, V2, PermuteImm, Zeroable, Mask, DAG)) {
35645 Shuffle = X86ISD::INSERTPS;
35646 ShuffleVT = MVT::v4f32;
35647 return true;
35648 }
35649
35650 // Attempt to combine to SHUFPD.
35651 if (AllowFloatDomain && EltSizeInBits == 64 &&
35652 ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
35653 (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
35654 (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
35655 bool ForceV1Zero = false, ForceV2Zero = false;
35656 if (matchShuffleWithSHUFPD(MaskVT, V1, V2, ForceV1Zero, ForceV2Zero,
35657 PermuteImm, Mask, Zeroable)) {
35658 V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
35659 V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
35660 Shuffle = X86ISD::SHUFP;
35661 ShuffleVT = MVT::getVectorVT(MVT::f64, MaskVT.getSizeInBits() / 64);
35662 return true;
35663 }
35664 }
35665
35666 // Attempt to combine to SHUFPS.
35667 if (AllowFloatDomain && EltSizeInBits == 32 &&
35668 ((MaskVT.is128BitVector() && Subtarget.hasSSE1()) ||
35669 (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
35670 (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
35671 SmallVector<int, 4> RepeatedMask;
35672 if (isRepeatedTargetShuffleMask(128, MaskVT, Mask, RepeatedMask)) {
35673 // Match each half of the repeated mask, to determine if its just
35674 // referencing one of the vectors, is zeroable or entirely undef.
35675 auto MatchHalf = [&](unsigned Offset, int &S0, int &S1) {
35676 int M0 = RepeatedMask[Offset];
35677 int M1 = RepeatedMask[Offset + 1];
35678
35679 if (isUndefInRange(RepeatedMask, Offset, 2)) {
35680 return DAG.getUNDEF(MaskVT);
35681 } else if (isUndefOrZeroInRange(RepeatedMask, Offset, 2)) {
35682 S0 = (SM_SentinelUndef == M0 ? -1 : 0);
35683 S1 = (SM_SentinelUndef == M1 ? -1 : 1);
35684 return getZeroVector(MaskVT, Subtarget, DAG, DL);
35685 } else if (isUndefOrInRange(M0, 0, 4) && isUndefOrInRange(M1, 0, 4)) {
35686 S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
35687 S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
35688 return V1;
35689 } else if (isUndefOrInRange(M0, 4, 8) && isUndefOrInRange(M1, 4, 8)) {
35690 S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
35691 S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
35692 return V2;
35693 }
35694
35695 return SDValue();
35696 };
35697
35698 int ShufMask[4] = {-1, -1, -1, -1};
35699 SDValue Lo = MatchHalf(0, ShufMask[0], ShufMask[1]);
35700 SDValue Hi = MatchHalf(2, ShufMask[2], ShufMask[3]);
35701
35702 if (Lo && Hi) {
35703 V1 = Lo;
35704 V2 = Hi;
35705 Shuffle = X86ISD::SHUFP;
35706 ShuffleVT = MVT::getVectorVT(MVT::f32, MaskVT.getSizeInBits() / 32);
35707 PermuteImm = getV4X86ShuffleImm(ShufMask);
35708 return true;
35709 }
35710 }
35711 }
35712
35713 // Attempt to combine to INSERTPS more generally if X86ISD::SHUFP failed.
35714 if (AllowFloatDomain && EltSizeInBits == 32 && Subtarget.hasSSE41() &&
35715 MaskVT.is128BitVector() &&
35716 matchShuffleAsInsertPS(V1, V2, PermuteImm, Zeroable, Mask, DAG)) {
35717 Shuffle = X86ISD::INSERTPS;
35718 ShuffleVT = MVT::v4f32;
35719 return true;
35720 }
35721
35722 return false;
35723}
35724
35725static SDValue combineX86ShuffleChainWithExtract(
35726 ArrayRef<SDValue> Inputs, SDValue Root, ArrayRef<int> BaseMask, int Depth,
35727 bool HasVariableMask, bool AllowVariableCrossLaneMask,
35728 bool AllowVariablePerLaneMask, SelectionDAG &DAG,
35729 const X86Subtarget &Subtarget);
35730
35731/// Combine an arbitrary chain of shuffles into a single instruction if
35732/// possible.
35733///
35734/// This is the leaf of the recursive combine below. When we have found some
35735/// chain of single-use x86 shuffle instructions and accumulated the combined
35736/// shuffle mask represented by them, this will try to pattern match that mask
35737/// into either a single instruction if there is a special purpose instruction
35738/// for this operation, or into a PSHUFB instruction which is a fully general
35739/// instruction but should only be used to replace chains over a certain depth.
35740static SDValue combineX86ShuffleChain(ArrayRef<SDValue> Inputs, SDValue Root,
35741 ArrayRef<int> BaseMask, int Depth,
35742 bool HasVariableMask,
35743 bool AllowVariableCrossLaneMask,
35744 bool AllowVariablePerLaneMask,
35745 SelectionDAG &DAG,
35746 const X86Subtarget &Subtarget) {
35747 assert(!BaseMask.empty() && "Cannot combine an empty shuffle mask!")(static_cast <bool> (!BaseMask.empty() && "Cannot combine an empty shuffle mask!"
) ? void (0) : __assert_fail ("!BaseMask.empty() && \"Cannot combine an empty shuffle mask!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35747, __extension__ __PRETTY_FUNCTION__))
;
35748 assert((Inputs.size() == 1 || Inputs.size() == 2) &&(static_cast <bool> ((Inputs.size() == 1 || Inputs.size
() == 2) && "Unexpected number of shuffle inputs!") ?
void (0) : __assert_fail ("(Inputs.size() == 1 || Inputs.size() == 2) && \"Unexpected number of shuffle inputs!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35749, __extension__ __PRETTY_FUNCTION__))
35749 "Unexpected number of shuffle inputs!")(static_cast <bool> ((Inputs.size() == 1 || Inputs.size
() == 2) && "Unexpected number of shuffle inputs!") ?
void (0) : __assert_fail ("(Inputs.size() == 1 || Inputs.size() == 2) && \"Unexpected number of shuffle inputs!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35749, __extension__ __PRETTY_FUNCTION__))
;
35750
35751 MVT RootVT = Root.getSimpleValueType();
35752 unsigned RootSizeInBits = RootVT.getSizeInBits();
35753 unsigned NumRootElts = RootVT.getVectorNumElements();
35754
35755 // Canonicalize shuffle input op to the requested type.
35756 // TODO: Support cases where Op is smaller than VT.
35757 auto CanonicalizeShuffleInput = [&](MVT VT, SDValue Op) {
35758 return DAG.getBitcast(VT, Op);
35759 };
35760
35761 // Find the inputs that enter the chain. Note that multiple uses are OK
35762 // here, we're not going to remove the operands we find.
35763 bool UnaryShuffle = (Inputs.size() == 1);
35764 SDValue V1 = peekThroughBitcasts(Inputs[0]);
35765 SDValue V2 = (UnaryShuffle ? DAG.getUNDEF(V1.getValueType())
35766 : peekThroughBitcasts(Inputs[1]));
35767
35768 MVT VT1 = V1.getSimpleValueType();
35769 MVT VT2 = V2.getSimpleValueType();
35770 assert(VT1.getSizeInBits() == RootSizeInBits &&(static_cast <bool> (VT1.getSizeInBits() == RootSizeInBits
&& VT2.getSizeInBits() == RootSizeInBits && "Vector size mismatch"
) ? void (0) : __assert_fail ("VT1.getSizeInBits() == RootSizeInBits && VT2.getSizeInBits() == RootSizeInBits && \"Vector size mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35771, __extension__ __PRETTY_FUNCTION__))
35771 VT2.getSizeInBits() == RootSizeInBits && "Vector size mismatch")(static_cast <bool> (VT1.getSizeInBits() == RootSizeInBits
&& VT2.getSizeInBits() == RootSizeInBits && "Vector size mismatch"
) ? void (0) : __assert_fail ("VT1.getSizeInBits() == RootSizeInBits && VT2.getSizeInBits() == RootSizeInBits && \"Vector size mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35771, __extension__ __PRETTY_FUNCTION__))
;
35772
35773 SDLoc DL(Root);
35774 SDValue Res;
35775
35776 unsigned NumBaseMaskElts = BaseMask.size();
35777 if (NumBaseMaskElts == 1) {
35778 assert(BaseMask[0] == 0 && "Invalid shuffle index found!")(static_cast <bool> (BaseMask[0] == 0 && "Invalid shuffle index found!"
) ? void (0) : __assert_fail ("BaseMask[0] == 0 && \"Invalid shuffle index found!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35778, __extension__ __PRETTY_FUNCTION__))
;
35779 return CanonicalizeShuffleInput(RootVT, V1);
35780 }
35781
35782 bool OptForSize = DAG.shouldOptForSize();
35783 unsigned BaseMaskEltSizeInBits = RootSizeInBits / NumBaseMaskElts;
35784 bool FloatDomain = VT1.isFloatingPoint() || VT2.isFloatingPoint() ||
35785 (RootVT.isFloatingPoint() && Depth >= 1) ||
35786 (RootVT.is256BitVector() && !Subtarget.hasAVX2());
35787
35788 // Don't combine if we are a AVX512/EVEX target and the mask element size
35789 // is different from the root element size - this would prevent writemasks
35790 // from being reused.
35791 bool IsMaskedShuffle = false;
35792 if (RootSizeInBits == 512 || (Subtarget.hasVLX() && RootSizeInBits >= 128)) {
35793 if (Root.hasOneUse() && Root->use_begin()->getOpcode() == ISD::VSELECT &&
35794 Root->use_begin()->getOperand(0).getScalarValueSizeInBits() == 1) {
35795 IsMaskedShuffle = true;
35796 }
35797 }
35798
35799 // If we are shuffling a broadcast (and not introducing zeros) then
35800 // we can just use the broadcast directly. This works for smaller broadcast
35801 // elements as well as they already repeat across each mask element
35802 if (UnaryShuffle && isTargetShuffleSplat(V1) && !isAnyZero(BaseMask) &&
35803 (BaseMaskEltSizeInBits % V1.getScalarValueSizeInBits()) == 0 &&
35804 V1.getValueSizeInBits() >= RootSizeInBits) {
35805 return CanonicalizeShuffleInput(RootVT, V1);
35806 }
35807
35808 // See if the shuffle is a hidden identity shuffle - repeated args in HOPs
35809 // etc. can be simplified.
35810 if (VT1 == VT2 && VT1.getSizeInBits() == RootSizeInBits) {
35811 SmallVector<int> ScaledMask, IdentityMask;
35812 unsigned NumElts = VT1.getVectorNumElements();
35813 if (BaseMask.size() <= NumElts &&
35814 scaleShuffleElements(BaseMask, NumElts, ScaledMask)) {
35815 for (unsigned i = 0; i != NumElts; ++i)
35816 IdentityMask.push_back(i);
35817 if (isTargetShuffleEquivalent(RootVT, ScaledMask, IdentityMask, V1, V2))
35818 return CanonicalizeShuffleInput(RootVT, V1);
35819 }
35820 }
35821
35822 // Handle 128/256-bit lane shuffles of 512-bit vectors.
35823 if (RootVT.is512BitVector() &&
35824 (NumBaseMaskElts == 2 || NumBaseMaskElts == 4)) {
35825 // If the upper subvectors are zeroable, then an extract+insert is more
35826 // optimal than using X86ISD::SHUF128. The insertion is free, even if it has
35827 // to zero the upper subvectors.
35828 if (isUndefOrZeroInRange(BaseMask, 1, NumBaseMaskElts - 1)) {
35829 if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
35830 return SDValue(); // Nothing to do!
35831 assert(isInRange(BaseMask[0], 0, NumBaseMaskElts) &&(static_cast <bool> (isInRange(BaseMask[0], 0, NumBaseMaskElts
) && "Unexpected lane shuffle") ? void (0) : __assert_fail
("isInRange(BaseMask[0], 0, NumBaseMaskElts) && \"Unexpected lane shuffle\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35832, __extension__ __PRETTY_FUNCTION__))
35832 "Unexpected lane shuffle")(static_cast <bool> (isInRange(BaseMask[0], 0, NumBaseMaskElts
) && "Unexpected lane shuffle") ? void (0) : __assert_fail
("isInRange(BaseMask[0], 0, NumBaseMaskElts) && \"Unexpected lane shuffle\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35832, __extension__ __PRETTY_FUNCTION__))
;
35833 Res = CanonicalizeShuffleInput(RootVT, V1);
35834 unsigned SubIdx = BaseMask[0] * (NumRootElts / NumBaseMaskElts);
35835 bool UseZero = isAnyZero(BaseMask);
35836 Res = extractSubVector(Res, SubIdx, DAG, DL, BaseMaskEltSizeInBits);
35837 return widenSubVector(Res, UseZero, Subtarget, DAG, DL, RootSizeInBits);
35838 }
35839
35840 // Narrow shuffle mask to v4x128.
35841 SmallVector<int, 4> Mask;
35842 assert((BaseMaskEltSizeInBits % 128) == 0 && "Illegal mask size")(static_cast <bool> ((BaseMaskEltSizeInBits % 128) == 0
&& "Illegal mask size") ? void (0) : __assert_fail (
"(BaseMaskEltSizeInBits % 128) == 0 && \"Illegal mask size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35842, __extension__ __PRETTY_FUNCTION__))
;
35843 narrowShuffleMaskElts(BaseMaskEltSizeInBits / 128, BaseMask, Mask);
35844
35845 // Try to lower to vshuf64x2/vshuf32x4.
35846 auto MatchSHUF128 = [&](MVT ShuffleVT, const SDLoc &DL, ArrayRef<int> Mask,
35847 SDValue V1, SDValue V2, SelectionDAG &DAG) {
35848 unsigned PermMask = 0;
35849 // Insure elements came from the same Op.
35850 SDValue Ops[2] = {DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT)};
35851 for (int i = 0; i < 4; ++i) {
35852 assert(Mask[i] >= -1 && "Illegal shuffle sentinel value")(static_cast <bool> (Mask[i] >= -1 && "Illegal shuffle sentinel value"
) ? void (0) : __assert_fail ("Mask[i] >= -1 && \"Illegal shuffle sentinel value\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35852, __extension__ __PRETTY_FUNCTION__))
;
35853 if (Mask[i] < 0)
35854 continue;
35855
35856 SDValue Op = Mask[i] >= 4 ? V2 : V1;
35857 unsigned OpIndex = i / 2;
35858 if (Ops[OpIndex].isUndef())
35859 Ops[OpIndex] = Op;
35860 else if (Ops[OpIndex] != Op)
35861 return SDValue();
35862
35863 // Convert the 128-bit shuffle mask selection values into 128-bit
35864 // selection bits defined by a vshuf64x2 instruction's immediate control
35865 // byte.
35866 PermMask |= (Mask[i] % 4) << (i * 2);
35867 }
35868
35869 return DAG.getNode(X86ISD::SHUF128, DL, ShuffleVT,
35870 CanonicalizeShuffleInput(ShuffleVT, Ops[0]),
35871 CanonicalizeShuffleInput(ShuffleVT, Ops[1]),
35872 DAG.getTargetConstant(PermMask, DL, MVT::i8));
35873 };
35874
35875 // FIXME: Is there a better way to do this? is256BitLaneRepeatedShuffleMask
35876 // doesn't work because our mask is for 128 bits and we don't have an MVT
35877 // to match that.
35878 bool PreferPERMQ =
35879 UnaryShuffle && isUndefOrInRange(Mask[0], 0, 2) &&
35880 isUndefOrInRange(Mask[1], 0, 2) && isUndefOrInRange(Mask[2], 2, 4) &&
35881 isUndefOrInRange(Mask[3], 2, 4) &&
35882 (Mask[0] < 0 || Mask[2] < 0 || Mask[0] == (Mask[2] % 2)) &&
35883 (Mask[1] < 0 || Mask[3] < 0 || Mask[1] == (Mask[3] % 2));
35884
35885 if (!isAnyZero(Mask) && !PreferPERMQ) {
35886 if (Depth == 0 && Root.getOpcode() == X86ISD::SHUF128)
35887 return SDValue(); // Nothing to do!
35888 MVT ShuffleVT = (FloatDomain ? MVT::v8f64 : MVT::v8i64);
35889 if (SDValue V = MatchSHUF128(ShuffleVT, DL, Mask, V1, V2, DAG))
35890 return DAG.getBitcast(RootVT, V);
35891 }
35892 }
35893
35894 // Handle 128-bit lane shuffles of 256-bit vectors.
35895 if (RootVT.is256BitVector() && NumBaseMaskElts == 2) {
35896 // If the upper half is zeroable, then an extract+insert is more optimal
35897 // than using X86ISD::VPERM2X128. The insertion is free, even if it has to
35898 // zero the upper half.
35899 if (isUndefOrZero(BaseMask[1])) {
35900 if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
35901 return SDValue(); // Nothing to do!
35902 assert(isInRange(BaseMask[0], 0, 2) && "Unexpected lane shuffle")(static_cast <bool> (isInRange(BaseMask[0], 0, 2) &&
"Unexpected lane shuffle") ? void (0) : __assert_fail ("isInRange(BaseMask[0], 0, 2) && \"Unexpected lane shuffle\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35902, __extension__ __PRETTY_FUNCTION__))
;
35903 Res = CanonicalizeShuffleInput(RootVT, V1);
35904 Res = extract128BitVector(Res, BaseMask[0] * (NumRootElts / 2), DAG, DL);
35905 return widenSubVector(Res, BaseMask[1] == SM_SentinelZero, Subtarget, DAG,
35906 DL, 256);
35907 }
35908
35909 // If we're splatting the low subvector, an insert-subvector 'concat'
35910 // pattern is quicker than VPERM2X128.
35911 // TODO: Add AVX2 support instead of VPERMQ/VPERMPD.
35912 if (BaseMask[0] == 0 && BaseMask[1] == 0 && !Subtarget.hasAVX2()) {
35913 if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
35914 return SDValue(); // Nothing to do!
35915 Res = CanonicalizeShuffleInput(RootVT, V1);
35916 Res = extractSubVector(Res, 0, DAG, DL, 128);
35917 return concatSubVectors(Res, Res, DAG, DL);
35918 }
35919
35920 if (Depth == 0 && Root.getOpcode() == X86ISD::VPERM2X128)
35921 return SDValue(); // Nothing to do!
35922
35923 // If we have AVX2, prefer to use VPERMQ/VPERMPD for unary shuffles unless
35924 // we need to use the zeroing feature.
35925 // Prefer blends for sequential shuffles unless we are optimizing for size.
35926 if (UnaryShuffle &&
35927 !(Subtarget.hasAVX2() && isUndefOrInRange(BaseMask, 0, 2)) &&
35928 (OptForSize || !isSequentialOrUndefOrZeroInRange(BaseMask, 0, 2, 0))) {
35929 unsigned PermMask = 0;
35930 PermMask |= ((BaseMask[0] < 0 ? 0x8 : (BaseMask[0] & 1)) << 0);
35931 PermMask |= ((BaseMask[1] < 0 ? 0x8 : (BaseMask[1] & 1)) << 4);
35932 return DAG.getNode(
35933 X86ISD::VPERM2X128, DL, RootVT, CanonicalizeShuffleInput(RootVT, V1),
35934 DAG.getUNDEF(RootVT), DAG.getTargetConstant(PermMask, DL, MVT::i8));
35935 }
35936
35937 if (Depth == 0 && Root.getOpcode() == X86ISD::SHUF128)
35938 return SDValue(); // Nothing to do!
35939
35940 // TODO - handle AVX512VL cases with X86ISD::SHUF128.
35941 if (!UnaryShuffle && !IsMaskedShuffle) {
35942 assert(llvm::all_of(BaseMask, [](int M) { return 0 <= M && M < 4; }) &&(static_cast <bool> (llvm::all_of(BaseMask, [](int M) {
return 0 <= M && M < 4; }) && "Unexpected shuffle sentinel value"
) ? void (0) : __assert_fail ("llvm::all_of(BaseMask, [](int M) { return 0 <= M && M < 4; }) && \"Unexpected shuffle sentinel value\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35943, __extension__ __PRETTY_FUNCTION__))
35943 "Unexpected shuffle sentinel value")(static_cast <bool> (llvm::all_of(BaseMask, [](int M) {
return 0 <= M && M < 4; }) && "Unexpected shuffle sentinel value"
) ? void (0) : __assert_fail ("llvm::all_of(BaseMask, [](int M) { return 0 <= M && M < 4; }) && \"Unexpected shuffle sentinel value\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35943, __extension__ __PRETTY_FUNCTION__))
;
35944 // Prefer blends to X86ISD::VPERM2X128.
35945 if (!((BaseMask[0] == 0 && BaseMask[1] == 3) ||
35946 (BaseMask[0] == 2 && BaseMask[1] == 1))) {
35947 unsigned PermMask = 0;
35948 PermMask |= ((BaseMask[0] & 3) << 0);
35949 PermMask |= ((BaseMask[1] & 3) << 4);
35950 SDValue LHS = isInRange(BaseMask[0], 0, 2) ? V1 : V2;
35951 SDValue RHS = isInRange(BaseMask[1], 0, 2) ? V1 : V2;
35952 return DAG.getNode(X86ISD::VPERM2X128, DL, RootVT,
35953 CanonicalizeShuffleInput(RootVT, LHS),
35954 CanonicalizeShuffleInput(RootVT, RHS),
35955 DAG.getTargetConstant(PermMask, DL, MVT::i8));
35956 }
35957 }
35958 }
35959
35960 // For masks that have been widened to 128-bit elements or more,
35961 // narrow back down to 64-bit elements.
35962 SmallVector<int, 64> Mask;
35963 if (BaseMaskEltSizeInBits > 64) {
35964 assert((BaseMaskEltSizeInBits % 64) == 0 && "Illegal mask size")(static_cast <bool> ((BaseMaskEltSizeInBits % 64) == 0 &&
"Illegal mask size") ? void (0) : __assert_fail ("(BaseMaskEltSizeInBits % 64) == 0 && \"Illegal mask size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35964, __extension__ __PRETTY_FUNCTION__))
;
35965 int MaskScale = BaseMaskEltSizeInBits / 64;
35966 narrowShuffleMaskElts(MaskScale, BaseMask, Mask);
35967 } else {
35968 Mask.assign(BaseMask.begin(), BaseMask.end());
35969 }
35970
35971 // For masked shuffles, we're trying to match the root width for better
35972 // writemask folding, attempt to scale the mask.
35973 // TODO - variable shuffles might need this to be widened again.
35974 if (IsMaskedShuffle && NumRootElts > Mask.size()) {
35975 assert((NumRootElts % Mask.size()) == 0 && "Illegal mask size")(static_cast <bool> ((NumRootElts % Mask.size()) == 0 &&
"Illegal mask size") ? void (0) : __assert_fail ("(NumRootElts % Mask.size()) == 0 && \"Illegal mask size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 35975, __extension__ __PRETTY_FUNCTION__))
;
35976 int MaskScale = NumRootElts / Mask.size();
35977 SmallVector<int, 64> ScaledMask;
35978 narrowShuffleMaskElts(MaskScale, Mask, ScaledMask);
35979 Mask = std::move(ScaledMask);
35980 }
35981
35982 unsigned NumMaskElts = Mask.size();
35983 unsigned MaskEltSizeInBits = RootSizeInBits / NumMaskElts;
35984
35985 // Determine the effective mask value type.
35986 FloatDomain &= (32 <= MaskEltSizeInBits);
35987 MVT MaskVT = FloatDomain ? MVT::getFloatingPointVT(MaskEltSizeInBits)
35988 : MVT::getIntegerVT(MaskEltSizeInBits);
35989 MaskVT = MVT::getVectorVT(MaskVT, NumMaskElts);
35990
35991 // Only allow legal mask types.
35992 if (!DAG.getTargetLoweringInfo().isTypeLegal(MaskVT))
35993 return SDValue();
35994
35995 // Attempt to match the mask against known shuffle patterns.
35996 MVT ShuffleSrcVT, ShuffleVT;
35997 unsigned Shuffle, PermuteImm;
35998
35999 // Which shuffle domains are permitted?
36000 // Permit domain crossing at higher combine depths.
36001 // TODO: Should we indicate which domain is preferred if both are allowed?
36002 bool AllowFloatDomain = FloatDomain || (Depth >= 3);
36003 bool AllowIntDomain = (!FloatDomain || (Depth >= 3)) && Subtarget.hasSSE2() &&
36004 (!MaskVT.is256BitVector() || Subtarget.hasAVX2());
36005
36006 // Determine zeroable mask elements.
36007 APInt KnownUndef, KnownZero;
36008 resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
36009 APInt Zeroable = KnownUndef | KnownZero;
36010
36011 if (UnaryShuffle) {
36012 // Attempt to match against broadcast-from-vector.
36013 // Limit AVX1 to cases where we're loading+broadcasting a scalar element.
36014 if ((Subtarget.hasAVX2() ||
36015 (Subtarget.hasAVX() && 32 <= MaskEltSizeInBits)) &&
36016 (!IsMaskedShuffle || NumRootElts == NumMaskElts)) {
36017 if (isUndefOrEqual(Mask, 0)) {
36018 if (V1.getValueType() == MaskVT &&
36019 V1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
36020 MayFoldLoad(V1.getOperand(0))) {
36021 if (Depth == 0 && Root.getOpcode() == X86ISD::VBROADCAST)
36022 return SDValue(); // Nothing to do!
36023 Res = V1.getOperand(0);
36024 Res = DAG.getNode(X86ISD::VBROADCAST, DL, MaskVT, Res);
36025 return DAG.getBitcast(RootVT, Res);
36026 }
36027 if (Subtarget.hasAVX2()) {
36028 if (Depth == 0 && Root.getOpcode() == X86ISD::VBROADCAST)
36029 return SDValue(); // Nothing to do!
36030 Res = CanonicalizeShuffleInput(MaskVT, V1);
36031 Res = DAG.getNode(X86ISD::VBROADCAST, DL, MaskVT, Res);
36032 return DAG.getBitcast(RootVT, Res);
36033 }
36034 }
36035 }
36036
36037 SDValue NewV1 = V1; // Save operand in case early exit happens.
36038 if (matchUnaryShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain, NewV1,
36039 DL, DAG, Subtarget, Shuffle, ShuffleSrcVT,
36040 ShuffleVT) &&
36041 (!IsMaskedShuffle ||
36042 (NumRootElts == ShuffleVT.getVectorNumElements()))) {
36043 if (Depth == 0 && Root.getOpcode() == Shuffle)
36044 return SDValue(); // Nothing to do!
36045 Res = CanonicalizeShuffleInput(ShuffleSrcVT, NewV1);
36046 Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res);
36047 return DAG.getBitcast(RootVT, Res);
36048 }
36049
36050 if (matchUnaryPermuteShuffle(MaskVT, Mask, Zeroable, AllowFloatDomain,
36051 AllowIntDomain, Subtarget, Shuffle, ShuffleVT,
36052 PermuteImm) &&
36053 (!IsMaskedShuffle ||
36054 (NumRootElts == ShuffleVT.getVectorNumElements()))) {
36055 if (Depth == 0 && Root.getOpcode() == Shuffle)
36056 return SDValue(); // Nothing to do!
36057 Res = CanonicalizeShuffleInput(ShuffleVT, V1);
36058 Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res,
36059 DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
36060 return DAG.getBitcast(RootVT, Res);
36061 }
36062 }
36063
36064 // Attempt to combine to INSERTPS, but only if the inserted element has come
36065 // from a scalar.
36066 // TODO: Handle other insertions here as well?
36067 if (!UnaryShuffle && AllowFloatDomain && RootSizeInBits == 128 &&
36068 Subtarget.hasSSE41() &&
36069 !isTargetShuffleEquivalent(MaskVT, Mask, {4, 1, 2, 3})) {
36070 if (MaskEltSizeInBits == 32) {
36071 SDValue SrcV1 = V1, SrcV2 = V2;
36072 if (matchShuffleAsInsertPS(SrcV1, SrcV2, PermuteImm, Zeroable, Mask,
36073 DAG) &&
36074 SrcV2.getOpcode() == ISD::SCALAR_TO_VECTOR) {
36075 if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTPS)
36076 return SDValue(); // Nothing to do!
36077 Res = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32,
36078 CanonicalizeShuffleInput(MVT::v4f32, SrcV1),
36079 CanonicalizeShuffleInput(MVT::v4f32, SrcV2),
36080 DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
36081 return DAG.getBitcast(RootVT, Res);
36082 }
36083 }
36084 if (MaskEltSizeInBits == 64 &&
36085 isTargetShuffleEquivalent(MaskVT, Mask, {0, 2}) &&
36086 V2.getOpcode() == ISD::SCALAR_TO_VECTOR &&
36087 V2.getScalarValueSizeInBits() <= 32) {
36088 if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTPS)
36089 return SDValue(); // Nothing to do!
36090 PermuteImm = (/*DstIdx*/2 << 4) | (/*SrcIdx*/0 << 0);
36091 Res = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32,
36092 CanonicalizeShuffleInput(MVT::v4f32, V1),
36093 CanonicalizeShuffleInput(MVT::v4f32, V2),
36094 DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
36095 return DAG.getBitcast(RootVT, Res);
36096 }
36097 }
36098
36099 SDValue NewV1 = V1; // Save operands in case early exit happens.
36100 SDValue NewV2 = V2;
36101 if (matchBinaryShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain, NewV1,
36102 NewV2, DL, DAG, Subtarget, Shuffle, ShuffleSrcVT,
36103 ShuffleVT, UnaryShuffle) &&
36104 (!IsMaskedShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
36105 if (Depth == 0 && Root.getOpcode() == Shuffle)
36106 return SDValue(); // Nothing to do!
36107 NewV1 = CanonicalizeShuffleInput(ShuffleSrcVT, NewV1);
36108 NewV2 = CanonicalizeShuffleInput(ShuffleSrcVT, NewV2);
36109 Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2);
36110 return DAG.getBitcast(RootVT, Res);
36111 }
36112
36113 NewV1 = V1; // Save operands in case early exit happens.
36114 NewV2 = V2;
36115 if (matchBinaryPermuteShuffle(MaskVT, Mask, Zeroable, AllowFloatDomain,
36116 AllowIntDomain, NewV1, NewV2, DL, DAG,
36117 Subtarget, Shuffle, ShuffleVT, PermuteImm) &&
36118 (!IsMaskedShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
36119 if (Depth == 0 && Root.getOpcode() == Shuffle)
36120 return SDValue(); // Nothing to do!
36121 NewV1 = CanonicalizeShuffleInput(ShuffleVT, NewV1);
36122 NewV2 = CanonicalizeShuffleInput(ShuffleVT, NewV2);
36123 Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2,
36124 DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
36125 return DAG.getBitcast(RootVT, Res);
36126 }
36127
36128 // Typically from here on, we need an integer version of MaskVT.
36129 MVT IntMaskVT = MVT::getIntegerVT(MaskEltSizeInBits);
36130 IntMaskVT = MVT::getVectorVT(IntMaskVT, NumMaskElts);
36131
36132 // Annoyingly, SSE4A instructions don't map into the above match helpers.
36133 if (Subtarget.hasSSE4A() && AllowIntDomain && RootSizeInBits == 128) {
36134 uint64_t BitLen, BitIdx;
36135 if (matchShuffleAsEXTRQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx,
36136 Zeroable)) {
36137 if (Depth == 0 && Root.getOpcode() == X86ISD::EXTRQI)
36138 return SDValue(); // Nothing to do!
36139 V1 = CanonicalizeShuffleInput(IntMaskVT, V1);
36140 Res = DAG.getNode(X86ISD::EXTRQI, DL, IntMaskVT, V1,
36141 DAG.getTargetConstant(BitLen, DL, MVT::i8),
36142 DAG.getTargetConstant(BitIdx, DL, MVT::i8));
36143 return DAG.getBitcast(RootVT, Res);
36144 }
36145
36146 if (matchShuffleAsINSERTQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx)) {
36147 if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTQI)
36148 return SDValue(); // Nothing to do!
36149 V1 = CanonicalizeShuffleInput(IntMaskVT, V1);
36150 V2 = CanonicalizeShuffleInput(IntMaskVT, V2);
36151 Res = DAG.getNode(X86ISD::INSERTQI, DL, IntMaskVT, V1, V2,
36152 DAG.getTargetConstant(BitLen, DL, MVT::i8),
36153 DAG.getTargetConstant(BitIdx, DL, MVT::i8));
36154 return DAG.getBitcast(RootVT, Res);
36155 }
36156 }
36157
36158 // Match shuffle against TRUNCATE patterns.
36159 if (AllowIntDomain && MaskEltSizeInBits < 64 && Subtarget.hasAVX512()) {
36160 // Match against a VTRUNC instruction, accounting for src/dst sizes.
36161 if (matchShuffleAsVTRUNC(ShuffleSrcVT, ShuffleVT, IntMaskVT, Mask, Zeroable,
36162 Subtarget)) {
36163 bool IsTRUNCATE = ShuffleVT.getVectorNumElements() ==
36164 ShuffleSrcVT.getVectorNumElements();
36165 unsigned Opc =
36166 IsTRUNCATE ? (unsigned)ISD::TRUNCATE : (unsigned)X86ISD::VTRUNC;
36167 if (Depth == 0 && Root.getOpcode() == Opc)
36168 return SDValue(); // Nothing to do!
36169 V1 = CanonicalizeShuffleInput(ShuffleSrcVT, V1);
36170 Res = DAG.getNode(Opc, DL, ShuffleVT, V1);
36171 if (ShuffleVT.getSizeInBits() < RootSizeInBits)
36172 Res = widenSubVector(Res, true, Subtarget, DAG, DL, RootSizeInBits);
36173 return DAG.getBitcast(RootVT, Res);
36174 }
36175
36176 // Do we need a more general binary truncation pattern?
36177 if (RootSizeInBits < 512 &&
36178 ((RootVT.is256BitVector() && Subtarget.useAVX512Regs()) ||
36179 (RootVT.is128BitVector() && Subtarget.hasVLX())) &&
36180 (MaskEltSizeInBits > 8 || Subtarget.hasBWI()) &&
36181 isSequentialOrUndefInRange(Mask, 0, NumMaskElts, 0, 2)) {
36182 if (Depth == 0 && Root.getOpcode() == ISD::TRUNCATE)
36183 return SDValue(); // Nothing to do!
36184 ShuffleSrcVT = MVT::getIntegerVT(MaskEltSizeInBits * 2);
36185 ShuffleSrcVT = MVT::getVectorVT(ShuffleSrcVT, NumMaskElts / 2);
36186 V1 = CanonicalizeShuffleInput(ShuffleSrcVT, V1);
36187 V2 = CanonicalizeShuffleInput(ShuffleSrcVT, V2);
36188 ShuffleSrcVT = MVT::getIntegerVT(MaskEltSizeInBits * 2);
36189 ShuffleSrcVT = MVT::getVectorVT(ShuffleSrcVT, NumMaskElts);
36190 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShuffleSrcVT, V1, V2);
36191 Res = DAG.getNode(ISD::TRUNCATE, DL, IntMaskVT, Res);
36192 return DAG.getBitcast(RootVT, Res);
36193 }
36194 }
36195
36196 // Don't try to re-form single instruction chains under any circumstances now
36197 // that we've done encoding canonicalization for them.
36198 if (Depth < 1)
36199 return SDValue();
36200
36201 // Depth threshold above which we can efficiently use variable mask shuffles.
36202 int VariableCrossLaneShuffleDepth =
36203 Subtarget.hasFastVariableCrossLaneShuffle() ? 1 : 2;
36204 int VariablePerLaneShuffleDepth =
36205 Subtarget.hasFastVariablePerLaneShuffle() ? 1 : 2;
36206 AllowVariableCrossLaneMask &=
36207 (Depth >= VariableCrossLaneShuffleDepth) || HasVariableMask;
36208 AllowVariablePerLaneMask &=
36209 (Depth >= VariablePerLaneShuffleDepth) || HasVariableMask;
36210 // VPERMI2W/VPERMI2B are 3 uops on Skylake and Icelake so we require a
36211 // higher depth before combining them.
36212 bool AllowBWIVPERMV3 =
36213 (Depth >= (VariableCrossLaneShuffleDepth + 2) || HasVariableMask);
36214
36215 bool MaskContainsZeros = isAnyZero(Mask);
36216
36217 if (is128BitLaneCrossingShuffleMask(MaskVT, Mask)) {
36218 // If we have a single input lane-crossing shuffle then lower to VPERMV.
36219 if (UnaryShuffle && AllowVariableCrossLaneMask && !MaskContainsZeros) {
36220 if (Subtarget.hasAVX2() &&
36221 (MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) {
36222 SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
36223 Res = CanonicalizeShuffleInput(MaskVT, V1);
36224 Res = DAG.getNode(X86ISD::VPERMV, DL, MaskVT, VPermMask, Res);
36225 return DAG.getBitcast(RootVT, Res);
36226 }
36227 // AVX512 variants (non-VLX will pad to 512-bit shuffles).
36228 if ((Subtarget.hasAVX512() &&
36229 (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
36230 MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
36231 (Subtarget.hasBWI() &&
36232 (MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
36233 (Subtarget.hasVBMI() &&
36234 (MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8))) {
36235 V1 = CanonicalizeShuffleInput(MaskVT, V1);
36236 V2 = DAG.getUNDEF(MaskVT);
36237 Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
36238 return DAG.getBitcast(RootVT, Res);
36239 }
36240 }
36241
36242 // Lower a unary+zero lane-crossing shuffle as VPERMV3 with a zero
36243 // vector as the second source (non-VLX will pad to 512-bit shuffles).
36244 if (UnaryShuffle && AllowVariableCrossLaneMask &&
36245 ((Subtarget.hasAVX512() &&
36246 (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
36247 MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
36248 MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32 ||
36249 MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
36250 (Subtarget.hasBWI() && AllowBWIVPERMV3 &&
36251 (MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
36252 (Subtarget.hasVBMI() && AllowBWIVPERMV3 &&
36253 (MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8)))) {
36254 // Adjust shuffle mask - replace SM_SentinelZero with second source index.
36255 for (unsigned i = 0; i != NumMaskElts; ++i)
36256 if (Mask[i] == SM_SentinelZero)
36257 Mask[i] = NumMaskElts + i;
36258 V1 = CanonicalizeShuffleInput(MaskVT, V1);
36259 V2 = getZeroVector(MaskVT, Subtarget, DAG, DL);
36260 Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
36261 return DAG.getBitcast(RootVT, Res);
36262 }
36263
36264 // If that failed and either input is extracted then try to combine as a
36265 // shuffle with the larger type.
36266 if (SDValue WideShuffle = combineX86ShuffleChainWithExtract(
36267 Inputs, Root, BaseMask, Depth, HasVariableMask,
36268 AllowVariableCrossLaneMask, AllowVariablePerLaneMask, DAG,
36269 Subtarget))
36270 return WideShuffle;
36271
36272 // If we have a dual input lane-crossing shuffle then lower to VPERMV3,
36273 // (non-VLX will pad to 512-bit shuffles).
36274 if (AllowVariableCrossLaneMask && !MaskContainsZeros &&
36275 ((Subtarget.hasAVX512() &&
36276 (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
36277 MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
36278 MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32 ||
36279 MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
36280 (Subtarget.hasBWI() && AllowBWIVPERMV3 &&
36281 (MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
36282 (Subtarget.hasVBMI() && AllowBWIVPERMV3 &&
36283 (MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8)))) {
36284 V1 = CanonicalizeShuffleInput(MaskVT, V1);
36285 V2 = CanonicalizeShuffleInput(MaskVT, V2);
36286 Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
36287 return DAG.getBitcast(RootVT, Res);
36288 }
36289 return SDValue();
36290 }
36291
36292 // See if we can combine a single input shuffle with zeros to a bit-mask,
36293 // which is much simpler than any shuffle.
36294 if (UnaryShuffle && MaskContainsZeros && AllowVariablePerLaneMask &&
36295 isSequentialOrUndefOrZeroInRange(Mask, 0, NumMaskElts, 0) &&
36296 DAG.getTargetLoweringInfo().isTypeLegal(MaskVT)) {
36297 APInt Zero = APInt::getNullValue(MaskEltSizeInBits);
36298 APInt AllOnes = APInt::getAllOnesValue(MaskEltSizeInBits);
36299 APInt UndefElts(NumMaskElts, 0);
36300 SmallVector<APInt, 64> EltBits(NumMaskElts, Zero);
36301 for (unsigned i = 0; i != NumMaskElts; ++i) {
36302 int M = Mask[i];
36303 if (M == SM_SentinelUndef) {
36304 UndefElts.setBit(i);
36305 continue;
36306 }
36307 if (M == SM_SentinelZero)
36308 continue;
36309 EltBits[i] = AllOnes;
36310 }
36311 SDValue BitMask = getConstVector(EltBits, UndefElts, MaskVT, DAG, DL);
36312 Res = CanonicalizeShuffleInput(MaskVT, V1);
36313 unsigned AndOpcode =
36314 MaskVT.isFloatingPoint() ? unsigned(X86ISD::FAND) : unsigned(ISD::AND);
36315 Res = DAG.getNode(AndOpcode, DL, MaskVT, Res, BitMask);
36316 return DAG.getBitcast(RootVT, Res);
36317 }
36318
36319 // If we have a single input shuffle with different shuffle patterns in the
36320 // the 128-bit lanes use the variable mask to VPERMILPS.
36321 // TODO Combine other mask types at higher depths.
36322 if (UnaryShuffle && AllowVariablePerLaneMask && !MaskContainsZeros &&
36323 ((MaskVT == MVT::v8f32 && Subtarget.hasAVX()) ||
36324 (MaskVT == MVT::v16f32 && Subtarget.hasAVX512()))) {
36325 SmallVector<SDValue, 16> VPermIdx;
36326 for (int M : Mask) {
36327 SDValue Idx =
36328 M < 0 ? DAG.getUNDEF(MVT::i32) : DAG.getConstant(M % 4, DL, MVT::i32);
36329 VPermIdx.push_back(Idx);
36330 }
36331 SDValue VPermMask = DAG.getBuildVector(IntMaskVT, DL, VPermIdx);
36332 Res = CanonicalizeShuffleInput(MaskVT, V1);
36333 Res = DAG.getNode(X86ISD::VPERMILPV, DL, MaskVT, Res, VPermMask);
36334 return DAG.getBitcast(RootVT, Res);
36335 }
36336
36337 // With XOP, binary shuffles of 128/256-bit floating point vectors can combine
36338 // to VPERMIL2PD/VPERMIL2PS.
36339 if (AllowVariablePerLaneMask && Subtarget.hasXOP() &&
36340 (MaskVT == MVT::v2f64 || MaskVT == MVT::v4f64 || MaskVT == MVT::v4f32 ||
36341 MaskVT == MVT::v8f32)) {
36342 // VPERMIL2 Operation.
36343 // Bits[3] - Match Bit.
36344 // Bits[2:1] - (Per Lane) PD Shuffle Mask.
36345 // Bits[2:0] - (Per Lane) PS Shuffle Mask.
36346 unsigned NumLanes = MaskVT.getSizeInBits() / 128;
36347 unsigned NumEltsPerLane = NumMaskElts / NumLanes;
36348 SmallVector<int, 8> VPerm2Idx;
36349 unsigned M2ZImm = 0;
36350 for (int M : Mask) {
36351 if (M == SM_SentinelUndef) {
36352 VPerm2Idx.push_back(-1);
36353 continue;
36354 }
36355 if (M == SM_SentinelZero) {
36356 M2ZImm = 2;
36357 VPerm2Idx.push_back(8);
36358 continue;
36359 }
36360 int Index = (M % NumEltsPerLane) + ((M / NumMaskElts) * NumEltsPerLane);
36361 Index = (MaskVT.getScalarSizeInBits() == 64 ? Index << 1 : Index);
36362 VPerm2Idx.push_back(Index);
36363 }
36364 V1 = CanonicalizeShuffleInput(MaskVT, V1);
36365 V2 = CanonicalizeShuffleInput(MaskVT, V2);
36366 SDValue VPerm2MaskOp = getConstVector(VPerm2Idx, IntMaskVT, DAG, DL, true);
36367 Res = DAG.getNode(X86ISD::VPERMIL2, DL, MaskVT, V1, V2, VPerm2MaskOp,
36368 DAG.getTargetConstant(M2ZImm, DL, MVT::i8));
36369 return DAG.getBitcast(RootVT, Res);
36370 }
36371
36372 // If we have 3 or more shuffle instructions or a chain involving a variable
36373 // mask, we can replace them with a single PSHUFB instruction profitably.
36374 // Intel's manuals suggest only using PSHUFB if doing so replacing 5
36375 // instructions, but in practice PSHUFB tends to be *very* fast so we're
36376 // more aggressive.
36377 if (UnaryShuffle && AllowVariablePerLaneMask &&
36378 ((RootVT.is128BitVector() && Subtarget.hasSSSE3()) ||
36379 (RootVT.is256BitVector() && Subtarget.hasAVX2()) ||
36380 (RootVT.is512BitVector() && Subtarget.hasBWI()))) {
36381 SmallVector<SDValue, 16> PSHUFBMask;
36382 int NumBytes = RootVT.getSizeInBits() / 8;
36383 int Ratio = NumBytes / NumMaskElts;
36384 for (int i = 0; i < NumBytes; ++i) {
36385 int M = Mask[i / Ratio];
36386 if (M == SM_SentinelUndef) {
36387 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
36388 continue;
36389 }
36390 if (M == SM_SentinelZero) {
36391 PSHUFBMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
36392 continue;
36393 }
36394 M = Ratio * M + i % Ratio;
36395 assert((M / 16) == (i / 16) && "Lane crossing detected")(static_cast <bool> ((M / 16) == (i / 16) && "Lane crossing detected"
) ? void (0) : __assert_fail ("(M / 16) == (i / 16) && \"Lane crossing detected\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 36395, __extension__ __PRETTY_FUNCTION__))
;
36396 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
36397 }
36398 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
36399 Res = CanonicalizeShuffleInput(ByteVT, V1);
36400 SDValue PSHUFBMaskOp = DAG.getBuildVector(ByteVT, DL, PSHUFBMask);
36401 Res = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Res, PSHUFBMaskOp);
36402 return DAG.getBitcast(RootVT, Res);
36403 }
36404
36405 // With XOP, if we have a 128-bit binary input shuffle we can always combine
36406 // to VPPERM. We match the depth requirement of PSHUFB - VPPERM is never
36407 // slower than PSHUFB on targets that support both.
36408 if (AllowVariablePerLaneMask && RootVT.is128BitVector() &&
36409 Subtarget.hasXOP()) {
36410 // VPPERM Mask Operation
36411 // Bits[4:0] - Byte Index (0 - 31)
36412 // Bits[7:5] - Permute Operation (0 - Source byte, 4 - ZERO)
36413 SmallVector<SDValue, 16> VPPERMMask;
36414 int NumBytes = 16;
36415 int Ratio = NumBytes / NumMaskElts;
36416 for (int i = 0; i < NumBytes; ++i) {
36417 int M = Mask[i / Ratio];
36418 if (M == SM_SentinelUndef) {
36419 VPPERMMask.push_back(DAG.getUNDEF(MVT::i8));
36420 continue;
36421 }
36422 if (M == SM_SentinelZero) {
36423 VPPERMMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
36424 continue;
36425 }
36426 M = Ratio * M + i % Ratio;
36427 VPPERMMask.push_back(DAG.getConstant(M, DL, MVT::i8));
36428 }
36429 MVT ByteVT = MVT::v16i8;
36430 V1 = CanonicalizeShuffleInput(ByteVT, V1);
36431 V2 = CanonicalizeShuffleInput(ByteVT, V2);
36432 SDValue VPPERMMaskOp = DAG.getBuildVector(ByteVT, DL, VPPERMMask);
36433 Res = DAG.getNode(X86ISD::VPPERM, DL, ByteVT, V1, V2, VPPERMMaskOp);
36434 return DAG.getBitcast(RootVT, Res);
36435 }
36436
36437 // If that failed and either input is extracted then try to combine as a
36438 // shuffle with the larger type.
36439 if (SDValue WideShuffle = combineX86ShuffleChainWithExtract(
36440 Inputs, Root, BaseMask, Depth, HasVariableMask,
36441 AllowVariableCrossLaneMask, AllowVariablePerLaneMask, DAG, Subtarget))
36442 return WideShuffle;
36443
36444 // If we have a dual input shuffle then lower to VPERMV3,
36445 // (non-VLX will pad to 512-bit shuffles)
36446 if (!UnaryShuffle && AllowVariablePerLaneMask && !MaskContainsZeros &&
36447 ((Subtarget.hasAVX512() &&
36448 (MaskVT == MVT::v2f64 || MaskVT == MVT::v4f64 || MaskVT == MVT::v8f64 ||
36449 MaskVT == MVT::v2i64 || MaskVT == MVT::v4i64 || MaskVT == MVT::v8i64 ||
36450 MaskVT == MVT::v4f32 || MaskVT == MVT::v4i32 || MaskVT == MVT::v8f32 ||
36451 MaskVT == MVT::v8i32 || MaskVT == MVT::v16f32 ||
36452 MaskVT == MVT::v16i32)) ||
36453 (Subtarget.hasBWI() && AllowBWIVPERMV3 &&
36454 (MaskVT == MVT::v8i16 || MaskVT == MVT::v16i16 ||
36455 MaskVT == MVT::v32i16)) ||
36456 (Subtarget.hasVBMI() && AllowBWIVPERMV3 &&
36457 (MaskVT == MVT::v16i8 || MaskVT == MVT::v32i8 ||
36458 MaskVT == MVT::v64i8)))) {
36459 V1 = CanonicalizeShuffleInput(MaskVT, V1);
36460 V2 = CanonicalizeShuffleInput(MaskVT, V2);
36461 Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
36462 return DAG.getBitcast(RootVT, Res);
36463 }
36464
36465 // Failed to find any combines.
36466 return SDValue();
36467}
36468
36469// Combine an arbitrary chain of shuffles + extract_subvectors into a single
36470// instruction if possible.
36471//
36472// Wrapper for combineX86ShuffleChain that extends the shuffle mask to a larger
36473// type size to attempt to combine:
36474// shuffle(extract_subvector(x,c1),extract_subvector(y,c2),m1)
36475// -->
36476// extract_subvector(shuffle(x,y,m2),0)
36477static SDValue combineX86ShuffleChainWithExtract(
36478 ArrayRef<SDValue> Inputs, SDValue Root, ArrayRef<int> BaseMask, int Depth,
36479 bool HasVariableMask, bool AllowVariableCrossLaneMask,
36480 bool AllowVariablePerLaneMask, SelectionDAG &DAG,
36481 const X86Subtarget &Subtarget) {
36482 unsigned NumMaskElts = BaseMask.size();
36483 unsigned NumInputs = Inputs.size();
36484 if (NumInputs == 0)
36485 return SDValue();
36486
36487 EVT RootVT = Root.getValueType();
36488 unsigned RootSizeInBits = RootVT.getSizeInBits();
36489 assert((RootSizeInBits % NumMaskElts) == 0 && "Unexpected root shuffle mask")(static_cast <bool> ((RootSizeInBits % NumMaskElts) == 0
&& "Unexpected root shuffle mask") ? void (0) : __assert_fail
("(RootSizeInBits % NumMaskElts) == 0 && \"Unexpected root shuffle mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 36489, __extension__ __PRETTY_FUNCTION__))
;
36490
36491 SmallVector<SDValue, 4> WideInputs(Inputs.begin(), Inputs.end());
36492 SmallVector<unsigned, 4> Offsets(NumInputs, 0);
36493
36494 // Peek through subvectors.
36495 // TODO: Support inter-mixed EXTRACT_SUBVECTORs + BITCASTs?
36496 unsigned WideSizeInBits = RootSizeInBits;
36497 for (unsigned i = 0; i != NumInputs; ++i) {
36498 SDValue &Src = WideInputs[i];
36499 unsigned &Offset = Offsets[i];
36500 Src = peekThroughBitcasts(Src);
36501 EVT BaseVT = Src.getValueType();
36502 while (Src.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
36503 Offset += Src.getConstantOperandVal(1);
36504 Src = Src.getOperand(0);
36505 }
36506 WideSizeInBits = std::max(WideSizeInBits,
36507 (unsigned)Src.getValueSizeInBits());
36508 assert((Offset % BaseVT.getVectorNumElements()) == 0 &&(static_cast <bool> ((Offset % BaseVT.getVectorNumElements
()) == 0 && "Unexpected subvector extraction") ? void
(0) : __assert_fail ("(Offset % BaseVT.getVectorNumElements()) == 0 && \"Unexpected subvector extraction\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 36509, __extension__ __PRETTY_FUNCTION__))
36509 "Unexpected subvector extraction")(static_cast <bool> ((Offset % BaseVT.getVectorNumElements
()) == 0 && "Unexpected subvector extraction") ? void
(0) : __assert_fail ("(Offset % BaseVT.getVectorNumElements()) == 0 && \"Unexpected subvector extraction\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 36509, __extension__ __PRETTY_FUNCTION__))
;
36510 Offset /= BaseVT.getVectorNumElements();
36511 Offset *= NumMaskElts;
36512 }
36513
36514 // Bail if we're always extracting from the lowest subvectors,
36515 // combineX86ShuffleChain should match this for the current width.
36516 if (llvm::all_of(Offsets, [](unsigned Offset) { return Offset == 0; }))
36517 return SDValue();
36518
36519 unsigned Scale = WideSizeInBits / RootSizeInBits;
36520 assert((WideSizeInBits % RootSizeInBits) == 0 &&(static_cast <bool> ((WideSizeInBits % RootSizeInBits) ==
0 && "Unexpected subvector extraction") ? void (0) :
__assert_fail ("(WideSizeInBits % RootSizeInBits) == 0 && \"Unexpected subvector extraction\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 36521, __extension__ __PRETTY_FUNCTION__))
36521 "Unexpected subvector extraction")(static_cast <bool> ((WideSizeInBits % RootSizeInBits) ==
0 && "Unexpected subvector extraction") ? void (0) :
__assert_fail ("(WideSizeInBits % RootSizeInBits) == 0 && \"Unexpected subvector extraction\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 36521, __extension__ __PRETTY_FUNCTION__))
;
36522
36523 // If the src vector types aren't the same, see if we can extend
36524 // them to match each other.
36525 // TODO: Support different scalar types?
36526 EVT WideSVT = WideInputs[0].getValueType().getScalarType();
36527 if (llvm::any_of(WideInputs, [&WideSVT, &DAG](SDValue Op) {
36528 return !DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()) ||
36529 Op.getValueType().getScalarType() != WideSVT;
36530 }))
36531 return SDValue();
36532
36533 for (SDValue &NewInput : WideInputs) {
36534 assert((WideSizeInBits % NewInput.getValueSizeInBits()) == 0 &&(static_cast <bool> ((WideSizeInBits % NewInput.getValueSizeInBits
()) == 0 && "Shuffle vector size mismatch") ? void (0
) : __assert_fail ("(WideSizeInBits % NewInput.getValueSizeInBits()) == 0 && \"Shuffle vector size mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 36535, __extension__ __PRETTY_FUNCTION__))
36535 "Shuffle vector size mismatch")(static_cast <bool> ((WideSizeInBits % NewInput.getValueSizeInBits
()) == 0 && "Shuffle vector size mismatch") ? void (0
) : __assert_fail ("(WideSizeInBits % NewInput.getValueSizeInBits()) == 0 && \"Shuffle vector size mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 36535, __extension__ __PRETTY_FUNCTION__))
;
36536 if (WideSizeInBits > NewInput.getValueSizeInBits())
36537 NewInput = widenSubVector(NewInput, false, Subtarget, DAG,
36538 SDLoc(NewInput), WideSizeInBits);
36539 assert(WideSizeInBits == NewInput.getValueSizeInBits() &&(static_cast <bool> (WideSizeInBits == NewInput.getValueSizeInBits
() && "Unexpected subvector extraction") ? void (0) :
__assert_fail ("WideSizeInBits == NewInput.getValueSizeInBits() && \"Unexpected subvector extraction\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 36540, __extension__ __PRETTY_FUNCTION__))
36540 "Unexpected subvector extraction")(static_cast <bool> (WideSizeInBits == NewInput.getValueSizeInBits
() && "Unexpected subvector extraction") ? void (0) :
__assert_fail ("WideSizeInBits == NewInput.getValueSizeInBits() && \"Unexpected subvector extraction\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 36540, __extension__ __PRETTY_FUNCTION__))
;
36541 }
36542
36543 // Create new mask for larger type.
36544 for (unsigned i = 1; i != NumInputs; ++i)
36545 Offsets[i] += i * Scale * NumMaskElts;
36546
36547 SmallVector<int, 64> WideMask(BaseMask.begin(), BaseMask.end());
36548 for (int &M : WideMask) {
36549 if (M < 0)
36550 continue;
36551 M = (M % NumMaskElts) + Offsets[M / NumMaskElts];
36552 }
36553 WideMask.append((Scale - 1) * NumMaskElts, SM_SentinelUndef);
36554
36555 // Remove unused/repeated shuffle source ops.
36556 resolveTargetShuffleInputsAndMask(WideInputs, WideMask);
36557 assert(!WideInputs.empty() && "Shuffle with no inputs detected")(static_cast <bool> (!WideInputs.empty() && "Shuffle with no inputs detected"
) ? void (0) : __assert_fail ("!WideInputs.empty() && \"Shuffle with no inputs detected\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 36557, __extension__ __PRETTY_FUNCTION__))
;
36558
36559 if (WideInputs.size() > 2)
36560 return SDValue();
36561
36562 // Increase depth for every upper subvector we've peeked through.
36563 Depth += count_if(Offsets, [](unsigned Offset) { return Offset > 0; });
36564
36565 // Attempt to combine wider chain.
36566 // TODO: Can we use a better Root?
36567 SDValue WideRoot = WideInputs[0];
36568 if (SDValue WideShuffle =
36569 combineX86ShuffleChain(WideInputs, WideRoot, WideMask, Depth,
36570 HasVariableMask, AllowVariableCrossLaneMask,
36571 AllowVariablePerLaneMask, DAG, Subtarget)) {
36572 WideShuffle =
36573 extractSubVector(WideShuffle, 0, DAG, SDLoc(Root), RootSizeInBits);
36574 return DAG.getBitcast(RootVT, WideShuffle);
36575 }
36576 return SDValue();
36577}
36578
36579// Canonicalize the combined shuffle mask chain with horizontal ops.
36580// NOTE: This may update the Ops and Mask.
36581static SDValue canonicalizeShuffleMaskWithHorizOp(
36582 MutableArrayRef<SDValue> Ops, MutableArrayRef<int> Mask,
36583 unsigned RootSizeInBits, const SDLoc &DL, SelectionDAG &DAG,
36584 const X86Subtarget &Subtarget) {
36585 if (Mask.empty() || Ops.empty())
36586 return SDValue();
36587
36588 SmallVector<SDValue> BC;
36589 for (SDValue Op : Ops)
36590 BC.push_back(peekThroughBitcasts(Op));
36591
36592 // All ops must be the same horizop + type.
36593 SDValue BC0 = BC[0];
36594 EVT VT0 = BC0.getValueType();
36595 unsigned Opcode0 = BC0.getOpcode();
36596 if (VT0.getSizeInBits() != RootSizeInBits || llvm::any_of(BC, [&](SDValue V) {
36597 return V.getOpcode() != Opcode0 || V.getValueType() != VT0;
36598 }))
36599 return SDValue();
36600
36601 bool isHoriz = (Opcode0 == X86ISD::FHADD || Opcode0 == X86ISD::HADD ||
36602 Opcode0 == X86ISD::FHSUB || Opcode0 == X86ISD::HSUB);
36603 bool isPack = (Opcode0 == X86ISD::PACKSS || Opcode0 == X86ISD::PACKUS);
36604 if (!isHoriz && !isPack)
36605 return SDValue();
36606
36607 // Do all ops have a single use?
36608 bool OneUseOps = llvm::all_of(Ops, [](SDValue Op) {
36609 return Op.hasOneUse() &&
36610 peekThroughBitcasts(Op) == peekThroughOneUseBitcasts(Op);
36611 });
36612
36613 int NumElts = VT0.getVectorNumElements();
36614 int NumLanes = VT0.getSizeInBits() / 128;
36615 int NumEltsPerLane = NumElts / NumLanes;
36616 int NumHalfEltsPerLane = NumEltsPerLane / 2;
36617 MVT SrcVT = BC0.getOperand(0).getSimpleValueType();
36618 unsigned EltSizeInBits = RootSizeInBits / Mask.size();
36619
36620 if (NumEltsPerLane >= 4 &&
36621 (isPack || shouldUseHorizontalOp(Ops.size() == 1, DAG, Subtarget))) {
36622 SmallVector<int> LaneMask, ScaledMask;
36623 if (isRepeatedTargetShuffleMask(128, EltSizeInBits, Mask, LaneMask) &&
36624 scaleShuffleElements(LaneMask, 4, ScaledMask)) {
36625 // See if we can remove the shuffle by resorting the HOP chain so that
36626 // the HOP args are pre-shuffled.
36627 // TODO: Generalize to any sized/depth chain.
36628 // TODO: Add support for PACKSS/PACKUS.
36629 if (isHoriz) {
36630 // Attempt to find a HOP(HOP(X,Y),HOP(Z,W)) source operand.
36631 auto GetHOpSrc = [&](int M) {
36632 if (M == SM_SentinelUndef)
36633 return DAG.getUNDEF(VT0);
36634 if (M == SM_SentinelZero)
36635 return getZeroVector(VT0.getSimpleVT(), Subtarget, DAG, DL);
36636 SDValue Src0 = BC[M / 4];
36637 SDValue Src1 = Src0.getOperand((M % 4) >= 2);
36638 if (Src1.getOpcode() == Opcode0 && Src0->isOnlyUserOf(Src1.getNode()))
36639 return Src1.getOperand(M % 2);
36640 return SDValue();
36641 };
36642 SDValue M0 = GetHOpSrc(ScaledMask[0]);
36643 SDValue M1 = GetHOpSrc(ScaledMask[1]);
36644 SDValue M2 = GetHOpSrc(ScaledMask[2]);
36645 SDValue M3 = GetHOpSrc(ScaledMask[3]);
36646 if (M0 && M1 && M2 && M3) {
36647 SDValue LHS = DAG.getNode(Opcode0, DL, SrcVT, M0, M1);
36648 SDValue RHS = DAG.getNode(Opcode0, DL, SrcVT, M2, M3);
36649 return DAG.getNode(Opcode0, DL, VT0, LHS, RHS);
36650 }
36651 }
36652 // shuffle(hop(x,y),hop(z,w)) -> permute(hop(x,z)) etc.
36653 if (Ops.size() >= 2) {
36654 SDValue LHS, RHS;
36655 auto GetHOpSrc = [&](int M, int &OutM) {
36656 // TODO: Support SM_SentinelZero
36657 if (M < 0)
36658 return M == SM_SentinelUndef;
36659 SDValue Src = BC[M / 4].getOperand((M % 4) >= 2);
36660 if (!LHS || LHS == Src) {
36661 LHS = Src;
36662 OutM = (M % 2);
36663 return true;
36664 }
36665 if (!RHS || RHS == Src) {
36666 RHS = Src;
36667 OutM = (M % 2) + 2;
36668 return true;
36669 }
36670 return false;
36671 };
36672 int PostMask[4] = {-1, -1, -1, -1};
36673 if (GetHOpSrc(ScaledMask[0], PostMask[0]) &&
36674 GetHOpSrc(ScaledMask[1], PostMask[1]) &&
36675 GetHOpSrc(ScaledMask[2], PostMask[2]) &&
36676 GetHOpSrc(ScaledMask[3], PostMask[3])) {
36677 LHS = DAG.getBitcast(SrcVT, LHS);
36678 RHS = DAG.getBitcast(SrcVT, RHS ? RHS : LHS);
36679 SDValue Res = DAG.getNode(Opcode0, DL, VT0, LHS, RHS);
36680 // Use SHUFPS for the permute so this will work on SSE3 targets,
36681 // shuffle combining and domain handling will simplify this later on.
36682 MVT ShuffleVT = MVT::getVectorVT(MVT::f32, RootSizeInBits / 32);
36683 Res = DAG.getBitcast(ShuffleVT, Res);
36684 return DAG.getNode(X86ISD::SHUFP, DL, ShuffleVT, Res, Res,
36685 getV4X86ShuffleImm8ForMask(PostMask, DL, DAG));
36686 }
36687 }
36688 }
36689 }
36690
36691 if (2 < Ops.size())
36692 return SDValue();
36693
36694 SDValue BC1 = BC[BC.size() - 1];
36695 if (Mask.size() == VT0.getVectorNumElements()) {
36696 // Canonicalize binary shuffles of horizontal ops that use the
36697 // same sources to an unary shuffle.
36698 // TODO: Try to perform this fold even if the shuffle remains.
36699 if (Ops.size() == 2) {
36700 auto ContainsOps = [](SDValue HOp, SDValue Op) {
36701 return Op == HOp.getOperand(0) || Op == HOp.getOperand(1);
36702 };
36703 // Commute if all BC0's ops are contained in BC1.
36704 if (ContainsOps(BC1, BC0.getOperand(0)) &&
36705 ContainsOps(BC1, BC0.getOperand(1))) {
36706 ShuffleVectorSDNode::commuteMask(Mask);
36707 std::swap(Ops[0], Ops[1]);
36708 std::swap(BC0, BC1);
36709 }
36710
36711 // If BC1 can be represented by BC0, then convert to unary shuffle.
36712 if (ContainsOps(BC0, BC1.getOperand(0)) &&
36713 ContainsOps(BC0, BC1.getOperand(1))) {
36714 for (int &M : Mask) {
36715 if (M < NumElts) // BC0 element or UNDEF/Zero sentinel.
36716 continue;
36717 int SubLane = ((M % NumEltsPerLane) >= NumHalfEltsPerLane) ? 1 : 0;
36718 M -= NumElts + (SubLane * NumHalfEltsPerLane);
36719 if (BC1.getOperand(SubLane) != BC0.getOperand(0))
36720 M += NumHalfEltsPerLane;
36721 }
36722 }
36723 }
36724
36725 // Canonicalize unary horizontal ops to only refer to lower halves.
36726 for (int i = 0; i != NumElts; ++i) {
36727 int &M = Mask[i];
36728 if (isUndefOrZero(M))
36729 continue;
36730 if (M < NumElts && BC0.getOperand(0) == BC0.getOperand(1) &&
36731 (M % NumEltsPerLane) >= NumHalfEltsPerLane)
36732 M -= NumHalfEltsPerLane;
36733 if (NumElts <= M && BC1.getOperand(0) == BC1.getOperand(1) &&
36734 (M % NumEltsPerLane) >= NumHalfEltsPerLane)
36735 M -= NumHalfEltsPerLane;
36736 }
36737 }
36738
36739 // Combine binary shuffle of 2 similar 'Horizontal' instructions into a
36740 // single instruction. Attempt to match a v2X64 repeating shuffle pattern that
36741 // represents the LHS/RHS inputs for the lower/upper halves.
36742 SmallVector<int, 16> TargetMask128, WideMask128;
36743 if (isRepeatedTargetShuffleMask(128, EltSizeInBits, Mask, TargetMask128) &&
36744 scaleShuffleElements(TargetMask128, 2, WideMask128)) {
36745 assert(isUndefOrZeroOrInRange(WideMask128, 0, 4) && "Illegal shuffle")(static_cast <bool> (isUndefOrZeroOrInRange(WideMask128
, 0, 4) && "Illegal shuffle") ? void (0) : __assert_fail
("isUndefOrZeroOrInRange(WideMask128, 0, 4) && \"Illegal shuffle\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 36745, __extension__ __PRETTY_FUNCTION__))
;
36746 bool SingleOp = (Ops.size() == 1);
36747 if (isPack || OneUseOps ||
36748 shouldUseHorizontalOp(SingleOp, DAG, Subtarget)) {
36749 SDValue Lo = isInRange(WideMask128[0], 0, 2) ? BC0 : BC1;
36750 SDValue Hi = isInRange(WideMask128[1], 0, 2) ? BC0 : BC1;
36751 Lo = Lo.getOperand(WideMask128[0] & 1);
36752 Hi = Hi.getOperand(WideMask128[1] & 1);
36753 if (SingleOp) {
36754 SDValue Undef = DAG.getUNDEF(SrcVT);
36755 SDValue Zero = getZeroVector(SrcVT, Subtarget, DAG, DL);
36756 Lo = (WideMask128[0] == SM_SentinelZero ? Zero : Lo);
36757 Hi = (WideMask128[1] == SM_SentinelZero ? Zero : Hi);
36758 Lo = (WideMask128[0] == SM_SentinelUndef ? Undef : Lo);
36759 Hi = (WideMask128[1] == SM_SentinelUndef ? Undef : Hi);
36760 }
36761 return DAG.getNode(Opcode0, DL, VT0, Lo, Hi);
36762 }
36763 }
36764
36765 return SDValue();
36766}
36767
36768// Attempt to constant fold all of the constant source ops.
36769// Returns true if the entire shuffle is folded to a constant.
36770// TODO: Extend this to merge multiple constant Ops and update the mask.
36771static SDValue combineX86ShufflesConstants(ArrayRef<SDValue> Ops,
36772 ArrayRef<int> Mask, SDValue Root,
36773 bool HasVariableMask,
36774 SelectionDAG &DAG,
36775 const X86Subtarget &Subtarget) {
36776 MVT VT = Root.getSimpleValueType();
36777
36778 unsigned SizeInBits = VT.getSizeInBits();
36779 unsigned NumMaskElts = Mask.size();
36780 unsigned MaskSizeInBits = SizeInBits / NumMaskElts;
36781 unsigned NumOps = Ops.size();
36782
36783 // Extract constant bits from each source op.
36784 bool OneUseConstantOp = false;
36785 SmallVector<APInt, 16> UndefEltsOps(NumOps);
36786 SmallVector<SmallVector<APInt, 16>, 16> RawBitsOps(NumOps);
36787 for (unsigned i = 0; i != NumOps; ++i) {
36788 SDValue SrcOp = Ops[i];
36789 OneUseConstantOp |= SrcOp.hasOneUse();
36790 if (!getTargetConstantBitsFromNode(SrcOp, MaskSizeInBits, UndefEltsOps[i],
36791 RawBitsOps[i]))
36792 return SDValue();
36793 }
36794
36795 // Only fold if at least one of the constants is only used once or
36796 // the combined shuffle has included a variable mask shuffle, this
36797 // is to avoid constant pool bloat.
36798 if (!OneUseConstantOp && !HasVariableMask)
36799 return SDValue();
36800
36801 // Shuffle the constant bits according to the mask.
36802 SDLoc DL(Root);
36803 APInt UndefElts(NumMaskElts, 0);
36804 APInt ZeroElts(NumMaskElts, 0);
36805 APInt ConstantElts(NumMaskElts, 0);
36806 SmallVector<APInt, 8> ConstantBitData(NumMaskElts,
36807 APInt::getNullValue(MaskSizeInBits));
36808 for (unsigned i = 0; i != NumMaskElts; ++i) {
36809 int M = Mask[i];
36810 if (M == SM_SentinelUndef) {
36811 UndefElts.setBit(i);
36812 continue;
36813 } else if (M == SM_SentinelZero) {
36814 ZeroElts.setBit(i);
36815 continue;
36816 }
36817 assert(0 <= M && M < (int)(NumMaskElts * NumOps))(static_cast <bool> (0 <= M && M < (int)(
NumMaskElts * NumOps)) ? void (0) : __assert_fail ("0 <= M && M < (int)(NumMaskElts * NumOps)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 36817, __extension__ __PRETTY_FUNCTION__))
;
36818
36819 unsigned SrcOpIdx = (unsigned)M / NumMaskElts;
36820 unsigned SrcMaskIdx = (unsigned)M % NumMaskElts;
36821
36822 auto &SrcUndefElts = UndefEltsOps[SrcOpIdx];
36823 if (SrcUndefElts[SrcMaskIdx]) {
36824 UndefElts.setBit(i);
36825 continue;
36826 }
36827
36828 auto &SrcEltBits = RawBitsOps[SrcOpIdx];
36829 APInt &Bits = SrcEltBits[SrcMaskIdx];
36830 if (!Bits) {
36831 ZeroElts.setBit(i);
36832 continue;
36833 }
36834
36835 ConstantElts.setBit(i);
36836 ConstantBitData[i] = Bits;
36837 }
36838 assert((UndefElts | ZeroElts | ConstantElts).isAllOnesValue())(static_cast <bool> ((UndefElts | ZeroElts | ConstantElts
).isAllOnesValue()) ? void (0) : __assert_fail ("(UndefElts | ZeroElts | ConstantElts).isAllOnesValue()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 36838, __extension__ __PRETTY_FUNCTION__))
;
36839
36840 // Attempt to create a zero vector.
36841 if ((UndefElts | ZeroElts).isAllOnesValue())
36842 return getZeroVector(Root.getSimpleValueType(), Subtarget, DAG, DL);
36843
36844 // Create the constant data.
36845 MVT MaskSVT;
36846 if (VT.isFloatingPoint() && (MaskSizeInBits == 32 || MaskSizeInBits == 64))
36847 MaskSVT = MVT::getFloatingPointVT(MaskSizeInBits);
36848 else
36849 MaskSVT = MVT::getIntegerVT(MaskSizeInBits);
36850
36851 MVT MaskVT = MVT::getVectorVT(MaskSVT, NumMaskElts);
36852 if (!DAG.getTargetLoweringInfo().isTypeLegal(MaskVT))
36853 return SDValue();
36854
36855 SDValue CstOp = getConstVector(ConstantBitData, UndefElts, MaskVT, DAG, DL);
36856 return DAG.getBitcast(VT, CstOp);
36857}
36858
36859namespace llvm {
36860 namespace X86 {
36861 enum {
36862 MaxShuffleCombineDepth = 8
36863 };
36864 }
36865} // namespace llvm
36866
36867/// Fully generic combining of x86 shuffle instructions.
36868///
36869/// This should be the last combine run over the x86 shuffle instructions. Once
36870/// they have been fully optimized, this will recursively consider all chains
36871/// of single-use shuffle instructions, build a generic model of the cumulative
36872/// shuffle operation, and check for simpler instructions which implement this
36873/// operation. We use this primarily for two purposes:
36874///
36875/// 1) Collapse generic shuffles to specialized single instructions when
36876/// equivalent. In most cases, this is just an encoding size win, but
36877/// sometimes we will collapse multiple generic shuffles into a single
36878/// special-purpose shuffle.
36879/// 2) Look for sequences of shuffle instructions with 3 or more total
36880/// instructions, and replace them with the slightly more expensive SSSE3
36881/// PSHUFB instruction if available. We do this as the last combining step
36882/// to ensure we avoid using PSHUFB if we can implement the shuffle with
36883/// a suitable short sequence of other instructions. The PSHUFB will either
36884/// use a register or have to read from memory and so is slightly (but only
36885/// slightly) more expensive than the other shuffle instructions.
36886///
36887/// Because this is inherently a quadratic operation (for each shuffle in
36888/// a chain, we recurse up the chain), the depth is limited to 8 instructions.
36889/// This should never be an issue in practice as the shuffle lowering doesn't
36890/// produce sequences of more than 8 instructions.
36891///
36892/// FIXME: We will currently miss some cases where the redundant shuffling
36893/// would simplify under the threshold for PSHUFB formation because of
36894/// combine-ordering. To fix this, we should do the redundant instruction
36895/// combining in this recursive walk.
36896static SDValue combineX86ShufflesRecursively(
36897 ArrayRef<SDValue> SrcOps, int SrcOpIndex, SDValue Root,
36898 ArrayRef<int> RootMask, ArrayRef<const SDNode *> SrcNodes, unsigned Depth,
36899 unsigned MaxDepth, bool HasVariableMask, bool AllowVariableCrossLaneMask,
36900 bool AllowVariablePerLaneMask, SelectionDAG &DAG,
36901 const X86Subtarget &Subtarget) {
36902 assert(RootMask.size() > 0 &&(static_cast <bool> (RootMask.size() > 0 && (
RootMask.size() > 1 || (RootMask[0] == 0 && SrcOpIndex
== 0)) && "Illegal shuffle root mask") ? void (0) : __assert_fail
("RootMask.size() > 0 && (RootMask.size() > 1 || (RootMask[0] == 0 && SrcOpIndex == 0)) && \"Illegal shuffle root mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 36904, __extension__ __PRETTY_FUNCTION__))
36903 (RootMask.size() > 1 || (RootMask[0] == 0 && SrcOpIndex == 0)) &&(static_cast <bool> (RootMask.size() > 0 && (
RootMask.size() > 1 || (RootMask[0] == 0 && SrcOpIndex
== 0)) && "Illegal shuffle root mask") ? void (0) : __assert_fail
("RootMask.size() > 0 && (RootMask.size() > 1 || (RootMask[0] == 0 && SrcOpIndex == 0)) && \"Illegal shuffle root mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 36904, __extension__ __PRETTY_FUNCTION__))
36904 "Illegal shuffle root mask")(static_cast <bool> (RootMask.size() > 0 && (
RootMask.size() > 1 || (RootMask[0] == 0 && SrcOpIndex
== 0)) && "Illegal shuffle root mask") ? void (0) : __assert_fail
("RootMask.size() > 0 && (RootMask.size() > 1 || (RootMask[0] == 0 && SrcOpIndex == 0)) && \"Illegal shuffle root mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 36904, __extension__ __PRETTY_FUNCTION__))
;
36905 assert(Root.getSimpleValueType().isVector() &&(static_cast <bool> (Root.getSimpleValueType().isVector
() && "Shuffles operate on vector types!") ? void (0)
: __assert_fail ("Root.getSimpleValueType().isVector() && \"Shuffles operate on vector types!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 36906, __extension__ __PRETTY_FUNCTION__))
36906 "Shuffles operate on vector types!")(static_cast <bool> (Root.getSimpleValueType().isVector
() && "Shuffles operate on vector types!") ? void (0)
: __assert_fail ("Root.getSimpleValueType().isVector() && \"Shuffles operate on vector types!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 36906, __extension__ __PRETTY_FUNCTION__))
;
36907 unsigned RootSizeInBits = Root.getSimpleValueType().getSizeInBits();
36908
36909 // Bound the depth of our recursive combine because this is ultimately
36910 // quadratic in nature.
36911 if (Depth >= MaxDepth)
36912 return SDValue();
36913
36914 // Directly rip through bitcasts to find the underlying operand.
36915 SDValue Op = SrcOps[SrcOpIndex];
36916 Op = peekThroughOneUseBitcasts(Op);
36917
36918 EVT VT = Op.getValueType();
36919 if (!VT.isVector() || !VT.isSimple())
36920 return SDValue(); // Bail if we hit a non-simple non-vector.
36921
36922 assert((RootSizeInBits % VT.getSizeInBits()) == 0 &&(static_cast <bool> ((RootSizeInBits % VT.getSizeInBits
()) == 0 && "Can only combine shuffles upto size of the root op."
) ? void (0) : __assert_fail ("(RootSizeInBits % VT.getSizeInBits()) == 0 && \"Can only combine shuffles upto size of the root op.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 36923, __extension__ __PRETTY_FUNCTION__))
36923 "Can only combine shuffles upto size of the root op.")(static_cast <bool> ((RootSizeInBits % VT.getSizeInBits
()) == 0 && "Can only combine shuffles upto size of the root op."
) ? void (0) : __assert_fail ("(RootSizeInBits % VT.getSizeInBits()) == 0 && \"Can only combine shuffles upto size of the root op.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 36923, __extension__ __PRETTY_FUNCTION__))
;
36924
36925 // Extract target shuffle mask and resolve sentinels and inputs.
36926 // TODO - determine Op's demanded elts from RootMask.
36927 SmallVector<int, 64> OpMask;
36928 SmallVector<SDValue, 2> OpInputs;
36929 APInt OpUndef, OpZero;
36930 APInt OpDemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
36931 bool IsOpVariableMask = isTargetShuffleVariableMask(Op.getOpcode());
36932 if (!getTargetShuffleInputs(Op, OpDemandedElts, OpInputs, OpMask, OpUndef,
36933 OpZero, DAG, Depth, false))
36934 return SDValue();
36935
36936 // Shuffle inputs must not be larger than the shuffle result.
36937 // TODO: Relax this for single input faux shuffles (trunc/extract_subvector).
36938 if (llvm::any_of(OpInputs, [VT](SDValue OpInput) {
36939 return OpInput.getValueSizeInBits() > VT.getSizeInBits();
36940 }))
36941 return SDValue();
36942
36943 // If the shuffle result was smaller than the root, we need to adjust the
36944 // mask indices and pad the mask with undefs.
36945 if (RootSizeInBits > VT.getSizeInBits()) {
36946 unsigned NumSubVecs = RootSizeInBits / VT.getSizeInBits();
36947 unsigned OpMaskSize = OpMask.size();
36948 if (OpInputs.size() > 1) {
36949 unsigned PaddedMaskSize = NumSubVecs * OpMaskSize;
36950 for (int &M : OpMask) {
36951 if (M < 0)
36952 continue;
36953 int EltIdx = M % OpMaskSize;
36954 int OpIdx = M / OpMaskSize;
36955 M = (PaddedMaskSize * OpIdx) + EltIdx;
36956 }
36957 }
36958 OpZero = OpZero.zext(NumSubVecs * OpMaskSize);
36959 OpUndef = OpUndef.zext(NumSubVecs * OpMaskSize);
36960 OpMask.append((NumSubVecs - 1) * OpMaskSize, SM_SentinelUndef);
36961 }
36962
36963 SmallVector<int, 64> Mask;
36964 SmallVector<SDValue, 16> Ops;
36965
36966 // We don't need to merge masks if the root is empty.
36967 bool EmptyRoot = (Depth == 0) && (RootMask.size() == 1);
36968 if (EmptyRoot) {
36969 // Only resolve zeros if it will remove an input, otherwise we might end
36970 // up in an infinite loop.
36971 bool ResolveKnownZeros = true;
36972 if (!OpZero.isNullValue()) {
36973 APInt UsedInputs = APInt::getNullValue(OpInputs.size());
36974 for (int i = 0, e = OpMask.size(); i != e; ++i) {
36975 int M = OpMask[i];
36976 if (OpUndef[i] || OpZero[i] || isUndefOrZero(M))
36977 continue;
36978 UsedInputs.setBit(M / OpMask.size());
36979 if (UsedInputs.isAllOnesValue()) {
36980 ResolveKnownZeros = false;
36981 break;
36982 }
36983 }
36984 }
36985 resolveTargetShuffleFromZeroables(OpMask, OpUndef, OpZero,
36986 ResolveKnownZeros);
36987
36988 Mask = OpMask;
36989 Ops.append(OpInputs.begin(), OpInputs.end());
36990 } else {
36991 resolveTargetShuffleFromZeroables(OpMask, OpUndef, OpZero);
36992
36993 // Add the inputs to the Ops list, avoiding duplicates.
36994 Ops.append(SrcOps.begin(), SrcOps.end());
36995
36996 auto AddOp = [&Ops](SDValue Input, int InsertionPoint) -> int {
36997 // Attempt to find an existing match.
36998 SDValue InputBC = peekThroughBitcasts(Input);
36999 for (int i = 0, e = Ops.size(); i < e; ++i)
37000 if (InputBC == peekThroughBitcasts(Ops[i]))
37001 return i;
37002 // Match failed - should we replace an existing Op?
37003 if (InsertionPoint >= 0) {
37004 Ops[InsertionPoint] = Input;
37005 return InsertionPoint;
37006 }
37007 // Add to the end of the Ops list.
37008 Ops.push_back(Input);
37009 return Ops.size() - 1;
37010 };
37011
37012 SmallVector<int, 2> OpInputIdx;
37013 for (SDValue OpInput : OpInputs)
37014 OpInputIdx.push_back(
37015 AddOp(OpInput, OpInputIdx.empty() ? SrcOpIndex : -1));
37016
37017 assert(((RootMask.size() > OpMask.size() &&(static_cast <bool> (((RootMask.size() > OpMask.size
() && RootMask.size() % OpMask.size() == 0) || (OpMask
.size() > RootMask.size() && OpMask.size() % RootMask
.size() == 0) || OpMask.size() == RootMask.size()) &&
"The smaller number of elements must divide the larger.") ? void
(0) : __assert_fail ("((RootMask.size() > OpMask.size() && RootMask.size() % OpMask.size() == 0) || (OpMask.size() > RootMask.size() && OpMask.size() % RootMask.size() == 0) || OpMask.size() == RootMask.size()) && \"The smaller number of elements must divide the larger.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37022, __extension__ __PRETTY_FUNCTION__))
37018 RootMask.size() % OpMask.size() == 0) ||(static_cast <bool> (((RootMask.size() > OpMask.size
() && RootMask.size() % OpMask.size() == 0) || (OpMask
.size() > RootMask.size() && OpMask.size() % RootMask
.size() == 0) || OpMask.size() == RootMask.size()) &&
"The smaller number of elements must divide the larger.") ? void
(0) : __assert_fail ("((RootMask.size() > OpMask.size() && RootMask.size() % OpMask.size() == 0) || (OpMask.size() > RootMask.size() && OpMask.size() % RootMask.size() == 0) || OpMask.size() == RootMask.size()) && \"The smaller number of elements must divide the larger.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37022, __extension__ __PRETTY_FUNCTION__))
37019 (OpMask.size() > RootMask.size() &&(static_cast <bool> (((RootMask.size() > OpMask.size
() && RootMask.size() % OpMask.size() == 0) || (OpMask
.size() > RootMask.size() && OpMask.size() % RootMask
.size() == 0) || OpMask.size() == RootMask.size()) &&
"The smaller number of elements must divide the larger.") ? void
(0) : __assert_fail ("((RootMask.size() > OpMask.size() && RootMask.size() % OpMask.size() == 0) || (OpMask.size() > RootMask.size() && OpMask.size() % RootMask.size() == 0) || OpMask.size() == RootMask.size()) && \"The smaller number of elements must divide the larger.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37022, __extension__ __PRETTY_FUNCTION__))
37020 OpMask.size() % RootMask.size() == 0) ||(static_cast <bool> (((RootMask.size() > OpMask.size
() && RootMask.size() % OpMask.size() == 0) || (OpMask
.size() > RootMask.size() && OpMask.size() % RootMask
.size() == 0) || OpMask.size() == RootMask.size()) &&
"The smaller number of elements must divide the larger.") ? void
(0) : __assert_fail ("((RootMask.size() > OpMask.size() && RootMask.size() % OpMask.size() == 0) || (OpMask.size() > RootMask.size() && OpMask.size() % RootMask.size() == 0) || OpMask.size() == RootMask.size()) && \"The smaller number of elements must divide the larger.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37022, __extension__ __PRETTY_FUNCTION__))
37021 OpMask.size() == RootMask.size()) &&(static_cast <bool> (((RootMask.size() > OpMask.size
() && RootMask.size() % OpMask.size() == 0) || (OpMask
.size() > RootMask.size() && OpMask.size() % RootMask
.size() == 0) || OpMask.size() == RootMask.size()) &&
"The smaller number of elements must divide the larger.") ? void
(0) : __assert_fail ("((RootMask.size() > OpMask.size() && RootMask.size() % OpMask.size() == 0) || (OpMask.size() > RootMask.size() && OpMask.size() % RootMask.size() == 0) || OpMask.size() == RootMask.size()) && \"The smaller number of elements must divide the larger.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37022, __extension__ __PRETTY_FUNCTION__))
37022 "The smaller number of elements must divide the larger.")(static_cast <bool> (((RootMask.size() > OpMask.size
() && RootMask.size() % OpMask.size() == 0) || (OpMask
.size() > RootMask.size() && OpMask.size() % RootMask
.size() == 0) || OpMask.size() == RootMask.size()) &&
"The smaller number of elements must divide the larger.") ? void
(0) : __assert_fail ("((RootMask.size() > OpMask.size() && RootMask.size() % OpMask.size() == 0) || (OpMask.size() > RootMask.size() && OpMask.size() % RootMask.size() == 0) || OpMask.size() == RootMask.size()) && \"The smaller number of elements must divide the larger.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37022, __extension__ __PRETTY_FUNCTION__))
;
37023
37024 // This function can be performance-critical, so we rely on the power-of-2
37025 // knowledge that we have about the mask sizes to replace div/rem ops with
37026 // bit-masks and shifts.
37027 assert(isPowerOf2_32(RootMask.size()) &&(static_cast <bool> (isPowerOf2_32(RootMask.size()) &&
"Non-power-of-2 shuffle mask sizes") ? void (0) : __assert_fail
("isPowerOf2_32(RootMask.size()) && \"Non-power-of-2 shuffle mask sizes\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37028, __extension__ __PRETTY_FUNCTION__))
37028 "Non-power-of-2 shuffle mask sizes")(static_cast <bool> (isPowerOf2_32(RootMask.size()) &&
"Non-power-of-2 shuffle mask sizes") ? void (0) : __assert_fail
("isPowerOf2_32(RootMask.size()) && \"Non-power-of-2 shuffle mask sizes\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37028, __extension__ __PRETTY_FUNCTION__))
;
37029 assert(isPowerOf2_32(OpMask.size()) && "Non-power-of-2 shuffle mask sizes")(static_cast <bool> (isPowerOf2_32(OpMask.size()) &&
"Non-power-of-2 shuffle mask sizes") ? void (0) : __assert_fail
("isPowerOf2_32(OpMask.size()) && \"Non-power-of-2 shuffle mask sizes\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37029, __extension__ __PRETTY_FUNCTION__))
;
37030 unsigned RootMaskSizeLog2 = countTrailingZeros(RootMask.size());
37031 unsigned OpMaskSizeLog2 = countTrailingZeros(OpMask.size());
37032
37033 unsigned MaskWidth = std::max<unsigned>(OpMask.size(), RootMask.size());
37034 unsigned RootRatio =
37035 std::max<unsigned>(1, OpMask.size() >> RootMaskSizeLog2);
37036 unsigned OpRatio = std::max<unsigned>(1, RootMask.size() >> OpMaskSizeLog2);
37037 assert((RootRatio == 1 || OpRatio == 1) &&(static_cast <bool> ((RootRatio == 1 || OpRatio == 1) &&
"Must not have a ratio for both incoming and op masks!") ? void
(0) : __assert_fail ("(RootRatio == 1 || OpRatio == 1) && \"Must not have a ratio for both incoming and op masks!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37038, __extension__ __PRETTY_FUNCTION__))
37038 "Must not have a ratio for both incoming and op masks!")(static_cast <bool> ((RootRatio == 1 || OpRatio == 1) &&
"Must not have a ratio for both incoming and op masks!") ? void
(0) : __assert_fail ("(RootRatio == 1 || OpRatio == 1) && \"Must not have a ratio for both incoming and op masks!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37038, __extension__ __PRETTY_FUNCTION__))
;
37039
37040 assert(isPowerOf2_32(MaskWidth) && "Non-power-of-2 shuffle mask sizes")(static_cast <bool> (isPowerOf2_32(MaskWidth) &&
"Non-power-of-2 shuffle mask sizes") ? void (0) : __assert_fail
("isPowerOf2_32(MaskWidth) && \"Non-power-of-2 shuffle mask sizes\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37040, __extension__ __PRETTY_FUNCTION__))
;
37041 assert(isPowerOf2_32(RootRatio) && "Non-power-of-2 shuffle mask sizes")(static_cast <bool> (isPowerOf2_32(RootRatio) &&
"Non-power-of-2 shuffle mask sizes") ? void (0) : __assert_fail
("isPowerOf2_32(RootRatio) && \"Non-power-of-2 shuffle mask sizes\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37041, __extension__ __PRETTY_FUNCTION__))
;
37042 assert(isPowerOf2_32(OpRatio) && "Non-power-of-2 shuffle mask sizes")(static_cast <bool> (isPowerOf2_32(OpRatio) && "Non-power-of-2 shuffle mask sizes"
) ? void (0) : __assert_fail ("isPowerOf2_32(OpRatio) && \"Non-power-of-2 shuffle mask sizes\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37042, __extension__ __PRETTY_FUNCTION__))
;
37043 unsigned RootRatioLog2 = countTrailingZeros(RootRatio);
37044 unsigned OpRatioLog2 = countTrailingZeros(OpRatio);
37045
37046 Mask.resize(MaskWidth, SM_SentinelUndef);
37047
37048 // Merge this shuffle operation's mask into our accumulated mask. Note that
37049 // this shuffle's mask will be the first applied to the input, followed by
37050 // the root mask to get us all the way to the root value arrangement. The
37051 // reason for this order is that we are recursing up the operation chain.
37052 for (unsigned i = 0; i < MaskWidth; ++i) {
37053 unsigned RootIdx = i >> RootRatioLog2;
37054 if (RootMask[RootIdx] < 0) {
37055 // This is a zero or undef lane, we're done.
37056 Mask[i] = RootMask[RootIdx];
37057 continue;
37058 }
37059
37060 unsigned RootMaskedIdx =
37061 RootRatio == 1
37062 ? RootMask[RootIdx]
37063 : (RootMask[RootIdx] << RootRatioLog2) + (i & (RootRatio - 1));
37064
37065 // Just insert the scaled root mask value if it references an input other
37066 // than the SrcOp we're currently inserting.
37067 if ((RootMaskedIdx < (SrcOpIndex * MaskWidth)) ||
37068 (((SrcOpIndex + 1) * MaskWidth) <= RootMaskedIdx)) {
37069 Mask[i] = RootMaskedIdx;
37070 continue;
37071 }
37072
37073 RootMaskedIdx = RootMaskedIdx & (MaskWidth - 1);
37074 unsigned OpIdx = RootMaskedIdx >> OpRatioLog2;
37075 if (OpMask[OpIdx] < 0) {
37076 // The incoming lanes are zero or undef, it doesn't matter which ones we
37077 // are using.
37078 Mask[i] = OpMask[OpIdx];
37079 continue;
37080 }
37081
37082 // Ok, we have non-zero lanes, map them through to one of the Op's inputs.
37083 unsigned OpMaskedIdx = OpRatio == 1 ? OpMask[OpIdx]
37084 : (OpMask[OpIdx] << OpRatioLog2) +
37085 (RootMaskedIdx & (OpRatio - 1));
37086
37087 OpMaskedIdx = OpMaskedIdx & (MaskWidth - 1);
37088 int InputIdx = OpMask[OpIdx] / (int)OpMask.size();
37089 assert(0 <= OpInputIdx[InputIdx] && "Unknown target shuffle input")(static_cast <bool> (0 <= OpInputIdx[InputIdx] &&
"Unknown target shuffle input") ? void (0) : __assert_fail (
"0 <= OpInputIdx[InputIdx] && \"Unknown target shuffle input\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37089, __extension__ __PRETTY_FUNCTION__))
;
37090 OpMaskedIdx += OpInputIdx[InputIdx] * MaskWidth;
37091
37092 Mask[i] = OpMaskedIdx;
37093 }
37094 }
37095
37096 // Remove unused/repeated shuffle source ops.
37097 resolveTargetShuffleInputsAndMask(Ops, Mask);
37098
37099 // Handle the all undef/zero/ones cases early.
37100 if (all_of(Mask, [](int Idx) { return Idx == SM_SentinelUndef; }))
37101 return DAG.getUNDEF(Root.getValueType());
37102 if (all_of(Mask, [](int Idx) { return Idx < 0; }))
37103 return getZeroVector(Root.getSimpleValueType(), Subtarget, DAG,
37104 SDLoc(Root));
37105 if (Ops.size() == 1 && ISD::isBuildVectorAllOnes(Ops[0].getNode()) &&
37106 none_of(Mask, [](int M) { return M == SM_SentinelZero; }))
37107 return getOnesVector(Root.getValueType(), DAG, SDLoc(Root));
37108
37109 assert(!Ops.empty() && "Shuffle with no inputs detected")(static_cast <bool> (!Ops.empty() && "Shuffle with no inputs detected"
) ? void (0) : __assert_fail ("!Ops.empty() && \"Shuffle with no inputs detected\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37109, __extension__ __PRETTY_FUNCTION__))
;
37110 HasVariableMask |= IsOpVariableMask;
37111
37112 // Update the list of shuffle nodes that have been combined so far.
37113 SmallVector<const SDNode *, 16> CombinedNodes(SrcNodes.begin(),
37114 SrcNodes.end());
37115 CombinedNodes.push_back(Op.getNode());
37116
37117 // See if we can recurse into each shuffle source op (if it's a target
37118 // shuffle). The source op should only be generally combined if it either has
37119 // a single use (i.e. current Op) or all its users have already been combined,
37120 // if not then we can still combine but should prevent generation of variable
37121 // shuffles to avoid constant pool bloat.
37122 // Don't recurse if we already have more source ops than we can combine in
37123 // the remaining recursion depth.
37124 if (Ops.size() < (MaxDepth - Depth)) {
37125 for (int i = 0, e = Ops.size(); i < e; ++i) {
37126 // For empty roots, we need to resolve zeroable elements before combining
37127 // them with other shuffles.
37128 SmallVector<int, 64> ResolvedMask = Mask;
37129 if (EmptyRoot)
37130 resolveTargetShuffleFromZeroables(ResolvedMask, OpUndef, OpZero);
37131 bool AllowCrossLaneVar = false;
37132 bool AllowPerLaneVar = false;
37133 if (Ops[i].getNode()->hasOneUse() ||
37134 SDNode::areOnlyUsersOf(CombinedNodes, Ops[i].getNode())) {
37135 AllowCrossLaneVar = AllowVariableCrossLaneMask;
37136 AllowPerLaneVar = AllowVariablePerLaneMask;
37137 }
37138 if (SDValue Res = combineX86ShufflesRecursively(
37139 Ops, i, Root, ResolvedMask, CombinedNodes, Depth + 1, MaxDepth,
37140 HasVariableMask, AllowCrossLaneVar, AllowPerLaneVar, DAG,
37141 Subtarget))
37142 return Res;
37143 }
37144 }
37145
37146 // Attempt to constant fold all of the constant source ops.
37147 if (SDValue Cst = combineX86ShufflesConstants(
37148 Ops, Mask, Root, HasVariableMask, DAG, Subtarget))
37149 return Cst;
37150
37151 // If constant fold failed and we only have constants - then we have
37152 // multiple uses by a single non-variable shuffle - just bail.
37153 if (Depth == 0 && llvm::all_of(Ops, [&](SDValue Op) {
37154 APInt UndefElts;
37155 SmallVector<APInt> RawBits;
37156 unsigned EltSizeInBits = RootSizeInBits / Mask.size();
37157 return getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts,
37158 RawBits);
37159 })) {
37160 return SDValue();
37161 }
37162
37163 // Canonicalize the combined shuffle mask chain with horizontal ops.
37164 // NOTE: This will update the Ops and Mask.
37165 if (SDValue HOp = canonicalizeShuffleMaskWithHorizOp(
37166 Ops, Mask, RootSizeInBits, SDLoc(Root), DAG, Subtarget))
37167 return DAG.getBitcast(Root.getValueType(), HOp);
37168
37169 // Widen any subvector shuffle inputs we've collected.
37170 if (any_of(Ops, [RootSizeInBits](SDValue Op) {
37171 return Op.getValueSizeInBits() < RootSizeInBits;
37172 })) {
37173 for (SDValue &Op : Ops)
37174 if (Op.getValueSizeInBits() < RootSizeInBits)
37175 Op = widenSubVector(Op, false, Subtarget, DAG, SDLoc(Op),
37176 RootSizeInBits);
37177 // Reresolve - we might have repeated subvector sources.
37178 resolveTargetShuffleInputsAndMask(Ops, Mask);
37179 }
37180
37181 // We can only combine unary and binary shuffle mask cases.
37182 if (Ops.size() <= 2) {
37183 // Minor canonicalization of the accumulated shuffle mask to make it easier
37184 // to match below. All this does is detect masks with sequential pairs of
37185 // elements, and shrink them to the half-width mask. It does this in a loop
37186 // so it will reduce the size of the mask to the minimal width mask which
37187 // performs an equivalent shuffle.
37188 while (Mask.size() > 1) {
37189 SmallVector<int, 64> WidenedMask;
37190 if (!canWidenShuffleElements(Mask, WidenedMask))
37191 break;
37192 Mask = std::move(WidenedMask);
37193 }
37194
37195 // Canonicalization of binary shuffle masks to improve pattern matching by
37196 // commuting the inputs.
37197 if (Ops.size() == 2 && canonicalizeShuffleMaskWithCommute(Mask)) {
37198 ShuffleVectorSDNode::commuteMask(Mask);
37199 std::swap(Ops[0], Ops[1]);
37200 }
37201
37202 // Finally, try to combine into a single shuffle instruction.
37203 return combineX86ShuffleChain(Ops, Root, Mask, Depth, HasVariableMask,
37204 AllowVariableCrossLaneMask,
37205 AllowVariablePerLaneMask, DAG, Subtarget);
37206 }
37207
37208 // If that failed and any input is extracted then try to combine as a
37209 // shuffle with the larger type.
37210 return combineX86ShuffleChainWithExtract(
37211 Ops, Root, Mask, Depth, HasVariableMask, AllowVariableCrossLaneMask,
37212 AllowVariablePerLaneMask, DAG, Subtarget);
37213}
37214
37215/// Helper entry wrapper to combineX86ShufflesRecursively.
37216static SDValue combineX86ShufflesRecursively(SDValue Op, SelectionDAG &DAG,
37217 const X86Subtarget &Subtarget) {
37218 return combineX86ShufflesRecursively(
37219 {Op}, 0, Op, {0}, {}, /*Depth*/ 0, X86::MaxShuffleCombineDepth,
37220 /*HasVarMask*/ false,
37221 /*AllowCrossLaneVarMask*/ true, /*AllowPerLaneVarMask*/ true, DAG,
37222 Subtarget);
37223}
37224
37225/// Get the PSHUF-style mask from PSHUF node.
37226///
37227/// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
37228/// PSHUF-style masks that can be reused with such instructions.
37229static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
37230 MVT VT = N.getSimpleValueType();
37231 SmallVector<int, 4> Mask;
37232 SmallVector<SDValue, 2> Ops;
37233 bool HaveMask =
37234 getTargetShuffleMask(N.getNode(), VT, false, Ops, Mask);
37235 (void)HaveMask;
37236 assert(HaveMask)(static_cast <bool> (HaveMask) ? void (0) : __assert_fail
("HaveMask", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37236, __extension__ __PRETTY_FUNCTION__))
;
37237
37238 // If we have more than 128-bits, only the low 128-bits of shuffle mask
37239 // matter. Check that the upper masks are repeats and remove them.
37240 if (VT.getSizeInBits() > 128) {
37241 int LaneElts = 128 / VT.getScalarSizeInBits();
37242#ifndef NDEBUG
37243 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
37244 for (int j = 0; j < LaneElts; ++j)
37245 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&(static_cast <bool> (Mask[j] == Mask[i * LaneElts + j] -
(LaneElts * i) && "Mask doesn't repeat in high 128-bit lanes!"
) ? void (0) : __assert_fail ("Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) && \"Mask doesn't repeat in high 128-bit lanes!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37246, __extension__ __PRETTY_FUNCTION__))
37246 "Mask doesn't repeat in high 128-bit lanes!")(static_cast <bool> (Mask[j] == Mask[i * LaneElts + j] -
(LaneElts * i) && "Mask doesn't repeat in high 128-bit lanes!"
) ? void (0) : __assert_fail ("Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) && \"Mask doesn't repeat in high 128-bit lanes!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37246, __extension__ __PRETTY_FUNCTION__))
;
37247#endif
37248 Mask.resize(LaneElts);
37249 }
37250
37251 switch (N.getOpcode()) {
37252 case X86ISD::PSHUFD:
37253 return Mask;
37254 case X86ISD::PSHUFLW:
37255 Mask.resize(4);
37256 return Mask;
37257 case X86ISD::PSHUFHW:
37258 Mask.erase(Mask.begin(), Mask.begin() + 4);
37259 for (int &M : Mask)
37260 M -= 4;
37261 return Mask;
37262 default:
37263 llvm_unreachable("No valid shuffle instruction found!")::llvm::llvm_unreachable_internal("No valid shuffle instruction found!"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37263)
;
37264 }
37265}
37266
37267/// Search for a combinable shuffle across a chain ending in pshufd.
37268///
37269/// We walk up the chain and look for a combinable shuffle, skipping over
37270/// shuffles that we could hoist this shuffle's transformation past without
37271/// altering anything.
37272static SDValue
37273combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
37274 SelectionDAG &DAG) {
37275 assert(N.getOpcode() == X86ISD::PSHUFD &&(static_cast <bool> (N.getOpcode() == X86ISD::PSHUFD &&
"Called with something other than an x86 128-bit half shuffle!"
) ? void (0) : __assert_fail ("N.getOpcode() == X86ISD::PSHUFD && \"Called with something other than an x86 128-bit half shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37276, __extension__ __PRETTY_FUNCTION__))
37276 "Called with something other than an x86 128-bit half shuffle!")(static_cast <bool> (N.getOpcode() == X86ISD::PSHUFD &&
"Called with something other than an x86 128-bit half shuffle!"
) ? void (0) : __assert_fail ("N.getOpcode() == X86ISD::PSHUFD && \"Called with something other than an x86 128-bit half shuffle!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37276, __extension__ __PRETTY_FUNCTION__))
;
37277 SDLoc DL(N);
37278
37279 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
37280 // of the shuffles in the chain so that we can form a fresh chain to replace
37281 // this one.
37282 SmallVector<SDValue, 8> Chain;
37283 SDValue V = N.getOperand(0);
37284 for (; V.hasOneUse(); V = V.getOperand(0)) {
37285 switch (V.getOpcode()) {
37286 default:
37287 return SDValue(); // Nothing combined!
37288
37289 case ISD::BITCAST:
37290 // Skip bitcasts as we always know the type for the target specific
37291 // instructions.
37292 continue;
37293
37294 case X86ISD::PSHUFD:
37295 // Found another dword shuffle.
37296 break;
37297
37298 case X86ISD::PSHUFLW:
37299 // Check that the low words (being shuffled) are the identity in the
37300 // dword shuffle, and the high words are self-contained.
37301 if (Mask[0] != 0 || Mask[1] != 1 ||
37302 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
37303 return SDValue();
37304
37305 Chain.push_back(V);
37306 continue;
37307
37308 case X86ISD::PSHUFHW:
37309 // Check that the high words (being shuffled) are the identity in the
37310 // dword shuffle, and the low words are self-contained.
37311 if (Mask[2] != 2 || Mask[3] != 3 ||
37312 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
37313 return SDValue();
37314
37315 Chain.push_back(V);
37316 continue;
37317
37318 case X86ISD::UNPCKL:
37319 case X86ISD::UNPCKH:
37320 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
37321 // shuffle into a preceding word shuffle.
37322 if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
37323 V.getSimpleValueType().getVectorElementType() != MVT::i16)
37324 return SDValue();
37325
37326 // Search for a half-shuffle which we can combine with.
37327 unsigned CombineOp =
37328 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
37329 if (V.getOperand(0) != V.getOperand(1) ||
37330 !V->isOnlyUserOf(V.getOperand(0).getNode()))
37331 return SDValue();
37332 Chain.push_back(V);
37333 V = V.getOperand(0);
37334 do {
37335 switch (V.getOpcode()) {
37336 default:
37337 return SDValue(); // Nothing to combine.
37338
37339 case X86ISD::PSHUFLW:
37340 case X86ISD::PSHUFHW:
37341 if (V.getOpcode() == CombineOp)
37342 break;
37343
37344 Chain.push_back(V);
37345
37346 LLVM_FALLTHROUGH[[gnu::fallthrough]];
37347 case ISD::BITCAST:
37348 V = V.getOperand(0);
37349 continue;
37350 }
37351 break;
37352 } while (V.hasOneUse());
37353 break;
37354 }
37355 // Break out of the loop if we break out of the switch.
37356 break;
37357 }
37358
37359 if (!V.hasOneUse())
37360 // We fell out of the loop without finding a viable combining instruction.
37361 return SDValue();
37362
37363 // Merge this node's mask and our incoming mask.
37364 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
37365 for (int &M : Mask)
37366 M = VMask[M];
37367 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
37368 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
37369
37370 // Rebuild the chain around this new shuffle.
37371 while (!Chain.empty()) {
37372 SDValue W = Chain.pop_back_val();
37373
37374 if (V.getValueType() != W.getOperand(0).getValueType())
37375 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
37376
37377 switch (W.getOpcode()) {
37378 default:
37379 llvm_unreachable("Only PSHUF and UNPCK instructions get here!")::llvm::llvm_unreachable_internal("Only PSHUF and UNPCK instructions get here!"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37379)
;
37380
37381 case X86ISD::UNPCKL:
37382 case X86ISD::UNPCKH:
37383 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
37384 break;
37385
37386 case X86ISD::PSHUFD:
37387 case X86ISD::PSHUFLW:
37388 case X86ISD::PSHUFHW:
37389 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
37390 break;
37391 }
37392 }
37393 if (V.getValueType() != N.getValueType())
37394 V = DAG.getBitcast(N.getValueType(), V);
37395
37396 // Return the new chain to replace N.
37397 return V;
37398}
37399
37400// Attempt to commute shufps LHS loads:
37401// permilps(shufps(load(),x)) --> permilps(shufps(x,load()))
37402static SDValue combineCommutableSHUFP(SDValue N, MVT VT, const SDLoc &DL,
37403 SelectionDAG &DAG) {
37404 // TODO: Add vXf64 support.
37405 if (VT != MVT::v4f32 && VT != MVT::v8f32 && VT != MVT::v16f32)
37406 return SDValue();
37407
37408 // SHUFP(LHS, RHS) -> SHUFP(RHS, LHS) iff LHS is foldable + RHS is not.
37409 auto commuteSHUFP = [&VT, &DL, &DAG](SDValue Parent, SDValue V) {
37410 if (V.getOpcode() != X86ISD::SHUFP || !Parent->isOnlyUserOf(V.getNode()))
37411 return SDValue();
37412 SDValue N0 = V.getOperand(0);
37413 SDValue N1 = V.getOperand(1);
37414 unsigned Imm = V.getConstantOperandVal(2);
37415 if (!MayFoldLoad(peekThroughOneUseBitcasts(N0)) ||
37416 MayFoldLoad(peekThroughOneUseBitcasts(N1)))
37417 return SDValue();
37418 Imm = ((Imm & 0x0F) << 4) | ((Imm & 0xF0) >> 4);
37419 return DAG.getNode(X86ISD::SHUFP, DL, VT, N1, N0,
37420 DAG.getTargetConstant(Imm, DL, MVT::i8));
37421 };
37422
37423 switch (N.getOpcode()) {
37424 case X86ISD::VPERMILPI:
37425 if (SDValue NewSHUFP = commuteSHUFP(N, N.getOperand(0))) {
37426 unsigned Imm = N.getConstantOperandVal(1);
37427 return DAG.getNode(X86ISD::VPERMILPI, DL, VT, NewSHUFP,
37428 DAG.getTargetConstant(Imm ^ 0xAA, DL, MVT::i8));
37429 }
37430 break;
37431 case X86ISD::SHUFP: {
37432 SDValue N0 = N.getOperand(0);
37433 SDValue N1 = N.getOperand(1);
37434 unsigned Imm = N.getConstantOperandVal(2);
37435 if (N0 == N1) {
37436 if (SDValue NewSHUFP = commuteSHUFP(N, N0))
37437 return DAG.getNode(X86ISD::SHUFP, DL, VT, NewSHUFP, NewSHUFP,
37438 DAG.getTargetConstant(Imm ^ 0xAA, DL, MVT::i8));
37439 } else if (SDValue NewSHUFP = commuteSHUFP(N, N0)) {
37440 return DAG.getNode(X86ISD::SHUFP, DL, VT, NewSHUFP, N1,
37441 DAG.getTargetConstant(Imm ^ 0x0A, DL, MVT::i8));
37442 } else if (SDValue NewSHUFP = commuteSHUFP(N, N1)) {
37443 return DAG.getNode(X86ISD::SHUFP, DL, VT, N0, NewSHUFP,
37444 DAG.getTargetConstant(Imm ^ 0xA0, DL, MVT::i8));
37445 }
37446 break;
37447 }
37448 }
37449
37450 return SDValue();
37451}
37452
37453// Canonicalize SHUFFLE(BINOP(X,Y)) -> BINOP(SHUFFLE(X),SHUFFLE(Y)).
37454static SDValue canonicalizeShuffleWithBinOps(SDValue N, SelectionDAG &DAG,
37455 const SDLoc &DL) {
37456 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
37457 EVT ShuffleVT = N.getValueType();
37458
37459 auto IsMergeableWithShuffle = [](SDValue Op) {
37460 // AllZeros/AllOnes constants are freely shuffled and will peek through
37461 // bitcasts. Other constant build vectors do not peek through bitcasts. Only
37462 // merge with target shuffles if it has one use so shuffle combining is
37463 // likely to kick in.
37464 return ISD::isBuildVectorAllOnes(Op.getNode()) ||
37465 ISD::isBuildVectorAllZeros(Op.getNode()) ||
37466 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
37467 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()) ||
37468 (isTargetShuffle(Op.getOpcode()) && Op->hasOneUse());
37469 };
37470 auto IsSafeToMoveShuffle = [ShuffleVT](SDValue Op, unsigned BinOp) {
37471 // Ensure we only shuffle whole vector src elements, unless its a logical
37472 // binops where we can more aggressively move shuffles from dst to src.
37473 return BinOp == ISD::AND || BinOp == ISD::OR || BinOp == ISD::XOR ||
37474 (Op.getScalarValueSizeInBits() <= ShuffleVT.getScalarSizeInBits());
37475 };
37476
37477 unsigned Opc = N.getOpcode();
37478 switch (Opc) {
37479 // Unary and Unary+Permute Shuffles.
37480 case X86ISD::PSHUFB: {
37481 // Don't merge PSHUFB if it contains zero'd elements.
37482 SmallVector<int> Mask;
37483 SmallVector<SDValue> Ops;
37484 if (!getTargetShuffleMask(N.getNode(), ShuffleVT.getSimpleVT(), false, Ops,
37485 Mask))
37486 break;
37487 LLVM_FALLTHROUGH[[gnu::fallthrough]];
37488 }
37489 case X86ISD::VBROADCAST:
37490 case X86ISD::MOVDDUP:
37491 case X86ISD::PSHUFD:
37492 case X86ISD::VPERMI:
37493 case X86ISD::VPERMILPI: {
37494 if (N.getOperand(0).getValueType() == ShuffleVT &&
37495 N->isOnlyUserOf(N.getOperand(0).getNode())) {
37496 SDValue N0 = peekThroughOneUseBitcasts(N.getOperand(0));
37497 unsigned SrcOpcode = N0.getOpcode();
37498 if (TLI.isBinOp(SrcOpcode) && IsSafeToMoveShuffle(N0, SrcOpcode)) {
37499 SDValue Op00 = peekThroughOneUseBitcasts(N0.getOperand(0));
37500 SDValue Op01 = peekThroughOneUseBitcasts(N0.getOperand(1));
37501 if (IsMergeableWithShuffle(Op00) || IsMergeableWithShuffle(Op01)) {
37502 SDValue LHS, RHS;
37503 Op00 = DAG.getBitcast(ShuffleVT, Op00);
37504 Op01 = DAG.getBitcast(ShuffleVT, Op01);
37505 if (N.getNumOperands() == 2) {
37506 LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00, N.getOperand(1));
37507 RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01, N.getOperand(1));
37508 } else {
37509 LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00);
37510 RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01);
37511 }
37512 EVT OpVT = N0.getValueType();
37513 return DAG.getBitcast(ShuffleVT,
37514 DAG.getNode(SrcOpcode, DL, OpVT,
37515 DAG.getBitcast(OpVT, LHS),
37516 DAG.getBitcast(OpVT, RHS)));
37517 }
37518 }
37519 }
37520 break;
37521 }
37522 // Binary and Binary+Permute Shuffles.
37523 case X86ISD::INSERTPS: {
37524 // Don't merge INSERTPS if it contains zero'd elements.
37525 unsigned InsertPSMask = N.getConstantOperandVal(2);
37526 unsigned ZeroMask = InsertPSMask & 0xF;
37527 if (ZeroMask != 0)
37528 break;
37529 LLVM_FALLTHROUGH[[gnu::fallthrough]];
37530 }
37531 case X86ISD::MOVSD:
37532 case X86ISD::MOVSS:
37533 case X86ISD::BLENDI:
37534 case X86ISD::SHUFP:
37535 case X86ISD::UNPCKH:
37536 case X86ISD::UNPCKL: {
37537 if (N->isOnlyUserOf(N.getOperand(0).getNode()) &&
37538 N->isOnlyUserOf(N.getOperand(1).getNode())) {
37539 SDValue N0 = peekThroughOneUseBitcasts(N.getOperand(0));
37540 SDValue N1 = peekThroughOneUseBitcasts(N.getOperand(1));
37541 unsigned SrcOpcode = N0.getOpcode();
37542 if (TLI.isBinOp(SrcOpcode) && N1.getOpcode() == SrcOpcode &&
37543 IsSafeToMoveShuffle(N0, SrcOpcode) &&
37544 IsSafeToMoveShuffle(N1, SrcOpcode)) {
37545 SDValue Op00 = peekThroughOneUseBitcasts(N0.getOperand(0));
37546 SDValue Op10 = peekThroughOneUseBitcasts(N1.getOperand(0));
37547 SDValue Op01 = peekThroughOneUseBitcasts(N0.getOperand(1));
37548 SDValue Op11 = peekThroughOneUseBitcasts(N1.getOperand(1));
37549 // Ensure the total number of shuffles doesn't increase by folding this
37550 // shuffle through to the source ops.
37551 if (((IsMergeableWithShuffle(Op00) && IsMergeableWithShuffle(Op10)) ||
37552 (IsMergeableWithShuffle(Op01) && IsMergeableWithShuffle(Op11))) ||
37553 ((IsMergeableWithShuffle(Op00) || IsMergeableWithShuffle(Op10)) &&
37554 (IsMergeableWithShuffle(Op01) || IsMergeableWithShuffle(Op11)))) {
37555 SDValue LHS, RHS;
37556 Op00 = DAG.getBitcast(ShuffleVT, Op00);
37557 Op10 = DAG.getBitcast(ShuffleVT, Op10);
37558 Op01 = DAG.getBitcast(ShuffleVT, Op01);
37559 Op11 = DAG.getBitcast(ShuffleVT, Op11);
37560 if (N.getNumOperands() == 3) {
37561 LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00, Op10, N.getOperand(2));
37562 RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01, Op11, N.getOperand(2));
37563 } else {
37564 LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00, Op10);
37565 RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01, Op11);
37566 }
37567 EVT OpVT = N0.getValueType();
37568 return DAG.getBitcast(ShuffleVT,
37569 DAG.getNode(SrcOpcode, DL, OpVT,
37570 DAG.getBitcast(OpVT, LHS),
37571 DAG.getBitcast(OpVT, RHS)));
37572 }
37573 }
37574 }
37575 break;
37576 }
37577 }
37578 return SDValue();
37579}
37580
37581/// Attempt to fold vpermf128(op(),op()) -> op(vpermf128(),vpermf128()).
37582static SDValue canonicalizeLaneShuffleWithRepeatedOps(SDValue V,
37583 SelectionDAG &DAG,
37584 const SDLoc &DL) {
37585 assert(V.getOpcode() == X86ISD::VPERM2X128 && "Unknown lane shuffle")(static_cast <bool> (V.getOpcode() == X86ISD::VPERM2X128
&& "Unknown lane shuffle") ? void (0) : __assert_fail
("V.getOpcode() == X86ISD::VPERM2X128 && \"Unknown lane shuffle\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37585, __extension__ __PRETTY_FUNCTION__))
;
37586
37587 MVT VT = V.getSimpleValueType();
37588 SDValue Src0 = peekThroughBitcasts(V.getOperand(0));
37589 SDValue Src1 = peekThroughBitcasts(V.getOperand(1));
37590 unsigned SrcOpc0 = Src0.getOpcode();
37591 unsigned SrcOpc1 = Src1.getOpcode();
37592 EVT SrcVT0 = Src0.getValueType();
37593 EVT SrcVT1 = Src1.getValueType();
37594
37595 if (!Src1.isUndef() && (SrcVT0 != SrcVT1 || SrcOpc0 != SrcOpc1))
37596 return SDValue();
37597
37598 switch (SrcOpc0) {
37599 case X86ISD::MOVDDUP: {
37600 SDValue LHS = Src0.getOperand(0);
37601 SDValue RHS = Src1.isUndef() ? Src1 : Src1.getOperand(0);
37602 SDValue Res =
37603 DAG.getNode(X86ISD::VPERM2X128, DL, SrcVT0, LHS, RHS, V.getOperand(2));
37604 Res = DAG.getNode(SrcOpc0, DL, SrcVT0, Res);
37605 return DAG.getBitcast(VT, Res);
37606 }
37607 case X86ISD::VPERMILPI:
37608 // TODO: Handle v4f64 permutes with different low/high lane masks.
37609 if (SrcVT0 == MVT::v4f64) {
37610 uint64_t Mask = Src0.getConstantOperandVal(1);
37611 if ((Mask & 0x3) != ((Mask >> 2) & 0x3))
37612 break;
37613 }
37614 LLVM_FALLTHROUGH[[gnu::fallthrough]];
37615 case X86ISD::VSHLI:
37616 case X86ISD::VSRLI:
37617 case X86ISD::VSRAI:
37618 case X86ISD::PSHUFD:
37619 if (Src1.isUndef() || Src0.getOperand(1) == Src1.getOperand(1)) {
37620 SDValue LHS = Src0.getOperand(0);
37621 SDValue RHS = Src1.isUndef() ? Src1 : Src1.getOperand(0);
37622 SDValue Res = DAG.getNode(X86ISD::VPERM2X128, DL, SrcVT0, LHS, RHS,
37623 V.getOperand(2));
37624 Res = DAG.getNode(SrcOpc0, DL, SrcVT0, Res, Src0.getOperand(1));
37625 return DAG.getBitcast(VT, Res);
37626 }
37627 break;
37628 }
37629
37630 return SDValue();
37631}
37632
37633/// Try to combine x86 target specific shuffles.
37634static SDValue combineTargetShuffle(SDValue N, SelectionDAG &DAG,
37635 TargetLowering::DAGCombinerInfo &DCI,
37636 const X86Subtarget &Subtarget) {
37637 SDLoc DL(N);
37638 MVT VT = N.getSimpleValueType();
37639 SmallVector<int, 4> Mask;
37640 unsigned Opcode = N.getOpcode();
37641
37642 if (SDValue R = combineCommutableSHUFP(N, VT, DL, DAG))
37643 return R;
37644
37645 if (SDValue R = canonicalizeShuffleWithBinOps(N, DAG, DL))
37646 return R;
37647
37648 // Handle specific target shuffles.
37649 switch (Opcode) {
37650 case X86ISD::MOVDDUP: {
37651 SDValue Src = N.getOperand(0);
37652 // Turn a 128-bit MOVDDUP of a full vector load into movddup+vzload.
37653 if (VT == MVT::v2f64 && Src.hasOneUse() &&
37654 ISD::isNormalLoad(Src.getNode())) {
37655 LoadSDNode *LN = cast<LoadSDNode>(Src);
37656 if (SDValue VZLoad = narrowLoadToVZLoad(LN, MVT::f64, MVT::v2f64, DAG)) {
37657 SDValue Movddup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, VZLoad);
37658 DCI.CombineTo(N.getNode(), Movddup);
37659 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
37660 DCI.recursivelyDeleteUnusedNodes(LN);
37661 return N; // Return N so it doesn't get rechecked!
37662 }
37663 }
37664
37665 return SDValue();
37666 }
37667 case X86ISD::VBROADCAST: {
37668 SDValue Src = N.getOperand(0);
37669 SDValue BC = peekThroughBitcasts(Src);
37670 EVT SrcVT = Src.getValueType();
37671 EVT BCVT = BC.getValueType();
37672
37673 // If broadcasting from another shuffle, attempt to simplify it.
37674 // TODO - we really need a general SimplifyDemandedVectorElts mechanism.
37675 if (isTargetShuffle(BC.getOpcode()) &&
37676 VT.getScalarSizeInBits() % BCVT.getScalarSizeInBits() == 0) {
37677 unsigned Scale = VT.getScalarSizeInBits() / BCVT.getScalarSizeInBits();
37678 SmallVector<int, 16> DemandedMask(BCVT.getVectorNumElements(),
37679 SM_SentinelUndef);
37680 for (unsigned i = 0; i != Scale; ++i)
37681 DemandedMask[i] = i;
37682 if (SDValue Res = combineX86ShufflesRecursively(
37683 {BC}, 0, BC, DemandedMask, {}, /*Depth*/ 0,
37684 X86::MaxShuffleCombineDepth,
37685 /*HasVarMask*/ false, /*AllowCrossLaneVarMask*/ true,
37686 /*AllowPerLaneVarMask*/ true, DAG, Subtarget))
37687 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
37688 DAG.getBitcast(SrcVT, Res));
37689 }
37690
37691 // broadcast(bitcast(src)) -> bitcast(broadcast(src))
37692 // 32-bit targets have to bitcast i64 to f64, so better to bitcast upward.
37693 if (Src.getOpcode() == ISD::BITCAST &&
37694 SrcVT.getScalarSizeInBits() == BCVT.getScalarSizeInBits() &&
37695 DAG.getTargetLoweringInfo().isTypeLegal(BCVT) &&
37696 FixedVectorType::isValidElementType(
37697 BCVT.getScalarType().getTypeForEVT(*DAG.getContext()))) {
37698 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), BCVT.getScalarType(),
37699 VT.getVectorNumElements());
37700 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, DL, NewVT, BC));
37701 }
37702
37703 // Reduce broadcast source vector to lowest 128-bits.
37704 if (SrcVT.getSizeInBits() > 128)
37705 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
37706 extract128BitVector(Src, 0, DAG, DL));
37707
37708 // broadcast(scalar_to_vector(x)) -> broadcast(x).
37709 if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR)
37710 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Src.getOperand(0));
37711
37712 // Share broadcast with the longest vector and extract low subvector (free).
37713 // Ensure the same SDValue from the SDNode use is being used.
37714 for (SDNode *User : Src->uses())
37715 if (User != N.getNode() && User->getOpcode() == X86ISD::VBROADCAST &&
37716 Src == User->getOperand(0) &&
37717 User->getValueSizeInBits(0).getFixedSize() >
37718 VT.getFixedSizeInBits()) {
37719 return extractSubVector(SDValue(User, 0), 0, DAG, DL,
37720 VT.getSizeInBits());
37721 }
37722
37723 // vbroadcast(scalarload X) -> vbroadcast_load X
37724 // For float loads, extract other uses of the scalar from the broadcast.
37725 if (!SrcVT.isVector() && (Src.hasOneUse() || VT.isFloatingPoint()) &&
37726 ISD::isNormalLoad(Src.getNode())) {
37727 LoadSDNode *LN = cast<LoadSDNode>(Src);
37728 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
37729 SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
37730 SDValue BcastLd =
37731 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
37732 LN->getMemoryVT(), LN->getMemOperand());
37733 // If the load value is used only by N, replace it via CombineTo N.
37734 bool NoReplaceExtract = Src.hasOneUse();
37735 DCI.CombineTo(N.getNode(), BcastLd);
37736 if (NoReplaceExtract) {
37737 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
37738 DCI.recursivelyDeleteUnusedNodes(LN);
37739 } else {
37740 SDValue Scl = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT, BcastLd,
37741 DAG.getIntPtrConstant(0, DL));
37742 DCI.CombineTo(LN, Scl, BcastLd.getValue(1));
37743 }
37744 return N; // Return N so it doesn't get rechecked!
37745 }
37746
37747 // Due to isTypeDesirableForOp, we won't always shrink a load truncated to
37748 // i16. So shrink it ourselves if we can make a broadcast_load.
37749 if (SrcVT == MVT::i16 && Src.getOpcode() == ISD::TRUNCATE &&
37750 Src.hasOneUse() && Src.getOperand(0).hasOneUse()) {
37751 assert(Subtarget.hasAVX2() && "Expected AVX2")(static_cast <bool> (Subtarget.hasAVX2() && "Expected AVX2"
) ? void (0) : __assert_fail ("Subtarget.hasAVX2() && \"Expected AVX2\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 37751, __extension__ __PRETTY_FUNCTION__))
;
37752 SDValue TruncIn = Src.getOperand(0);
37753
37754 // If this is a truncate of a non extending load we can just narrow it to
37755 // use a broadcast_load.
37756 if (ISD::isNormalLoad(TruncIn.getNode())) {
37757 LoadSDNode *LN = cast<LoadSDNode>(TruncIn);
37758 // Unless its volatile or atomic.
37759 if (LN->isSimple()) {
37760 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
37761 SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
37762 SDValue BcastLd = DAG.getMemIntrinsicNode(
37763 X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::i16,
37764 LN->getPointerInfo(), LN->getOriginalAlign(),
37765 LN->getMemOperand()->getFlags());
37766 DCI.CombineTo(N.getNode(), BcastLd);
37767 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
37768 DCI.recursivelyDeleteUnusedNodes(Src.getNode());
37769 return N; // Return N so it doesn't get rechecked!
37770 }
37771 }
37772
37773 // If this is a truncate of an i16 extload, we can directly replace it.
37774 if (ISD::isUNINDEXEDLoad(Src.getOperand(0).getNode()) &&
37775 ISD::isEXTLoad(Src.getOperand(0).getNode())) {
37776 LoadSDNode *LN = cast<LoadSDNode>(Src.getOperand(0));
37777 if (LN->getMemoryVT().getSizeInBits() == 16) {
37778 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
37779 SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
37780 SDValue BcastLd =
37781 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
37782 LN->getMemoryVT(), LN->getMemOperand());
37783 DCI.CombineTo(N.getNode(), BcastLd);
37784 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
37785 DCI.recursivelyDeleteUnusedNodes(Src.getNode());
37786 return N; // Return N so it doesn't get rechecked!
37787 }
37788 }
37789
37790 // If this is a truncate of load that has been shifted right, we can
37791 // offset the pointer and use a narrower load.
37792 if (TruncIn.getOpcode() == ISD::SRL &&
37793 TruncIn.getOperand(0).hasOneUse() &&
37794 isa<ConstantSDNode>(TruncIn.getOperand(1)) &&
37795 ISD::isNormalLoad(TruncIn.getOperand(0).getNode())) {
37796 LoadSDNode *LN = cast<LoadSDNode>(TruncIn.getOperand(0));
37797 unsigned ShiftAmt = TruncIn.getConstantOperandVal(1);
37798 // Make sure the shift amount and the load size are divisible by 16.
37799 // Don't do this if the load is volatile or atomic.
37800 if (ShiftAmt % 16 == 0 && TruncIn.getValueSizeInBits() % 16 == 0 &&
37801 LN->isSimple()) {
37802 unsigned Offset = ShiftAmt / 8;
37803 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
37804 SDValue Ptr = DAG.getMemBasePlusOffset(LN->getBasePtr(),
37805 TypeSize::Fixed(Offset), DL);
37806 SDValue Ops[] = { LN->getChain(), Ptr };
37807 SDValue BcastLd = DAG.getMemIntrinsicNode(
37808 X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::i16,
37809 LN->getPointerInfo().getWithOffset(Offset),
37810 LN->getOriginalAlign(),
37811 LN->getMemOperand()->getFlags());
37812 DCI.CombineTo(N.getNode(), BcastLd);
37813 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
37814 DCI.recursivelyDeleteUnusedNodes(Src.getNode());
37815 return N; // Return N so it doesn't get rechecked!
37816 }
37817 }
37818 }
37819
37820 // vbroadcast(vzload X) -> vbroadcast_load X
37821 if (Src.getOpcode() == X86ISD::VZEXT_LOAD && Src.hasOneUse()) {
37822 MemSDNode *LN = cast<MemIntrinsicSDNode>(Src);
37823 if (LN->getMemoryVT().getSizeInBits() == VT.getScalarSizeInBits()) {
37824 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
37825 SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
37826 SDValue BcastLd =
37827 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
37828 LN->getMemoryVT(), LN->getMemOperand());
37829 DCI.CombineTo(N.getNode(), BcastLd);
37830 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
37831 DCI.recursivelyDeleteUnusedNodes(LN);
37832 return N; // Return N so it doesn't get rechecked!
37833 }
37834 }
37835
37836 // vbroadcast(vector load X) -> vbroadcast_load
37837 if ((SrcVT == MVT::v2f64 || SrcVT == MVT::v4f32 || SrcVT == MVT::v2i64 ||
37838 SrcVT == MVT::v4i32) &&
37839 Src.hasOneUse() && ISD::isNormalLoad(Src.getNode())) {
37840 LoadSDNode *LN = cast<LoadSDNode>(Src);
37841 // Unless the load is volatile or atomic.
37842 if (LN->isSimple()) {
37843 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
37844 SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
37845 SDValue BcastLd = DAG.getMemIntrinsicNode(
37846 X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, SrcVT.getScalarType(),
37847 LN->getPointerInfo(), LN->getOriginalAlign(),
37848 LN->getMemOperand()->getFlags());
37849 DCI.CombineTo(N.getNode(), BcastLd);
37850 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
37851 DCI.recursivelyDeleteUnusedNodes(LN);
37852 return N; // Return N so it doesn't get rechecked!
37853 }
37854 }
37855
37856 return SDValue();
37857 }
37858 case X86ISD::VZEXT_MOVL: {
37859 SDValue N0 = N.getOperand(0);
37860
37861 // If this a vzmovl of a full vector load, replace it with a vzload, unless
37862 // the load is volatile.
37863 if (N0.hasOneUse() && ISD::isNormalLoad(N0.getNode())) {
37864 auto *LN = cast<LoadSDNode>(N0);
37865 if (SDValue VZLoad =
37866 narrowLoadToVZLoad(LN, VT.getVectorElementType(), VT, DAG)) {
37867 DCI.CombineTo(N.getNode(), VZLoad);
37868 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
37869 DCI.recursivelyDeleteUnusedNodes(LN);
37870 return N;
37871 }
37872 }
37873
37874 // If this a VZEXT_MOVL of a VBROADCAST_LOAD, we don't need the broadcast
37875 // and can just use a VZEXT_LOAD.
37876 // FIXME: Is there some way to do this with SimplifyDemandedVectorElts?
37877 if (N0.hasOneUse() && N0.getOpcode() == X86ISD::VBROADCAST_LOAD) {
37878 auto *LN = cast<MemSDNode>(N0);
37879 if (VT.getScalarSizeInBits() == LN->getMemoryVT().getSizeInBits()) {
37880 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
37881 SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
37882 SDValue VZLoad =
37883 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
37884 LN->getMemoryVT(), LN->getMemOperand());
37885 DCI.CombineTo(N.getNode(), VZLoad);
37886 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
37887 DCI.recursivelyDeleteUnusedNodes(LN);
37888 return N;
37889 }
37890 }
37891
37892 // Turn (v2i64 (vzext_movl (scalar_to_vector (i64 X)))) into
37893 // (v2i64 (bitcast (v4i32 (vzext_movl (scalar_to_vector (i32 (trunc X)))))))
37894 // if the upper bits of the i64 are zero.
37895 if (N0.hasOneUse() && N0.getOpcode() == ISD::SCALAR_TO_VECTOR &&
37896 N0.getOperand(0).hasOneUse() &&
37897 N0.getOperand(0).getValueType() == MVT::i64) {
37898 SDValue In = N0.getOperand(0);
37899 APInt Mask = APInt::getHighBitsSet(64, 32);
37900 if (DAG.MaskedValueIsZero(In, Mask)) {
37901 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, In);
37902 MVT VecVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
37903 SDValue SclVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Trunc);
37904 SDValue Movl = DAG.getNode(X86ISD::VZEXT_MOVL, DL, VecVT, SclVec);
37905 return DAG.getBitcast(VT, Movl);
37906 }
37907 }
37908
37909 // Load a scalar integer constant directly to XMM instead of transferring an
37910 // immediate value from GPR.
37911 // vzext_movl (scalar_to_vector C) --> load [C,0...]
37912 if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR) {
37913 if (auto *C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
37914 // Create a vector constant - scalar constant followed by zeros.
37915 EVT ScalarVT = N0.getOperand(0).getValueType();
37916 Type *ScalarTy = ScalarVT.getTypeForEVT(*DAG.getContext());
37917 unsigned NumElts = VT.getVectorNumElements();
37918 Constant *Zero = ConstantInt::getNullValue(ScalarTy);
37919 SmallVector<Constant *, 32> ConstantVec(NumElts, Zero);
37920 ConstantVec[0] = const_cast<ConstantInt *>(C->getConstantIntValue());
37921
37922 // Load the vector constant from constant pool.
37923 MVT PVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
37924 SDValue CP = DAG.getConstantPool(ConstantVector::get(ConstantVec), PVT);
37925 MachinePointerInfo MPI =
37926 MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
37927 Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
37928 return DAG.getLoad(VT, DL, DAG.getEntryNode(), CP, MPI, Alignment,
37929 MachineMemOperand::MOLoad);
37930 }
37931 }
37932
37933 // Pull subvector inserts into undef through VZEXT_MOVL by making it an
37934 // insert into a zero vector. This helps get VZEXT_MOVL closer to
37935 // scalar_to_vectors where 256/512 are canonicalized to an insert and a
37936 // 128-bit scalar_to_vector. This reduces the number of isel patterns.
37937 if (!DCI.isBeforeLegalizeOps() && N0.hasOneUse()) {
37938 SDValue V = peekThroughOneUseBitcasts(N0);
37939
37940 if (V.getOpcode() == ISD::INSERT_SUBVECTOR && V.getOperand(0).isUndef() &&
37941 isNullConstant(V.getOperand(2))) {
37942 SDValue In = V.getOperand(1);
37943 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
37944 In.getValueSizeInBits() /
37945 VT.getScalarSizeInBits());
37946 In = DAG.getBitcast(SubVT, In);
37947 SDValue Movl = DAG.getNode(X86ISD::VZEXT_MOVL, DL, SubVT, In);
37948 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
37949 getZeroVector(VT, Subtarget, DAG, DL), Movl,
37950 V.getOperand(2));
37951 }
37952 }
37953
37954 return SDValue();
37955 }
37956 case X86ISD::BLENDI: {
37957 SDValue N0 = N.getOperand(0);
37958 SDValue N1 = N.getOperand(1);
37959
37960 // blend(bitcast(x),bitcast(y)) -> bitcast(blend(x,y)) to narrower types.
37961 // TODO: Handle MVT::v16i16 repeated blend mask.
37962 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
37963 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
37964 MVT SrcVT = N0.getOperand(0).getSimpleValueType();
37965 if ((VT.getScalarSizeInBits() % SrcVT.getScalarSizeInBits()) == 0 &&
37966 SrcVT.getScalarSizeInBits() >= 32) {
37967 unsigned BlendMask = N.getConstantOperandVal(2);
37968 unsigned Size = VT.getVectorNumElements();
37969 unsigned Scale = VT.getScalarSizeInBits() / SrcVT.getScalarSizeInBits();
37970 BlendMask = scaleVectorShuffleBlendMask(BlendMask, Size, Scale);
37971 return DAG.getBitcast(
37972 VT, DAG.getNode(X86ISD::BLENDI, DL, SrcVT, N0.getOperand(0),
37973 N1.getOperand(0),
37974 DAG.getTargetConstant(BlendMask, DL, MVT::i8)));
37975 }
37976 }
37977 return SDValue();
37978 }
37979 case X86ISD::VPERMI: {
37980 // vpermi(bitcast(x)) -> bitcast(vpermi(x)) for same number of elements.
37981 // TODO: Remove when we have preferred domains in combineX86ShuffleChain.
37982 SDValue N0 = N.getOperand(0);
37983 SDValue N1 = N.getOperand(1);
37984 unsigned EltSizeInBits = VT.getScalarSizeInBits();
37985 if (N0.getOpcode() == ISD::BITCAST &&
37986 N0.getOperand(0).getScalarValueSizeInBits() == EltSizeInBits) {
37987 SDValue Src = N0.getOperand(0);
37988 EVT SrcVT = Src.getValueType();
37989 SDValue Res = DAG.getNode(X86ISD::VPERMI, DL, SrcVT, Src, N1);
37990 return DAG.getBitcast(VT, Res);
37991 }
37992 return SDValue();
37993 }
37994 case X86ISD::VPERM2X128: {
37995 // Fold vperm2x128(bitcast(x),bitcast(y),c) -> bitcast(vperm2x128(x,y,c)).
37996 SDValue LHS = N->getOperand(0);
37997 SDValue RHS = N->getOperand(1);
37998 if (LHS.getOpcode() == ISD::BITCAST &&
37999 (RHS.getOpcode() == ISD::BITCAST || RHS.isUndef())) {
38000 EVT SrcVT = LHS.getOperand(0).getValueType();
38001 if (RHS.isUndef() || SrcVT == RHS.getOperand(0).getValueType()) {
38002 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VPERM2X128, DL, SrcVT,
38003 DAG.getBitcast(SrcVT, LHS),
38004 DAG.getBitcast(SrcVT, RHS),
38005 N->getOperand(2)));
38006 }
38007 }
38008
38009 // Fold vperm2x128(op(),op()) -> op(vperm2x128(),vperm2x128()).
38010 if (SDValue Res = canonicalizeLaneShuffleWithRepeatedOps(N, DAG, DL))
38011 return Res;
38012
38013 // Fold vperm2x128 subvector shuffle with an inner concat pattern.
38014 // vperm2x128(concat(X,Y),concat(Z,W)) --> concat X,Y etc.
38015 auto FindSubVector128 = [&](unsigned Idx) {
38016 if (Idx > 3)
38017 return SDValue();
38018 SDValue Src = peekThroughBitcasts(N.getOperand(Idx < 2 ? 0 : 1));
38019 SmallVector<SDValue> SubOps;
38020 if (collectConcatOps(Src.getNode(), SubOps) && SubOps.size() == 2)
38021 return SubOps[Idx & 1];
38022 unsigned NumElts = Src.getValueType().getVectorNumElements();
38023 if ((Idx & 1) == 1 && Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
38024 Src.getOperand(1).getValueSizeInBits() == 128 &&
38025 Src.getConstantOperandAPInt(2) == (NumElts / 2)) {
38026 return Src.getOperand(1);
38027 }
38028 return SDValue();
38029 };
38030 unsigned Imm = N.getConstantOperandVal(2);
38031 if (SDValue SubLo = FindSubVector128(Imm & 0x0F)) {
38032 if (SDValue SubHi = FindSubVector128((Imm & 0xF0) >> 4)) {
38033 MVT SubVT = VT.getHalfNumVectorElementsVT();
38034 SubLo = DAG.getBitcast(SubVT, SubLo);
38035 SubHi = DAG.getBitcast(SubVT, SubHi);
38036 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, SubLo, SubHi);
38037 }
38038 }
38039 return SDValue();
38040 }
38041 case X86ISD::PSHUFD:
38042 case X86ISD::PSHUFLW:
38043 case X86ISD::PSHUFHW:
38044 Mask = getPSHUFShuffleMask(N);
38045 assert(Mask.size() == 4)(static_cast <bool> (Mask.size() == 4) ? void (0) : __assert_fail
("Mask.size() == 4", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 38045, __extension__ __PRETTY_FUNCTION__))
;
38046 break;
38047 case X86ISD::MOVSD:
38048 case X86ISD::MOVSS: {
38049 SDValue N0 = N.getOperand(0);
38050 SDValue N1 = N.getOperand(1);
38051
38052 // Canonicalize scalar FPOps:
38053 // MOVS*(N0, OP(N0, N1)) --> MOVS*(N0, SCALAR_TO_VECTOR(OP(N0[0], N1[0])))
38054 // If commutable, allow OP(N1[0], N0[0]).
38055 unsigned Opcode1 = N1.getOpcode();
38056 if (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL || Opcode1 == ISD::FSUB ||
38057 Opcode1 == ISD::FDIV) {
38058 SDValue N10 = N1.getOperand(0);
38059 SDValue N11 = N1.getOperand(1);
38060 if (N10 == N0 ||
38061 (N11 == N0 && (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL))) {
38062 if (N10 != N0)
38063 std::swap(N10, N11);
38064 MVT SVT = VT.getVectorElementType();
38065 SDValue ZeroIdx = DAG.getIntPtrConstant(0, DL);
38066 N10 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N10, ZeroIdx);
38067 N11 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N11, ZeroIdx);
38068 SDValue Scl = DAG.getNode(Opcode1, DL, SVT, N10, N11);
38069 SDValue SclVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Scl);
38070 return DAG.getNode(Opcode, DL, VT, N0, SclVec);
38071 }
38072 }
38073
38074 return SDValue();
38075 }
38076 case X86ISD::INSERTPS: {
38077 assert(VT == MVT::v4f32 && "INSERTPS ValueType must be MVT::v4f32")(static_cast <bool> (VT == MVT::v4f32 && "INSERTPS ValueType must be MVT::v4f32"
) ? void (0) : __assert_fail ("VT == MVT::v4f32 && \"INSERTPS ValueType must be MVT::v4f32\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 38077, __extension__ __PRETTY_FUNCTION__))
;
38078 SDValue Op0 = N.getOperand(0);
38079 SDValue Op1 = N.getOperand(1);
38080 unsigned InsertPSMask = N.getConstantOperandVal(2);
38081 unsigned SrcIdx = (InsertPSMask >> 6) & 0x3;
38082 unsigned DstIdx = (InsertPSMask >> 4) & 0x3;
38083 unsigned ZeroMask = InsertPSMask & 0xF;
38084
38085 // If we zero out all elements from Op0 then we don't need to reference it.
38086 if (((ZeroMask | (1u << DstIdx)) == 0xF) && !Op0.isUndef())
38087 return DAG.getNode(X86ISD::INSERTPS, DL, VT, DAG.getUNDEF(VT), Op1,
38088 DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
38089
38090 // If we zero out the element from Op1 then we don't need to reference it.
38091 if ((ZeroMask & (1u << DstIdx)) && !Op1.isUndef())
38092 return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
38093 DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
38094
38095 // Attempt to merge insertps Op1 with an inner target shuffle node.
38096 SmallVector<int, 8> TargetMask1;
38097 SmallVector<SDValue, 2> Ops1;
38098 APInt KnownUndef1, KnownZero1;
38099 if (getTargetShuffleAndZeroables(Op1, TargetMask1, Ops1, KnownUndef1,
38100 KnownZero1)) {
38101 if (KnownUndef1[SrcIdx] || KnownZero1[SrcIdx]) {
38102 // Zero/UNDEF insertion - zero out element and remove dependency.
38103 InsertPSMask |= (1u << DstIdx);
38104 return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
38105 DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
38106 }
38107 // Update insertps mask srcidx and reference the source input directly.
38108 int M = TargetMask1[SrcIdx];
38109 assert(0 <= M && M < 8 && "Shuffle index out of range")(static_cast <bool> (0 <= M && M < 8 &&
"Shuffle index out of range") ? void (0) : __assert_fail ("0 <= M && M < 8 && \"Shuffle index out of range\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 38109, __extension__ __PRETTY_FUNCTION__))
;
38110 InsertPSMask = (InsertPSMask & 0x3f) | ((M & 0x3) << 6);
38111 Op1 = Ops1[M < 4 ? 0 : 1];
38112 return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
38113 DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
38114 }
38115
38116 // Attempt to merge insertps Op0 with an inner target shuffle node.
38117 SmallVector<int, 8> TargetMask0;
38118 SmallVector<SDValue, 2> Ops0;
38119 APInt KnownUndef0, KnownZero0;
38120 if (getTargetShuffleAndZeroables(Op0, TargetMask0, Ops0, KnownUndef0,
38121 KnownZero0)) {
38122 bool Updated = false;
38123 bool UseInput00 = false;
38124 bool UseInput01 = false;
38125 for (int i = 0; i != 4; ++i) {
38126 if ((InsertPSMask & (1u << i)) || (i == (int)DstIdx)) {
38127 // No change if element is already zero or the inserted element.
38128 continue;
38129 } else if (KnownUndef0[i] || KnownZero0[i]) {
38130 // If the target mask is undef/zero then we must zero the element.
38131 InsertPSMask |= (1u << i);
38132 Updated = true;
38133 continue;
38134 }
38135
38136 // The input vector element must be inline.
38137 int M = TargetMask0[i];
38138 if (M != i && M != (i + 4))
38139 return SDValue();
38140
38141 // Determine which inputs of the target shuffle we're using.
38142 UseInput00 |= (0 <= M && M < 4);
38143 UseInput01 |= (4 <= M);
38144 }
38145
38146 // If we're not using both inputs of the target shuffle then use the
38147 // referenced input directly.
38148 if (UseInput00 && !UseInput01) {
38149 Updated = true;
38150 Op0 = Ops0[0];
38151 } else if (!UseInput00 && UseInput01) {
38152 Updated = true;
38153 Op0 = Ops0[1];
38154 }
38155
38156 if (Updated)
38157 return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
38158 DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
38159 }
38160
38161 // If we're inserting an element from a vbroadcast load, fold the
38162 // load into the X86insertps instruction. We need to convert the scalar
38163 // load to a vector and clear the source lane of the INSERTPS control.
38164 if (Op1.getOpcode() == X86ISD::VBROADCAST_LOAD && Op1.hasOneUse()) {
38165 auto *MemIntr = cast<MemIntrinsicSDNode>(Op1);
38166 if (MemIntr->getMemoryVT().getScalarSizeInBits() == 32) {
38167 SDValue Load = DAG.getLoad(MVT::f32, DL, MemIntr->getChain(),
38168 MemIntr->getBasePtr(),
38169 MemIntr->getMemOperand());
38170 SDValue Insert = DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0,
38171 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT,
38172 Load),
38173 DAG.getTargetConstant(InsertPSMask & 0x3f, DL, MVT::i8));
38174 DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), Load.getValue(1));
38175 return Insert;
38176 }
38177 }
38178
38179 return SDValue();
38180 }
38181 default:
38182 return SDValue();
38183 }
38184
38185 // Nuke no-op shuffles that show up after combining.
38186 if (isNoopShuffleMask(Mask))
38187 return N.getOperand(0);
38188
38189 // Look for simplifications involving one or two shuffle instructions.
38190 SDValue V = N.getOperand(0);
38191 switch (N.getOpcode()) {
38192 default:
38193 break;
38194 case X86ISD::PSHUFLW:
38195 case X86ISD::PSHUFHW:
38196 assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!")(static_cast <bool> (VT.getVectorElementType() == MVT::
i16 && "Bad word shuffle type!") ? void (0) : __assert_fail
("VT.getVectorElementType() == MVT::i16 && \"Bad word shuffle type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 38196, __extension__ __PRETTY_FUNCTION__))
;
38197
38198 // See if this reduces to a PSHUFD which is no more expensive and can
38199 // combine with more operations. Note that it has to at least flip the
38200 // dwords as otherwise it would have been removed as a no-op.
38201 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
38202 int DMask[] = {0, 1, 2, 3};
38203 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
38204 DMask[DOffset + 0] = DOffset + 1;
38205 DMask[DOffset + 1] = DOffset + 0;
38206 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
38207 V = DAG.getBitcast(DVT, V);
38208 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
38209 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
38210 return DAG.getBitcast(VT, V);
38211 }
38212
38213 // Look for shuffle patterns which can be implemented as a single unpack.
38214 // FIXME: This doesn't handle the location of the PSHUFD generically, and
38215 // only works when we have a PSHUFD followed by two half-shuffles.
38216 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
38217 (V.getOpcode() == X86ISD::PSHUFLW ||
38218 V.getOpcode() == X86ISD::PSHUFHW) &&
38219 V.getOpcode() != N.getOpcode() &&
38220 V.hasOneUse() && V.getOperand(0).hasOneUse()) {
38221 SDValue D = peekThroughOneUseBitcasts(V.getOperand(0));
38222 if (D.getOpcode() == X86ISD::PSHUFD) {
38223 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
38224 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
38225 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
38226 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
38227 int WordMask[8];
38228 for (int i = 0; i < 4; ++i) {
38229 WordMask[i + NOffset] = Mask[i] + NOffset;
38230 WordMask[i + VOffset] = VMask[i] + VOffset;
38231 }
38232 // Map the word mask through the DWord mask.
38233 int MappedMask[8];
38234 for (int i = 0; i < 8; ++i)
38235 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
38236 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
38237 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
38238 // We can replace all three shuffles with an unpack.
38239 V = DAG.getBitcast(VT, D.getOperand(0));
38240 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
38241 : X86ISD::UNPCKH,
38242 DL, VT, V, V);
38243 }
38244 }
38245 }
38246
38247 break;
38248
38249 case X86ISD::PSHUFD:
38250 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG))
38251 return NewN;
38252
38253 break;
38254 }
38255
38256 return SDValue();
38257}
38258
38259/// Checks if the shuffle mask takes subsequent elements
38260/// alternately from two vectors.
38261/// For example <0, 5, 2, 7> or <8, 1, 10, 3, 12, 5, 14, 7> are both correct.
38262static bool isAddSubOrSubAddMask(ArrayRef<int> Mask, bool &Op0Even) {
38263
38264 int ParitySrc[2] = {-1, -1};
38265 unsigned Size = Mask.size();
38266 for (unsigned i = 0; i != Size; ++i) {
38267 int M = Mask[i];
38268 if (M < 0)
38269 continue;
38270
38271 // Make sure we are using the matching element from the input.
38272 if ((M % Size) != i)
38273 return false;
38274
38275 // Make sure we use the same input for all elements of the same parity.
38276 int Src = M / Size;
38277 if (ParitySrc[i % 2] >= 0 && ParitySrc[i % 2] != Src)
38278 return false;
38279 ParitySrc[i % 2] = Src;
38280 }
38281
38282 // Make sure each input is used.
38283 if (ParitySrc[0] < 0 || ParitySrc[1] < 0 || ParitySrc[0] == ParitySrc[1])
38284 return false;
38285
38286 Op0Even = ParitySrc[0] == 0;
38287 return true;
38288}
38289
38290/// Returns true iff the shuffle node \p N can be replaced with ADDSUB(SUBADD)
38291/// operation. If true is returned then the operands of ADDSUB(SUBADD) operation
38292/// are written to the parameters \p Opnd0 and \p Opnd1.
38293///
38294/// We combine shuffle to ADDSUB(SUBADD) directly on the abstract vector shuffle nodes
38295/// so it is easier to generically match. We also insert dummy vector shuffle
38296/// nodes for the operands which explicitly discard the lanes which are unused
38297/// by this operation to try to flow through the rest of the combiner
38298/// the fact that they're unused.
38299static bool isAddSubOrSubAdd(SDNode *N, const X86Subtarget &Subtarget,
38300 SelectionDAG &DAG, SDValue &Opnd0, SDValue &Opnd1,
38301 bool &IsSubAdd) {
38302
38303 EVT VT = N->getValueType(0);
38304 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
38305 if (!Subtarget.hasSSE3() || !TLI.isTypeLegal(VT) ||
38306 !VT.getSimpleVT().isFloatingPoint())
38307 return false;
38308
38309 // We only handle target-independent shuffles.
38310 // FIXME: It would be easy and harmless to use the target shuffle mask
38311 // extraction tool to support more.
38312 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
38313 return false;
38314
38315 SDValue V1 = N->getOperand(0);
38316 SDValue V2 = N->getOperand(1);
38317
38318 // Make sure we have an FADD and an FSUB.
38319 if ((V1.getOpcode() != ISD::FADD && V1.getOpcode() != ISD::FSUB) ||
38320 (V2.getOpcode() != ISD::FADD && V2.getOpcode() != ISD::FSUB) ||
38321 V1.getOpcode() == V2.getOpcode())
38322 return false;
38323
38324 // If there are other uses of these operations we can't fold them.
38325 if (!V1->hasOneUse() || !V2->hasOneUse())
38326 return false;
38327
38328 // Ensure that both operations have the same operands. Note that we can
38329 // commute the FADD operands.
38330 SDValue LHS, RHS;
38331 if (V1.getOpcode() == ISD::FSUB) {
38332 LHS = V1->getOperand(0); RHS = V1->getOperand(1);
38333 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
38334 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
38335 return false;
38336 } else {
38337 assert(V2.getOpcode() == ISD::FSUB && "Unexpected opcode")(static_cast <bool> (V2.getOpcode() == ISD::FSUB &&
"Unexpected opcode") ? void (0) : __assert_fail ("V2.getOpcode() == ISD::FSUB && \"Unexpected opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 38337, __extension__ __PRETTY_FUNCTION__))
;
38338 LHS = V2->getOperand(0); RHS = V2->getOperand(1);
38339 if ((V1->getOperand(0) != LHS || V1->getOperand(1) != RHS) &&
38340 (V1->getOperand(0) != RHS || V1->getOperand(1) != LHS))
38341 return false;
38342 }
38343
38344 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
38345 bool Op0Even;
38346 if (!isAddSubOrSubAddMask(Mask, Op0Even))
38347 return false;
38348
38349 // It's a subadd if the vector in the even parity is an FADD.
38350 IsSubAdd = Op0Even ? V1->getOpcode() == ISD::FADD
38351 : V2->getOpcode() == ISD::FADD;
38352
38353 Opnd0 = LHS;
38354 Opnd1 = RHS;
38355 return true;
38356}
38357
38358/// Combine shuffle of two fma nodes into FMAddSub or FMSubAdd.
38359static SDValue combineShuffleToFMAddSub(SDNode *N,
38360 const X86Subtarget &Subtarget,
38361 SelectionDAG &DAG) {
38362 // We only handle target-independent shuffles.
38363 // FIXME: It would be easy and harmless to use the target shuffle mask
38364 // extraction tool to support more.
38365 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
38366 return SDValue();
38367
38368 MVT VT = N->getSimpleValueType(0);
38369 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
38370 if (!Subtarget.hasAnyFMA() || !TLI.isTypeLegal(VT))
38371 return SDValue();
38372
38373 // We're trying to match (shuffle fma(a, b, c), X86Fmsub(a, b, c).
38374 SDValue Op0 = N->getOperand(0);
38375 SDValue Op1 = N->getOperand(1);
38376 SDValue FMAdd = Op0, FMSub = Op1;
38377 if (FMSub.getOpcode() != X86ISD::FMSUB)
38378 std::swap(FMAdd, FMSub);
38379
38380 if (FMAdd.getOpcode() != ISD::FMA || FMSub.getOpcode() != X86ISD::FMSUB ||
38381 FMAdd.getOperand(0) != FMSub.getOperand(0) || !FMAdd.hasOneUse() ||
38382 FMAdd.getOperand(1) != FMSub.getOperand(1) || !FMSub.hasOneUse() ||
38383 FMAdd.getOperand(2) != FMSub.getOperand(2))
38384 return SDValue();
38385
38386 // Check for correct shuffle mask.
38387 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
38388 bool Op0Even;
38389 if (!isAddSubOrSubAddMask(Mask, Op0Even))
38390 return SDValue();
38391
38392 // FMAddSub takes zeroth operand from FMSub node.
38393 SDLoc DL(N);
38394 bool IsSubAdd = Op0Even ? Op0 == FMAdd : Op1 == FMAdd;
38395 unsigned Opcode = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
38396 return DAG.getNode(Opcode, DL, VT, FMAdd.getOperand(0), FMAdd.getOperand(1),
38397 FMAdd.getOperand(2));
38398}
38399
38400/// Try to combine a shuffle into a target-specific add-sub or
38401/// mul-add-sub node.
38402static SDValue combineShuffleToAddSubOrFMAddSub(SDNode *N,
38403 const X86Subtarget &Subtarget,
38404 SelectionDAG &DAG) {
38405 if (SDValue V = combineShuffleToFMAddSub(N, Subtarget, DAG))
38406 return V;
38407
38408 SDValue Opnd0, Opnd1;
38409 bool IsSubAdd;
38410 if (!isAddSubOrSubAdd(N, Subtarget, DAG, Opnd0, Opnd1, IsSubAdd))
38411 return SDValue();
38412
38413 MVT VT = N->getSimpleValueType(0);
38414 SDLoc DL(N);
38415
38416 // Try to generate X86ISD::FMADDSUB node here.
38417 SDValue Opnd2;
38418 if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, 2)) {
38419 unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
38420 return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
38421 }
38422
38423 if (IsSubAdd)
38424 return SDValue();
38425
38426 // Do not generate X86ISD::ADDSUB node for 512-bit types even though
38427 // the ADDSUB idiom has been successfully recognized. There are no known
38428 // X86 targets with 512-bit ADDSUB instructions!
38429 if (VT.is512BitVector())
38430 return SDValue();
38431
38432 return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
38433}
38434
38435// We are looking for a shuffle where both sources are concatenated with undef
38436// and have a width that is half of the output's width. AVX2 has VPERMD/Q, so
38437// if we can express this as a single-source shuffle, that's preferable.
38438static SDValue combineShuffleOfConcatUndef(SDNode *N, SelectionDAG &DAG,
38439 const X86Subtarget &Subtarget) {
38440 if (!Subtarget.hasAVX2() || !isa<ShuffleVectorSDNode>(N))
38441 return SDValue();
38442
38443 EVT VT = N->getValueType(0);
38444
38445 // We only care about shuffles of 128/256-bit vectors of 32/64-bit values.
38446 if (!VT.is128BitVector() && !VT.is256BitVector())
38447 return SDValue();
38448
38449 if (VT.getVectorElementType() != MVT::i32 &&
38450 VT.getVectorElementType() != MVT::i64 &&
38451 VT.getVectorElementType() != MVT::f32 &&
38452 VT.getVectorElementType() != MVT::f64)
38453 return SDValue();
38454
38455 SDValue N0 = N->getOperand(0);
38456 SDValue N1 = N->getOperand(1);
38457
38458 // Check that both sources are concats with undef.
38459 if (N0.getOpcode() != ISD::CONCAT_VECTORS ||
38460 N1.getOpcode() != ISD::CONCAT_VECTORS || N0.getNumOperands() != 2 ||
38461 N1.getNumOperands() != 2 || !N0.getOperand(1).isUndef() ||
38462 !N1.getOperand(1).isUndef())
38463 return SDValue();
38464
38465 // Construct the new shuffle mask. Elements from the first source retain their
38466 // index, but elements from the second source no longer need to skip an undef.
38467 SmallVector<int, 8> Mask;
38468 int NumElts = VT.getVectorNumElements();
38469
38470 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
38471 for (int Elt : SVOp->getMask())
38472 Mask.push_back(Elt < NumElts ? Elt : (Elt - NumElts / 2));
38473
38474 SDLoc DL(N);
38475 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, N0.getOperand(0),
38476 N1.getOperand(0));
38477 return DAG.getVectorShuffle(VT, DL, Concat, DAG.getUNDEF(VT), Mask);
38478}
38479
38480/// If we have a shuffle of AVX/AVX512 (256/512 bit) vectors that only uses the
38481/// low half of each source vector and does not set any high half elements in
38482/// the destination vector, narrow the shuffle to half its original size.
38483static SDValue narrowShuffle(ShuffleVectorSDNode *Shuf, SelectionDAG &DAG) {
38484 if (!Shuf->getValueType(0).isSimple())
38485 return SDValue();
38486 MVT VT = Shuf->getSimpleValueType(0);
38487 if (!VT.is256BitVector() && !VT.is512BitVector())
38488 return SDValue();
38489
38490 // See if we can ignore all of the high elements of the shuffle.
38491 ArrayRef<int> Mask = Shuf->getMask();
38492 if (!isUndefUpperHalf(Mask))
38493 return SDValue();
38494
38495 // Check if the shuffle mask accesses only the low half of each input vector
38496 // (half-index output is 0 or 2).
38497 int HalfIdx1, HalfIdx2;
38498 SmallVector<int, 8> HalfMask(Mask.size() / 2);
38499 if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2) ||
38500 (HalfIdx1 % 2 == 1) || (HalfIdx2 % 2 == 1))
38501 return SDValue();
38502
38503 // Create a half-width shuffle to replace the unnecessarily wide shuffle.
38504 // The trick is knowing that all of the insert/extract are actually free
38505 // subregister (zmm<->ymm or ymm<->xmm) ops. That leaves us with a shuffle
38506 // of narrow inputs into a narrow output, and that is always cheaper than
38507 // the wide shuffle that we started with.
38508 return getShuffleHalfVectors(SDLoc(Shuf), Shuf->getOperand(0),
38509 Shuf->getOperand(1), HalfMask, HalfIdx1,
38510 HalfIdx2, false, DAG, /*UseConcat*/true);
38511}
38512
38513static SDValue combineShuffle(SDNode *N, SelectionDAG &DAG,
38514 TargetLowering::DAGCombinerInfo &DCI,
38515 const X86Subtarget &Subtarget) {
38516 if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(N))
38517 if (SDValue V = narrowShuffle(Shuf, DAG))
38518 return V;
38519
38520 // If we have legalized the vector types, look for blends of FADD and FSUB
38521 // nodes that we can fuse into an ADDSUB, FMADDSUB, or FMSUBADD node.
38522 SDLoc dl(N);
38523 EVT VT = N->getValueType(0);
38524 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
38525 if (TLI.isTypeLegal(VT))
38526 if (SDValue AddSub = combineShuffleToAddSubOrFMAddSub(N, Subtarget, DAG))
38527 return AddSub;
38528
38529 // Attempt to combine into a vector load/broadcast.
38530 if (SDValue LD = combineToConsecutiveLoads(
38531 VT, SDValue(N, 0), dl, DAG, Subtarget, /*IsAfterLegalize*/ true))
38532 return LD;
38533
38534 // For AVX2, we sometimes want to combine
38535 // (vector_shuffle <mask> (concat_vectors t1, undef)
38536 // (concat_vectors t2, undef))
38537 // Into:
38538 // (vector_shuffle <mask> (concat_vectors t1, t2), undef)
38539 // Since the latter can be efficiently lowered with VPERMD/VPERMQ
38540 if (SDValue ShufConcat = combineShuffleOfConcatUndef(N, DAG, Subtarget))
38541 return ShufConcat;
38542
38543 if (isTargetShuffle(N->getOpcode())) {
38544 SDValue Op(N, 0);
38545 if (SDValue Shuffle = combineTargetShuffle(Op, DAG, DCI, Subtarget))
38546 return Shuffle;
38547
38548 // Try recursively combining arbitrary sequences of x86 shuffle
38549 // instructions into higher-order shuffles. We do this after combining
38550 // specific PSHUF instruction sequences into their minimal form so that we
38551 // can evaluate how many specialized shuffle instructions are involved in
38552 // a particular chain.
38553 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
38554 return Res;
38555
38556 // Simplify source operands based on shuffle mask.
38557 // TODO - merge this into combineX86ShufflesRecursively.
38558 APInt KnownUndef, KnownZero;
38559 APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
38560 if (TLI.SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero,
38561 DCI))
38562 return SDValue(N, 0);
38563 }
38564
38565 return SDValue();
38566}
38567
38568// Simplify variable target shuffle masks based on the demanded elements.
38569// TODO: Handle DemandedBits in mask indices as well?
38570bool X86TargetLowering::SimplifyDemandedVectorEltsForTargetShuffle(
38571 SDValue Op, const APInt &DemandedElts, unsigned MaskIndex,
38572 TargetLowering::TargetLoweringOpt &TLO, unsigned Depth) const {
38573 // If we're demanding all elements don't bother trying to simplify the mask.
38574 unsigned NumElts = DemandedElts.getBitWidth();
38575 if (DemandedElts.isAllOnesValue())
38576 return false;
38577
38578 SDValue Mask = Op.getOperand(MaskIndex);
38579 if (!Mask.hasOneUse())
38580 return false;
38581
38582 // Attempt to generically simplify the variable shuffle mask.
38583 APInt MaskUndef, MaskZero;
38584 if (SimplifyDemandedVectorElts(Mask, DemandedElts, MaskUndef, MaskZero, TLO,
38585 Depth + 1))
38586 return true;
38587
38588 // Attempt to extract+simplify a (constant pool load) shuffle mask.
38589 // TODO: Support other types from getTargetShuffleMaskIndices?
38590 SDValue BC = peekThroughOneUseBitcasts(Mask);
38591 EVT BCVT = BC.getValueType();
38592 auto *Load = dyn_cast<LoadSDNode>(BC);
38593 if (!Load)
38594 return false;
38595
38596 const Constant *C = getTargetConstantFromNode(Load);
38597 if (!C)
38598 return false;
38599
38600 Type *CTy = C->getType();
38601 if (!CTy->isVectorTy() ||
38602 CTy->getPrimitiveSizeInBits() != Mask.getValueSizeInBits())
38603 return false;
38604
38605 // Handle scaling for i64 elements on 32-bit targets.
38606 unsigned NumCstElts = cast<FixedVectorType>(CTy)->getNumElements();
38607 if (NumCstElts != NumElts && NumCstElts != (NumElts * 2))
38608 return false;
38609 unsigned Scale = NumCstElts / NumElts;
38610
38611 // Simplify mask if we have an undemanded element that is not undef.
38612 bool Simplified = false;
38613 SmallVector<Constant *, 32> ConstVecOps;
38614 for (unsigned i = 0; i != NumCstElts; ++i) {
38615 Constant *Elt = C->getAggregateElement(i);
38616 if (!DemandedElts[i / Scale] && !isa<UndefValue>(Elt)) {
38617 ConstVecOps.push_back(UndefValue::get(Elt->getType()));
38618 Simplified = true;
38619 continue;
38620 }
38621 ConstVecOps.push_back(Elt);
38622 }
38623 if (!Simplified)
38624 return false;
38625
38626 // Generate new constant pool entry + legalize immediately for the load.
38627 SDLoc DL(Op);
38628 SDValue CV = TLO.DAG.getConstantPool(ConstantVector::get(ConstVecOps), BCVT);
38629 SDValue LegalCV = LowerConstantPool(CV, TLO.DAG);
38630 SDValue NewMask = TLO.DAG.getLoad(
38631 BCVT, DL, TLO.DAG.getEntryNode(), LegalCV,
38632 MachinePointerInfo::getConstantPool(TLO.DAG.getMachineFunction()),
38633 Load->getAlign());
38634 return TLO.CombineTo(Mask, TLO.DAG.getBitcast(Mask.getValueType(), NewMask));
38635}
38636
38637bool X86TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
38638 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
38639 TargetLoweringOpt &TLO, unsigned Depth) const {
38640 int NumElts = DemandedElts.getBitWidth();
38641 unsigned Opc = Op.getOpcode();
38642 EVT VT = Op.getValueType();
38643
38644 // Handle special case opcodes.
38645 switch (Opc) {
38646 case X86ISD::PMULDQ:
38647 case X86ISD::PMULUDQ: {
38648 APInt LHSUndef, LHSZero;
38649 APInt RHSUndef, RHSZero;
38650 SDValue LHS = Op.getOperand(0);
38651 SDValue RHS = Op.getOperand(1);
38652 if (SimplifyDemandedVectorElts(LHS, DemandedElts, LHSUndef, LHSZero, TLO,
38653 Depth + 1))
38654 return true;
38655 if (SimplifyDemandedVectorElts(RHS, DemandedElts, RHSUndef, RHSZero, TLO,
38656 Depth + 1))
38657 return true;
38658 // Multiply by zero.
38659 KnownZero = LHSZero | RHSZero;
38660 break;
38661 }
38662 case X86ISD::VSHL:
38663 case X86ISD::VSRL:
38664 case X86ISD::VSRA: {
38665 // We only need the bottom 64-bits of the (128-bit) shift amount.
38666 SDValue Amt = Op.getOperand(1);
38667 MVT AmtVT = Amt.getSimpleValueType();
38668 assert(AmtVT.is128BitVector() && "Unexpected value type")(static_cast <bool> (AmtVT.is128BitVector() && "Unexpected value type"
) ? void (0) : __assert_fail ("AmtVT.is128BitVector() && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 38668, __extension__ __PRETTY_FUNCTION__))
;
38669
38670 // If we reuse the shift amount just for sse shift amounts then we know that
38671 // only the bottom 64-bits are only ever used.
38672 bool AssumeSingleUse = llvm::all_of(Amt->uses(), [&Amt](SDNode *Use) {
38673 unsigned UseOpc = Use->getOpcode();
38674 return (UseOpc == X86ISD::VSHL || UseOpc == X86ISD::VSRL ||
38675 UseOpc == X86ISD::VSRA) &&
38676 Use->getOperand(0) != Amt;
38677 });
38678
38679 APInt AmtUndef, AmtZero;
38680 unsigned NumAmtElts = AmtVT.getVectorNumElements();
38681 APInt AmtElts = APInt::getLowBitsSet(NumAmtElts, NumAmtElts / 2);
38682 if (SimplifyDemandedVectorElts(Amt, AmtElts, AmtUndef, AmtZero, TLO,
38683 Depth + 1, AssumeSingleUse))
38684 return true;
38685 LLVM_FALLTHROUGH[[gnu::fallthrough]];
38686 }
38687 case X86ISD::VSHLI:
38688 case X86ISD::VSRLI:
38689 case X86ISD::VSRAI: {
38690 SDValue Src = Op.getOperand(0);
38691 APInt SrcUndef;
38692 if (SimplifyDemandedVectorElts(Src, DemandedElts, SrcUndef, KnownZero, TLO,
38693 Depth + 1))
38694 return true;
38695
38696 // Aggressively peek through ops to get at the demanded elts.
38697 if (!DemandedElts.isAllOnesValue())
38698 if (SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
38699 Src, DemandedElts, TLO.DAG, Depth + 1))
38700 return TLO.CombineTo(
38701 Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc, Op.getOperand(1)));
38702 break;
38703 }
38704 case X86ISD::KSHIFTL: {
38705 SDValue Src = Op.getOperand(0);
38706 auto *Amt = cast<ConstantSDNode>(Op.getOperand(1));
38707 assert(Amt->getAPIntValue().ult(NumElts) && "Out of range shift amount")(static_cast <bool> (Amt->getAPIntValue().ult(NumElts
) && "Out of range shift amount") ? void (0) : __assert_fail
("Amt->getAPIntValue().ult(NumElts) && \"Out of range shift amount\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 38707, __extension__ __PRETTY_FUNCTION__))
;
38708 unsigned ShiftAmt = Amt->getZExtValue();
38709
38710 if (ShiftAmt == 0)
38711 return TLO.CombineTo(Op, Src);
38712
38713 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
38714 // single shift. We can do this if the bottom bits (which are shifted
38715 // out) are never demanded.
38716 if (Src.getOpcode() == X86ISD::KSHIFTR) {
38717 if (!DemandedElts.intersects(APInt::getLowBitsSet(NumElts, ShiftAmt))) {
38718 unsigned C1 = Src.getConstantOperandVal(1);
38719 unsigned NewOpc = X86ISD::KSHIFTL;
38720 int Diff = ShiftAmt - C1;
38721 if (Diff < 0) {
38722 Diff = -Diff;
38723 NewOpc = X86ISD::KSHIFTR;
38724 }
38725
38726 SDLoc dl(Op);
38727 SDValue NewSA = TLO.DAG.getTargetConstant(Diff, dl, MVT::i8);
38728 return TLO.CombineTo(
38729 Op, TLO.DAG.getNode(NewOpc, dl, VT, Src.getOperand(0), NewSA));
38730 }
38731 }
38732
38733 APInt DemandedSrc = DemandedElts.lshr(ShiftAmt);
38734 if (SimplifyDemandedVectorElts(Src, DemandedSrc, KnownUndef, KnownZero, TLO,
38735 Depth + 1))
38736 return true;
38737
38738 KnownUndef <<= ShiftAmt;
38739 KnownZero <<= ShiftAmt;
38740 KnownZero.setLowBits(ShiftAmt);
38741 break;
38742 }
38743 case X86ISD::KSHIFTR: {
38744 SDValue Src = Op.getOperand(0);
38745 auto *Amt = cast<ConstantSDNode>(Op.getOperand(1));
38746 assert(Amt->getAPIntValue().ult(NumElts) && "Out of range shift amount")(static_cast <bool> (Amt->getAPIntValue().ult(NumElts
) && "Out of range shift amount") ? void (0) : __assert_fail
("Amt->getAPIntValue().ult(NumElts) && \"Out of range shift amount\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 38746, __extension__ __PRETTY_FUNCTION__))
;
38747 unsigned ShiftAmt = Amt->getZExtValue();
38748
38749 if (ShiftAmt == 0)
38750 return TLO.CombineTo(Op, Src);
38751
38752 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
38753 // single shift. We can do this if the top bits (which are shifted
38754 // out) are never demanded.
38755 if (Src.getOpcode() == X86ISD::KSHIFTL) {
38756 if (!DemandedElts.intersects(APInt::getHighBitsSet(NumElts, ShiftAmt))) {
38757 unsigned C1 = Src.getConstantOperandVal(1);
38758 unsigned NewOpc = X86ISD::KSHIFTR;
38759 int Diff = ShiftAmt - C1;
38760 if (Diff < 0) {
38761 Diff = -Diff;
38762 NewOpc = X86ISD::KSHIFTL;
38763 }
38764
38765 SDLoc dl(Op);
38766 SDValue NewSA = TLO.DAG.getTargetConstant(Diff, dl, MVT::i8);
38767 return TLO.CombineTo(
38768 Op, TLO.DAG.getNode(NewOpc, dl, VT, Src.getOperand(0), NewSA));
38769 }
38770 }
38771
38772 APInt DemandedSrc = DemandedElts.shl(ShiftAmt);
38773 if (SimplifyDemandedVectorElts(Src, DemandedSrc, KnownUndef, KnownZero, TLO,
38774 Depth + 1))
38775 return true;
38776
38777 KnownUndef.lshrInPlace(ShiftAmt);
38778 KnownZero.lshrInPlace(ShiftAmt);
38779 KnownZero.setHighBits(ShiftAmt);
38780 break;
38781 }
38782 case X86ISD::CVTSI2P:
38783 case X86ISD::CVTUI2P: {
38784 SDValue Src = Op.getOperand(0);
38785 MVT SrcVT = Src.getSimpleValueType();
38786 APInt SrcUndef, SrcZero;
38787 APInt SrcElts = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
38788 if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
38789 Depth + 1))
38790 return true;
38791 break;
38792 }
38793 case X86ISD::PACKSS:
38794 case X86ISD::PACKUS: {
38795 SDValue N0 = Op.getOperand(0);
38796 SDValue N1 = Op.getOperand(1);
38797
38798 APInt DemandedLHS, DemandedRHS;
38799 getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
38800
38801 APInt LHSUndef, LHSZero;
38802 if (SimplifyDemandedVectorElts(N0, DemandedLHS, LHSUndef, LHSZero, TLO,
38803 Depth + 1))
38804 return true;
38805 APInt RHSUndef, RHSZero;
38806 if (SimplifyDemandedVectorElts(N1, DemandedRHS, RHSUndef, RHSZero, TLO,
38807 Depth + 1))
38808 return true;
38809
38810 // TODO - pass on known zero/undef.
38811
38812 // Aggressively peek through ops to get at the demanded elts.
38813 // TODO - we should do this for all target/faux shuffles ops.
38814 if (!DemandedElts.isAllOnesValue()) {
38815 SDValue NewN0 = SimplifyMultipleUseDemandedVectorElts(N0, DemandedLHS,
38816 TLO.DAG, Depth + 1);
38817 SDValue NewN1 = SimplifyMultipleUseDemandedVectorElts(N1, DemandedRHS,
38818 TLO.DAG, Depth + 1);
38819 if (NewN0 || NewN1) {
38820 NewN0 = NewN0 ? NewN0 : N0;
38821 NewN1 = NewN1 ? NewN1 : N1;
38822 return TLO.CombineTo(Op,
38823 TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewN0, NewN1));
38824 }
38825 }
38826 break;
38827 }
38828 case X86ISD::HADD:
38829 case X86ISD::HSUB:
38830 case X86ISD::FHADD:
38831 case X86ISD::FHSUB: {
38832 SDValue N0 = Op.getOperand(0);
38833 SDValue N1 = Op.getOperand(1);
38834
38835 APInt DemandedLHS, DemandedRHS;
38836 getHorizDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
38837
38838 APInt LHSUndef, LHSZero;
38839 if (SimplifyDemandedVectorElts(N0, DemandedLHS, LHSUndef, LHSZero, TLO,
38840 Depth + 1))
38841 return true;
38842 APInt RHSUndef, RHSZero;
38843 if (SimplifyDemandedVectorElts(N1, DemandedRHS, RHSUndef, RHSZero, TLO,
38844 Depth + 1))
38845 return true;
38846
38847 // TODO - pass on known zero/undef.
38848
38849 // Aggressively peek through ops to get at the demanded elts.
38850 // TODO: Handle repeated operands.
38851 if (N0 != N1 && !DemandedElts.isAllOnesValue()) {
38852 SDValue NewN0 = SimplifyMultipleUseDemandedVectorElts(N0, DemandedLHS,
38853 TLO.DAG, Depth + 1);
38854 SDValue NewN1 = SimplifyMultipleUseDemandedVectorElts(N1, DemandedRHS,
38855 TLO.DAG, Depth + 1);
38856 if (NewN0 || NewN1) {
38857 NewN0 = NewN0 ? NewN0 : N0;
38858 NewN1 = NewN1 ? NewN1 : N1;
38859 return TLO.CombineTo(Op,
38860 TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewN0, NewN1));
38861 }
38862 }
38863 break;
38864 }
38865 case X86ISD::VTRUNC:
38866 case X86ISD::VTRUNCS:
38867 case X86ISD::VTRUNCUS: {
38868 SDValue Src = Op.getOperand(0);
38869 MVT SrcVT = Src.getSimpleValueType();
38870 APInt DemandedSrc = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
38871 APInt SrcUndef, SrcZero;
38872 if (SimplifyDemandedVectorElts(Src, DemandedSrc, SrcUndef, SrcZero, TLO,
38873 Depth + 1))
38874 return true;
38875 KnownZero = SrcZero.zextOrTrunc(NumElts);
38876 KnownUndef = SrcUndef.zextOrTrunc(NumElts);
38877 break;
38878 }
38879 case X86ISD::BLENDV: {
38880 APInt SelUndef, SelZero;
38881 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, SelUndef,
38882 SelZero, TLO, Depth + 1))
38883 return true;
38884
38885 // TODO: Use SelZero to adjust LHS/RHS DemandedElts.
38886 APInt LHSUndef, LHSZero;
38887 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, LHSUndef,
38888 LHSZero, TLO, Depth + 1))
38889 return true;
38890
38891 APInt RHSUndef, RHSZero;
38892 if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedElts, RHSUndef,
38893 RHSZero, TLO, Depth + 1))
38894 return true;
38895
38896 KnownZero = LHSZero & RHSZero;
38897 KnownUndef = LHSUndef & RHSUndef;
38898 break;
38899 }
38900 case X86ISD::VZEXT_MOVL: {
38901 // If upper demanded elements are already zero then we have nothing to do.
38902 SDValue Src = Op.getOperand(0);
38903 APInt DemandedUpperElts = DemandedElts;
38904 DemandedUpperElts.clearLowBits(1);
38905 if (TLO.DAG.computeKnownBits(Src, DemandedUpperElts, Depth + 1).isZero())
38906 return TLO.CombineTo(Op, Src);
38907 break;
38908 }
38909 case X86ISD::VBROADCAST: {
38910 SDValue Src = Op.getOperand(0);
38911 MVT SrcVT = Src.getSimpleValueType();
38912 if (!SrcVT.isVector())
38913 break;
38914 // Don't bother broadcasting if we just need the 0'th element.
38915 if (DemandedElts == 1) {
38916 if (Src.getValueType() != VT)
38917 Src = widenSubVector(VT.getSimpleVT(), Src, false, Subtarget, TLO.DAG,
38918 SDLoc(Op));
38919 return TLO.CombineTo(Op, Src);
38920 }
38921 APInt SrcUndef, SrcZero;
38922 APInt SrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(), 0);
38923 if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
38924 Depth + 1))
38925 return true;
38926 // Aggressively peek through src to get at the demanded elt.
38927 // TODO - we should do this for all target/faux shuffles ops.
38928 if (SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
38929 Src, SrcElts, TLO.DAG, Depth + 1))
38930 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
38931 break;
38932 }
38933 case X86ISD::VPERMV:
38934 if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 0, TLO,
38935 Depth))
38936 return true;
38937 break;
38938 case X86ISD::PSHUFB:
38939 case X86ISD::VPERMV3:
38940 case X86ISD::VPERMILPV:
38941 if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 1, TLO,
38942 Depth))
38943 return true;
38944 break;
38945 case X86ISD::VPPERM:
38946 case X86ISD::VPERMIL2:
38947 if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 2, TLO,
38948 Depth))
38949 return true;
38950 break;
38951 }
38952
38953 // For 256/512-bit ops that are 128/256-bit ops glued together, if we do not
38954 // demand any of the high elements, then narrow the op to 128/256-bits: e.g.
38955 // (op ymm0, ymm1) --> insert undef, (op xmm0, xmm1), 0
38956 if ((VT.is256BitVector() || VT.is512BitVector()) &&
38957 DemandedElts.lshr(NumElts / 2) == 0) {
38958 unsigned SizeInBits = VT.getSizeInBits();
38959 unsigned ExtSizeInBits = SizeInBits / 2;
38960
38961 // See if 512-bit ops only use the bottom 128-bits.
38962 if (VT.is512BitVector() && DemandedElts.lshr(NumElts / 4) == 0)
38963 ExtSizeInBits = SizeInBits / 4;
38964
38965 switch (Opc) {
38966 // Scalar broadcast.
38967 case X86ISD::VBROADCAST: {
38968 SDLoc DL(Op);
38969 SDValue Src = Op.getOperand(0);
38970 if (Src.getValueSizeInBits() > ExtSizeInBits)
38971 Src = extractSubVector(Src, 0, TLO.DAG, DL, ExtSizeInBits);
38972 EVT BcstVT = EVT::getVectorVT(*TLO.DAG.getContext(), VT.getScalarType(),
38973 ExtSizeInBits / VT.getScalarSizeInBits());
38974 SDValue Bcst = TLO.DAG.getNode(X86ISD::VBROADCAST, DL, BcstVT, Src);
38975 return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Bcst, 0,
38976 TLO.DAG, DL, ExtSizeInBits));
38977 }
38978 case X86ISD::VBROADCAST_LOAD: {
38979 SDLoc DL(Op);
38980 auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
38981 EVT BcstVT = EVT::getVectorVT(*TLO.DAG.getContext(), VT.getScalarType(),
38982 ExtSizeInBits / VT.getScalarSizeInBits());
38983 SDVTList Tys = TLO.DAG.getVTList(BcstVT, MVT::Other);
38984 SDValue Ops[] = {MemIntr->getOperand(0), MemIntr->getOperand(1)};
38985 SDValue Bcst = TLO.DAG.getMemIntrinsicNode(
38986 X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MemIntr->getMemoryVT(),
38987 MemIntr->getMemOperand());
38988 TLO.DAG.makeEquivalentMemoryOrdering(SDValue(MemIntr, 1),
38989 Bcst.getValue(1));
38990 return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Bcst, 0,
38991 TLO.DAG, DL, ExtSizeInBits));
38992 }
38993 // Subvector broadcast.
38994 case X86ISD::SUBV_BROADCAST_LOAD: {
38995 SDLoc DL(Op);
38996 auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
38997 EVT MemVT = MemIntr->getMemoryVT();
38998 if (ExtSizeInBits == MemVT.getStoreSizeInBits()) {
38999 SDValue Ld =
39000 TLO.DAG.getLoad(MemVT, DL, MemIntr->getChain(),
39001 MemIntr->getBasePtr(), MemIntr->getMemOperand());
39002 TLO.DAG.makeEquivalentMemoryOrdering(SDValue(MemIntr, 1),
39003 Ld.getValue(1));
39004 return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Ld, 0,
39005 TLO.DAG, DL, ExtSizeInBits));
39006 } else if ((ExtSizeInBits % MemVT.getStoreSizeInBits()) == 0) {
39007 EVT BcstVT = EVT::getVectorVT(*TLO.DAG.getContext(), VT.getScalarType(),
39008 ExtSizeInBits / VT.getScalarSizeInBits());
39009 if (SDValue BcstLd =
39010 getBROADCAST_LOAD(Opc, DL, BcstVT, MemVT, MemIntr, 0, TLO.DAG))
39011 return TLO.CombineTo(Op,
39012 insertSubVector(TLO.DAG.getUNDEF(VT), BcstLd, 0,
39013 TLO.DAG, DL, ExtSizeInBits));
39014 }
39015 break;
39016 }
39017 // Byte shifts by immediate.
39018 case X86ISD::VSHLDQ:
39019 case X86ISD::VSRLDQ:
39020 // Shift by uniform.
39021 case X86ISD::VSHL:
39022 case X86ISD::VSRL:
39023 case X86ISD::VSRA:
39024 // Shift by immediate.
39025 case X86ISD::VSHLI:
39026 case X86ISD::VSRLI:
39027 case X86ISD::VSRAI: {
39028 SDLoc DL(Op);
39029 SDValue Ext0 =
39030 extractSubVector(Op.getOperand(0), 0, TLO.DAG, DL, ExtSizeInBits);
39031 SDValue ExtOp =
39032 TLO.DAG.getNode(Opc, DL, Ext0.getValueType(), Ext0, Op.getOperand(1));
39033 SDValue UndefVec = TLO.DAG.getUNDEF(VT);
39034 SDValue Insert =
39035 insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
39036 return TLO.CombineTo(Op, Insert);
39037 }
39038 case X86ISD::VPERMI: {
39039 // Simplify PERMPD/PERMQ to extract_subvector.
39040 // TODO: This should be done in shuffle combining.
39041 if (VT == MVT::v4f64 || VT == MVT::v4i64) {
39042 SmallVector<int, 4> Mask;
39043 DecodeVPERMMask(NumElts, Op.getConstantOperandVal(1), Mask);
39044 if (isUndefOrEqual(Mask[0], 2) && isUndefOrEqual(Mask[1], 3)) {
39045 SDLoc DL(Op);
39046 SDValue Ext = extractSubVector(Op.getOperand(0), 2, TLO.DAG, DL, 128);
39047 SDValue UndefVec = TLO.DAG.getUNDEF(VT);
39048 SDValue Insert = insertSubVector(UndefVec, Ext, 0, TLO.DAG, DL, 128);
39049 return TLO.CombineTo(Op, Insert);
39050 }
39051 }
39052 break;
39053 }
39054 case X86ISD::VPERM2X128: {
39055 // Simplify VPERM2F128/VPERM2I128 to extract_subvector.
39056 SDLoc DL(Op);
39057 unsigned LoMask = Op.getConstantOperandVal(2) & 0xF;
39058 if (LoMask & 0x8)
39059 return TLO.CombineTo(
39060 Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, DL));
39061 unsigned EltIdx = (LoMask & 0x1) * (NumElts / 2);
39062 unsigned SrcIdx = (LoMask & 0x2) >> 1;
39063 SDValue ExtOp =
39064 extractSubVector(Op.getOperand(SrcIdx), EltIdx, TLO.DAG, DL, 128);
39065 SDValue UndefVec = TLO.DAG.getUNDEF(VT);
39066 SDValue Insert =
39067 insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
39068 return TLO.CombineTo(Op, Insert);
39069 }
39070 // Zero upper elements.
39071 case X86ISD::VZEXT_MOVL:
39072 // Target unary shuffles by immediate:
39073 case X86ISD::PSHUFD:
39074 case X86ISD::PSHUFLW:
39075 case X86ISD::PSHUFHW:
39076 case X86ISD::VPERMILPI:
39077 // (Non-Lane Crossing) Target Shuffles.
39078 case X86ISD::VPERMILPV:
39079 case X86ISD::VPERMIL2:
39080 case X86ISD::PSHUFB:
39081 case X86ISD::UNPCKL:
39082 case X86ISD::UNPCKH:
39083 case X86ISD::BLENDI:
39084 // Integer ops.
39085 case X86ISD::AVG:
39086 case X86ISD::PACKSS:
39087 case X86ISD::PACKUS:
39088 // Horizontal Ops.
39089 case X86ISD::HADD:
39090 case X86ISD::HSUB:
39091 case X86ISD::FHADD:
39092 case X86ISD::FHSUB: {
39093 SDLoc DL(Op);
39094 SmallVector<SDValue, 4> Ops;
39095 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
39096 SDValue SrcOp = Op.getOperand(i);
39097 EVT SrcVT = SrcOp.getValueType();
39098 assert((!SrcVT.isVector() || SrcVT.getSizeInBits() == SizeInBits) &&(static_cast <bool> ((!SrcVT.isVector() || SrcVT.getSizeInBits
() == SizeInBits) && "Unsupported vector size") ? void
(0) : __assert_fail ("(!SrcVT.isVector() || SrcVT.getSizeInBits() == SizeInBits) && \"Unsupported vector size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 39099, __extension__ __PRETTY_FUNCTION__))
39099 "Unsupported vector size")(static_cast <bool> ((!SrcVT.isVector() || SrcVT.getSizeInBits
() == SizeInBits) && "Unsupported vector size") ? void
(0) : __assert_fail ("(!SrcVT.isVector() || SrcVT.getSizeInBits() == SizeInBits) && \"Unsupported vector size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 39099, __extension__ __PRETTY_FUNCTION__))
;
39100 Ops.push_back(SrcVT.isVector() ? extractSubVector(SrcOp, 0, TLO.DAG, DL,
39101 ExtSizeInBits)
39102 : SrcOp);
39103 }
39104 MVT ExtVT = VT.getSimpleVT();
39105 ExtVT = MVT::getVectorVT(ExtVT.getScalarType(),
39106 ExtSizeInBits / ExtVT.getScalarSizeInBits());
39107 SDValue ExtOp = TLO.DAG.getNode(Opc, DL, ExtVT, Ops);
39108 SDValue UndefVec = TLO.DAG.getUNDEF(VT);
39109 SDValue Insert =
39110 insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
39111 return TLO.CombineTo(Op, Insert);
39112 }
39113 }
39114 }
39115
39116 // Get target/faux shuffle mask.
39117 APInt OpUndef, OpZero;
39118 SmallVector<int, 64> OpMask;
39119 SmallVector<SDValue, 2> OpInputs;
39120 if (!getTargetShuffleInputs(Op, DemandedElts, OpInputs, OpMask, OpUndef,
39121 OpZero, TLO.DAG, Depth, false))
39122 return false;
39123
39124 // Shuffle inputs must be the same size as the result.
39125 if (OpMask.size() != (unsigned)NumElts ||
39126 llvm::any_of(OpInputs, [VT](SDValue V) {
39127 return VT.getSizeInBits() != V.getValueSizeInBits() ||
39128 !V.getValueType().isVector();
39129 }))
39130 return false;
39131
39132 KnownZero = OpZero;
39133 KnownUndef = OpUndef;
39134
39135 // Check if shuffle mask can be simplified to undef/zero/identity.
39136 int NumSrcs = OpInputs.size();
39137 for (int i = 0; i != NumElts; ++i)
39138 if (!DemandedElts[i])
39139 OpMask[i] = SM_SentinelUndef;
39140
39141 if (isUndefInRange(OpMask, 0, NumElts)) {
39142 KnownUndef.setAllBits();
39143 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
39144 }
39145 if (isUndefOrZeroInRange(OpMask, 0, NumElts)) {
39146 KnownZero.setAllBits();
39147 return TLO.CombineTo(
39148 Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, SDLoc(Op)));
39149 }
39150 for (int Src = 0; Src != NumSrcs; ++Src)
39151 if (isSequentialOrUndefInRange(OpMask, 0, NumElts, Src * NumElts))
39152 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, OpInputs[Src]));
39153
39154 // Attempt to simplify inputs.
39155 for (int Src = 0; Src != NumSrcs; ++Src) {
39156 // TODO: Support inputs of different types.
39157 if (OpInputs[Src].getValueType() != VT)
39158 continue;
39159
39160 int Lo = Src * NumElts;
39161 APInt SrcElts = APInt::getNullValue(NumElts);
39162 for (int i = 0; i != NumElts; ++i)
39163 if (DemandedElts[i]) {
39164 int M = OpMask[i] - Lo;
39165 if (0 <= M && M < NumElts)
39166 SrcElts.setBit(M);
39167 }
39168
39169 // TODO - Propagate input undef/zero elts.
39170 APInt SrcUndef, SrcZero;
39171 if (SimplifyDemandedVectorElts(OpInputs[Src], SrcElts, SrcUndef, SrcZero,
39172 TLO, Depth + 1))
39173 return true;
39174 }
39175
39176 // If we don't demand all elements, then attempt to combine to a simpler
39177 // shuffle.
39178 // We need to convert the depth to something combineX86ShufflesRecursively
39179 // can handle - so pretend its Depth == 0 again, and reduce the max depth
39180 // to match. This prevents combineX86ShuffleChain from returning a
39181 // combined shuffle that's the same as the original root, causing an
39182 // infinite loop.
39183 if (!DemandedElts.isAllOnesValue()) {
39184 assert(Depth < X86::MaxShuffleCombineDepth && "Depth out of range")(static_cast <bool> (Depth < X86::MaxShuffleCombineDepth
&& "Depth out of range") ? void (0) : __assert_fail (
"Depth < X86::MaxShuffleCombineDepth && \"Depth out of range\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 39184, __extension__ __PRETTY_FUNCTION__))
;
39185
39186 SmallVector<int, 64> DemandedMask(NumElts, SM_SentinelUndef);
39187 for (int i = 0; i != NumElts; ++i)
39188 if (DemandedElts[i])
39189 DemandedMask[i] = i;
39190
39191 SDValue NewShuffle = combineX86ShufflesRecursively(
39192 {Op}, 0, Op, DemandedMask, {}, 0, X86::MaxShuffleCombineDepth - Depth,
39193 /*HasVarMask*/ false,
39194 /*AllowCrossLaneVarMask*/ true, /*AllowPerLaneVarMask*/ true, TLO.DAG,
39195 Subtarget);
39196 if (NewShuffle)
39197 return TLO.CombineTo(Op, NewShuffle);
39198 }
39199
39200 return false;
39201}
39202
39203bool X86TargetLowering::SimplifyDemandedBitsForTargetNode(
39204 SDValue Op, const APInt &OriginalDemandedBits,
39205 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
39206 unsigned Depth) const {
39207 EVT VT = Op.getValueType();
39208 unsigned BitWidth = OriginalDemandedBits.getBitWidth();
39209 unsigned Opc = Op.getOpcode();
39210 switch(Opc) {
39211 case X86ISD::VTRUNC: {
39212 KnownBits KnownOp;
39213 SDValue Src = Op.getOperand(0);
39214 MVT SrcVT = Src.getSimpleValueType();
39215
39216 // Simplify the input, using demanded bit information.
39217 APInt TruncMask = OriginalDemandedBits.zext(SrcVT.getScalarSizeInBits());
39218 APInt DemandedElts = OriginalDemandedElts.trunc(SrcVT.getVectorNumElements());
39219 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, KnownOp, TLO, Depth + 1))
39220 return true;
39221 break;
39222 }
39223 case X86ISD::PMULDQ:
39224 case X86ISD::PMULUDQ: {
39225 // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
39226 KnownBits KnownOp;
39227 SDValue LHS = Op.getOperand(0);
39228 SDValue RHS = Op.getOperand(1);
39229 // FIXME: Can we bound this better?
39230 APInt DemandedMask = APInt::getLowBitsSet(64, 32);
39231 if (SimplifyDemandedBits(LHS, DemandedMask, OriginalDemandedElts, KnownOp,
39232 TLO, Depth + 1))
39233 return true;
39234 if (SimplifyDemandedBits(RHS, DemandedMask, OriginalDemandedElts, KnownOp,
39235 TLO, Depth + 1))
39236 return true;
39237
39238 // Aggressively peek through ops to get at the demanded low bits.
39239 SDValue DemandedLHS = SimplifyMultipleUseDemandedBits(
39240 LHS, DemandedMask, OriginalDemandedElts, TLO.DAG, Depth + 1);
39241 SDValue DemandedRHS = SimplifyMultipleUseDemandedBits(
39242 RHS, DemandedMask, OriginalDemandedElts, TLO.DAG, Depth + 1);
39243 if (DemandedLHS || DemandedRHS) {
39244 DemandedLHS = DemandedLHS ? DemandedLHS : LHS;
39245 DemandedRHS = DemandedRHS ? DemandedRHS : RHS;
39246 return TLO.CombineTo(
39247 Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, DemandedLHS, DemandedRHS));
39248 }
39249 break;
39250 }
39251 case X86ISD::VSHLI: {
39252 SDValue Op0 = Op.getOperand(0);
39253
39254 unsigned ShAmt = Op.getConstantOperandVal(1);
39255 if (ShAmt >= BitWidth)
39256 break;
39257
39258 APInt DemandedMask = OriginalDemandedBits.lshr(ShAmt);
39259
39260 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
39261 // single shift. We can do this if the bottom bits (which are shifted
39262 // out) are never demanded.
39263 if (Op0.getOpcode() == X86ISD::VSRLI &&
39264 OriginalDemandedBits.countTrailingZeros() >= ShAmt) {
39265 unsigned Shift2Amt = Op0.getConstantOperandVal(1);
39266 if (Shift2Amt < BitWidth) {
39267 int Diff = ShAmt - Shift2Amt;
39268 if (Diff == 0)
39269 return TLO.CombineTo(Op, Op0.getOperand(0));
39270
39271 unsigned NewOpc = Diff < 0 ? X86ISD::VSRLI : X86ISD::VSHLI;
39272 SDValue NewShift = TLO.DAG.getNode(
39273 NewOpc, SDLoc(Op), VT, Op0.getOperand(0),
39274 TLO.DAG.getTargetConstant(std::abs(Diff), SDLoc(Op), MVT::i8));
39275 return TLO.CombineTo(Op, NewShift);
39276 }
39277 }
39278
39279 // If we are only demanding sign bits then we can use the shift source directly.
39280 unsigned NumSignBits =
39281 TLO.DAG.ComputeNumSignBits(Op0, OriginalDemandedElts, Depth + 1);
39282 unsigned UpperDemandedBits =
39283 BitWidth - OriginalDemandedBits.countTrailingZeros();
39284 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= UpperDemandedBits)
39285 return TLO.CombineTo(Op, Op0);
39286
39287 if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
39288 TLO, Depth + 1))
39289 return true;
39290
39291 assert(!Known.hasConflict() && "Bits known to be one AND zero?")(static_cast <bool> (!Known.hasConflict() && "Bits known to be one AND zero?"
) ? void (0) : __assert_fail ("!Known.hasConflict() && \"Bits known to be one AND zero?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 39291, __extension__ __PRETTY_FUNCTION__))
;
39292 Known.Zero <<= ShAmt;
39293 Known.One <<= ShAmt;
39294
39295 // Low bits known zero.
39296 Known.Zero.setLowBits(ShAmt);
39297 return false;
39298 }
39299 case X86ISD::VSRLI: {
39300 unsigned ShAmt = Op.getConstantOperandVal(1);
39301 if (ShAmt >= BitWidth)
39302 break;
39303
39304 APInt DemandedMask = OriginalDemandedBits << ShAmt;
39305
39306 if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask,
39307 OriginalDemandedElts, Known, TLO, Depth + 1))
39308 return true;
39309
39310 assert(!Known.hasConflict() && "Bits known to be one AND zero?")(static_cast <bool> (!Known.hasConflict() && "Bits known to be one AND zero?"
) ? void (0) : __assert_fail ("!Known.hasConflict() && \"Bits known to be one AND zero?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 39310, __extension__ __PRETTY_FUNCTION__))
;
39311 Known.Zero.lshrInPlace(ShAmt);
39312 Known.One.lshrInPlace(ShAmt);
39313
39314 // High bits known zero.
39315 Known.Zero.setHighBits(ShAmt);
39316 return false;
39317 }
39318 case X86ISD::VSRAI: {
39319 SDValue Op0 = Op.getOperand(0);
39320 SDValue Op1 = Op.getOperand(1);
39321
39322 unsigned ShAmt = cast<ConstantSDNode>(Op1)->getZExtValue();
39323 if (ShAmt >= BitWidth)
39324 break;
39325
39326 APInt DemandedMask = OriginalDemandedBits << ShAmt;
39327
39328 // If we just want the sign bit then we don't need to shift it.
39329 if (OriginalDemandedBits.isSignMask())
39330 return TLO.CombineTo(Op, Op0);
39331
39332 // fold (VSRAI (VSHLI X, C1), C1) --> X iff NumSignBits(X) > C1
39333 if (Op0.getOpcode() == X86ISD::VSHLI &&
39334 Op.getOperand(1) == Op0.getOperand(1)) {
39335 SDValue Op00 = Op0.getOperand(0);
39336 unsigned NumSignBits =
39337 TLO.DAG.ComputeNumSignBits(Op00, OriginalDemandedElts);
39338 if (ShAmt < NumSignBits)
39339 return TLO.CombineTo(Op, Op00);
39340 }
39341
39342 // If any of the demanded bits are produced by the sign extension, we also
39343 // demand the input sign bit.
39344 if (OriginalDemandedBits.countLeadingZeros() < ShAmt)
39345 DemandedMask.setSignBit();
39346
39347 if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
39348 TLO, Depth + 1))
39349 return true;
39350
39351 assert(!Known.hasConflict() && "Bits known to be one AND zero?")(static_cast <bool> (!Known.hasConflict() && "Bits known to be one AND zero?"
) ? void (0) : __assert_fail ("!Known.hasConflict() && \"Bits known to be one AND zero?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 39351, __extension__ __PRETTY_FUNCTION__))
;
39352 Known.Zero.lshrInPlace(ShAmt);
39353 Known.One.lshrInPlace(ShAmt);
39354
39355 // If the input sign bit is known to be zero, or if none of the top bits
39356 // are demanded, turn this into an unsigned shift right.
39357 if (Known.Zero[BitWidth - ShAmt - 1] ||
39358 OriginalDemandedBits.countLeadingZeros() >= ShAmt)
39359 return TLO.CombineTo(
39360 Op, TLO.DAG.getNode(X86ISD::VSRLI, SDLoc(Op), VT, Op0, Op1));
39361
39362 // High bits are known one.
39363 if (Known.One[BitWidth - ShAmt - 1])
39364 Known.One.setHighBits(ShAmt);
39365 return false;
39366 }
39367 case X86ISD::PEXTRB:
39368 case X86ISD::PEXTRW: {
39369 SDValue Vec = Op.getOperand(0);
39370 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
39371 MVT VecVT = Vec.getSimpleValueType();
39372 unsigned NumVecElts = VecVT.getVectorNumElements();
39373
39374 if (CIdx && CIdx->getAPIntValue().ult(NumVecElts)) {
39375 unsigned Idx = CIdx->getZExtValue();
39376 unsigned VecBitWidth = VecVT.getScalarSizeInBits();
39377
39378 // If we demand no bits from the vector then we must have demanded
39379 // bits from the implict zext - simplify to zero.
39380 APInt DemandedVecBits = OriginalDemandedBits.trunc(VecBitWidth);
39381 if (DemandedVecBits == 0)
39382 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
39383
39384 APInt KnownUndef, KnownZero;
39385 APInt DemandedVecElts = APInt::getOneBitSet(NumVecElts, Idx);
39386 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
39387 KnownZero, TLO, Depth + 1))
39388 return true;
39389
39390 KnownBits KnownVec;
39391 if (SimplifyDemandedBits(Vec, DemandedVecBits, DemandedVecElts,
39392 KnownVec, TLO, Depth + 1))
39393 return true;
39394
39395 if (SDValue V = SimplifyMultipleUseDemandedBits(
39396 Vec, DemandedVecBits, DemandedVecElts, TLO.DAG, Depth + 1))
39397 return TLO.CombineTo(
39398 Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, V, Op.getOperand(1)));
39399
39400 Known = KnownVec.zext(BitWidth);
39401 return false;
39402 }
39403 break;
39404 }
39405 case X86ISD::PINSRB:
39406 case X86ISD::PINSRW: {
39407 SDValue Vec = Op.getOperand(0);
39408 SDValue Scl = Op.getOperand(1);
39409 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
39410 MVT VecVT = Vec.getSimpleValueType();
39411
39412 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
39413 unsigned Idx = CIdx->getZExtValue();
39414 if (!OriginalDemandedElts[Idx])
39415 return TLO.CombineTo(Op, Vec);
39416
39417 KnownBits KnownVec;
39418 APInt DemandedVecElts(OriginalDemandedElts);
39419 DemandedVecElts.clearBit(Idx);
39420 if (SimplifyDemandedBits(Vec, OriginalDemandedBits, DemandedVecElts,
39421 KnownVec, TLO, Depth + 1))
39422 return true;
39423
39424 KnownBits KnownScl;
39425 unsigned NumSclBits = Scl.getScalarValueSizeInBits();
39426 APInt DemandedSclBits = OriginalDemandedBits.zext(NumSclBits);
39427 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
39428 return true;
39429
39430 KnownScl = KnownScl.trunc(VecVT.getScalarSizeInBits());
39431 Known = KnownBits::commonBits(KnownVec, KnownScl);
39432 return false;
39433 }
39434 break;
39435 }
39436 case X86ISD::PACKSS:
39437 // PACKSS saturates to MIN/MAX integer values. So if we just want the
39438 // sign bit then we can just ask for the source operands sign bit.
39439 // TODO - add known bits handling.
39440 if (OriginalDemandedBits.isSignMask()) {
39441 APInt DemandedLHS, DemandedRHS;
39442 getPackDemandedElts(VT, OriginalDemandedElts, DemandedLHS, DemandedRHS);
39443
39444 KnownBits KnownLHS, KnownRHS;
39445 APInt SignMask = APInt::getSignMask(BitWidth * 2);
39446 if (SimplifyDemandedBits(Op.getOperand(0), SignMask, DemandedLHS,
39447 KnownLHS, TLO, Depth + 1))
39448 return true;
39449 if (SimplifyDemandedBits(Op.getOperand(1), SignMask, DemandedRHS,
39450 KnownRHS, TLO, Depth + 1))
39451 return true;
39452
39453 // Attempt to avoid multi-use ops if we don't need anything from them.
39454 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
39455 Op.getOperand(0), SignMask, DemandedLHS, TLO.DAG, Depth + 1);
39456 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
39457 Op.getOperand(1), SignMask, DemandedRHS, TLO.DAG, Depth + 1);
39458 if (DemandedOp0 || DemandedOp1) {
39459 SDValue Op0 = DemandedOp0 ? DemandedOp0 : Op.getOperand(0);
39460 SDValue Op1 = DemandedOp1 ? DemandedOp1 : Op.getOperand(1);
39461 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, Op0, Op1));
39462 }
39463 }
39464 // TODO - add general PACKSS/PACKUS SimplifyDemandedBits support.
39465 break;
39466 case X86ISD::VBROADCAST: {
39467 SDValue Src = Op.getOperand(0);
39468 MVT SrcVT = Src.getSimpleValueType();
39469 APInt DemandedElts = APInt::getOneBitSet(
39470 SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1, 0);
39471 if (SimplifyDemandedBits(Src, OriginalDemandedBits, DemandedElts, Known,
39472 TLO, Depth + 1))
39473 return true;
39474 // If we don't need the upper bits, attempt to narrow the broadcast source.
39475 // Don't attempt this on AVX512 as it might affect broadcast folding.
39476 // TODO: Should we attempt this for i32/i16 splats? They tend to be slower.
39477 if ((BitWidth == 64) && SrcVT.isScalarInteger() && !Subtarget.hasAVX512() &&
39478 OriginalDemandedBits.countLeadingZeros() >= (BitWidth / 2)) {
39479 MVT NewSrcVT = MVT::getIntegerVT(BitWidth / 2);
39480 SDValue NewSrc =
39481 TLO.DAG.getNode(ISD::TRUNCATE, SDLoc(Src), NewSrcVT, Src);
39482 MVT NewVT = MVT::getVectorVT(NewSrcVT, VT.getVectorNumElements() * 2);
39483 SDValue NewBcst =
39484 TLO.DAG.getNode(X86ISD::VBROADCAST, SDLoc(Op), NewVT, NewSrc);
39485 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, NewBcst));
39486 }
39487 break;
39488 }
39489 case X86ISD::PCMPGT:
39490 // icmp sgt(0, R) == ashr(R, BitWidth-1).
39491 // iff we only need the sign bit then we can use R directly.
39492 if (OriginalDemandedBits.isSignMask() &&
39493 ISD::isBuildVectorAllZeros(Op.getOperand(0).getNode()))
39494 return TLO.CombineTo(Op, Op.getOperand(1));
39495 break;
39496 case X86ISD::MOVMSK: {
39497 SDValue Src = Op.getOperand(0);
39498 MVT SrcVT = Src.getSimpleValueType();
39499 unsigned SrcBits = SrcVT.getScalarSizeInBits();
39500 unsigned NumElts = SrcVT.getVectorNumElements();
39501
39502 // If we don't need the sign bits at all just return zero.
39503 if (OriginalDemandedBits.countTrailingZeros() >= NumElts)
39504 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
39505
39506 // Only demand the vector elements of the sign bits we need.
39507 APInt KnownUndef, KnownZero;
39508 APInt DemandedElts = OriginalDemandedBits.zextOrTrunc(NumElts);
39509 if (SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, KnownZero,
39510 TLO, Depth + 1))
39511 return true;
39512
39513 Known.Zero = KnownZero.zextOrSelf(BitWidth);
39514 Known.Zero.setHighBits(BitWidth - NumElts);
39515
39516 // MOVMSK only uses the MSB from each vector element.
39517 KnownBits KnownSrc;
39518 APInt DemandedSrcBits = APInt::getSignMask(SrcBits);
39519 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, KnownSrc, TLO,
39520 Depth + 1))
39521 return true;
39522
39523 if (KnownSrc.One[SrcBits - 1])
39524 Known.One.setLowBits(NumElts);
39525 else if (KnownSrc.Zero[SrcBits - 1])
39526 Known.Zero.setLowBits(NumElts);
39527
39528 // Attempt to avoid multi-use os if we don't need anything from it.
39529 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
39530 Src, DemandedSrcBits, DemandedElts, TLO.DAG, Depth + 1))
39531 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
39532 return false;
39533 }
39534 case X86ISD::BEXTR:
39535 case X86ISD::BEXTRI: {
39536 SDValue Op0 = Op.getOperand(0);
39537 SDValue Op1 = Op.getOperand(1);
39538
39539 // Only bottom 16-bits of the control bits are required.
39540 if (auto *Cst1 = dyn_cast<ConstantSDNode>(Op1)) {
39541 // NOTE: SimplifyDemandedBits won't do this for constants.
39542 uint64_t Val1 = Cst1->getZExtValue();
39543 uint64_t MaskedVal1 = Val1 & 0xFFFF;
39544 if (Opc == X86ISD::BEXTR && MaskedVal1 != Val1) {
39545 SDLoc DL(Op);
39546 return TLO.CombineTo(
39547 Op, TLO.DAG.getNode(X86ISD::BEXTR, DL, VT, Op0,
39548 TLO.DAG.getConstant(MaskedVal1, DL, VT)));
39549 }
39550
39551 unsigned Shift = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 0);
39552 unsigned Length = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 8);
39553
39554 // If the length is 0, the result is 0.
39555 if (Length == 0) {
39556 Known.setAllZero();
39557 return false;
39558 }
39559
39560 if ((Shift + Length) <= BitWidth) {
39561 APInt DemandedMask = APInt::getBitsSet(BitWidth, Shift, Shift + Length);
39562 if (SimplifyDemandedBits(Op0, DemandedMask, Known, TLO, Depth + 1))
39563 return true;
39564
39565 Known = Known.extractBits(Length, Shift);
39566 Known = Known.zextOrTrunc(BitWidth);
39567 return false;
39568 }
39569 } else {
39570 assert(Opc == X86ISD::BEXTR && "Unexpected opcode!")(static_cast <bool> (Opc == X86ISD::BEXTR && "Unexpected opcode!"
) ? void (0) : __assert_fail ("Opc == X86ISD::BEXTR && \"Unexpected opcode!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 39570, __extension__ __PRETTY_FUNCTION__))
;
39571 KnownBits Known1;
39572 APInt DemandedMask(APInt::getLowBitsSet(BitWidth, 16));
39573 if (SimplifyDemandedBits(Op1, DemandedMask, Known1, TLO, Depth + 1))
39574 return true;
39575
39576 // If the length is 0, replace with 0.
39577 KnownBits LengthBits = Known1.extractBits(8, 8);
39578 if (LengthBits.isZero())
39579 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
39580 }
39581
39582 break;
39583 }
39584 case X86ISD::PDEP: {
39585 SDValue Op0 = Op.getOperand(0);
39586 SDValue Op1 = Op.getOperand(1);
39587
39588 unsigned DemandedBitsLZ = OriginalDemandedBits.countLeadingZeros();
39589 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
39590
39591 // If the demanded bits has leading zeroes, we don't demand those from the
39592 // mask.
39593 if (SimplifyDemandedBits(Op1, LoMask, Known, TLO, Depth + 1))
39594 return true;
39595
39596 // The number of possible 1s in the mask determines the number of LSBs of
39597 // operand 0 used. Undemanded bits from the mask don't matter so filter
39598 // them before counting.
39599 KnownBits Known2;
39600 uint64_t Count = (~Known.Zero & LoMask).countPopulation();
39601 APInt DemandedMask(APInt::getLowBitsSet(BitWidth, Count));
39602 if (SimplifyDemandedBits(Op0, DemandedMask, Known2, TLO, Depth + 1))
39603 return true;
39604
39605 // Zeroes are retained from the mask, but not ones.
39606 Known.One.clearAllBits();
39607 // The result will have at least as many trailing zeros as the non-mask
39608 // operand since bits can only map to the same or higher bit position.
39609 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
39610 return false;
39611 }
39612 }
39613
39614 return TargetLowering::SimplifyDemandedBitsForTargetNode(
39615 Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
39616}
39617
39618SDValue X86TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
39619 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
39620 SelectionDAG &DAG, unsigned Depth) const {
39621 int NumElts = DemandedElts.getBitWidth();
39622 unsigned Opc = Op.getOpcode();
39623 EVT VT = Op.getValueType();
39624
39625 switch (Opc) {
39626 case X86ISD::PINSRB:
39627 case X86ISD::PINSRW: {
39628 // If we don't demand the inserted element, return the base vector.
39629 SDValue Vec = Op.getOperand(0);
39630 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
39631 MVT VecVT = Vec.getSimpleValueType();
39632 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
39633 !DemandedElts[CIdx->getZExtValue()])
39634 return Vec;
39635 break;
39636 }
39637 case X86ISD::VSHLI: {
39638 // If we are only demanding sign bits then we can use the shift source
39639 // directly.
39640 SDValue Op0 = Op.getOperand(0);
39641 unsigned ShAmt = Op.getConstantOperandVal(1);
39642 unsigned BitWidth = DemandedBits.getBitWidth();
39643 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
39644 unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
39645 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= UpperDemandedBits)
39646 return Op0;
39647 break;
39648 }
39649 case X86ISD::VSRAI:
39650 // iff we only need the sign bit then we can use the source directly.
39651 // TODO: generalize where we only demand extended signbits.
39652 if (DemandedBits.isSignMask())
39653 return Op.getOperand(0);
39654 break;
39655 case X86ISD::PCMPGT:
39656 // icmp sgt(0, R) == ashr(R, BitWidth-1).
39657 // iff we only need the sign bit then we can use R directly.
39658 if (DemandedBits.isSignMask() &&
39659 ISD::isBuildVectorAllZeros(Op.getOperand(0).getNode()))
39660 return Op.getOperand(1);
39661 break;
39662 }
39663
39664 APInt ShuffleUndef, ShuffleZero;
39665 SmallVector<int, 16> ShuffleMask;
39666 SmallVector<SDValue, 2> ShuffleOps;
39667 if (getTargetShuffleInputs(Op, DemandedElts, ShuffleOps, ShuffleMask,
39668 ShuffleUndef, ShuffleZero, DAG, Depth, false)) {
39669 // If all the demanded elts are from one operand and are inline,
39670 // then we can use the operand directly.
39671 int NumOps = ShuffleOps.size();
39672 if (ShuffleMask.size() == (unsigned)NumElts &&
39673 llvm::all_of(ShuffleOps, [VT](SDValue V) {
39674 return VT.getSizeInBits() == V.getValueSizeInBits();
39675 })) {
39676
39677 if (DemandedElts.isSubsetOf(ShuffleUndef))
39678 return DAG.getUNDEF(VT);
39679 if (DemandedElts.isSubsetOf(ShuffleUndef | ShuffleZero))
39680 return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, SDLoc(Op));
39681
39682 // Bitmask that indicates which ops have only been accessed 'inline'.
39683 APInt IdentityOp = APInt::getAllOnesValue(NumOps);
39684 for (int i = 0; i != NumElts; ++i) {
39685 int M = ShuffleMask[i];
39686 if (!DemandedElts[i] || ShuffleUndef[i])
39687 continue;
39688 int OpIdx = M / NumElts;
39689 int EltIdx = M % NumElts;
39690 if (M < 0 || EltIdx != i) {
39691 IdentityOp.clearAllBits();
39692 break;
39693 }
39694 IdentityOp &= APInt::getOneBitSet(NumOps, OpIdx);
39695 if (IdentityOp == 0)
39696 break;
39697 }
39698 assert((IdentityOp == 0 || IdentityOp.countPopulation() == 1) &&(static_cast <bool> ((IdentityOp == 0 || IdentityOp.countPopulation
() == 1) && "Multiple identity shuffles detected") ? void
(0) : __assert_fail ("(IdentityOp == 0 || IdentityOp.countPopulation() == 1) && \"Multiple identity shuffles detected\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 39699, __extension__ __PRETTY_FUNCTION__))
39699 "Multiple identity shuffles detected")(static_cast <bool> ((IdentityOp == 0 || IdentityOp.countPopulation
() == 1) && "Multiple identity shuffles detected") ? void
(0) : __assert_fail ("(IdentityOp == 0 || IdentityOp.countPopulation() == 1) && \"Multiple identity shuffles detected\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 39699, __extension__ __PRETTY_FUNCTION__))
;
39700
39701 if (IdentityOp != 0)
39702 return DAG.getBitcast(VT, ShuffleOps[IdentityOp.countTrailingZeros()]);
39703 }
39704 }
39705
39706 return TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
39707 Op, DemandedBits, DemandedElts, DAG, Depth);
39708}
39709
39710// Helper to peek through bitops/trunc/setcc to determine size of source vector.
39711// Allows combineBitcastvxi1 to determine what size vector generated a <X x i1>.
39712static bool checkBitcastSrcVectorSize(SDValue Src, unsigned Size,
39713 bool AllowTruncate) {
39714 switch (Src.getOpcode()) {
39715 case ISD::TRUNCATE:
39716 if (!AllowTruncate)
39717 return false;
39718 LLVM_FALLTHROUGH[[gnu::fallthrough]];
39719 case ISD::SETCC:
39720 return Src.getOperand(0).getValueSizeInBits() == Size;
39721 case ISD::AND:
39722 case ISD::XOR:
39723 case ISD::OR:
39724 return checkBitcastSrcVectorSize(Src.getOperand(0), Size, AllowTruncate) &&
39725 checkBitcastSrcVectorSize(Src.getOperand(1), Size, AllowTruncate);
39726 }
39727 return false;
39728}
39729
39730// Helper to flip between AND/OR/XOR opcodes and their X86ISD FP equivalents.
39731static unsigned getAltBitOpcode(unsigned Opcode) {
39732 switch(Opcode) {
39733 case ISD::AND: return X86ISD::FAND;
39734 case ISD::OR: return X86ISD::FOR;
39735 case ISD::XOR: return X86ISD::FXOR;
39736 case X86ISD::ANDNP: return X86ISD::FANDN;
39737 }
39738 llvm_unreachable("Unknown bitwise opcode")::llvm::llvm_unreachable_internal("Unknown bitwise opcode", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 39738)
;
39739}
39740
39741// Helper to adjust v4i32 MOVMSK expansion to work with SSE1-only targets.
39742static SDValue adjustBitcastSrcVectorSSE1(SelectionDAG &DAG, SDValue Src,
39743 const SDLoc &DL) {
39744 EVT SrcVT = Src.getValueType();
39745 if (SrcVT != MVT::v4i1)
39746 return SDValue();
39747
39748 switch (Src.getOpcode()) {
39749 case ISD::SETCC:
39750 if (Src.getOperand(0).getValueType() == MVT::v4i32 &&
39751 ISD::isBuildVectorAllZeros(Src.getOperand(1).getNode()) &&
39752 cast<CondCodeSDNode>(Src.getOperand(2))->get() == ISD::SETLT) {
39753 SDValue Op0 = Src.getOperand(0);
39754 if (ISD::isNormalLoad(Op0.getNode()))
39755 return DAG.getBitcast(MVT::v4f32, Op0);
39756 if (Op0.getOpcode() == ISD::BITCAST &&
39757 Op0.getOperand(0).getValueType() == MVT::v4f32)
39758 return Op0.getOperand(0);
39759 }
39760 break;
39761 case ISD::AND:
39762 case ISD::XOR:
39763 case ISD::OR: {
39764 SDValue Op0 = adjustBitcastSrcVectorSSE1(DAG, Src.getOperand(0), DL);
39765 SDValue Op1 = adjustBitcastSrcVectorSSE1(DAG, Src.getOperand(1), DL);
39766 if (Op0 && Op1)
39767 return DAG.getNode(getAltBitOpcode(Src.getOpcode()), DL, MVT::v4f32, Op0,
39768 Op1);
39769 break;
39770 }
39771 }
39772 return SDValue();
39773}
39774
39775// Helper to push sign extension of vXi1 SETCC result through bitops.
39776static SDValue signExtendBitcastSrcVector(SelectionDAG &DAG, EVT SExtVT,
39777 SDValue Src, const SDLoc &DL) {
39778 switch (Src.getOpcode()) {
39779 case ISD::SETCC:
39780 case ISD::TRUNCATE:
39781 return DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
39782 case ISD::AND:
39783 case ISD::XOR:
39784 case ISD::OR:
39785 return DAG.getNode(
39786 Src.getOpcode(), DL, SExtVT,
39787 signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(0), DL),
39788 signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(1), DL));
39789 }
39790 llvm_unreachable("Unexpected node type for vXi1 sign extension")::llvm::llvm_unreachable_internal("Unexpected node type for vXi1 sign extension"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 39790)
;
39791}
39792
39793// Try to match patterns such as
39794// (i16 bitcast (v16i1 x))
39795// ->
39796// (i16 movmsk (16i8 sext (v16i1 x)))
39797// before the illegal vector is scalarized on subtargets that don't have legal
39798// vxi1 types.
39799static SDValue combineBitcastvxi1(SelectionDAG &DAG, EVT VT, SDValue Src,
39800 const SDLoc &DL,
39801 const X86Subtarget &Subtarget) {
39802 EVT SrcVT = Src.getValueType();
39803 if (!SrcVT.isSimple() || SrcVT.getScalarType() != MVT::i1)
39804 return SDValue();
39805
39806 // Recognize the IR pattern for the movmsk intrinsic under SSE1 before type
39807 // legalization destroys the v4i32 type.
39808 if (Subtarget.hasSSE1() && !Subtarget.hasSSE2()) {
39809 if (SDValue V = adjustBitcastSrcVectorSSE1(DAG, Src, DL)) {
39810 V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32,
39811 DAG.getBitcast(MVT::v4f32, V));
39812 return DAG.getZExtOrTrunc(V, DL, VT);
39813 }
39814 }
39815
39816 // If the input is a truncate from v16i8 or v32i8 go ahead and use a
39817 // movmskb even with avx512. This will be better than truncating to vXi1 and
39818 // using a kmov. This can especially help KNL if the input is a v16i8/v32i8
39819 // vpcmpeqb/vpcmpgtb.
39820 bool PreferMovMsk = Src.getOpcode() == ISD::TRUNCATE && Src.hasOneUse() &&
39821 (Src.getOperand(0).getValueType() == MVT::v16i8 ||
39822 Src.getOperand(0).getValueType() == MVT::v32i8 ||
39823 Src.getOperand(0).getValueType() == MVT::v64i8);
39824
39825 // Prefer movmsk for AVX512 for (bitcast (setlt X, 0)) which can be handled
39826 // directly with vpmovmskb/vmovmskps/vmovmskpd.
39827 if (Src.getOpcode() == ISD::SETCC && Src.hasOneUse() &&
39828 cast<CondCodeSDNode>(Src.getOperand(2))->get() == ISD::SETLT &&
39829 ISD::isBuildVectorAllZeros(Src.getOperand(1).getNode())) {
39830 EVT CmpVT = Src.getOperand(0).getValueType();
39831 EVT EltVT = CmpVT.getVectorElementType();
39832 if (CmpVT.getSizeInBits() <= 256 &&
39833 (EltVT == MVT::i8 || EltVT == MVT::i32 || EltVT == MVT::i64))
39834 PreferMovMsk = true;
39835 }
39836
39837 // With AVX512 vxi1 types are legal and we prefer using k-regs.
39838 // MOVMSK is supported in SSE2 or later.
39839 if (!Subtarget.hasSSE2() || (Subtarget.hasAVX512() && !PreferMovMsk))
39840 return SDValue();
39841
39842 // There are MOVMSK flavors for types v16i8, v32i8, v4f32, v8f32, v4f64 and
39843 // v8f64. So all legal 128-bit and 256-bit vectors are covered except for
39844 // v8i16 and v16i16.
39845 // For these two cases, we can shuffle the upper element bytes to a
39846 // consecutive sequence at the start of the vector and treat the results as
39847 // v16i8 or v32i8, and for v16i8 this is the preferable solution. However,
39848 // for v16i16 this is not the case, because the shuffle is expensive, so we
39849 // avoid sign-extending to this type entirely.
39850 // For example, t0 := (v8i16 sext(v8i1 x)) needs to be shuffled as:
39851 // (v16i8 shuffle <0,2,4,6,8,10,12,14,u,u,...,u> (v16i8 bitcast t0), undef)
39852 MVT SExtVT;
39853 bool PropagateSExt = false;
39854 switch (SrcVT.getSimpleVT().SimpleTy) {
39855 default:
39856 return SDValue();
39857 case MVT::v2i1:
39858 SExtVT = MVT::v2i64;
39859 break;
39860 case MVT::v4i1:
39861 SExtVT = MVT::v4i32;
39862 // For cases such as (i4 bitcast (v4i1 setcc v4i64 v1, v2))
39863 // sign-extend to a 256-bit operation to avoid truncation.
39864 if (Subtarget.hasAVX() &&
39865 checkBitcastSrcVectorSize(Src, 256, Subtarget.hasAVX2())) {
39866 SExtVT = MVT::v4i64;
39867 PropagateSExt = true;
39868 }
39869 break;
39870 case MVT::v8i1:
39871 SExtVT = MVT::v8i16;
39872 // For cases such as (i8 bitcast (v8i1 setcc v8i32 v1, v2)),
39873 // sign-extend to a 256-bit operation to match the compare.
39874 // If the setcc operand is 128-bit, prefer sign-extending to 128-bit over
39875 // 256-bit because the shuffle is cheaper than sign extending the result of
39876 // the compare.
39877 if (Subtarget.hasAVX() && (checkBitcastSrcVectorSize(Src, 256, true) ||
39878 checkBitcastSrcVectorSize(Src, 512, true))) {
39879 SExtVT = MVT::v8i32;
39880 PropagateSExt = true;
39881 }
39882 break;
39883 case MVT::v16i1:
39884 SExtVT = MVT::v16i8;
39885 // For the case (i16 bitcast (v16i1 setcc v16i16 v1, v2)),
39886 // it is not profitable to sign-extend to 256-bit because this will
39887 // require an extra cross-lane shuffle which is more expensive than
39888 // truncating the result of the compare to 128-bits.
39889 break;
39890 case MVT::v32i1:
39891 SExtVT = MVT::v32i8;
39892 break;
39893 case MVT::v64i1:
39894 // If we have AVX512F, but not AVX512BW and the input is truncated from
39895 // v64i8 checked earlier. Then split the input and make two pmovmskbs.
39896 if (Subtarget.hasAVX512()) {
39897 if (Subtarget.hasBWI())
39898 return SDValue();
39899 SExtVT = MVT::v64i8;
39900 break;
39901 }
39902 // Split if this is a <64 x i8> comparison result.
39903 if (checkBitcastSrcVectorSize(Src, 512, false)) {
39904 SExtVT = MVT::v64i8;
39905 break;
39906 }
39907 return SDValue();
39908 };
39909
39910 SDValue V = PropagateSExt ? signExtendBitcastSrcVector(DAG, SExtVT, Src, DL)
39911 : DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
39912
39913 if (SExtVT == MVT::v16i8 || SExtVT == MVT::v32i8 || SExtVT == MVT::v64i8) {
39914 V = getPMOVMSKB(DL, V, DAG, Subtarget);
39915 } else {
39916 if (SExtVT == MVT::v8i16)
39917 V = DAG.getNode(X86ISD::PACKSS, DL, MVT::v16i8, V,
39918 DAG.getUNDEF(MVT::v8i16));
39919 V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
39920 }
39921
39922 EVT IntVT =
39923 EVT::getIntegerVT(*DAG.getContext(), SrcVT.getVectorNumElements());
39924 V = DAG.getZExtOrTrunc(V, DL, IntVT);
39925 return DAG.getBitcast(VT, V);
39926}
39927
39928// Convert a vXi1 constant build vector to the same width scalar integer.
39929static SDValue combinevXi1ConstantToInteger(SDValue Op, SelectionDAG &DAG) {
39930 EVT SrcVT = Op.getValueType();
39931 assert(SrcVT.getVectorElementType() == MVT::i1 &&(static_cast <bool> (SrcVT.getVectorElementType() == MVT
::i1 && "Expected a vXi1 vector") ? void (0) : __assert_fail
("SrcVT.getVectorElementType() == MVT::i1 && \"Expected a vXi1 vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 39932, __extension__ __PRETTY_FUNCTION__))
39932 "Expected a vXi1 vector")(static_cast <bool> (SrcVT.getVectorElementType() == MVT
::i1 && "Expected a vXi1 vector") ? void (0) : __assert_fail
("SrcVT.getVectorElementType() == MVT::i1 && \"Expected a vXi1 vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 39932, __extension__ __PRETTY_FUNCTION__))
;
39933 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&(static_cast <bool> (ISD::isBuildVectorOfConstantSDNodes
(Op.getNode()) && "Expected a constant build vector")
? void (0) : __assert_fail ("ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && \"Expected a constant build vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 39934, __extension__ __PRETTY_FUNCTION__))
39934 "Expected a constant build vector")(static_cast <bool> (ISD::isBuildVectorOfConstantSDNodes
(Op.getNode()) && "Expected a constant build vector")
? void (0) : __assert_fail ("ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && \"Expected a constant build vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 39934, __extension__ __PRETTY_FUNCTION__))
;
39935
39936 APInt Imm(SrcVT.getVectorNumElements(), 0);
39937 for (unsigned Idx = 0, e = Op.getNumOperands(); Idx < e; ++Idx) {
39938 SDValue In = Op.getOperand(Idx);
39939 if (!In.isUndef() && (cast<ConstantSDNode>(In)->getZExtValue() & 0x1))
39940 Imm.setBit(Idx);
39941 }
39942 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), Imm.getBitWidth());
39943 return DAG.getConstant(Imm, SDLoc(Op), IntVT);
39944}
39945
39946static SDValue combineCastedMaskArithmetic(SDNode *N, SelectionDAG &DAG,
39947 TargetLowering::DAGCombinerInfo &DCI,
39948 const X86Subtarget &Subtarget) {
39949 assert(N->getOpcode() == ISD::BITCAST && "Expected a bitcast")(static_cast <bool> (N->getOpcode() == ISD::BITCAST &&
"Expected a bitcast") ? void (0) : __assert_fail ("N->getOpcode() == ISD::BITCAST && \"Expected a bitcast\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 39949, __extension__ __PRETTY_FUNCTION__))
;
39950
39951 if (!DCI.isBeforeLegalizeOps())
39952 return SDValue();
39953
39954 // Only do this if we have k-registers.
39955 if (!Subtarget.hasAVX512())
39956 return SDValue();
39957
39958 EVT DstVT = N->getValueType(0);
39959 SDValue Op = N->getOperand(0);
39960 EVT SrcVT = Op.getValueType();
39961
39962 if (!Op.hasOneUse())
39963 return SDValue();
39964
39965 // Look for logic ops.
39966 if (Op.getOpcode() != ISD::AND &&
39967 Op.getOpcode() != ISD::OR &&
39968 Op.getOpcode() != ISD::XOR)
39969 return SDValue();
39970
39971 // Make sure we have a bitcast between mask registers and a scalar type.
39972 if (!(SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
39973 DstVT.isScalarInteger()) &&
39974 !(DstVT.isVector() && DstVT.getVectorElementType() == MVT::i1 &&
39975 SrcVT.isScalarInteger()))
39976 return SDValue();
39977
39978 SDValue LHS = Op.getOperand(0);
39979 SDValue RHS = Op.getOperand(1);
39980
39981 if (LHS.hasOneUse() && LHS.getOpcode() == ISD::BITCAST &&
39982 LHS.getOperand(0).getValueType() == DstVT)
39983 return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT, LHS.getOperand(0),
39984 DAG.getBitcast(DstVT, RHS));
39985
39986 if (RHS.hasOneUse() && RHS.getOpcode() == ISD::BITCAST &&
39987 RHS.getOperand(0).getValueType() == DstVT)
39988 return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
39989 DAG.getBitcast(DstVT, LHS), RHS.getOperand(0));
39990
39991 // If the RHS is a vXi1 build vector, this is a good reason to flip too.
39992 // Most of these have to move a constant from the scalar domain anyway.
39993 if (ISD::isBuildVectorOfConstantSDNodes(RHS.getNode())) {
39994 RHS = combinevXi1ConstantToInteger(RHS, DAG);
39995 return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
39996 DAG.getBitcast(DstVT, LHS), RHS);
39997 }
39998
39999 return SDValue();
40000}
40001
40002static SDValue createMMXBuildVector(BuildVectorSDNode *BV, SelectionDAG &DAG,
40003 const X86Subtarget &Subtarget) {
40004 SDLoc DL(BV);
40005 unsigned NumElts = BV->getNumOperands();
40006 SDValue Splat = BV->getSplatValue();
40007
40008 // Build MMX element from integer GPR or SSE float values.
40009 auto CreateMMXElement = [&](SDValue V) {
40010 if (V.isUndef())
40011 return DAG.getUNDEF(MVT::x86mmx);
40012 if (V.getValueType().isFloatingPoint()) {
40013 if (Subtarget.hasSSE1() && !isa<ConstantFPSDNode>(V)) {
40014 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4f32, V);
40015 V = DAG.getBitcast(MVT::v2i64, V);
40016 return DAG.getNode(X86ISD::MOVDQ2Q, DL, MVT::x86mmx, V);
40017 }
40018 V = DAG.getBitcast(MVT::i32, V);
40019 } else {
40020 V = DAG.getAnyExtOrTrunc(V, DL, MVT::i32);
40021 }
40022 return DAG.getNode(X86ISD::MMX_MOVW2D, DL, MVT::x86mmx, V);
40023 };
40024
40025 // Convert build vector ops to MMX data in the bottom elements.
40026 SmallVector<SDValue, 8> Ops;
40027
40028 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40029
40030 // Broadcast - use (PUNPCKL+)PSHUFW to broadcast single element.
40031 if (Splat) {
40032 if (Splat.isUndef())
40033 return DAG.getUNDEF(MVT::x86mmx);
40034
40035 Splat = CreateMMXElement(Splat);
40036
40037 if (Subtarget.hasSSE1()) {
40038 // Unpack v8i8 to splat i8 elements to lowest 16-bits.
40039 if (NumElts == 8)
40040 Splat = DAG.getNode(
40041 ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
40042 DAG.getTargetConstant(Intrinsic::x86_mmx_punpcklbw, DL,
40043 TLI.getPointerTy(DAG.getDataLayout())),
40044 Splat, Splat);
40045
40046 // Use PSHUFW to repeat 16-bit elements.
40047 unsigned ShufMask = (NumElts > 2 ? 0 : 0x44);
40048 return DAG.getNode(
40049 ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
40050 DAG.getTargetConstant(Intrinsic::x86_sse_pshuf_w, DL,
40051 TLI.getPointerTy(DAG.getDataLayout())),
40052 Splat, DAG.getTargetConstant(ShufMask, DL, MVT::i8));
40053 }
40054 Ops.append(NumElts, Splat);
40055 } else {
40056 for (unsigned i = 0; i != NumElts; ++i)
40057 Ops.push_back(CreateMMXElement(BV->getOperand(i)));
40058 }
40059
40060 // Use tree of PUNPCKLs to build up general MMX vector.
40061 while (Ops.size() > 1) {
40062 unsigned NumOps = Ops.size();
40063 unsigned IntrinOp =
40064 (NumOps == 2 ? Intrinsic::x86_mmx_punpckldq
40065 : (NumOps == 4 ? Intrinsic::x86_mmx_punpcklwd
40066 : Intrinsic::x86_mmx_punpcklbw));
40067 SDValue Intrin = DAG.getTargetConstant(
40068 IntrinOp, DL, TLI.getPointerTy(DAG.getDataLayout()));
40069 for (unsigned i = 0; i != NumOps; i += 2)
40070 Ops[i / 2] = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx, Intrin,
40071 Ops[i], Ops[i + 1]);
40072 Ops.resize(NumOps / 2);
40073 }
40074
40075 return Ops[0];
40076}
40077
40078// Recursive function that attempts to find if a bool vector node was originally
40079// a vector/float/double that got truncated/extended/bitcast to/from a scalar
40080// integer. If so, replace the scalar ops with bool vector equivalents back down
40081// the chain.
40082static SDValue combineBitcastToBoolVector(EVT VT, SDValue V, const SDLoc &DL,
40083 SelectionDAG &DAG,
40084 const X86Subtarget &Subtarget) {
40085 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40086 unsigned Opc = V.getOpcode();
40087 switch (Opc) {
40088 case ISD::BITCAST: {
40089 // Bitcast from a vector/float/double, we can cheaply bitcast to VT.
40090 SDValue Src = V.getOperand(0);
40091 EVT SrcVT = Src.getValueType();
40092 if (SrcVT.isVector() || SrcVT.isFloatingPoint())
40093 return DAG.getBitcast(VT, Src);
40094 break;
40095 }
40096 case ISD::TRUNCATE: {
40097 // If we find a suitable source, a truncated scalar becomes a subvector.
40098 SDValue Src = V.getOperand(0);
40099 EVT NewSrcVT =
40100 EVT::getVectorVT(*DAG.getContext(), MVT::i1, Src.getValueSizeInBits());
40101 if (TLI.isTypeLegal(NewSrcVT))
40102 if (SDValue N0 =
40103 combineBitcastToBoolVector(NewSrcVT, Src, DL, DAG, Subtarget))
40104 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, N0,
40105 DAG.getIntPtrConstant(0, DL));
40106 break;
40107 }
40108 case ISD::ANY_EXTEND:
40109 case ISD::ZERO_EXTEND: {
40110 // If we find a suitable source, an extended scalar becomes a subvector.
40111 SDValue Src = V.getOperand(0);
40112 EVT NewSrcVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
40113 Src.getScalarValueSizeInBits());
40114 if (TLI.isTypeLegal(NewSrcVT))
40115 if (SDValue N0 =
40116 combineBitcastToBoolVector(NewSrcVT, Src, DL, DAG, Subtarget))
40117 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
40118 Opc == ISD::ANY_EXTEND ? DAG.getUNDEF(VT)
40119 : DAG.getConstant(0, DL, VT),
40120 N0, DAG.getIntPtrConstant(0, DL));
40121 break;
40122 }
40123 case ISD::OR: {
40124 // If we find suitable sources, we can just move an OR to the vector domain.
40125 SDValue Src0 = V.getOperand(0);
40126 SDValue Src1 = V.getOperand(1);
40127 if (SDValue N0 = combineBitcastToBoolVector(VT, Src0, DL, DAG, Subtarget))
40128 if (SDValue N1 = combineBitcastToBoolVector(VT, Src1, DL, DAG, Subtarget))
40129 return DAG.getNode(Opc, DL, VT, N0, N1);
40130 break;
40131 }
40132 case ISD::SHL: {
40133 // If we find a suitable source, a SHL becomes a KSHIFTL.
40134 SDValue Src0 = V.getOperand(0);
40135 if ((VT == MVT::v8i1 && !Subtarget.hasDQI()) ||
40136 ((VT == MVT::v32i1 || VT == MVT::v64i1) && !Subtarget.hasBWI()))
40137 break;
40138
40139 if (auto *Amt = dyn_cast<ConstantSDNode>(V.getOperand(1)))
40140 if (SDValue N0 = combineBitcastToBoolVector(VT, Src0, DL, DAG, Subtarget))
40141 return DAG.getNode(
40142 X86ISD::KSHIFTL, DL, VT, N0,
40143 DAG.getTargetConstant(Amt->getZExtValue(), DL, MVT::i8));
40144 break;
40145 }
40146 }
40147 return SDValue();
40148}
40149
40150static SDValue combineBitcast(SDNode *N, SelectionDAG &DAG,
40151 TargetLowering::DAGCombinerInfo &DCI,
40152 const X86Subtarget &Subtarget) {
40153 SDValue N0 = N->getOperand(0);
40154 EVT VT = N->getValueType(0);
40155 EVT SrcVT = N0.getValueType();
40156 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40157
40158 // Try to match patterns such as
40159 // (i16 bitcast (v16i1 x))
40160 // ->
40161 // (i16 movmsk (16i8 sext (v16i1 x)))
40162 // before the setcc result is scalarized on subtargets that don't have legal
40163 // vxi1 types.
40164 if (DCI.isBeforeLegalize()) {
40165 SDLoc dl(N);
40166 if (SDValue V = combineBitcastvxi1(DAG, VT, N0, dl, Subtarget))
40167 return V;
40168
40169 // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
40170 // type, widen both sides to avoid a trip through memory.
40171 if ((VT == MVT::v4i1 || VT == MVT::v2i1) && SrcVT.isScalarInteger() &&
40172 Subtarget.hasAVX512()) {
40173 N0 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, N0);
40174 N0 = DAG.getBitcast(MVT::v8i1, N0);
40175 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, N0,
40176 DAG.getIntPtrConstant(0, dl));
40177 }
40178
40179 // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
40180 // type, widen both sides to avoid a trip through memory.
40181 if ((SrcVT == MVT::v4i1 || SrcVT == MVT::v2i1) && VT.isScalarInteger() &&
40182 Subtarget.hasAVX512()) {
40183 // Use zeros for the widening if we already have some zeroes. This can
40184 // allow SimplifyDemandedBits to remove scalar ANDs that may be down
40185 // stream of this.
40186 // FIXME: It might make sense to detect a concat_vectors with a mix of
40187 // zeroes and undef and turn it into insert_subvector for i1 vectors as
40188 // a separate combine. What we can't do is canonicalize the operands of
40189 // such a concat or we'll get into a loop with SimplifyDemandedBits.
40190 if (N0.getOpcode() == ISD::CONCAT_VECTORS) {
40191 SDValue LastOp = N0.getOperand(N0.getNumOperands() - 1);
40192 if (ISD::isBuildVectorAllZeros(LastOp.getNode())) {
40193 SrcVT = LastOp.getValueType();
40194 unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
40195 SmallVector<SDValue, 4> Ops(N0->op_begin(), N0->op_end());
40196 Ops.resize(NumConcats, DAG.getConstant(0, dl, SrcVT));
40197 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
40198 N0 = DAG.getBitcast(MVT::i8, N0);
40199 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
40200 }
40201 }
40202
40203 unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
40204 SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT));
40205 Ops[0] = N0;
40206 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
40207 N0 = DAG.getBitcast(MVT::i8, N0);
40208 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
40209 }
40210 } else {
40211 // If we're bitcasting from iX to vXi1, see if the integer originally
40212 // began as a vXi1 and whether we can remove the bitcast entirely.
40213 if (VT.isVector() && VT.getScalarType() == MVT::i1 &&
40214 SrcVT.isScalarInteger() && TLI.isTypeLegal(VT)) {
40215 if (SDValue V =
40216 combineBitcastToBoolVector(VT, N0, SDLoc(N), DAG, Subtarget))
40217 return V;
40218 }
40219 }
40220
40221 // Look for (i8 (bitcast (v8i1 (extract_subvector (v16i1 X), 0)))) and
40222 // replace with (i8 (trunc (i16 (bitcast (v16i1 X))))). This can occur
40223 // due to insert_subvector legalization on KNL. By promoting the copy to i16
40224 // we can help with known bits propagation from the vXi1 domain to the
40225 // scalar domain.
40226 if (VT == MVT::i8 && SrcVT == MVT::v8i1 && Subtarget.hasAVX512() &&
40227 !Subtarget.hasDQI() && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
40228 N0.getOperand(0).getValueType() == MVT::v16i1 &&
40229 isNullConstant(N0.getOperand(1)))
40230 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT,
40231 DAG.getBitcast(MVT::i16, N0.getOperand(0)));
40232
40233 // Canonicalize (bitcast (vbroadcast_load)) so that the output of the bitcast
40234 // and the vbroadcast_load are both integer or both fp. In some cases this
40235 // will remove the bitcast entirely.
40236 if (N0.getOpcode() == X86ISD::VBROADCAST_LOAD && N0.hasOneUse() &&
40237 VT.isFloatingPoint() != SrcVT.isFloatingPoint() && VT.isVector()) {
40238 auto *BCast = cast<MemIntrinsicSDNode>(N0);
40239 unsigned SrcVTSize = SrcVT.getScalarSizeInBits();
40240 unsigned MemSize = BCast->getMemoryVT().getScalarSizeInBits();
40241 // Don't swap i8/i16 since don't have fp types that size.
40242 if (MemSize >= 32) {
40243 MVT MemVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(MemSize)
40244 : MVT::getIntegerVT(MemSize);
40245 MVT LoadVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(SrcVTSize)
40246 : MVT::getIntegerVT(SrcVTSize);
40247 LoadVT = MVT::getVectorVT(LoadVT, SrcVT.getVectorNumElements());
40248
40249 SDVTList Tys = DAG.getVTList(LoadVT, MVT::Other);
40250 SDValue Ops[] = { BCast->getChain(), BCast->getBasePtr() };
40251 SDValue ResNode =
40252 DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, SDLoc(N), Tys, Ops,
40253 MemVT, BCast->getMemOperand());
40254 DAG.ReplaceAllUsesOfValueWith(SDValue(BCast, 1), ResNode.getValue(1));
40255 return DAG.getBitcast(VT, ResNode);
40256 }
40257 }
40258
40259 // Since MMX types are special and don't usually play with other vector types,
40260 // it's better to handle them early to be sure we emit efficient code by
40261 // avoiding store-load conversions.
40262 if (VT == MVT::x86mmx) {
40263 // Detect MMX constant vectors.
40264 APInt UndefElts;
40265 SmallVector<APInt, 1> EltBits;
40266 if (getTargetConstantBitsFromNode(N0, 64, UndefElts, EltBits)) {
40267 SDLoc DL(N0);
40268 // Handle zero-extension of i32 with MOVD.
40269 if (EltBits[0].countLeadingZeros() >= 32)
40270 return DAG.getNode(X86ISD::MMX_MOVW2D, DL, VT,
40271 DAG.getConstant(EltBits[0].trunc(32), DL, MVT::i32));
40272 // Else, bitcast to a double.
40273 // TODO - investigate supporting sext 32-bit immediates on x86_64.
40274 APFloat F64(APFloat::IEEEdouble(), EltBits[0]);
40275 return DAG.getBitcast(VT, DAG.getConstantFP(F64, DL, MVT::f64));
40276 }
40277
40278 // Detect bitcasts to x86mmx low word.
40279 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
40280 (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) &&
40281 N0.getOperand(0).getValueType() == SrcVT.getScalarType()) {
40282 bool LowUndef = true, AllUndefOrZero = true;
40283 for (unsigned i = 1, e = SrcVT.getVectorNumElements(); i != e; ++i) {
40284 SDValue Op = N0.getOperand(i);
40285 LowUndef &= Op.isUndef() || (i >= e/2);
40286 AllUndefOrZero &= (Op.isUndef() || isNullConstant(Op));
40287 }
40288 if (AllUndefOrZero) {
40289 SDValue N00 = N0.getOperand(0);
40290 SDLoc dl(N00);
40291 N00 = LowUndef ? DAG.getAnyExtOrTrunc(N00, dl, MVT::i32)
40292 : DAG.getZExtOrTrunc(N00, dl, MVT::i32);
40293 return DAG.getNode(X86ISD::MMX_MOVW2D, dl, VT, N00);
40294 }
40295 }
40296
40297 // Detect bitcasts of 64-bit build vectors and convert to a
40298 // MMX UNPCK/PSHUFW which takes MMX type inputs with the value in the
40299 // lowest element.
40300 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
40301 (SrcVT == MVT::v2f32 || SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 ||
40302 SrcVT == MVT::v8i8))
40303 return createMMXBuildVector(cast<BuildVectorSDNode>(N0), DAG, Subtarget);
40304
40305 // Detect bitcasts between element or subvector extraction to x86mmx.
40306 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
40307 N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) &&
40308 isNullConstant(N0.getOperand(1))) {
40309 SDValue N00 = N0.getOperand(0);
40310 if (N00.getValueType().is128BitVector())
40311 return DAG.getNode(X86ISD::MOVDQ2Q, SDLoc(N00), VT,
40312 DAG.getBitcast(MVT::v2i64, N00));
40313 }
40314
40315 // Detect bitcasts from FP_TO_SINT to x86mmx.
40316 if (SrcVT == MVT::v2i32 && N0.getOpcode() == ISD::FP_TO_SINT) {
40317 SDLoc DL(N0);
40318 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
40319 DAG.getUNDEF(MVT::v2i32));
40320 return DAG.getNode(X86ISD::MOVDQ2Q, DL, VT,
40321 DAG.getBitcast(MVT::v2i64, Res));
40322 }
40323 }
40324
40325 // Try to remove a bitcast of constant vXi1 vector. We have to legalize
40326 // most of these to scalar anyway.
40327 if (Subtarget.hasAVX512() && VT.isScalarInteger() &&
40328 SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
40329 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
40330 return combinevXi1ConstantToInteger(N0, DAG);
40331 }
40332
40333 if (Subtarget.hasAVX512() && SrcVT.isScalarInteger() &&
40334 VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
40335 isa<ConstantSDNode>(N0)) {
40336 auto *C = cast<ConstantSDNode>(N0);
40337 if (C->isAllOnesValue())
40338 return DAG.getConstant(1, SDLoc(N0), VT);
40339 if (C->isNullValue())
40340 return DAG.getConstant(0, SDLoc(N0), VT);
40341 }
40342
40343 // Look for MOVMSK that is maybe truncated and then bitcasted to vXi1.
40344 // Turn it into a sign bit compare that produces a k-register. This avoids
40345 // a trip through a GPR.
40346 if (Subtarget.hasAVX512() && SrcVT.isScalarInteger() &&
40347 VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
40348 isPowerOf2_32(VT.getVectorNumElements())) {
40349 unsigned NumElts = VT.getVectorNumElements();
40350 SDValue Src = N0;
40351
40352 // Peek through truncate.
40353 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse())
40354 Src = N0.getOperand(0);
40355
40356 if (Src.getOpcode() == X86ISD::MOVMSK && Src.hasOneUse()) {
40357 SDValue MovmskIn = Src.getOperand(0);
40358 MVT MovmskVT = MovmskIn.getSimpleValueType();
40359 unsigned MovMskElts = MovmskVT.getVectorNumElements();
40360
40361 // We allow extra bits of the movmsk to be used since they are known zero.
40362 // We can't convert a VPMOVMSKB without avx512bw.
40363 if (MovMskElts <= NumElts &&
40364 (Subtarget.hasBWI() || MovmskVT.getVectorElementType() != MVT::i8)) {
40365 EVT IntVT = EVT(MovmskVT).changeVectorElementTypeToInteger();
40366 MovmskIn = DAG.getBitcast(IntVT, MovmskIn);
40367 SDLoc dl(N);
40368 MVT CmpVT = MVT::getVectorVT(MVT::i1, MovMskElts);
40369 SDValue Cmp = DAG.getSetCC(dl, CmpVT, MovmskIn,
40370 DAG.getConstant(0, dl, IntVT), ISD::SETLT);
40371 if (EVT(CmpVT) == VT)
40372 return Cmp;
40373
40374 // Pad with zeroes up to original VT to replace the zeroes that were
40375 // being used from the MOVMSK.
40376 unsigned NumConcats = NumElts / MovMskElts;
40377 SmallVector<SDValue, 4> Ops(NumConcats, DAG.getConstant(0, dl, CmpVT));
40378 Ops[0] = Cmp;
40379 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Ops);
40380 }
40381 }
40382 }
40383
40384 // Try to remove bitcasts from input and output of mask arithmetic to
40385 // remove GPR<->K-register crossings.
40386 if (SDValue V = combineCastedMaskArithmetic(N, DAG, DCI, Subtarget))
40387 return V;
40388
40389 // Convert a bitcasted integer logic operation that has one bitcasted
40390 // floating-point operand into a floating-point logic operation. This may
40391 // create a load of a constant, but that is cheaper than materializing the
40392 // constant in an integer register and transferring it to an SSE register or
40393 // transferring the SSE operand to integer register and back.
40394 unsigned FPOpcode;
40395 switch (N0.getOpcode()) {
40396 case ISD::AND: FPOpcode = X86ISD::FAND; break;
40397 case ISD::OR: FPOpcode = X86ISD::FOR; break;
40398 case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
40399 default: return SDValue();
40400 }
40401
40402 // Check if we have a bitcast from another integer type as well.
40403 if (!((Subtarget.hasSSE1() && VT == MVT::f32) ||
40404 (Subtarget.hasSSE2() && VT == MVT::f64) ||
40405 (Subtarget.hasSSE2() && VT.isInteger() && VT.isVector() &&
40406 TLI.isTypeLegal(VT))))
40407 return SDValue();
40408
40409 SDValue LogicOp0 = N0.getOperand(0);
40410 SDValue LogicOp1 = N0.getOperand(1);
40411 SDLoc DL0(N0);
40412
40413 // bitcast(logic(bitcast(X), Y)) --> logic'(X, bitcast(Y))
40414 if (N0.hasOneUse() && LogicOp0.getOpcode() == ISD::BITCAST &&
40415 LogicOp0.hasOneUse() && LogicOp0.getOperand(0).hasOneUse() &&
40416 LogicOp0.getOperand(0).getValueType() == VT &&
40417 !isa<ConstantSDNode>(LogicOp0.getOperand(0))) {
40418 SDValue CastedOp1 = DAG.getBitcast(VT, LogicOp1);
40419 unsigned Opcode = VT.isFloatingPoint() ? FPOpcode : N0.getOpcode();
40420 return DAG.getNode(Opcode, DL0, VT, LogicOp0.getOperand(0), CastedOp1);
40421 }
40422 // bitcast(logic(X, bitcast(Y))) --> logic'(bitcast(X), Y)
40423 if (N0.hasOneUse() && LogicOp1.getOpcode() == ISD::BITCAST &&
40424 LogicOp1.hasOneUse() && LogicOp1.getOperand(0).hasOneUse() &&
40425 LogicOp1.getOperand(0).getValueType() == VT &&
40426 !isa<ConstantSDNode>(LogicOp1.getOperand(0))) {
40427 SDValue CastedOp0 = DAG.getBitcast(VT, LogicOp0);
40428 unsigned Opcode = VT.isFloatingPoint() ? FPOpcode : N0.getOpcode();
40429 return DAG.getNode(Opcode, DL0, VT, LogicOp1.getOperand(0), CastedOp0);
40430 }
40431
40432 return SDValue();
40433}
40434
40435// Given a ABS node, detect the following pattern:
40436// (ABS (SUB (ZERO_EXTEND a), (ZERO_EXTEND b))).
40437// This is useful as it is the input into a SAD pattern.
40438static bool detectZextAbsDiff(const SDValue &Abs, SDValue &Op0, SDValue &Op1) {
40439 SDValue AbsOp1 = Abs->getOperand(0);
40440 if (AbsOp1.getOpcode() != ISD::SUB)
40441 return false;
40442
40443 Op0 = AbsOp1.getOperand(0);
40444 Op1 = AbsOp1.getOperand(1);
40445
40446 // Check if the operands of the sub are zero-extended from vectors of i8.
40447 if (Op0.getOpcode() != ISD::ZERO_EXTEND ||
40448 Op0.getOperand(0).getValueType().getVectorElementType() != MVT::i8 ||
40449 Op1.getOpcode() != ISD::ZERO_EXTEND ||
40450 Op1.getOperand(0).getValueType().getVectorElementType() != MVT::i8)
40451 return false;
40452
40453 return true;
40454}
40455
40456// Given two zexts of <k x i8> to <k x i32>, create a PSADBW of the inputs
40457// to these zexts.
40458static SDValue createPSADBW(SelectionDAG &DAG, const SDValue &Zext0,
40459 const SDValue &Zext1, const SDLoc &DL,
40460 const X86Subtarget &Subtarget) {
40461 // Find the appropriate width for the PSADBW.
40462 EVT InVT = Zext0.getOperand(0).getValueType();
40463 unsigned RegSize = std::max(128u, (unsigned)InVT.getSizeInBits());
40464
40465 // "Zero-extend" the i8 vectors. This is not a per-element zext, rather we
40466 // fill in the missing vector elements with 0.
40467 unsigned NumConcat = RegSize / InVT.getSizeInBits();
40468 SmallVector<SDValue, 16> Ops(NumConcat, DAG.getConstant(0, DL, InVT));
40469 Ops[0] = Zext0.getOperand(0);
40470 MVT ExtendedVT = MVT::getVectorVT(MVT::i8, RegSize / 8);
40471 SDValue SadOp0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
40472 Ops[0] = Zext1.getOperand(0);
40473 SDValue SadOp1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
40474
40475 // Actually build the SAD, split as 128/256/512 bits for SSE/AVX2/AVX512BW.
40476 auto PSADBWBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
40477 ArrayRef<SDValue> Ops) {
40478 MVT VT = MVT::getVectorVT(MVT::i64, Ops[0].getValueSizeInBits() / 64);
40479 return DAG.getNode(X86ISD::PSADBW, DL, VT, Ops);
40480 };
40481 MVT SadVT = MVT::getVectorVT(MVT::i64, RegSize / 64);
40482 return SplitOpsAndApply(DAG, Subtarget, DL, SadVT, { SadOp0, SadOp1 },
40483 PSADBWBuilder);
40484}
40485
40486// Attempt to replace an min/max v8i16/v16i8 horizontal reduction with
40487// PHMINPOSUW.
40488static SDValue combineMinMaxReduction(SDNode *Extract, SelectionDAG &DAG,
40489 const X86Subtarget &Subtarget) {
40490 // Bail without SSE41.
40491 if (!Subtarget.hasSSE41())
40492 return SDValue();
40493
40494 EVT ExtractVT = Extract->getValueType(0);
40495 if (ExtractVT != MVT::i16 && ExtractVT != MVT::i8)
40496 return SDValue();
40497
40498 // Check for SMAX/SMIN/UMAX/UMIN horizontal reduction patterns.
40499 ISD::NodeType BinOp;
40500 SDValue Src = DAG.matchBinOpReduction(
40501 Extract, BinOp, {ISD::SMAX, ISD::SMIN, ISD::UMAX, ISD::UMIN}, true);
40502 if (!Src)
40503 return SDValue();
40504
40505 EVT SrcVT = Src.getValueType();
40506 EVT SrcSVT = SrcVT.getScalarType();
40507 if (SrcSVT != ExtractVT || (SrcVT.getSizeInBits() % 128) != 0)
40508 return SDValue();
40509
40510 SDLoc DL(Extract);
40511 SDValue MinPos = Src;
40512
40513 // First, reduce the source down to 128-bit, applying BinOp to lo/hi.
40514 while (SrcVT.getSizeInBits() > 128) {
40515 SDValue Lo, Hi;
40516 std::tie(Lo, Hi) = splitVector(MinPos, DAG, DL);
40517 SrcVT = Lo.getValueType();
40518 MinPos = DAG.getNode(BinOp, DL, SrcVT, Lo, Hi);
40519 }
40520 assert(((SrcVT == MVT::v8i16 && ExtractVT == MVT::i16) ||(static_cast <bool> (((SrcVT == MVT::v8i16 && ExtractVT
== MVT::i16) || (SrcVT == MVT::v16i8 && ExtractVT ==
MVT::i8)) && "Unexpected value type") ? void (0) : __assert_fail
("((SrcVT == MVT::v8i16 && ExtractVT == MVT::i16) || (SrcVT == MVT::v16i8 && ExtractVT == MVT::i8)) && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 40522, __extension__ __PRETTY_FUNCTION__))
40521 (SrcVT == MVT::v16i8 && ExtractVT == MVT::i8)) &&(static_cast <bool> (((SrcVT == MVT::v8i16 && ExtractVT
== MVT::i16) || (SrcVT == MVT::v16i8 && ExtractVT ==
MVT::i8)) && "Unexpected value type") ? void (0) : __assert_fail
("((SrcVT == MVT::v8i16 && ExtractVT == MVT::i16) || (SrcVT == MVT::v16i8 && ExtractVT == MVT::i8)) && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 40522, __extension__ __PRETTY_FUNCTION__))
40522 "Unexpected value type")(static_cast <bool> (((SrcVT == MVT::v8i16 && ExtractVT
== MVT::i16) || (SrcVT == MVT::v16i8 && ExtractVT ==
MVT::i8)) && "Unexpected value type") ? void (0) : __assert_fail
("((SrcVT == MVT::v8i16 && ExtractVT == MVT::i16) || (SrcVT == MVT::v16i8 && ExtractVT == MVT::i8)) && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 40522, __extension__ __PRETTY_FUNCTION__))
;
40523
40524 // PHMINPOSUW applies to UMIN(v8i16), for SMIN/SMAX/UMAX we must apply a mask
40525 // to flip the value accordingly.
40526 SDValue Mask;
40527 unsigned MaskEltsBits = ExtractVT.getSizeInBits();
40528 if (BinOp == ISD::SMAX)
40529 Mask = DAG.getConstant(APInt::getSignedMaxValue(MaskEltsBits), DL, SrcVT);
40530 else if (BinOp == ISD::SMIN)
40531 Mask = DAG.getConstant(APInt::getSignedMinValue(MaskEltsBits), DL, SrcVT);
40532 else if (BinOp == ISD::UMAX)
40533 Mask = DAG.getConstant(APInt::getAllOnesValue(MaskEltsBits), DL, SrcVT);
40534
40535 if (Mask)
40536 MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
40537
40538 // For v16i8 cases we need to perform UMIN on pairs of byte elements,
40539 // shuffling each upper element down and insert zeros. This means that the
40540 // v16i8 UMIN will leave the upper element as zero, performing zero-extension
40541 // ready for the PHMINPOS.
40542 if (ExtractVT == MVT::i8) {
40543 SDValue Upper = DAG.getVectorShuffle(
40544 SrcVT, DL, MinPos, DAG.getConstant(0, DL, MVT::v16i8),
40545 {1, 16, 3, 16, 5, 16, 7, 16, 9, 16, 11, 16, 13, 16, 15, 16});
40546 MinPos = DAG.getNode(ISD::UMIN, DL, SrcVT, MinPos, Upper);
40547 }
40548
40549 // Perform the PHMINPOS on a v8i16 vector,
40550 MinPos = DAG.getBitcast(MVT::v8i16, MinPos);
40551 MinPos = DAG.getNode(X86ISD::PHMINPOS, DL, MVT::v8i16, MinPos);
40552 MinPos = DAG.getBitcast(SrcVT, MinPos);
40553
40554 if (Mask)
40555 MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
40556
40557 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, MinPos,
40558 DAG.getIntPtrConstant(0, DL));
40559}
40560
40561// Attempt to replace an all_of/any_of/parity style horizontal reduction with a MOVMSK.
40562static SDValue combinePredicateReduction(SDNode *Extract, SelectionDAG &DAG,
40563 const X86Subtarget &Subtarget) {
40564 // Bail without SSE2.
40565 if (!Subtarget.hasSSE2())
40566 return SDValue();
40567
40568 EVT ExtractVT = Extract->getValueType(0);
40569 unsigned BitWidth = ExtractVT.getSizeInBits();
40570 if (ExtractVT != MVT::i64 && ExtractVT != MVT::i32 && ExtractVT != MVT::i16 &&
40571 ExtractVT != MVT::i8 && ExtractVT != MVT::i1)
40572 return SDValue();
40573
40574 // Check for OR(any_of)/AND(all_of)/XOR(parity) horizontal reduction patterns.
40575 ISD::NodeType BinOp;
40576 SDValue Match = DAG.matchBinOpReduction(Extract, BinOp, {ISD::OR, ISD::AND});
40577 if (!Match && ExtractVT == MVT::i1)
40578 Match = DAG.matchBinOpReduction(Extract, BinOp, {ISD::XOR});
40579 if (!Match)
40580 return SDValue();
40581
40582 // EXTRACT_VECTOR_ELT can require implicit extension of the vector element
40583 // which we can't support here for now.
40584 if (Match.getScalarValueSizeInBits() != BitWidth)
40585 return SDValue();
40586
40587 SDValue Movmsk;
40588 SDLoc DL(Extract);
40589 EVT MatchVT = Match.getValueType();
40590 unsigned NumElts = MatchVT.getVectorNumElements();
40591 unsigned MaxElts = Subtarget.hasInt256() ? 32 : 16;
40592 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40593
40594 if (ExtractVT == MVT::i1) {
40595 // Special case for (pre-legalization) vXi1 reductions.
40596 if (NumElts > 64 || !isPowerOf2_32(NumElts))
40597 return SDValue();
40598 if (TLI.isTypeLegal(MatchVT)) {
40599 // If this is a legal AVX512 predicate type then we can just bitcast.
40600 EVT MovmskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
40601 Movmsk = DAG.getBitcast(MovmskVT, Match);
40602 } else {
40603 // For all_of(setcc(vec,0,eq)) - avoid vXi64 comparisons if we don't have
40604 // PCMPEQQ (SSE41+), use PCMPEQD instead.
40605 if (BinOp == ISD::AND && !Subtarget.hasSSE41() &&
40606 Match.getOpcode() == ISD::SETCC &&
40607 ISD::isBuildVectorAllZeros(Match.getOperand(1).getNode()) &&
40608 cast<CondCodeSDNode>(Match.getOperand(2))->get() ==
40609 ISD::CondCode::SETEQ) {
40610 SDValue Vec = Match.getOperand(0);
40611 if (Vec.getValueType().getScalarType() == MVT::i64 &&
40612 (2 * NumElts) <= MaxElts) {
40613 NumElts *= 2;
40614 EVT CmpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
40615 MatchVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, NumElts);
40616 Match = DAG.getSetCC(
40617 DL, MatchVT, DAG.getBitcast(CmpVT, Match.getOperand(0)),
40618 DAG.getBitcast(CmpVT, Match.getOperand(1)), ISD::CondCode::SETEQ);
40619 }
40620 }
40621
40622 // Use combineBitcastvxi1 to create the MOVMSK.
40623 while (NumElts > MaxElts) {
40624 SDValue Lo, Hi;
40625 std::tie(Lo, Hi) = DAG.SplitVector(Match, DL);
40626 Match = DAG.getNode(BinOp, DL, Lo.getValueType(), Lo, Hi);
40627 NumElts /= 2;
40628 }
40629 EVT MovmskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
40630 Movmsk = combineBitcastvxi1(DAG, MovmskVT, Match, DL, Subtarget);
40631 }
40632 if (!Movmsk)
40633 return SDValue();
40634 Movmsk = DAG.getZExtOrTrunc(Movmsk, DL, NumElts > 32 ? MVT::i64 : MVT::i32);
40635 } else {
40636 // FIXME: Better handling of k-registers or 512-bit vectors?
40637 unsigned MatchSizeInBits = Match.getValueSizeInBits();
40638 if (!(MatchSizeInBits == 128 ||
40639 (MatchSizeInBits == 256 && Subtarget.hasAVX())))
40640 return SDValue();
40641
40642 // Make sure this isn't a vector of 1 element. The perf win from using
40643 // MOVMSK diminishes with less elements in the reduction, but it is
40644 // generally better to get the comparison over to the GPRs as soon as
40645 // possible to reduce the number of vector ops.
40646 if (Match.getValueType().getVectorNumElements() < 2)
40647 return SDValue();
40648
40649 // Check that we are extracting a reduction of all sign bits.
40650 if (DAG.ComputeNumSignBits(Match) != BitWidth)
40651 return SDValue();
40652
40653 if (MatchSizeInBits == 256 && BitWidth < 32 && !Subtarget.hasInt256()) {
40654 SDValue Lo, Hi;
40655 std::tie(Lo, Hi) = DAG.SplitVector(Match, DL);
40656 Match = DAG.getNode(BinOp, DL, Lo.getValueType(), Lo, Hi);
40657 MatchSizeInBits = Match.getValueSizeInBits();
40658 }
40659
40660 // For 32/64 bit comparisons use MOVMSKPS/MOVMSKPD, else PMOVMSKB.
40661 MVT MaskSrcVT;
40662 if (64 == BitWidth || 32 == BitWidth)
40663 MaskSrcVT = MVT::getVectorVT(MVT::getFloatingPointVT(BitWidth),
40664 MatchSizeInBits / BitWidth);
40665 else
40666 MaskSrcVT = MVT::getVectorVT(MVT::i8, MatchSizeInBits / 8);
40667
40668 SDValue BitcastLogicOp = DAG.getBitcast(MaskSrcVT, Match);
40669 Movmsk = getPMOVMSKB(DL, BitcastLogicOp, DAG, Subtarget);
40670 NumElts = MaskSrcVT.getVectorNumElements();
40671 }
40672 assert((NumElts <= 32 || NumElts == 64) &&(static_cast <bool> ((NumElts <= 32 || NumElts == 64
) && "Not expecting more than 64 elements") ? void (0
) : __assert_fail ("(NumElts <= 32 || NumElts == 64) && \"Not expecting more than 64 elements\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 40673, __extension__ __PRETTY_FUNCTION__))
40673 "Not expecting more than 64 elements")(static_cast <bool> ((NumElts <= 32 || NumElts == 64
) && "Not expecting more than 64 elements") ? void (0
) : __assert_fail ("(NumElts <= 32 || NumElts == 64) && \"Not expecting more than 64 elements\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 40673, __extension__ __PRETTY_FUNCTION__))
;
40674
40675 MVT CmpVT = NumElts == 64 ? MVT::i64 : MVT::i32;
40676 if (BinOp == ISD::XOR) {
40677 // parity -> (PARITY(MOVMSK X))
40678 SDValue Result = DAG.getNode(ISD::PARITY, DL, CmpVT, Movmsk);
40679 return DAG.getZExtOrTrunc(Result, DL, ExtractVT);
40680 }
40681
40682 SDValue CmpC;
40683 ISD::CondCode CondCode;
40684 if (BinOp == ISD::OR) {
40685 // any_of -> MOVMSK != 0
40686 CmpC = DAG.getConstant(0, DL, CmpVT);
40687 CondCode = ISD::CondCode::SETNE;
40688 } else {
40689 // all_of -> MOVMSK == ((1 << NumElts) - 1)
40690 CmpC = DAG.getConstant(APInt::getLowBitsSet(CmpVT.getSizeInBits(), NumElts),
40691 DL, CmpVT);
40692 CondCode = ISD::CondCode::SETEQ;
40693 }
40694
40695 // The setcc produces an i8 of 0/1, so extend that to the result width and
40696 // negate to get the final 0/-1 mask value.
40697 EVT SetccVT =
40698 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT);
40699 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Movmsk, CmpC, CondCode);
40700 SDValue Zext = DAG.getZExtOrTrunc(Setcc, DL, ExtractVT);
40701 SDValue Zero = DAG.getConstant(0, DL, ExtractVT);
40702 return DAG.getNode(ISD::SUB, DL, ExtractVT, Zero, Zext);
40703}
40704
40705static SDValue combineBasicSADPattern(SDNode *Extract, SelectionDAG &DAG,
40706 const X86Subtarget &Subtarget) {
40707 // PSADBW is only supported on SSE2 and up.
40708 if (!Subtarget.hasSSE2())
40709 return SDValue();
40710
40711 EVT ExtractVT = Extract->getValueType(0);
40712 // Verify the type we're extracting is either i32 or i64.
40713 // FIXME: Could support other types, but this is what we have coverage for.
40714 if (ExtractVT != MVT::i32 && ExtractVT != MVT::i64)
40715 return SDValue();
40716
40717 EVT VT = Extract->getOperand(0).getValueType();
40718 if (!isPowerOf2_32(VT.getVectorNumElements()))
40719 return SDValue();
40720
40721 // Match shuffle + add pyramid.
40722 ISD::NodeType BinOp;
40723 SDValue Root = DAG.matchBinOpReduction(Extract, BinOp, {ISD::ADD});
40724
40725 // The operand is expected to be zero extended from i8
40726 // (verified in detectZextAbsDiff).
40727 // In order to convert to i64 and above, additional any/zero/sign
40728 // extend is expected.
40729 // The zero extend from 32 bit has no mathematical effect on the result.
40730 // Also the sign extend is basically zero extend
40731 // (extends the sign bit which is zero).
40732 // So it is correct to skip the sign/zero extend instruction.
40733 if (Root && (Root.getOpcode() == ISD::SIGN_EXTEND ||
40734 Root.getOpcode() == ISD::ZERO_EXTEND ||
40735 Root.getOpcode() == ISD::ANY_EXTEND))
40736 Root = Root.getOperand(0);
40737
40738 // If there was a match, we want Root to be a select that is the root of an
40739 // abs-diff pattern.
40740 if (!Root || Root.getOpcode() != ISD::ABS)
40741 return SDValue();
40742
40743 // Check whether we have an abs-diff pattern feeding into the select.
40744 SDValue Zext0, Zext1;
40745 if (!detectZextAbsDiff(Root, Zext0, Zext1))
40746 return SDValue();
40747
40748 // Create the SAD instruction.
40749 SDLoc DL(Extract);
40750 SDValue SAD = createPSADBW(DAG, Zext0, Zext1, DL, Subtarget);
40751
40752 // If the original vector was wider than 8 elements, sum over the results
40753 // in the SAD vector.
40754 unsigned Stages = Log2_32(VT.getVectorNumElements());
40755 EVT SadVT = SAD.getValueType();
40756 if (Stages > 3) {
40757 unsigned SadElems = SadVT.getVectorNumElements();
40758
40759 for(unsigned i = Stages - 3; i > 0; --i) {
40760 SmallVector<int, 16> Mask(SadElems, -1);
40761 for(unsigned j = 0, MaskEnd = 1 << (i - 1); j < MaskEnd; ++j)
40762 Mask[j] = MaskEnd + j;
40763
40764 SDValue Shuffle =
40765 DAG.getVectorShuffle(SadVT, DL, SAD, DAG.getUNDEF(SadVT), Mask);
40766 SAD = DAG.getNode(ISD::ADD, DL, SadVT, SAD, Shuffle);
40767 }
40768 }
40769
40770 unsigned ExtractSizeInBits = ExtractVT.getSizeInBits();
40771 // Return the lowest ExtractSizeInBits bits.
40772 EVT ResVT = EVT::getVectorVT(*DAG.getContext(), ExtractVT,
40773 SadVT.getSizeInBits() / ExtractSizeInBits);
40774 SAD = DAG.getBitcast(ResVT, SAD);
40775 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, SAD,
40776 Extract->getOperand(1));
40777}
40778
40779// Attempt to peek through a target shuffle and extract the scalar from the
40780// source.
40781static SDValue combineExtractWithShuffle(SDNode *N, SelectionDAG &DAG,
40782 TargetLowering::DAGCombinerInfo &DCI,
40783 const X86Subtarget &Subtarget) {
40784 if (DCI.isBeforeLegalizeOps())
40785 return SDValue();
40786
40787 SDLoc dl(N);
40788 SDValue Src = N->getOperand(0);
40789 SDValue Idx = N->getOperand(1);
40790
40791 EVT VT = N->getValueType(0);
40792 EVT SrcVT = Src.getValueType();
40793 EVT SrcSVT = SrcVT.getVectorElementType();
40794 unsigned SrcEltBits = SrcSVT.getSizeInBits();
40795 unsigned NumSrcElts = SrcVT.getVectorNumElements();
40796
40797 // Don't attempt this for boolean mask vectors or unknown extraction indices.
40798 if (SrcSVT == MVT::i1 || !isa<ConstantSDNode>(Idx))
40799 return SDValue();
40800
40801 const APInt &IdxC = N->getConstantOperandAPInt(1);
40802 if (IdxC.uge(NumSrcElts))
40803 return SDValue();
40804
40805 SDValue SrcBC = peekThroughBitcasts(Src);
40806
40807 // Handle extract(bitcast(broadcast(scalar_value))).
40808 if (X86ISD::VBROADCAST == SrcBC.getOpcode()) {
40809 SDValue SrcOp = SrcBC.getOperand(0);
40810 EVT SrcOpVT = SrcOp.getValueType();
40811 if (SrcOpVT.isScalarInteger() && VT.isInteger() &&
40812 (SrcOpVT.getSizeInBits() % SrcEltBits) == 0) {
40813 unsigned Scale = SrcOpVT.getSizeInBits() / SrcEltBits;
40814 unsigned Offset = IdxC.urem(Scale) * SrcEltBits;
40815 // TODO support non-zero offsets.
40816 if (Offset == 0) {
40817 SrcOp = DAG.getZExtOrTrunc(SrcOp, dl, SrcVT.getScalarType());
40818 SrcOp = DAG.getZExtOrTrunc(SrcOp, dl, VT);
40819 return SrcOp;
40820 }
40821 }
40822 }
40823
40824 // If we're extracting a single element from a broadcast load and there are
40825 // no other users, just create a single load.
40826 if (SrcBC.getOpcode() == X86ISD::VBROADCAST_LOAD && SrcBC.hasOneUse()) {
40827 auto *MemIntr = cast<MemIntrinsicSDNode>(SrcBC);
40828 unsigned SrcBCWidth = SrcBC.getScalarValueSizeInBits();
40829 if (MemIntr->getMemoryVT().getSizeInBits() == SrcBCWidth &&
40830 VT.getSizeInBits() == SrcBCWidth && SrcEltBits == SrcBCWidth) {
40831 SDValue Load = DAG.getLoad(VT, dl, MemIntr->getChain(),
40832 MemIntr->getBasePtr(),
40833 MemIntr->getPointerInfo(),
40834 MemIntr->getOriginalAlign(),
40835 MemIntr->getMemOperand()->getFlags());
40836 DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), Load.getValue(1));
40837 return Load;
40838 }
40839 }
40840
40841 // Handle extract(bitcast(scalar_to_vector(scalar_value))) for integers.
40842 // TODO: Move to DAGCombine?
40843 if (SrcBC.getOpcode() == ISD::SCALAR_TO_VECTOR && VT.isInteger() &&
40844 SrcBC.getValueType().isInteger() &&
40845 (SrcBC.getScalarValueSizeInBits() % SrcEltBits) == 0 &&
40846 SrcBC.getScalarValueSizeInBits() ==
40847 SrcBC.getOperand(0).getValueSizeInBits()) {
40848 unsigned Scale = SrcBC.getScalarValueSizeInBits() / SrcEltBits;
40849 if (IdxC.ult(Scale)) {
40850 unsigned Offset = IdxC.getZExtValue() * SrcVT.getScalarSizeInBits();
40851 SDValue Scl = SrcBC.getOperand(0);
40852 EVT SclVT = Scl.getValueType();
40853 if (Offset) {
40854 Scl = DAG.getNode(ISD::SRL, dl, SclVT, Scl,
40855 DAG.getShiftAmountConstant(Offset, SclVT, dl));
40856 }
40857 Scl = DAG.getZExtOrTrunc(Scl, dl, SrcVT.getScalarType());
40858 Scl = DAG.getZExtOrTrunc(Scl, dl, VT);
40859 return Scl;
40860 }
40861 }
40862
40863 // Handle extract(truncate(x)) for 0'th index.
40864 // TODO: Treat this as a faux shuffle?
40865 // TODO: When can we use this for general indices?
40866 if (ISD::TRUNCATE == Src.getOpcode() && IdxC == 0 &&
40867 (SrcVT.getSizeInBits() % 128) == 0) {
40868 Src = extract128BitVector(Src.getOperand(0), 0, DAG, dl);
40869 MVT ExtractVT = MVT::getVectorVT(SrcSVT.getSimpleVT(), 128 / SrcEltBits);
40870 return DAG.getNode(N->getOpcode(), dl, VT, DAG.getBitcast(ExtractVT, Src),
40871 Idx);
40872 }
40873
40874 // We can only legally extract other elements from 128-bit vectors and in
40875 // certain circumstances, depending on SSE-level.
40876 // TODO: Investigate float/double extraction if it will be just stored.
40877 auto GetLegalExtract = [&Subtarget, &DAG, &dl](SDValue Vec, EVT VecVT,
40878 unsigned Idx) {
40879 EVT VecSVT = VecVT.getScalarType();
40880 if ((VecVT.is256BitVector() || VecVT.is512BitVector()) &&
40881 (VecSVT == MVT::i8 || VecSVT == MVT::i16 || VecSVT == MVT::i32 ||
40882 VecSVT == MVT::i64)) {
40883 unsigned EltSizeInBits = VecSVT.getSizeInBits();
40884 unsigned NumEltsPerLane = 128 / EltSizeInBits;
40885 unsigned LaneOffset = (Idx & ~(NumEltsPerLane - 1)) * EltSizeInBits;
40886 unsigned LaneIdx = LaneOffset / Vec.getScalarValueSizeInBits();
40887 VecVT = EVT::getVectorVT(*DAG.getContext(), VecSVT, NumEltsPerLane);
40888 Vec = extract128BitVector(Vec, LaneIdx, DAG, dl);
40889 Idx &= (NumEltsPerLane - 1);
40890 }
40891 if ((VecVT == MVT::v4i32 || VecVT == MVT::v2i64) &&
40892 ((Idx == 0 && Subtarget.hasSSE2()) || Subtarget.hasSSE41())) {
40893 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VecVT.getScalarType(),
40894 DAG.getBitcast(VecVT, Vec),
40895 DAG.getIntPtrConstant(Idx, dl));
40896 }
40897 if ((VecVT == MVT::v8i16 && Subtarget.hasSSE2()) ||
40898 (VecVT == MVT::v16i8 && Subtarget.hasSSE41())) {
40899 unsigned OpCode = (VecVT == MVT::v8i16 ? X86ISD::PEXTRW : X86ISD::PEXTRB);
40900 return DAG.getNode(OpCode, dl, MVT::i32, DAG.getBitcast(VecVT, Vec),
40901 DAG.getTargetConstant(Idx, dl, MVT::i8));
40902 }
40903 return SDValue();
40904 };
40905
40906 // Resolve the target shuffle inputs and mask.
40907 SmallVector<int, 16> Mask;
40908 SmallVector<SDValue, 2> Ops;
40909 if (!getTargetShuffleInputs(SrcBC, Ops, Mask, DAG))
40910 return SDValue();
40911
40912 // Shuffle inputs must be the same size as the result.
40913 if (llvm::any_of(Ops, [SrcVT](SDValue Op) {
40914 return SrcVT.getSizeInBits() != Op.getValueSizeInBits();
40915 }))
40916 return SDValue();
40917
40918 // Attempt to narrow/widen the shuffle mask to the correct size.
40919 if (Mask.size() != NumSrcElts) {
40920 if ((NumSrcElts % Mask.size()) == 0) {
40921 SmallVector<int, 16> ScaledMask;
40922 int Scale = NumSrcElts / Mask.size();
40923 narrowShuffleMaskElts(Scale, Mask, ScaledMask);
40924 Mask = std::move(ScaledMask);
40925 } else if ((Mask.size() % NumSrcElts) == 0) {
40926 // Simplify Mask based on demanded element.
40927 int ExtractIdx = (int)IdxC.getZExtValue();
40928 int Scale = Mask.size() / NumSrcElts;
40929 int Lo = Scale * ExtractIdx;
40930 int Hi = Scale * (ExtractIdx + 1);
40931 for (int i = 0, e = (int)Mask.size(); i != e; ++i)
40932 if (i < Lo || Hi <= i)
40933 Mask[i] = SM_SentinelUndef;
40934
40935 SmallVector<int, 16> WidenedMask;
40936 while (Mask.size() > NumSrcElts &&
40937 canWidenShuffleElements(Mask, WidenedMask))
40938 Mask = std::move(WidenedMask);
40939 }
40940 }
40941
40942 // If narrowing/widening failed, see if we can extract+zero-extend.
40943 int ExtractIdx;
40944 EVT ExtractVT;
40945 if (Mask.size() == NumSrcElts) {
40946 ExtractIdx = Mask[IdxC.getZExtValue()];
40947 ExtractVT = SrcVT;
40948 } else {
40949 unsigned Scale = Mask.size() / NumSrcElts;
40950 if ((Mask.size() % NumSrcElts) != 0 || SrcVT.isFloatingPoint())
40951 return SDValue();
40952 unsigned ScaledIdx = Scale * IdxC.getZExtValue();
40953 if (!isUndefOrZeroInRange(Mask, ScaledIdx + 1, Scale - 1))
40954 return SDValue();
40955 ExtractIdx = Mask[ScaledIdx];
40956 EVT ExtractSVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltBits / Scale);
40957 ExtractVT = EVT::getVectorVT(*DAG.getContext(), ExtractSVT, Mask.size());
40958 assert(SrcVT.getSizeInBits() == ExtractVT.getSizeInBits() &&(static_cast <bool> (SrcVT.getSizeInBits() == ExtractVT
.getSizeInBits() && "Failed to widen vector type") ? void
(0) : __assert_fail ("SrcVT.getSizeInBits() == ExtractVT.getSizeInBits() && \"Failed to widen vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 40959, __extension__ __PRETTY_FUNCTION__))
40959 "Failed to widen vector type")(static_cast <bool> (SrcVT.getSizeInBits() == ExtractVT
.getSizeInBits() && "Failed to widen vector type") ? void
(0) : __assert_fail ("SrcVT.getSizeInBits() == ExtractVT.getSizeInBits() && \"Failed to widen vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 40959, __extension__ __PRETTY_FUNCTION__))
;
40960 }
40961
40962 // If the shuffle source element is undef/zero then we can just accept it.
40963 if (ExtractIdx == SM_SentinelUndef)
40964 return DAG.getUNDEF(VT);
40965
40966 if (ExtractIdx == SM_SentinelZero)
40967 return VT.isFloatingPoint() ? DAG.getConstantFP(0.0, dl, VT)
40968 : DAG.getConstant(0, dl, VT);
40969
40970 SDValue SrcOp = Ops[ExtractIdx / Mask.size()];
40971 ExtractIdx = ExtractIdx % Mask.size();
40972 if (SDValue V = GetLegalExtract(SrcOp, ExtractVT, ExtractIdx))
40973 return DAG.getZExtOrTrunc(V, dl, VT);
40974
40975 return SDValue();
40976}
40977
40978/// Extracting a scalar FP value from vector element 0 is free, so extract each
40979/// operand first, then perform the math as a scalar op.
40980static SDValue scalarizeExtEltFP(SDNode *ExtElt, SelectionDAG &DAG) {
40981 assert(ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Expected extract")(static_cast <bool> (ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT
&& "Expected extract") ? void (0) : __assert_fail ("ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && \"Expected extract\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 40981, __extension__ __PRETTY_FUNCTION__))
;
40982 SDValue Vec = ExtElt->getOperand(0);
40983 SDValue Index = ExtElt->getOperand(1);
40984 EVT VT = ExtElt->getValueType(0);
40985 EVT VecVT = Vec.getValueType();
40986
40987 // TODO: If this is a unary/expensive/expand op, allow extraction from a
40988 // non-zero element because the shuffle+scalar op will be cheaper?
40989 if (!Vec.hasOneUse() || !isNullConstant(Index) || VecVT.getScalarType() != VT)
40990 return SDValue();
40991
40992 // Vector FP compares don't fit the pattern of FP math ops (propagate, not
40993 // extract, the condition code), so deal with those as a special-case.
40994 if (Vec.getOpcode() == ISD::SETCC && VT == MVT::i1) {
40995 EVT OpVT = Vec.getOperand(0).getValueType().getScalarType();
40996 if (OpVT != MVT::f32 && OpVT != MVT::f64)
40997 return SDValue();
40998
40999 // extract (setcc X, Y, CC), 0 --> setcc (extract X, 0), (extract Y, 0), CC
41000 SDLoc DL(ExtElt);
41001 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT,
41002 Vec.getOperand(0), Index);
41003 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT,
41004 Vec.getOperand(1), Index);
41005 return DAG.getNode(Vec.getOpcode(), DL, VT, Ext0, Ext1, Vec.getOperand(2));
41006 }
41007
41008 if (VT != MVT::f32 && VT != MVT::f64)
41009 return SDValue();
41010
41011 // Vector FP selects don't fit the pattern of FP math ops (because the
41012 // condition has a different type and we have to change the opcode), so deal
41013 // with those here.
41014 // FIXME: This is restricted to pre type legalization by ensuring the setcc
41015 // has i1 elements. If we loosen this we need to convert vector bool to a
41016 // scalar bool.
41017 if (Vec.getOpcode() == ISD::VSELECT &&
41018 Vec.getOperand(0).getOpcode() == ISD::SETCC &&
41019 Vec.getOperand(0).getValueType().getScalarType() == MVT::i1 &&
41020 Vec.getOperand(0).getOperand(0).getValueType() == VecVT) {
41021 // ext (sel Cond, X, Y), 0 --> sel (ext Cond, 0), (ext X, 0), (ext Y, 0)
41022 SDLoc DL(ExtElt);
41023 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
41024 Vec.getOperand(0).getValueType().getScalarType(),
41025 Vec.getOperand(0), Index);
41026 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
41027 Vec.getOperand(1), Index);
41028 SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
41029 Vec.getOperand(2), Index);
41030 return DAG.getNode(ISD::SELECT, DL, VT, Ext0, Ext1, Ext2);
41031 }
41032
41033 // TODO: This switch could include FNEG and the x86-specific FP logic ops
41034 // (FAND, FANDN, FOR, FXOR). But that may require enhancements to avoid
41035 // missed load folding and fma+fneg combining.
41036 switch (Vec.getOpcode()) {
41037 case ISD::FMA: // Begin 3 operands
41038 case ISD::FMAD:
41039 case ISD::FADD: // Begin 2 operands
41040 case ISD::FSUB:
41041 case ISD::FMUL:
41042 case ISD::FDIV:
41043 case ISD::FREM:
41044 case ISD::FCOPYSIGN:
41045 case ISD::FMINNUM:
41046 case ISD::FMAXNUM:
41047 case ISD::FMINNUM_IEEE:
41048 case ISD::FMAXNUM_IEEE:
41049 case ISD::FMAXIMUM:
41050 case ISD::FMINIMUM:
41051 case X86ISD::FMAX:
41052 case X86ISD::FMIN:
41053 case ISD::FABS: // Begin 1 operand
41054 case ISD::FSQRT:
41055 case ISD::FRINT:
41056 case ISD::FCEIL:
41057 case ISD::FTRUNC:
41058 case ISD::FNEARBYINT:
41059 case ISD::FROUND:
41060 case ISD::FFLOOR:
41061 case X86ISD::FRCP:
41062 case X86ISD::FRSQRT: {
41063 // extract (fp X, Y, ...), 0 --> fp (extract X, 0), (extract Y, 0), ...
41064 SDLoc DL(ExtElt);
41065 SmallVector<SDValue, 4> ExtOps;
41066 for (SDValue Op : Vec->ops())
41067 ExtOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op, Index));
41068 return DAG.getNode(Vec.getOpcode(), DL, VT, ExtOps);
41069 }
41070 default:
41071 return SDValue();
41072 }
41073 llvm_unreachable("All opcodes should return within switch")::llvm::llvm_unreachable_internal("All opcodes should return within switch"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 41073)
;
41074}
41075
41076/// Try to convert a vector reduction sequence composed of binops and shuffles
41077/// into horizontal ops.
41078static SDValue combineArithReduction(SDNode *ExtElt, SelectionDAG &DAG,
41079 const X86Subtarget &Subtarget) {
41080 assert(ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unexpected caller")(static_cast <bool> (ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT
&& "Unexpected caller") ? void (0) : __assert_fail (
"ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && \"Unexpected caller\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 41080, __extension__ __PRETTY_FUNCTION__))
;
41081
41082 // We need at least SSE2 to anything here.
41083 if (!Subtarget.hasSSE2())
41084 return SDValue();
41085
41086 ISD::NodeType Opc;
41087 SDValue Rdx = DAG.matchBinOpReduction(ExtElt, Opc,
41088 {ISD::ADD, ISD::MUL, ISD::FADD}, true);
41089 if (!Rdx)
41090 return SDValue();
41091
41092 SDValue Index = ExtElt->getOperand(1);
41093 assert(isNullConstant(Index) &&(static_cast <bool> (isNullConstant(Index) && "Reduction doesn't end in an extract from index 0"
) ? void (0) : __assert_fail ("isNullConstant(Index) && \"Reduction doesn't end in an extract from index 0\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 41094, __extension__ __PRETTY_FUNCTION__))
41094 "Reduction doesn't end in an extract from index 0")(static_cast <bool> (isNullConstant(Index) && "Reduction doesn't end in an extract from index 0"
) ? void (0) : __assert_fail ("isNullConstant(Index) && \"Reduction doesn't end in an extract from index 0\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 41094, __extension__ __PRETTY_FUNCTION__))
;
41095
41096 EVT VT = ExtElt->getValueType(0);
41097 EVT VecVT = Rdx.getValueType();
41098 if (VecVT.getScalarType() != VT)
41099 return SDValue();
41100
41101 SDLoc DL(ExtElt);
41102
41103 // vXi8 mul reduction - promote to vXi16 mul reduction.
41104 if (Opc == ISD::MUL) {
41105 unsigned NumElts = VecVT.getVectorNumElements();
41106 if (VT != MVT::i8 || NumElts < 4 || !isPowerOf2_32(NumElts))
41107 return SDValue();
41108 if (VecVT.getSizeInBits() >= 128) {
41109 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16, NumElts / 2);
41110 SDValue Lo = getUnpackl(DAG, DL, VecVT, Rdx, DAG.getUNDEF(VecVT));
41111 SDValue Hi = getUnpackh(DAG, DL, VecVT, Rdx, DAG.getUNDEF(VecVT));
41112 Lo = DAG.getBitcast(WideVT, Lo);
41113 Hi = DAG.getBitcast(WideVT, Hi);
41114 Rdx = DAG.getNode(Opc, DL, WideVT, Lo, Hi);
41115 while (Rdx.getValueSizeInBits() > 128) {
41116 std::tie(Lo, Hi) = splitVector(Rdx, DAG, DL);
41117 Rdx = DAG.getNode(Opc, DL, Lo.getValueType(), Lo, Hi);
41118 }
41119 } else {
41120 if (VecVT == MVT::v4i8)
41121 Rdx = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i8, Rdx,
41122 DAG.getUNDEF(MVT::v4i8));
41123 Rdx = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, Rdx,
41124 DAG.getUNDEF(MVT::v8i8));
41125 Rdx = getUnpackl(DAG, DL, MVT::v16i8, Rdx, DAG.getUNDEF(MVT::v16i8));
41126 Rdx = DAG.getBitcast(MVT::v8i16, Rdx);
41127 }
41128 if (NumElts >= 8)
41129 Rdx = DAG.getNode(Opc, DL, MVT::v8i16, Rdx,
41130 DAG.getVectorShuffle(MVT::v8i16, DL, Rdx, Rdx,
41131 {4, 5, 6, 7, -1, -1, -1, -1}));
41132 Rdx = DAG.getNode(Opc, DL, MVT::v8i16, Rdx,
41133 DAG.getVectorShuffle(MVT::v8i16, DL, Rdx, Rdx,
41134 {2, 3, -1, -1, -1, -1, -1, -1}));
41135 Rdx = DAG.getNode(Opc, DL, MVT::v8i16, Rdx,
41136 DAG.getVectorShuffle(MVT::v8i16, DL, Rdx, Rdx,
41137 {1, -1, -1, -1, -1, -1, -1, -1}));
41138 Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
41139 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
41140 }
41141
41142 // vXi8 add reduction - sub 128-bit vector.
41143 if (VecVT == MVT::v4i8 || VecVT == MVT::v8i8) {
41144 if (VecVT == MVT::v4i8) {
41145 // Pad with zero.
41146 if (Subtarget.hasSSE41()) {
41147 Rdx = DAG.getBitcast(MVT::i32, Rdx);
41148 Rdx = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v4i32,
41149 DAG.getConstant(0, DL, MVT::v4i32), Rdx,
41150 DAG.getIntPtrConstant(0, DL));
41151 Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
41152 } else {
41153 Rdx = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i8, Rdx,
41154 DAG.getConstant(0, DL, VecVT));
41155 }
41156 }
41157 if (Rdx.getValueType() == MVT::v8i8) {
41158 // Pad with undef.
41159 Rdx = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, Rdx,
41160 DAG.getUNDEF(MVT::v8i8));
41161 }
41162 Rdx = DAG.getNode(X86ISD::PSADBW, DL, MVT::v2i64, Rdx,
41163 DAG.getConstant(0, DL, MVT::v16i8));
41164 Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
41165 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
41166 }
41167
41168 // Must be a >=128-bit vector with pow2 elements.
41169 if ((VecVT.getSizeInBits() % 128) != 0 ||
41170 !isPowerOf2_32(VecVT.getVectorNumElements()))
41171 return SDValue();
41172
41173 // vXi8 add reduction - sum lo/hi halves then use PSADBW.
41174 if (VT == MVT::i8) {
41175 while (Rdx.getValueSizeInBits() > 128) {
41176 SDValue Lo, Hi;
41177 std::tie(Lo, Hi) = splitVector(Rdx, DAG, DL);
41178 VecVT = Lo.getValueType();
41179 Rdx = DAG.getNode(ISD::ADD, DL, VecVT, Lo, Hi);
41180 }
41181 assert(VecVT == MVT::v16i8 && "v16i8 reduction expected")(static_cast <bool> (VecVT == MVT::v16i8 && "v16i8 reduction expected"
) ? void (0) : __assert_fail ("VecVT == MVT::v16i8 && \"v16i8 reduction expected\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 41181, __extension__ __PRETTY_FUNCTION__))
;
41182
41183 SDValue Hi = DAG.getVectorShuffle(
41184 MVT::v16i8, DL, Rdx, Rdx,
41185 {8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1});
41186 Rdx = DAG.getNode(ISD::ADD, DL, MVT::v16i8, Rdx, Hi);
41187 Rdx = DAG.getNode(X86ISD::PSADBW, DL, MVT::v2i64, Rdx,
41188 getZeroVector(MVT::v16i8, Subtarget, DAG, DL));
41189 Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
41190 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
41191 }
41192
41193 // Only use (F)HADD opcodes if they aren't microcoded or minimizes codesize.
41194 if (!shouldUseHorizontalOp(true, DAG, Subtarget))
41195 return SDValue();
41196
41197 unsigned HorizOpcode = Opc == ISD::ADD ? X86ISD::HADD : X86ISD::FHADD;
41198
41199 // 256-bit horizontal instructions operate on 128-bit chunks rather than
41200 // across the whole vector, so we need an extract + hop preliminary stage.
41201 // This is the only step where the operands of the hop are not the same value.
41202 // TODO: We could extend this to handle 512-bit or even longer vectors.
41203 if (((VecVT == MVT::v16i16 || VecVT == MVT::v8i32) && Subtarget.hasSSSE3()) ||
41204 ((VecVT == MVT::v8f32 || VecVT == MVT::v4f64) && Subtarget.hasSSE3())) {
41205 unsigned NumElts = VecVT.getVectorNumElements();
41206 SDValue Hi = extract128BitVector(Rdx, NumElts / 2, DAG, DL);
41207 SDValue Lo = extract128BitVector(Rdx, 0, DAG, DL);
41208 Rdx = DAG.getNode(HorizOpcode, DL, Lo.getValueType(), Hi, Lo);
41209 VecVT = Rdx.getValueType();
41210 }
41211 if (!((VecVT == MVT::v8i16 || VecVT == MVT::v4i32) && Subtarget.hasSSSE3()) &&
41212 !((VecVT == MVT::v4f32 || VecVT == MVT::v2f64) && Subtarget.hasSSE3()))
41213 return SDValue();
41214
41215 // extract (add (shuf X), X), 0 --> extract (hadd X, X), 0
41216 unsigned ReductionSteps = Log2_32(VecVT.getVectorNumElements());
41217 for (unsigned i = 0; i != ReductionSteps; ++i)
41218 Rdx = DAG.getNode(HorizOpcode, DL, VecVT, Rdx, Rdx);
41219
41220 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
41221}
41222
41223/// Detect vector gather/scatter index generation and convert it from being a
41224/// bunch of shuffles and extracts into a somewhat faster sequence.
41225/// For i686, the best sequence is apparently storing the value and loading
41226/// scalars back, while for x64 we should use 64-bit extracts and shifts.
41227static SDValue combineExtractVectorElt(SDNode *N, SelectionDAG &DAG,
41228 TargetLowering::DAGCombinerInfo &DCI,
41229 const X86Subtarget &Subtarget) {
41230 if (SDValue NewOp = combineExtractWithShuffle(N, DAG, DCI, Subtarget))
41231 return NewOp;
41232
41233 SDValue InputVector = N->getOperand(0);
41234 SDValue EltIdx = N->getOperand(1);
41235 auto *CIdx = dyn_cast<ConstantSDNode>(EltIdx);
41236
41237 EVT SrcVT = InputVector.getValueType();
41238 EVT VT = N->getValueType(0);
41239 SDLoc dl(InputVector);
41240 bool IsPextr = N->getOpcode() != ISD::EXTRACT_VECTOR_ELT;
41241 unsigned NumSrcElts = SrcVT.getVectorNumElements();
41242
41243 if (CIdx && CIdx->getAPIntValue().uge(NumSrcElts))
41244 return IsPextr ? DAG.getConstant(0, dl, VT) : DAG.getUNDEF(VT);
41245
41246 // Integer Constant Folding.
41247 if (CIdx && VT.isInteger()) {
41248 APInt UndefVecElts;
41249 SmallVector<APInt, 16> EltBits;
41250 unsigned VecEltBitWidth = SrcVT.getScalarSizeInBits();
41251 if (getTargetConstantBitsFromNode(InputVector, VecEltBitWidth, UndefVecElts,
41252 EltBits, true, false)) {
41253 uint64_t Idx = CIdx->getZExtValue();
41254 if (UndefVecElts[Idx])
41255 return IsPextr ? DAG.getConstant(0, dl, VT) : DAG.getUNDEF(VT);
41256 return DAG.getConstant(EltBits[Idx].zextOrSelf(VT.getScalarSizeInBits()),
41257 dl, VT);
41258 }
41259 }
41260
41261 if (IsPextr) {
41262 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
41263 if (TLI.SimplifyDemandedBits(
41264 SDValue(N, 0), APInt::getAllOnesValue(VT.getSizeInBits()), DCI))
41265 return SDValue(N, 0);
41266
41267 // PEXTR*(PINSR*(v, s, c), c) -> s (with implicit zext handling).
41268 if ((InputVector.getOpcode() == X86ISD::PINSRB ||
41269 InputVector.getOpcode() == X86ISD::PINSRW) &&
41270 InputVector.getOperand(2) == EltIdx) {
41271 assert(SrcVT == InputVector.getOperand(0).getValueType() &&(static_cast <bool> (SrcVT == InputVector.getOperand(0)
.getValueType() && "Vector type mismatch") ? void (0)
: __assert_fail ("SrcVT == InputVector.getOperand(0).getValueType() && \"Vector type mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 41272, __extension__ __PRETTY_FUNCTION__))
41272 "Vector type mismatch")(static_cast <bool> (SrcVT == InputVector.getOperand(0)
.getValueType() && "Vector type mismatch") ? void (0)
: __assert_fail ("SrcVT == InputVector.getOperand(0).getValueType() && \"Vector type mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 41272, __extension__ __PRETTY_FUNCTION__))
;
41273 SDValue Scl = InputVector.getOperand(1);
41274 Scl = DAG.getNode(ISD::TRUNCATE, dl, SrcVT.getScalarType(), Scl);
41275 return DAG.getZExtOrTrunc(Scl, dl, VT);
41276 }
41277
41278 // TODO - Remove this once we can handle the implicit zero-extension of
41279 // X86ISD::PEXTRW/X86ISD::PEXTRB in combinePredicateReduction and
41280 // combineBasicSADPattern.
41281 return SDValue();
41282 }
41283
41284 // Detect mmx extraction of all bits as a i64. It works better as a bitcast.
41285 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
41286 VT == MVT::i64 && SrcVT == MVT::v1i64 && isNullConstant(EltIdx)) {
41287 SDValue MMXSrc = InputVector.getOperand(0);
41288
41289 // The bitcast source is a direct mmx result.
41290 if (MMXSrc.getValueType() == MVT::x86mmx)
41291 return DAG.getBitcast(VT, InputVector);
41292 }
41293
41294 // Detect mmx to i32 conversion through a v2i32 elt extract.
41295 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
41296 VT == MVT::i32 && SrcVT == MVT::v2i32 && isNullConstant(EltIdx)) {
41297 SDValue MMXSrc = InputVector.getOperand(0);
41298
41299 // The bitcast source is a direct mmx result.
41300 if (MMXSrc.getValueType() == MVT::x86mmx)
41301 return DAG.getNode(X86ISD::MMX_MOVD2W, dl, MVT::i32, MMXSrc);
41302 }
41303
41304 // Check whether this extract is the root of a sum of absolute differences
41305 // pattern. This has to be done here because we really want it to happen
41306 // pre-legalization,
41307 if (SDValue SAD = combineBasicSADPattern(N, DAG, Subtarget))
41308 return SAD;
41309
41310 // Attempt to replace an all_of/any_of horizontal reduction with a MOVMSK.
41311 if (SDValue Cmp = combinePredicateReduction(N, DAG, Subtarget))
41312 return Cmp;
41313
41314 // Attempt to replace min/max v8i16/v16i8 reductions with PHMINPOSUW.
41315 if (SDValue MinMax = combineMinMaxReduction(N, DAG, Subtarget))
41316 return MinMax;
41317
41318 // Attempt to optimize ADD/FADD/MUL reductions with HADD, promotion etc..
41319 if (SDValue V = combineArithReduction(N, DAG, Subtarget))
41320 return V;
41321
41322 if (SDValue V = scalarizeExtEltFP(N, DAG))
41323 return V;
41324
41325 // Attempt to extract a i1 element by using MOVMSK to extract the signbits
41326 // and then testing the relevant element.
41327 //
41328 // Note that we only combine extracts on the *same* result number, i.e.
41329 // t0 = merge_values a0, a1, a2, a3
41330 // i1 = extract_vector_elt t0, Constant:i64<2>
41331 // i1 = extract_vector_elt t0, Constant:i64<3>
41332 // but not
41333 // i1 = extract_vector_elt t0:1, Constant:i64<2>
41334 // since the latter would need its own MOVMSK.
41335 if (CIdx && SrcVT.getScalarType() == MVT::i1) {
41336 SmallVector<SDNode *, 16> BoolExtracts;
41337 unsigned ResNo = InputVector.getResNo();
41338 auto IsBoolExtract = [&BoolExtracts, &ResNo](SDNode *Use) {
41339 if (Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
41340 isa<ConstantSDNode>(Use->getOperand(1)) &&
41341 Use->getOperand(0).getResNo() == ResNo &&
41342 Use->getValueType(0) == MVT::i1) {
41343 BoolExtracts.push_back(Use);
41344 return true;
41345 }
41346 return false;
41347 };
41348 if (all_of(InputVector->uses(), IsBoolExtract) &&
41349 BoolExtracts.size() > 1) {
41350 EVT BCVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcElts);
41351 if (SDValue BC =
41352 combineBitcastvxi1(DAG, BCVT, InputVector, dl, Subtarget)) {
41353 for (SDNode *Use : BoolExtracts) {
41354 // extractelement vXi1 X, MaskIdx --> ((movmsk X) & Mask) == Mask
41355 unsigned MaskIdx = Use->getConstantOperandVal(1);
41356 APInt MaskBit = APInt::getOneBitSet(NumSrcElts, MaskIdx);
41357 SDValue Mask = DAG.getConstant(MaskBit, dl, BCVT);
41358 SDValue Res = DAG.getNode(ISD::AND, dl, BCVT, BC, Mask);
41359 Res = DAG.getSetCC(dl, MVT::i1, Res, Mask, ISD::SETEQ);
41360 DCI.CombineTo(Use, Res);
41361 }
41362 return SDValue(N, 0);
41363 }
41364 }
41365 }
41366
41367 return SDValue();
41368}
41369
41370/// If a vector select has an operand that is -1 or 0, try to simplify the
41371/// select to a bitwise logic operation.
41372/// TODO: Move to DAGCombiner, possibly using TargetLowering::hasAndNot()?
41373static SDValue
41374combineVSelectWithAllOnesOrZeros(SDNode *N, SelectionDAG &DAG,
41375 TargetLowering::DAGCombinerInfo &DCI,
41376 const X86Subtarget &Subtarget) {
41377 SDValue Cond = N->getOperand(0);
41378 SDValue LHS = N->getOperand(1);
41379 SDValue RHS = N->getOperand(2);
41380 EVT VT = LHS.getValueType();
41381 EVT CondVT = Cond.getValueType();
41382 SDLoc DL(N);
41383 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
41384
41385 if (N->getOpcode() != ISD::VSELECT)
41386 return SDValue();
41387
41388 assert(CondVT.isVector() && "Vector select expects a vector selector!")(static_cast <bool> (CondVT.isVector() && "Vector select expects a vector selector!"
) ? void (0) : __assert_fail ("CondVT.isVector() && \"Vector select expects a vector selector!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 41388, __extension__ __PRETTY_FUNCTION__))
;
41389
41390 // TODO: Use isNullOrNullSplat() to distinguish constants with undefs?
41391 // TODO: Can we assert that both operands are not zeros (because that should
41392 // get simplified at node creation time)?
41393 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
41394 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
41395
41396 // If both inputs are 0/undef, create a complete zero vector.
41397 // FIXME: As noted above this should be handled by DAGCombiner/getNode.
41398 if (TValIsAllZeros && FValIsAllZeros) {
41399 if (VT.isFloatingPoint())
41400 return DAG.getConstantFP(0.0, DL, VT);
41401 return DAG.getConstant(0, DL, VT);
41402 }
41403
41404 // To use the condition operand as a bitwise mask, it must have elements that
41405 // are the same size as the select elements. Ie, the condition operand must
41406 // have already been promoted from the IR select condition type <N x i1>.
41407 // Don't check if the types themselves are equal because that excludes
41408 // vector floating-point selects.
41409 if (CondVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
41410 return SDValue();
41411
41412 // Try to invert the condition if true value is not all 1s and false value is
41413 // not all 0s. Only do this if the condition has one use.
41414 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
41415 if (!TValIsAllOnes && !FValIsAllZeros && Cond.hasOneUse() &&
41416 // Check if the selector will be produced by CMPP*/PCMP*.
41417 Cond.getOpcode() == ISD::SETCC &&
41418 // Check if SETCC has already been promoted.
41419 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
41420 CondVT) {
41421 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
41422
41423 if (TValIsAllZeros || FValIsAllOnes) {
41424 SDValue CC = Cond.getOperand(2);
41425 ISD::CondCode NewCC = ISD::getSetCCInverse(
41426 cast<CondCodeSDNode>(CC)->get(), Cond.getOperand(0).getValueType());
41427 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1),
41428 NewCC);
41429 std::swap(LHS, RHS);
41430 TValIsAllOnes = FValIsAllOnes;
41431 FValIsAllZeros = TValIsAllZeros;
41432 }
41433 }
41434
41435 // Cond value must be 'sign splat' to be converted to a logical op.
41436 if (DAG.ComputeNumSignBits(Cond) != CondVT.getScalarSizeInBits())
41437 return SDValue();
41438
41439 // vselect Cond, 111..., 000... -> Cond
41440 if (TValIsAllOnes && FValIsAllZeros)
41441 return DAG.getBitcast(VT, Cond);
41442
41443 if (!TLI.isTypeLegal(CondVT))
41444 return SDValue();
41445
41446 // vselect Cond, 111..., X -> or Cond, X
41447 if (TValIsAllOnes) {
41448 SDValue CastRHS = DAG.getBitcast(CondVT, RHS);
41449 SDValue Or = DAG.getNode(ISD::OR, DL, CondVT, Cond, CastRHS);
41450 return DAG.getBitcast(VT, Or);
41451 }
41452
41453 // vselect Cond, X, 000... -> and Cond, X
41454 if (FValIsAllZeros) {
41455 SDValue CastLHS = DAG.getBitcast(CondVT, LHS);
41456 SDValue And = DAG.getNode(ISD::AND, DL, CondVT, Cond, CastLHS);
41457 return DAG.getBitcast(VT, And);
41458 }
41459
41460 // vselect Cond, 000..., X -> andn Cond, X
41461 if (TValIsAllZeros) {
41462 SDValue CastRHS = DAG.getBitcast(CondVT, RHS);
41463 SDValue AndN;
41464 // The canonical form differs for i1 vectors - x86andnp is not used
41465 if (CondVT.getScalarType() == MVT::i1)
41466 AndN = DAG.getNode(ISD::AND, DL, CondVT, DAG.getNOT(DL, Cond, CondVT),
41467 CastRHS);
41468 else
41469 AndN = DAG.getNode(X86ISD::ANDNP, DL, CondVT, Cond, CastRHS);
41470 return DAG.getBitcast(VT, AndN);
41471 }
41472
41473 return SDValue();
41474}
41475
41476/// If both arms of a vector select are concatenated vectors, split the select,
41477/// and concatenate the result to eliminate a wide (256-bit) vector instruction:
41478/// vselect Cond, (concat T0, T1), (concat F0, F1) -->
41479/// concat (vselect (split Cond), T0, F0), (vselect (split Cond), T1, F1)
41480static SDValue narrowVectorSelect(SDNode *N, SelectionDAG &DAG,
41481 const X86Subtarget &Subtarget) {
41482 unsigned Opcode = N->getOpcode();
41483 if (Opcode != X86ISD::BLENDV && Opcode != ISD::VSELECT)
41484 return SDValue();
41485
41486 // TODO: Split 512-bit vectors too?
41487 EVT VT = N->getValueType(0);
41488 if (!VT.is256BitVector())
41489 return SDValue();
41490
41491 // TODO: Split as long as any 2 of the 3 operands are concatenated?
41492 SDValue Cond = N->getOperand(0);
41493 SDValue TVal = N->getOperand(1);
41494 SDValue FVal = N->getOperand(2);
41495 SmallVector<SDValue, 4> CatOpsT, CatOpsF;
41496 if (!TVal.hasOneUse() || !FVal.hasOneUse() ||
41497 !collectConcatOps(TVal.getNode(), CatOpsT) ||
41498 !collectConcatOps(FVal.getNode(), CatOpsF))
41499 return SDValue();
41500
41501 auto makeBlend = [Opcode](SelectionDAG &DAG, const SDLoc &DL,
41502 ArrayRef<SDValue> Ops) {
41503 return DAG.getNode(Opcode, DL, Ops[1].getValueType(), Ops);
41504 };
41505 return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { Cond, TVal, FVal },
41506 makeBlend, /*CheckBWI*/ false);
41507}
41508
41509static SDValue combineSelectOfTwoConstants(SDNode *N, SelectionDAG &DAG) {
41510 SDValue Cond = N->getOperand(0);
41511 SDValue LHS = N->getOperand(1);
41512 SDValue RHS = N->getOperand(2);
41513 SDLoc DL(N);
41514
41515 auto *TrueC = dyn_cast<ConstantSDNode>(LHS);
41516 auto *FalseC = dyn_cast<ConstantSDNode>(RHS);
41517 if (!TrueC || !FalseC)
41518 return SDValue();
41519
41520 // Don't do this for crazy integer types.
41521 EVT VT = N->getValueType(0);
41522 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
41523 return SDValue();
41524
41525 // We're going to use the condition bit in math or logic ops. We could allow
41526 // this with a wider condition value (post-legalization it becomes an i8),
41527 // but if nothing is creating selects that late, it doesn't matter.
41528 if (Cond.getValueType() != MVT::i1)
41529 return SDValue();
41530
41531 // A power-of-2 multiply is just a shift. LEA also cheaply handles multiply by
41532 // 3, 5, or 9 with i32/i64, so those get transformed too.
41533 // TODO: For constants that overflow or do not differ by power-of-2 or small
41534 // multiplier, convert to 'and' + 'add'.
41535 const APInt &TrueVal = TrueC->getAPIntValue();
41536 const APInt &FalseVal = FalseC->getAPIntValue();
41537 bool OV;
41538 APInt Diff = TrueVal.ssub_ov(FalseVal, OV);
41539 if (OV)
41540 return SDValue();
41541
41542 APInt AbsDiff = Diff.abs();
41543 if (AbsDiff.isPowerOf2() ||
41544 ((VT == MVT::i32 || VT == MVT::i64) &&
41545 (AbsDiff == 3 || AbsDiff == 5 || AbsDiff == 9))) {
41546
41547 // We need a positive multiplier constant for shift/LEA codegen. The 'not'
41548 // of the condition can usually be folded into a compare predicate, but even
41549 // without that, the sequence should be cheaper than a CMOV alternative.
41550 if (TrueVal.slt(FalseVal)) {
41551 Cond = DAG.getNOT(DL, Cond, MVT::i1);
41552 std::swap(TrueC, FalseC);
41553 }
41554
41555 // select Cond, TC, FC --> (zext(Cond) * (TC - FC)) + FC
41556 SDValue R = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
41557
41558 // Multiply condition by the difference if non-one.
41559 if (!AbsDiff.isOneValue())
41560 R = DAG.getNode(ISD::MUL, DL, VT, R, DAG.getConstant(AbsDiff, DL, VT));
41561
41562 // Add the base if non-zero.
41563 if (!FalseC->isNullValue())
41564 R = DAG.getNode(ISD::ADD, DL, VT, R, SDValue(FalseC, 0));
41565
41566 return R;
41567 }
41568
41569 return SDValue();
41570}
41571
41572/// If this is a *dynamic* select (non-constant condition) and we can match
41573/// this node with one of the variable blend instructions, restructure the
41574/// condition so that blends can use the high (sign) bit of each element.
41575/// This function will also call SimplifyDemandedBits on already created
41576/// BLENDV to perform additional simplifications.
41577static SDValue combineVSelectToBLENDV(SDNode *N, SelectionDAG &DAG,
41578 TargetLowering::DAGCombinerInfo &DCI,
41579 const X86Subtarget &Subtarget) {
41580 SDValue Cond = N->getOperand(0);
41581 if ((N->getOpcode() != ISD::VSELECT &&
41582 N->getOpcode() != X86ISD::BLENDV) ||
41583 ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
41584 return SDValue();
41585
41586 // Don't optimize before the condition has been transformed to a legal type
41587 // and don't ever optimize vector selects that map to AVX512 mask-registers.
41588 unsigned BitWidth = Cond.getScalarValueSizeInBits();
41589 if (BitWidth < 8 || BitWidth > 64)
41590 return SDValue();
41591
41592 // We can only handle the cases where VSELECT is directly legal on the
41593 // subtarget. We custom lower VSELECT nodes with constant conditions and
41594 // this makes it hard to see whether a dynamic VSELECT will correctly
41595 // lower, so we both check the operation's status and explicitly handle the
41596 // cases where a *dynamic* blend will fail even though a constant-condition
41597 // blend could be custom lowered.
41598 // FIXME: We should find a better way to handle this class of problems.
41599 // Potentially, we should combine constant-condition vselect nodes
41600 // pre-legalization into shuffles and not mark as many types as custom
41601 // lowered.
41602 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
41603 EVT VT = N->getValueType(0);
41604 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
41605 return SDValue();
41606 // FIXME: We don't support i16-element blends currently. We could and
41607 // should support them by making *all* the bits in the condition be set
41608 // rather than just the high bit and using an i8-element blend.
41609 if (VT.getVectorElementType() == MVT::i16)
41610 return SDValue();
41611 // Dynamic blending was only available from SSE4.1 onward.
41612 if (VT.is128BitVector() && !Subtarget.hasSSE41())
41613 return SDValue();
41614 // Byte blends are only available in AVX2
41615 if (VT == MVT::v32i8 && !Subtarget.hasAVX2())
41616 return SDValue();
41617 // There are no 512-bit blend instructions that use sign bits.
41618 if (VT.is512BitVector())
41619 return SDValue();
41620
41621 auto OnlyUsedAsSelectCond = [](SDValue Cond) {
41622 for (SDNode::use_iterator UI = Cond->use_begin(), UE = Cond->use_end();
41623 UI != UE; ++UI)
41624 if ((UI->getOpcode() != ISD::VSELECT &&
41625 UI->getOpcode() != X86ISD::BLENDV) ||
41626 UI.getOperandNo() != 0)
41627 return false;
41628
41629 return true;
41630 };
41631
41632 APInt DemandedBits(APInt::getSignMask(BitWidth));
41633
41634 if (OnlyUsedAsSelectCond(Cond)) {
41635 KnownBits Known;
41636 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
41637 !DCI.isBeforeLegalizeOps());
41638 if (!TLI.SimplifyDemandedBits(Cond, DemandedBits, Known, TLO, 0, true))
41639 return SDValue();
41640
41641 // If we changed the computation somewhere in the DAG, this change will
41642 // affect all users of Cond. Update all the nodes so that we do not use
41643 // the generic VSELECT anymore. Otherwise, we may perform wrong
41644 // optimizations as we messed with the actual expectation for the vector
41645 // boolean values.
41646 for (SDNode *U : Cond->uses()) {
41647 if (U->getOpcode() == X86ISD::BLENDV)
41648 continue;
41649
41650 SDValue SB = DAG.getNode(X86ISD::BLENDV, SDLoc(U), U->getValueType(0),
41651 Cond, U->getOperand(1), U->getOperand(2));
41652 DAG.ReplaceAllUsesOfValueWith(SDValue(U, 0), SB);
41653 DCI.AddToWorklist(U);
41654 }
41655 DCI.CommitTargetLoweringOpt(TLO);
41656 return SDValue(N, 0);
41657 }
41658
41659 // Otherwise we can still at least try to simplify multiple use bits.
41660 if (SDValue V = TLI.SimplifyMultipleUseDemandedBits(Cond, DemandedBits, DAG))
41661 return DAG.getNode(X86ISD::BLENDV, SDLoc(N), N->getValueType(0), V,
41662 N->getOperand(1), N->getOperand(2));
41663
41664 return SDValue();
41665}
41666
41667// Try to match:
41668// (or (and (M, (sub 0, X)), (pandn M, X)))
41669// which is a special case of:
41670// (select M, (sub 0, X), X)
41671// Per:
41672// http://graphics.stanford.edu/~seander/bithacks.html#ConditionalNegate
41673// We know that, if fNegate is 0 or 1:
41674// (fNegate ? -v : v) == ((v ^ -fNegate) + fNegate)
41675//
41676// Here, we have a mask, M (all 1s or 0), and, similarly, we know that:
41677// ((M & 1) ? -X : X) == ((X ^ -(M & 1)) + (M & 1))
41678// ( M ? -X : X) == ((X ^ M ) + (M & 1))
41679// This lets us transform our vselect to:
41680// (add (xor X, M), (and M, 1))
41681// And further to:
41682// (sub (xor X, M), M)
41683static SDValue combineLogicBlendIntoConditionalNegate(
41684 EVT VT, SDValue Mask, SDValue X, SDValue Y, const SDLoc &DL,
41685 SelectionDAG &DAG, const X86Subtarget &Subtarget) {
41686 EVT MaskVT = Mask.getValueType();
41687 assert(MaskVT.isInteger() &&(static_cast <bool> (MaskVT.isInteger() && DAG.
ComputeNumSignBits(Mask) == MaskVT.getScalarSizeInBits() &&
"Mask must be zero/all-bits") ? void (0) : __assert_fail ("MaskVT.isInteger() && DAG.ComputeNumSignBits(Mask) == MaskVT.getScalarSizeInBits() && \"Mask must be zero/all-bits\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 41689, __extension__ __PRETTY_FUNCTION__))
41688 DAG.ComputeNumSignBits(Mask) == MaskVT.getScalarSizeInBits() &&(static_cast <bool> (MaskVT.isInteger() && DAG.
ComputeNumSignBits(Mask) == MaskVT.getScalarSizeInBits() &&
"Mask must be zero/all-bits") ? void (0) : __assert_fail ("MaskVT.isInteger() && DAG.ComputeNumSignBits(Mask) == MaskVT.getScalarSizeInBits() && \"Mask must be zero/all-bits\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 41689, __extension__ __PRETTY_FUNCTION__))
41689 "Mask must be zero/all-bits")(static_cast <bool> (MaskVT.isInteger() && DAG.
ComputeNumSignBits(Mask) == MaskVT.getScalarSizeInBits() &&
"Mask must be zero/all-bits") ? void (0) : __assert_fail ("MaskVT.isInteger() && DAG.ComputeNumSignBits(Mask) == MaskVT.getScalarSizeInBits() && \"Mask must be zero/all-bits\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 41689, __extension__ __PRETTY_FUNCTION__))
;
41690
41691 if (X.getValueType() != MaskVT || Y.getValueType() != MaskVT)
41692 return SDValue();
41693 if (!DAG.getTargetLoweringInfo().isOperationLegal(ISD::SUB, MaskVT))
41694 return SDValue();
41695
41696 auto IsNegV = [](SDNode *N, SDValue V) {
41697 return N->getOpcode() == ISD::SUB && N->getOperand(1) == V &&
41698 ISD::isBuildVectorAllZeros(N->getOperand(0).getNode());
41699 };
41700
41701 SDValue V;
41702 if (IsNegV(Y.getNode(), X))
41703 V = X;
41704 else if (IsNegV(X.getNode(), Y))
41705 V = Y;
41706 else
41707 return SDValue();
41708
41709 SDValue SubOp1 = DAG.getNode(ISD::XOR, DL, MaskVT, V, Mask);
41710 SDValue SubOp2 = Mask;
41711
41712 // If the negate was on the false side of the select, then
41713 // the operands of the SUB need to be swapped. PR 27251.
41714 // This is because the pattern being matched above is
41715 // (vselect M, (sub (0, X), X) -> (sub (xor X, M), M)
41716 // but if the pattern matched was
41717 // (vselect M, X, (sub (0, X))), that is really negation of the pattern
41718 // above, -(vselect M, (sub 0, X), X), and therefore the replacement
41719 // pattern also needs to be a negation of the replacement pattern above.
41720 // And -(sub X, Y) is just sub (Y, X), so swapping the operands of the
41721 // sub accomplishes the negation of the replacement pattern.
41722 if (V == Y)
41723 std::swap(SubOp1, SubOp2);
41724
41725 SDValue Res = DAG.getNode(ISD::SUB, DL, MaskVT, SubOp1, SubOp2);
41726 return DAG.getBitcast(VT, Res);
41727}
41728
41729/// Do target-specific dag combines on SELECT and VSELECT nodes.
41730static SDValue combineSelect(SDNode *N, SelectionDAG &DAG,
41731 TargetLowering::DAGCombinerInfo &DCI,
41732 const X86Subtarget &Subtarget) {
41733 SDLoc DL(N);
41734 SDValue Cond = N->getOperand(0);
41735 SDValue LHS = N->getOperand(1);
41736 SDValue RHS = N->getOperand(2);
41737
41738 // Try simplification again because we use this function to optimize
41739 // BLENDV nodes that are not handled by the generic combiner.
41740 if (SDValue V = DAG.simplifySelect(Cond, LHS, RHS))
41741 return V;
41742
41743 EVT VT = LHS.getValueType();
41744 EVT CondVT = Cond.getValueType();
41745 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
41746 bool CondConstantVector = ISD::isBuildVectorOfConstantSDNodes(Cond.getNode());
41747
41748 // Attempt to combine (select M, (sub 0, X), X) -> (sub (xor X, M), M).
41749 // Limit this to cases of non-constant masks that createShuffleMaskFromVSELECT
41750 // can't catch, plus vXi8 cases where we'd likely end up with BLENDV.
41751 if (CondVT.isVector() && CondVT.isInteger() &&
41752 CondVT.getScalarSizeInBits() == VT.getScalarSizeInBits() &&
41753 (!CondConstantVector || CondVT.getScalarType() == MVT::i8) &&
41754 DAG.ComputeNumSignBits(Cond) == CondVT.getScalarSizeInBits())
41755 if (SDValue V = combineLogicBlendIntoConditionalNegate(VT, Cond, RHS, LHS,
41756 DL, DAG, Subtarget))
41757 return V;
41758
41759 // Convert vselects with constant condition into shuffles.
41760 if (CondConstantVector && DCI.isBeforeLegalizeOps()) {
41761 SmallVector<int, 64> Mask;
41762 if (createShuffleMaskFromVSELECT(Mask, Cond))
41763 return DAG.getVectorShuffle(VT, DL, LHS, RHS, Mask);
41764 }
41765
41766 // fold vselect(cond, pshufb(x), pshufb(y)) -> or (pshufb(x), pshufb(y))
41767 // by forcing the unselected elements to zero.
41768 // TODO: Can we handle more shuffles with this?
41769 if (N->getOpcode() == ISD::VSELECT && CondVT.isVector() &&
41770 LHS.getOpcode() == X86ISD::PSHUFB && RHS.getOpcode() == X86ISD::PSHUFB &&
41771 LHS.hasOneUse() && RHS.hasOneUse()) {
41772 MVT SimpleVT = VT.getSimpleVT();
41773 SmallVector<SDValue, 1> LHSOps, RHSOps;
41774 SmallVector<int, 64> LHSMask, RHSMask, CondMask;
41775 if (createShuffleMaskFromVSELECT(CondMask, Cond) &&
41776 getTargetShuffleMask(LHS.getNode(), SimpleVT, true, LHSOps, LHSMask) &&
41777 getTargetShuffleMask(RHS.getNode(), SimpleVT, true, RHSOps, RHSMask)) {
41778 int NumElts = VT.getVectorNumElements();
41779 for (int i = 0; i != NumElts; ++i) {
41780 if (CondMask[i] < NumElts)
41781 RHSMask[i] = 0x80;
41782 else
41783 LHSMask[i] = 0x80;
41784 }
41785 LHS = DAG.getNode(X86ISD::PSHUFB, DL, VT, LHS.getOperand(0),
41786 getConstVector(LHSMask, SimpleVT, DAG, DL, true));
41787 RHS = DAG.getNode(X86ISD::PSHUFB, DL, VT, RHS.getOperand(0),
41788 getConstVector(RHSMask, SimpleVT, DAG, DL, true));
41789 return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
41790 }
41791 }
41792
41793 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
41794 // instructions match the semantics of the common C idiom x<y?x:y but not
41795 // x<=y?x:y, because of how they handle negative zero (which can be
41796 // ignored in unsafe-math mode).
41797 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
41798 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
41799 VT != MVT::f80 && VT != MVT::f128 &&
41800 (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
41801 (Subtarget.hasSSE2() ||
41802 (Subtarget.hasSSE1() && VT.getScalarType() == MVT::f32))) {
41803 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
41804
41805 unsigned Opcode = 0;
41806 // Check for x CC y ? x : y.
41807 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
41808 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
41809 switch (CC) {
41810 default: break;
41811 case ISD::SETULT:
41812 // Converting this to a min would handle NaNs incorrectly, and swapping
41813 // the operands would cause it to handle comparisons between positive
41814 // and negative zero incorrectly.
41815 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
41816 if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
41817 !(DAG.isKnownNeverZeroFloat(LHS) ||
41818 DAG.isKnownNeverZeroFloat(RHS)))
41819 break;
41820 std::swap(LHS, RHS);
41821 }
41822 Opcode = X86ISD::FMIN;
41823 break;
41824 case ISD::SETOLE:
41825 // Converting this to a min would handle comparisons between positive
41826 // and negative zero incorrectly.
41827 if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
41828 !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
41829 break;
41830 Opcode = X86ISD::FMIN;
41831 break;
41832 case ISD::SETULE:
41833 // Converting this to a min would handle both negative zeros and NaNs
41834 // incorrectly, but we can swap the operands to fix both.
41835 std::swap(LHS, RHS);
41836 LLVM_FALLTHROUGH[[gnu::fallthrough]];
41837 case ISD::SETOLT:
41838 case ISD::SETLT:
41839 case ISD::SETLE:
41840 Opcode = X86ISD::FMIN;
41841 break;
41842
41843 case ISD::SETOGE:
41844 // Converting this to a max would handle comparisons between positive
41845 // and negative zero incorrectly.
41846 if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
41847 !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
41848 break;
41849 Opcode = X86ISD::FMAX;
41850 break;
41851 case ISD::SETUGT:
41852 // Converting this to a max would handle NaNs incorrectly, and swapping
41853 // the operands would cause it to handle comparisons between positive
41854 // and negative zero incorrectly.
41855 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
41856 if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
41857 !(DAG.isKnownNeverZeroFloat(LHS) ||
41858 DAG.isKnownNeverZeroFloat(RHS)))
41859 break;
41860 std::swap(LHS, RHS);
41861 }
41862 Opcode = X86ISD::FMAX;
41863 break;
41864 case ISD::SETUGE:
41865 // Converting this to a max would handle both negative zeros and NaNs
41866 // incorrectly, but we can swap the operands to fix both.
41867 std::swap(LHS, RHS);
41868 LLVM_FALLTHROUGH[[gnu::fallthrough]];
41869 case ISD::SETOGT:
41870 case ISD::SETGT:
41871 case ISD::SETGE:
41872 Opcode = X86ISD::FMAX;
41873 break;
41874 }
41875 // Check for x CC y ? y : x -- a min/max with reversed arms.
41876 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
41877 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
41878 switch (CC) {
41879 default: break;
41880 case ISD::SETOGE:
41881 // Converting this to a min would handle comparisons between positive
41882 // and negative zero incorrectly, and swapping the operands would
41883 // cause it to handle NaNs incorrectly.
41884 if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
41885 !(DAG.isKnownNeverZeroFloat(LHS) ||
41886 DAG.isKnownNeverZeroFloat(RHS))) {
41887 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
41888 break;
41889 std::swap(LHS, RHS);
41890 }
41891 Opcode = X86ISD::FMIN;
41892 break;
41893 case ISD::SETUGT:
41894 // Converting this to a min would handle NaNs incorrectly.
41895 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
41896 break;
41897 Opcode = X86ISD::FMIN;
41898 break;
41899 case ISD::SETUGE:
41900 // Converting this to a min would handle both negative zeros and NaNs
41901 // incorrectly, but we can swap the operands to fix both.
41902 std::swap(LHS, RHS);
41903 LLVM_FALLTHROUGH[[gnu::fallthrough]];
41904 case ISD::SETOGT:
41905 case ISD::SETGT:
41906 case ISD::SETGE:
41907 Opcode = X86ISD::FMIN;
41908 break;
41909
41910 case ISD::SETULT:
41911 // Converting this to a max would handle NaNs incorrectly.
41912 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
41913 break;
41914 Opcode = X86ISD::FMAX;
41915 break;
41916 case ISD::SETOLE:
41917 // Converting this to a max would handle comparisons between positive
41918 // and negative zero incorrectly, and swapping the operands would
41919 // cause it to handle NaNs incorrectly.
41920 if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
41921 !DAG.isKnownNeverZeroFloat(LHS) &&
41922 !DAG.isKnownNeverZeroFloat(RHS)) {
41923 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
41924 break;
41925 std::swap(LHS, RHS);
41926 }
41927 Opcode = X86ISD::FMAX;
41928 break;
41929 case ISD::SETULE:
41930 // Converting this to a max would handle both negative zeros and NaNs
41931 // incorrectly, but we can swap the operands to fix both.
41932 std::swap(LHS, RHS);
41933 LLVM_FALLTHROUGH[[gnu::fallthrough]];
41934 case ISD::SETOLT:
41935 case ISD::SETLT:
41936 case ISD::SETLE:
41937 Opcode = X86ISD::FMAX;
41938 break;
41939 }
41940 }
41941
41942 if (Opcode)
41943 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
41944 }
41945
41946 // Some mask scalar intrinsics rely on checking if only one bit is set
41947 // and implement it in C code like this:
41948 // A[0] = (U & 1) ? A[0] : W[0];
41949 // This creates some redundant instructions that break pattern matching.
41950 // fold (select (setcc (and (X, 1), 0, seteq), Y, Z)) -> select(and(X, 1),Z,Y)
41951 if (Subtarget.hasAVX512() && N->getOpcode() == ISD::SELECT &&
41952 Cond.getOpcode() == ISD::SETCC && (VT == MVT::f32 || VT == MVT::f64)) {
41953 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
41954 SDValue AndNode = Cond.getOperand(0);
41955 if (AndNode.getOpcode() == ISD::AND && CC == ISD::SETEQ &&
41956 isNullConstant(Cond.getOperand(1)) &&
41957 isOneConstant(AndNode.getOperand(1))) {
41958 // LHS and RHS swapped due to
41959 // setcc outputting 1 when AND resulted in 0 and vice versa.
41960 AndNode = DAG.getZExtOrTrunc(AndNode, DL, MVT::i8);
41961 return DAG.getNode(ISD::SELECT, DL, VT, AndNode, RHS, LHS);
41962 }
41963 }
41964
41965 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
41966 // lowering on KNL. In this case we convert it to
41967 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
41968 // The same situation all vectors of i8 and i16 without BWI.
41969 // Make sure we extend these even before type legalization gets a chance to
41970 // split wide vectors.
41971 // Since SKX these selects have a proper lowering.
41972 if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && CondVT.isVector() &&
41973 CondVT.getVectorElementType() == MVT::i1 &&
41974 (VT.getVectorElementType() == MVT::i8 ||
41975 VT.getVectorElementType() == MVT::i16)) {
41976 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
41977 return DAG.getNode(N->getOpcode(), DL, VT, Cond, LHS, RHS);
41978 }
41979
41980 // AVX512 - Extend select with zero to merge with target shuffle.
41981 // select(mask, extract_subvector(shuffle(x)), zero) -->
41982 // extract_subvector(select(insert_subvector(mask), shuffle(x), zero))
41983 // TODO - support non target shuffles as well.
41984 if (Subtarget.hasAVX512() && CondVT.isVector() &&
41985 CondVT.getVectorElementType() == MVT::i1) {
41986 auto SelectableOp = [&TLI](SDValue Op) {
41987 return Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
41988 isTargetShuffle(Op.getOperand(0).getOpcode()) &&
41989 isNullConstant(Op.getOperand(1)) &&
41990 TLI.isTypeLegal(Op.getOperand(0).getValueType()) &&
41991 Op.hasOneUse() && Op.getOperand(0).hasOneUse();
41992 };
41993
41994 bool SelectableLHS = SelectableOp(LHS);
41995 bool SelectableRHS = SelectableOp(RHS);
41996 bool ZeroLHS = ISD::isBuildVectorAllZeros(LHS.getNode());
41997 bool ZeroRHS = ISD::isBuildVectorAllZeros(RHS.getNode());
41998
41999 if ((SelectableLHS && ZeroRHS) || (SelectableRHS && ZeroLHS)) {
42000 EVT SrcVT = SelectableLHS ? LHS.getOperand(0).getValueType()
42001 : RHS.getOperand(0).getValueType();
42002 EVT SrcCondVT = SrcVT.changeVectorElementType(MVT::i1);
42003 LHS = insertSubVector(DAG.getUNDEF(SrcVT), LHS, 0, DAG, DL,
42004 VT.getSizeInBits());
42005 RHS = insertSubVector(DAG.getUNDEF(SrcVT), RHS, 0, DAG, DL,
42006 VT.getSizeInBits());
42007 Cond = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SrcCondVT,
42008 DAG.getUNDEF(SrcCondVT), Cond,
42009 DAG.getIntPtrConstant(0, DL));
42010 SDValue Res = DAG.getSelect(DL, SrcVT, Cond, LHS, RHS);
42011 return extractSubVector(Res, 0, DAG, DL, VT.getSizeInBits());
42012 }
42013 }
42014
42015 if (SDValue V = combineSelectOfTwoConstants(N, DAG))
42016 return V;
42017
42018 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
42019 Cond.hasOneUse()) {
42020 EVT CondVT = Cond.getValueType();
42021 SDValue Cond0 = Cond.getOperand(0);
42022 SDValue Cond1 = Cond.getOperand(1);
42023 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
42024
42025 // Canonicalize min/max:
42026 // (x > 0) ? x : 0 -> (x >= 0) ? x : 0
42027 // (x < -1) ? x : -1 -> (x <= -1) ? x : -1
42028 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
42029 // the need for an extra compare against zero. e.g.
42030 // (a - b) > 0 : (a - b) ? 0 -> (a - b) >= 0 : (a - b) ? 0
42031 // subl %esi, %edi
42032 // testl %edi, %edi
42033 // movl $0, %eax
42034 // cmovgl %edi, %eax
42035 // =>
42036 // xorl %eax, %eax
42037 // subl %esi, $edi
42038 // cmovsl %eax, %edi
42039 //
42040 // We can also canonicalize
42041 // (x s> 1) ? x : 1 -> (x s>= 1) ? x : 1 -> (x s> 0) ? x : 1
42042 // (x u> 1) ? x : 1 -> (x u>= 1) ? x : 1 -> (x != 0) ? x : 1
42043 // This allows the use of a test instruction for the compare.
42044 if (LHS == Cond0 && RHS == Cond1) {
42045 if ((CC == ISD::SETGT && (isNullConstant(RHS) || isOneConstant(RHS))) ||
42046 (CC == ISD::SETLT && isAllOnesConstant(RHS))) {
42047 ISD::CondCode NewCC = CC == ISD::SETGT ? ISD::SETGE : ISD::SETLE;
42048 Cond = DAG.getSetCC(SDLoc(Cond), CondVT, Cond0, Cond1, NewCC);
42049 return DAG.getSelect(DL, VT, Cond, LHS, RHS);
42050 }
42051 if (CC == ISD::SETUGT && isOneConstant(RHS)) {
42052 ISD::CondCode NewCC = ISD::SETUGE;
42053 Cond = DAG.getSetCC(SDLoc(Cond), CondVT, Cond0, Cond1, NewCC);
42054 return DAG.getSelect(DL, VT, Cond, LHS, RHS);
42055 }
42056 }
42057
42058 // Similar to DAGCombine's select(or(CC0,CC1),X,Y) fold but for legal types.
42059 // fold eq + gt/lt nested selects into ge/le selects
42060 // select (cmpeq Cond0, Cond1), LHS, (select (cmpugt Cond0, Cond1), LHS, Y)
42061 // --> (select (cmpuge Cond0, Cond1), LHS, Y)
42062 // select (cmpslt Cond0, Cond1), LHS, (select (cmpeq Cond0, Cond1), LHS, Y)
42063 // --> (select (cmpsle Cond0, Cond1), LHS, Y)
42064 // .. etc ..
42065 if (RHS.getOpcode() == ISD::SELECT && RHS.getOperand(1) == LHS &&
42066 RHS.getOperand(0).getOpcode() == ISD::SETCC) {
42067 SDValue InnerSetCC = RHS.getOperand(0);
42068 ISD::CondCode InnerCC =
42069 cast<CondCodeSDNode>(InnerSetCC.getOperand(2))->get();
42070 if ((CC == ISD::SETEQ || InnerCC == ISD::SETEQ) &&
42071 Cond0 == InnerSetCC.getOperand(0) &&
42072 Cond1 == InnerSetCC.getOperand(1)) {
42073 ISD::CondCode NewCC;
42074 switch (CC == ISD::SETEQ ? InnerCC : CC) {
42075 case ISD::SETGT: NewCC = ISD::SETGE; break;
42076 case ISD::SETLT: NewCC = ISD::SETLE; break;
42077 case ISD::SETUGT: NewCC = ISD::SETUGE; break;
42078 case ISD::SETULT: NewCC = ISD::SETULE; break;
42079 default: NewCC = ISD::SETCC_INVALID; break;
42080 }
42081 if (NewCC != ISD::SETCC_INVALID) {
42082 Cond = DAG.getSetCC(DL, CondVT, Cond0, Cond1, NewCC);
42083 return DAG.getSelect(DL, VT, Cond, LHS, RHS.getOperand(2));
42084 }
42085 }
42086 }
42087 }
42088
42089 // Check if the first operand is all zeros and Cond type is vXi1.
42090 // If this an avx512 target we can improve the use of zero masking by
42091 // swapping the operands and inverting the condition.
42092 if (N->getOpcode() == ISD::VSELECT && Cond.hasOneUse() &&
42093 Subtarget.hasAVX512() && CondVT.getVectorElementType() == MVT::i1 &&
42094 ISD::isBuildVectorAllZeros(LHS.getNode()) &&
42095 !ISD::isBuildVectorAllZeros(RHS.getNode())) {
42096 // Invert the cond to not(cond) : xor(op,allones)=not(op)
42097 SDValue CondNew = DAG.getNOT(DL, Cond, CondVT);
42098 // Vselect cond, op1, op2 = Vselect not(cond), op2, op1
42099 return DAG.getSelect(DL, VT, CondNew, RHS, LHS);
42100 }
42101
42102 // Early exit check
42103 if (!TLI.isTypeLegal(VT))
42104 return SDValue();
42105
42106 if (SDValue V = combineVSelectWithAllOnesOrZeros(N, DAG, DCI, Subtarget))
42107 return V;
42108
42109 if (SDValue V = combineVSelectToBLENDV(N, DAG, DCI, Subtarget))
42110 return V;
42111
42112 if (SDValue V = narrowVectorSelect(N, DAG, Subtarget))
42113 return V;
42114
42115 // select(~Cond, X, Y) -> select(Cond, Y, X)
42116 if (CondVT.getScalarType() != MVT::i1) {
42117 if (SDValue CondNot = IsNOT(Cond, DAG))
42118 return DAG.getNode(N->getOpcode(), DL, VT,
42119 DAG.getBitcast(CondVT, CondNot), RHS, LHS);
42120 // pcmpgt(X, -1) -> pcmpgt(0, X) to help select/blendv just use the signbit.
42121 if (Cond.getOpcode() == X86ISD::PCMPGT && Cond.hasOneUse() &&
42122 ISD::isBuildVectorAllOnes(Cond.getOperand(1).getNode())) {
42123 Cond = DAG.getNode(X86ISD::PCMPGT, DL, CondVT,
42124 DAG.getConstant(0, DL, CondVT), Cond.getOperand(0));
42125 return DAG.getNode(N->getOpcode(), DL, VT, Cond, RHS, LHS);
42126 }
42127 }
42128
42129 // Try to optimize vXi1 selects if both operands are either all constants or
42130 // bitcasts from scalar integer type. In that case we can convert the operands
42131 // to integer and use an integer select which will be converted to a CMOV.
42132 // We need to take a little bit of care to avoid creating an i64 type after
42133 // type legalization.
42134 if (N->getOpcode() == ISD::SELECT && VT.isVector() &&
42135 VT.getVectorElementType() == MVT::i1 &&
42136 (DCI.isBeforeLegalize() || (VT != MVT::v64i1 || Subtarget.is64Bit()))) {
42137 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getVectorNumElements());
42138 bool LHSIsConst = ISD::isBuildVectorOfConstantSDNodes(LHS.getNode());
42139 bool RHSIsConst = ISD::isBuildVectorOfConstantSDNodes(RHS.getNode());
42140
42141 if ((LHSIsConst ||
42142 (LHS.getOpcode() == ISD::BITCAST &&
42143 LHS.getOperand(0).getValueType() == IntVT)) &&
42144 (RHSIsConst ||
42145 (RHS.getOpcode() == ISD::BITCAST &&
42146 RHS.getOperand(0).getValueType() == IntVT))) {
42147 if (LHSIsConst)
42148 LHS = combinevXi1ConstantToInteger(LHS, DAG);
42149 else
42150 LHS = LHS.getOperand(0);
42151
42152 if (RHSIsConst)
42153 RHS = combinevXi1ConstantToInteger(RHS, DAG);
42154 else
42155 RHS = RHS.getOperand(0);
42156
42157 SDValue Select = DAG.getSelect(DL, IntVT, Cond, LHS, RHS);
42158 return DAG.getBitcast(VT, Select);
42159 }
42160 }
42161
42162 // If this is "((X & C) == 0) ? Y : Z" and C is a constant mask vector of
42163 // single bits, then invert the predicate and swap the select operands.
42164 // This can lower using a vector shift bit-hack rather than mask and compare.
42165 if (DCI.isBeforeLegalize() && !Subtarget.hasAVX512() &&
42166 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
42167 Cond.hasOneUse() && CondVT.getVectorElementType() == MVT::i1 &&
42168 Cond.getOperand(0).getOpcode() == ISD::AND &&
42169 isNullOrNullSplat(Cond.getOperand(1)) &&
42170 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
42171 Cond.getOperand(0).getValueType() == VT) {
42172 // The 'and' mask must be composed of power-of-2 constants.
42173 SDValue And = Cond.getOperand(0);
42174 auto *C = isConstOrConstSplat(And.getOperand(1));
42175 if (C && C->getAPIntValue().isPowerOf2()) {
42176 // vselect (X & C == 0), LHS, RHS --> vselect (X & C != 0), RHS, LHS
42177 SDValue NotCond =
42178 DAG.getSetCC(DL, CondVT, And, Cond.getOperand(1), ISD::SETNE);
42179 return DAG.getSelect(DL, VT, NotCond, RHS, LHS);
42180 }
42181
42182 // If we have a non-splat but still powers-of-2 mask, AVX1 can use pmulld
42183 // and AVX2 can use vpsllv{dq}. 8-bit lacks a proper shift or multiply.
42184 // 16-bit lacks a proper blendv.
42185 unsigned EltBitWidth = VT.getScalarSizeInBits();
42186 bool CanShiftBlend =
42187 TLI.isTypeLegal(VT) && ((Subtarget.hasAVX() && EltBitWidth == 32) ||
42188 (Subtarget.hasAVX2() && EltBitWidth == 64) ||
42189 (Subtarget.hasXOP()));
42190 if (CanShiftBlend &&
42191 ISD::matchUnaryPredicate(And.getOperand(1), [](ConstantSDNode *C) {
42192 return C->getAPIntValue().isPowerOf2();
42193 })) {
42194 // Create a left-shift constant to get the mask bits over to the sign-bit.
42195 SDValue Mask = And.getOperand(1);
42196 SmallVector<int, 32> ShlVals;
42197 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
42198 auto *MaskVal = cast<ConstantSDNode>(Mask.getOperand(i));
42199 ShlVals.push_back(EltBitWidth - 1 -
42200 MaskVal->getAPIntValue().exactLogBase2());
42201 }
42202 // vsel ((X & C) == 0), LHS, RHS --> vsel ((shl X, C') < 0), RHS, LHS
42203 SDValue ShlAmt = getConstVector(ShlVals, VT.getSimpleVT(), DAG, DL);
42204 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And.getOperand(0), ShlAmt);
42205 SDValue NewCond =
42206 DAG.getSetCC(DL, CondVT, Shl, Cond.getOperand(1), ISD::SETLT);
42207 return DAG.getSelect(DL, VT, NewCond, RHS, LHS);
42208 }
42209 }
42210
42211 return SDValue();
42212}
42213
42214/// Combine:
42215/// (brcond/cmov/setcc .., (cmp (atomic_load_add x, 1), 0), COND_S)
42216/// to:
42217/// (brcond/cmov/setcc .., (LADD x, 1), COND_LE)
42218/// i.e., reusing the EFLAGS produced by the LOCKed instruction.
42219/// Note that this is only legal for some op/cc combinations.
42220static SDValue combineSetCCAtomicArith(SDValue Cmp, X86::CondCode &CC,
42221 SelectionDAG &DAG,
42222 const X86Subtarget &Subtarget) {
42223 // This combine only operates on CMP-like nodes.
42224 if (!(Cmp.getOpcode() == X86ISD::CMP ||
42225 (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
42226 return SDValue();
42227
42228 // Can't replace the cmp if it has more uses than the one we're looking at.
42229 // FIXME: We would like to be able to handle this, but would need to make sure
42230 // all uses were updated.
42231 if (!Cmp.hasOneUse())
42232 return SDValue();
42233
42234 // This only applies to variations of the common case:
42235 // (icmp slt x, 0) -> (icmp sle (add x, 1), 0)
42236 // (icmp sge x, 0) -> (icmp sgt (add x, 1), 0)
42237 // (icmp sle x, 0) -> (icmp slt (sub x, 1), 0)
42238 // (icmp sgt x, 0) -> (icmp sge (sub x, 1), 0)
42239 // Using the proper condcodes (see below), overflow is checked for.
42240
42241 // FIXME: We can generalize both constraints:
42242 // - XOR/OR/AND (if they were made to survive AtomicExpand)
42243 // - LHS != 1
42244 // if the result is compared.
42245
42246 SDValue CmpLHS = Cmp.getOperand(0);
42247 SDValue CmpRHS = Cmp.getOperand(1);
42248 EVT CmpVT = CmpLHS.getValueType();
42249
42250 if (!CmpLHS.hasOneUse())
42251 return SDValue();
42252
42253 unsigned Opc = CmpLHS.getOpcode();
42254 if (Opc != ISD::ATOMIC_LOAD_ADD && Opc != ISD::ATOMIC_LOAD_SUB)
42255 return SDValue();
42256
42257 SDValue OpRHS = CmpLHS.getOperand(2);
42258 auto *OpRHSC = dyn_cast<ConstantSDNode>(OpRHS);
42259 if (!OpRHSC)
42260 return SDValue();
42261
42262 APInt Addend = OpRHSC->getAPIntValue();
42263 if (Opc == ISD::ATOMIC_LOAD_SUB)
42264 Addend = -Addend;
42265
42266 auto *CmpRHSC = dyn_cast<ConstantSDNode>(CmpRHS);
42267 if (!CmpRHSC)
42268 return SDValue();
42269
42270 APInt Comparison = CmpRHSC->getAPIntValue();
42271 APInt NegAddend = -Addend;
42272
42273 // See if we can adjust the CC to make the comparison match the negated
42274 // addend.
42275 if (Comparison != NegAddend) {
42276 APInt IncComparison = Comparison + 1;
42277 if (IncComparison == NegAddend) {
42278 if (CC == X86::COND_A && !Comparison.isMaxValue()) {
42279 Comparison = IncComparison;
42280 CC = X86::COND_AE;
42281 } else if (CC == X86::COND_LE && !Comparison.isMaxSignedValue()) {
42282 Comparison = IncComparison;
42283 CC = X86::COND_L;
42284 }
42285 }
42286 APInt DecComparison = Comparison - 1;
42287 if (DecComparison == NegAddend) {
42288 if (CC == X86::COND_AE && !Comparison.isMinValue()) {
42289 Comparison = DecComparison;
42290 CC = X86::COND_A;
42291 } else if (CC == X86::COND_L && !Comparison.isMinSignedValue()) {
42292 Comparison = DecComparison;
42293 CC = X86::COND_LE;
42294 }
42295 }
42296 }
42297
42298 // If the addend is the negation of the comparison value, then we can do
42299 // a full comparison by emitting the atomic arithmetic as a locked sub.
42300 if (Comparison == NegAddend) {
42301 // The CC is fine, but we need to rewrite the LHS of the comparison as an
42302 // atomic sub.
42303 auto *AN = cast<AtomicSDNode>(CmpLHS.getNode());
42304 auto AtomicSub = DAG.getAtomic(
42305 ISD::ATOMIC_LOAD_SUB, SDLoc(CmpLHS), CmpVT,
42306 /*Chain*/ CmpLHS.getOperand(0), /*LHS*/ CmpLHS.getOperand(1),
42307 /*RHS*/ DAG.getConstant(NegAddend, SDLoc(CmpRHS), CmpVT),
42308 AN->getMemOperand());
42309 auto LockOp = lowerAtomicArithWithLOCK(AtomicSub, DAG, Subtarget);
42310 DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0), DAG.getUNDEF(CmpVT));
42311 DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
42312 return LockOp;
42313 }
42314
42315 // We can handle comparisons with zero in a number of cases by manipulating
42316 // the CC used.
42317 if (!Comparison.isNullValue())
42318 return SDValue();
42319
42320 if (CC == X86::COND_S && Addend == 1)
42321 CC = X86::COND_LE;
42322 else if (CC == X86::COND_NS && Addend == 1)
42323 CC = X86::COND_G;
42324 else if (CC == X86::COND_G && Addend == -1)
42325 CC = X86::COND_GE;
42326 else if (CC == X86::COND_LE && Addend == -1)
42327 CC = X86::COND_L;
42328 else
42329 return SDValue();
42330
42331 SDValue LockOp = lowerAtomicArithWithLOCK(CmpLHS, DAG, Subtarget);
42332 DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0), DAG.getUNDEF(CmpVT));
42333 DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
42334 return LockOp;
42335}
42336
42337// Check whether a boolean test is testing a boolean value generated by
42338// X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
42339// code.
42340//
42341// Simplify the following patterns:
42342// (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
42343// (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
42344// to (Op EFLAGS Cond)
42345//
42346// (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
42347// (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
42348// to (Op EFLAGS !Cond)
42349//
42350// where Op could be BRCOND or CMOV.
42351//
42352static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
42353 // This combine only operates on CMP-like nodes.
42354 if (!(Cmp.getOpcode() == X86ISD::CMP ||
42355 (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
42356 return SDValue();
42357
42358 // Quit if not used as a boolean value.
42359 if (CC != X86::COND_E && CC != X86::COND_NE)
42360 return SDValue();
42361
42362 // Check CMP operands. One of them should be 0 or 1 and the other should be
42363 // an SetCC or extended from it.
42364 SDValue Op1 = Cmp.getOperand(0);
42365 SDValue Op2 = Cmp.getOperand(1);
42366
42367 SDValue SetCC;
42368 const ConstantSDNode* C = nullptr;
42369 bool needOppositeCond = (CC == X86::COND_E);
42370 bool checkAgainstTrue = false; // Is it a comparison against 1?
42371
42372 if ((C = dyn_cast<ConstantSDNode>(Op1)))
42373 SetCC = Op2;
42374 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
42375 SetCC = Op1;
42376 else // Quit if all operands are not constants.
42377 return SDValue();
42378
42379 if (C->getZExtValue() == 1) {
42380 needOppositeCond = !needOppositeCond;
42381 checkAgainstTrue = true;
42382 } else if (C->getZExtValue() != 0)
42383 // Quit if the constant is neither 0 or 1.
42384 return SDValue();
42385
42386 bool truncatedToBoolWithAnd = false;
42387 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
42388 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
42389 SetCC.getOpcode() == ISD::TRUNCATE ||
42390 SetCC.getOpcode() == ISD::AND) {
42391 if (SetCC.getOpcode() == ISD::AND) {
42392 int OpIdx = -1;
42393 if (isOneConstant(SetCC.getOperand(0)))
42394 OpIdx = 1;
42395 if (isOneConstant(SetCC.getOperand(1)))
42396 OpIdx = 0;
42397 if (OpIdx < 0)
42398 break;
42399 SetCC = SetCC.getOperand(OpIdx);
42400 truncatedToBoolWithAnd = true;
42401 } else
42402 SetCC = SetCC.getOperand(0);
42403 }
42404
42405 switch (SetCC.getOpcode()) {
42406 case X86ISD::SETCC_CARRY:
42407 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
42408 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
42409 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
42410 // truncated to i1 using 'and'.
42411 if (checkAgainstTrue && !truncatedToBoolWithAnd)
42412 break;
42413 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&(static_cast <bool> (X86::CondCode(SetCC.getConstantOperandVal
(0)) == X86::COND_B && "Invalid use of SETCC_CARRY!")
? void (0) : __assert_fail ("X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B && \"Invalid use of SETCC_CARRY!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 42414, __extension__ __PRETTY_FUNCTION__))
42414 "Invalid use of SETCC_CARRY!")(static_cast <bool> (X86::CondCode(SetCC.getConstantOperandVal
(0)) == X86::COND_B && "Invalid use of SETCC_CARRY!")
? void (0) : __assert_fail ("X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B && \"Invalid use of SETCC_CARRY!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 42414, __extension__ __PRETTY_FUNCTION__))
;
42415 LLVM_FALLTHROUGH[[gnu::fallthrough]];
42416 case X86ISD::SETCC:
42417 // Set the condition code or opposite one if necessary.
42418 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
42419 if (needOppositeCond)
42420 CC = X86::GetOppositeBranchCondition(CC);
42421 return SetCC.getOperand(1);
42422 case X86ISD::CMOV: {
42423 // Check whether false/true value has canonical one, i.e. 0 or 1.
42424 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
42425 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
42426 // Quit if true value is not a constant.
42427 if (!TVal)
42428 return SDValue();
42429 // Quit if false value is not a constant.
42430 if (!FVal) {
42431 SDValue Op = SetCC.getOperand(0);
42432 // Skip 'zext' or 'trunc' node.
42433 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
42434 Op.getOpcode() == ISD::TRUNCATE)
42435 Op = Op.getOperand(0);
42436 // A special case for rdrand/rdseed, where 0 is set if false cond is
42437 // found.
42438 if ((Op.getOpcode() != X86ISD::RDRAND &&
42439 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
42440 return SDValue();
42441 }
42442 // Quit if false value is not the constant 0 or 1.
42443 bool FValIsFalse = true;
42444 if (FVal && FVal->getZExtValue() != 0) {
42445 if (FVal->getZExtValue() != 1)
42446 return SDValue();
42447 // If FVal is 1, opposite cond is needed.
42448 needOppositeCond = !needOppositeCond;
42449 FValIsFalse = false;
42450 }
42451 // Quit if TVal is not the constant opposite of FVal.
42452 if (FValIsFalse && TVal->getZExtValue() != 1)
42453 return SDValue();
42454 if (!FValIsFalse && TVal->getZExtValue() != 0)
42455 return SDValue();
42456 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
42457 if (needOppositeCond)
42458 CC = X86::GetOppositeBranchCondition(CC);
42459 return SetCC.getOperand(3);
42460 }
42461 }
42462
42463 return SDValue();
42464}
42465
42466/// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
42467/// Match:
42468/// (X86or (X86setcc) (X86setcc))
42469/// (X86cmp (and (X86setcc) (X86setcc)), 0)
42470static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
42471 X86::CondCode &CC1, SDValue &Flags,
42472 bool &isAnd) {
42473 if (Cond->getOpcode() == X86ISD::CMP) {
42474 if (!isNullConstant(Cond->getOperand(1)))
42475 return false;
42476
42477 Cond = Cond->getOperand(0);
42478 }
42479
42480 isAnd = false;
42481
42482 SDValue SetCC0, SetCC1;
42483 switch (Cond->getOpcode()) {
42484 default: return false;
42485 case ISD::AND:
42486 case X86ISD::AND:
42487 isAnd = true;
42488 LLVM_FALLTHROUGH[[gnu::fallthrough]];
42489 case ISD::OR:
42490 case X86ISD::OR:
42491 SetCC0 = Cond->getOperand(0);
42492 SetCC1 = Cond->getOperand(1);
42493 break;
42494 };
42495
42496 // Make sure we have SETCC nodes, using the same flags value.
42497 if (SetCC0.getOpcode() != X86ISD::SETCC ||
42498 SetCC1.getOpcode() != X86ISD::SETCC ||
42499 SetCC0->getOperand(1) != SetCC1->getOperand(1))
42500 return false;
42501
42502 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
42503 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
42504 Flags = SetCC0->getOperand(1);
42505 return true;
42506}
42507
42508// When legalizing carry, we create carries via add X, -1
42509// If that comes from an actual carry, via setcc, we use the
42510// carry directly.
42511static SDValue combineCarryThroughADD(SDValue EFLAGS, SelectionDAG &DAG) {
42512 if (EFLAGS.getOpcode() == X86ISD::ADD) {
42513 if (isAllOnesConstant(EFLAGS.getOperand(1))) {
42514 SDValue Carry = EFLAGS.getOperand(0);
42515 while (Carry.getOpcode() == ISD::TRUNCATE ||
42516 Carry.getOpcode() == ISD::ZERO_EXTEND ||
42517 Carry.getOpcode() == ISD::SIGN_EXTEND ||
42518 Carry.getOpcode() == ISD::ANY_EXTEND ||
42519 (Carry.getOpcode() == ISD::AND &&
42520 isOneConstant(Carry.getOperand(1))))
42521 Carry = Carry.getOperand(0);
42522 if (Carry.getOpcode() == X86ISD::SETCC ||
42523 Carry.getOpcode() == X86ISD::SETCC_CARRY) {
42524 // TODO: Merge this code with equivalent in combineAddOrSubToADCOrSBB?
42525 uint64_t CarryCC = Carry.getConstantOperandVal(0);
42526 SDValue CarryOp1 = Carry.getOperand(1);
42527 if (CarryCC == X86::COND_B)
42528 return CarryOp1;
42529 if (CarryCC == X86::COND_A) {
42530 // Try to convert COND_A into COND_B in an attempt to facilitate
42531 // materializing "setb reg".
42532 //
42533 // Do not flip "e > c", where "c" is a constant, because Cmp
42534 // instruction cannot take an immediate as its first operand.
42535 //
42536 if (CarryOp1.getOpcode() == X86ISD::SUB &&
42537 CarryOp1.getNode()->hasOneUse() &&
42538 CarryOp1.getValueType().isInteger() &&
42539 !isa<ConstantSDNode>(CarryOp1.getOperand(1))) {
42540 SDValue SubCommute =
42541 DAG.getNode(X86ISD::SUB, SDLoc(CarryOp1), CarryOp1->getVTList(),
42542 CarryOp1.getOperand(1), CarryOp1.getOperand(0));
42543 return SDValue(SubCommute.getNode(), CarryOp1.getResNo());
42544 }
42545 }
42546 // If this is a check of the z flag of an add with 1, switch to the
42547 // C flag.
42548 if (CarryCC == X86::COND_E &&
42549 CarryOp1.getOpcode() == X86ISD::ADD &&
42550 isOneConstant(CarryOp1.getOperand(1)))
42551 return CarryOp1;
42552 }
42553 }
42554 }
42555
42556 return SDValue();
42557}
42558
42559/// If we are inverting an PTEST/TESTP operand, attempt to adjust the CC
42560/// to avoid the inversion.
42561static SDValue combinePTESTCC(SDValue EFLAGS, X86::CondCode &CC,
42562 SelectionDAG &DAG,
42563 const X86Subtarget &Subtarget) {
42564 // TODO: Handle X86ISD::KTEST/X86ISD::KORTEST.
42565 if (EFLAGS.getOpcode() != X86ISD::PTEST &&
42566 EFLAGS.getOpcode() != X86ISD::TESTP)
42567 return SDValue();
42568
42569 // PTEST/TESTP sets EFLAGS as:
42570 // TESTZ: ZF = (Op0 & Op1) == 0
42571 // TESTC: CF = (~Op0 & Op1) == 0
42572 // TESTNZC: ZF == 0 && CF == 0
42573 EVT VT = EFLAGS.getValueType();
42574 SDValue Op0 = EFLAGS.getOperand(0);
42575 SDValue Op1 = EFLAGS.getOperand(1);
42576 EVT OpVT = Op0.getValueType();
42577
42578 // TEST*(~X,Y) == TEST*(X,Y)
42579 if (SDValue NotOp0 = IsNOT(Op0, DAG)) {
42580 X86::CondCode InvCC;
42581 switch (CC) {
42582 case X86::COND_B:
42583 // testc -> testz.
42584 InvCC = X86::COND_E;
42585 break;
42586 case X86::COND_AE:
42587 // !testc -> !testz.
42588 InvCC = X86::COND_NE;
42589 break;
42590 case X86::COND_E:
42591 // testz -> testc.
42592 InvCC = X86::COND_B;
42593 break;
42594 case X86::COND_NE:
42595 // !testz -> !testc.
42596 InvCC = X86::COND_AE;
42597 break;
42598 case X86::COND_A:
42599 case X86::COND_BE:
42600 // testnzc -> testnzc (no change).
42601 InvCC = CC;
42602 break;
42603 default:
42604 InvCC = X86::COND_INVALID;
42605 break;
42606 }
42607
42608 if (InvCC != X86::COND_INVALID) {
42609 CC = InvCC;
42610 return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
42611 DAG.getBitcast(OpVT, NotOp0), Op1);
42612 }
42613 }
42614
42615 if (CC == X86::COND_E || CC == X86::COND_NE) {
42616 // TESTZ(X,~Y) == TESTC(Y,X)
42617 if (SDValue NotOp1 = IsNOT(Op1, DAG)) {
42618 CC = (CC == X86::COND_E ? X86::COND_B : X86::COND_AE);
42619 return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
42620 DAG.getBitcast(OpVT, NotOp1), Op0);
42621 }
42622
42623 if (Op0 == Op1) {
42624 SDValue BC = peekThroughBitcasts(Op0);
42625 EVT BCVT = BC.getValueType();
42626 assert(BCVT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(BCVT) &&(static_cast <bool> (BCVT.isVector() && DAG.getTargetLoweringInfo
().isTypeLegal(BCVT) && "Unexpected vector type") ? void
(0) : __assert_fail ("BCVT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(BCVT) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 42627, __extension__ __PRETTY_FUNCTION__))
42627 "Unexpected vector type")(static_cast <bool> (BCVT.isVector() && DAG.getTargetLoweringInfo
().isTypeLegal(BCVT) && "Unexpected vector type") ? void
(0) : __assert_fail ("BCVT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(BCVT) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 42627, __extension__ __PRETTY_FUNCTION__))
;
42628
42629 // TESTZ(AND(X,Y),AND(X,Y)) == TESTZ(X,Y)
42630 if (BC.getOpcode() == ISD::AND || BC.getOpcode() == X86ISD::FAND) {
42631 return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
42632 DAG.getBitcast(OpVT, BC.getOperand(0)),
42633 DAG.getBitcast(OpVT, BC.getOperand(1)));
42634 }
42635
42636 // TESTZ(AND(~X,Y),AND(~X,Y)) == TESTC(X,Y)
42637 if (BC.getOpcode() == X86ISD::ANDNP || BC.getOpcode() == X86ISD::FANDN) {
42638 CC = (CC == X86::COND_E ? X86::COND_B : X86::COND_AE);
42639 return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
42640 DAG.getBitcast(OpVT, BC.getOperand(0)),
42641 DAG.getBitcast(OpVT, BC.getOperand(1)));
42642 }
42643
42644 // If every element is an all-sign value, see if we can use MOVMSK to
42645 // more efficiently extract the sign bits and compare that.
42646 // TODO: Handle TESTC with comparison inversion.
42647 // TODO: Can we remove SimplifyMultipleUseDemandedBits and rely on
42648 // MOVMSK combines to make sure its never worse than PTEST?
42649 unsigned EltBits = BCVT.getScalarSizeInBits();
42650 if (DAG.ComputeNumSignBits(BC) == EltBits) {
42651 assert(VT == MVT::i32 && "Expected i32 EFLAGS comparison result")(static_cast <bool> (VT == MVT::i32 && "Expected i32 EFLAGS comparison result"
) ? void (0) : __assert_fail ("VT == MVT::i32 && \"Expected i32 EFLAGS comparison result\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 42651, __extension__ __PRETTY_FUNCTION__))
;
42652 APInt SignMask = APInt::getSignMask(EltBits);
42653 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42654 if (SDValue Res =
42655 TLI.SimplifyMultipleUseDemandedBits(BC, SignMask, DAG)) {
42656 // For vXi16 cases we need to use pmovmksb and extract every other
42657 // sign bit.
42658 SDLoc DL(EFLAGS);
42659 if (EltBits == 16) {
42660 MVT MovmskVT = BCVT.is128BitVector() ? MVT::v16i8 : MVT::v32i8;
42661 Res = DAG.getBitcast(MovmskVT, Res);
42662 Res = getPMOVMSKB(DL, Res, DAG, Subtarget);
42663 Res = DAG.getNode(ISD::AND, DL, MVT::i32, Res,
42664 DAG.getConstant(0xAAAAAAAA, DL, MVT::i32));
42665 } else {
42666 Res = getPMOVMSKB(DL, Res, DAG, Subtarget);
42667 }
42668 return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Res,
42669 DAG.getConstant(0, DL, MVT::i32));
42670 }
42671 }
42672 }
42673
42674 // TESTZ(-1,X) == TESTZ(X,X)
42675 if (ISD::isBuildVectorAllOnes(Op0.getNode()))
42676 return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT, Op1, Op1);
42677
42678 // TESTZ(X,-1) == TESTZ(X,X)
42679 if (ISD::isBuildVectorAllOnes(Op1.getNode()))
42680 return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT, Op0, Op0);
42681 }
42682
42683 return SDValue();
42684}
42685
42686// Attempt to simplify the MOVMSK input based on the comparison type.
42687static SDValue combineSetCCMOVMSK(SDValue EFLAGS, X86::CondCode &CC,
42688 SelectionDAG &DAG,
42689 const X86Subtarget &Subtarget) {
42690 // Handle eq/ne against zero (any_of).
42691 // Handle eq/ne against -1 (all_of).
42692 if (!(CC == X86::COND_E || CC == X86::COND_NE))
42693 return SDValue();
42694 if (EFLAGS.getValueType() != MVT::i32)
42695 return SDValue();
42696 unsigned CmpOpcode = EFLAGS.getOpcode();
42697 if (CmpOpcode != X86ISD::CMP && CmpOpcode != X86ISD::SUB)
42698 return SDValue();
42699 auto *CmpConstant = dyn_cast<ConstantSDNode>(EFLAGS.getOperand(1));
42700 if (!CmpConstant)
42701 return SDValue();
42702 const APInt &CmpVal = CmpConstant->getAPIntValue();
42703
42704 SDValue CmpOp = EFLAGS.getOperand(0);
42705 unsigned CmpBits = CmpOp.getValueSizeInBits();
42706 assert(CmpBits == CmpVal.getBitWidth() && "Value size mismatch")(static_cast <bool> (CmpBits == CmpVal.getBitWidth() &&
"Value size mismatch") ? void (0) : __assert_fail ("CmpBits == CmpVal.getBitWidth() && \"Value size mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 42706, __extension__ __PRETTY_FUNCTION__))
;
42707
42708 // Peek through any truncate.
42709 if (CmpOp.getOpcode() == ISD::TRUNCATE)
42710 CmpOp = CmpOp.getOperand(0);
42711
42712 // Bail if we don't find a MOVMSK.
42713 if (CmpOp.getOpcode() != X86ISD::MOVMSK)
42714 return SDValue();
42715
42716 SDValue Vec = CmpOp.getOperand(0);
42717 MVT VecVT = Vec.getSimpleValueType();
42718 assert((VecVT.is128BitVector() || VecVT.is256BitVector()) &&(static_cast <bool> ((VecVT.is128BitVector() || VecVT.is256BitVector
()) && "Unexpected MOVMSK operand") ? void (0) : __assert_fail
("(VecVT.is128BitVector() || VecVT.is256BitVector()) && \"Unexpected MOVMSK operand\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 42719, __extension__ __PRETTY_FUNCTION__))
42719 "Unexpected MOVMSK operand")(static_cast <bool> ((VecVT.is128BitVector() || VecVT.is256BitVector
()) && "Unexpected MOVMSK operand") ? void (0) : __assert_fail
("(VecVT.is128BitVector() || VecVT.is256BitVector()) && \"Unexpected MOVMSK operand\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 42719, __extension__ __PRETTY_FUNCTION__))
;
42720 unsigned NumElts = VecVT.getVectorNumElements();
42721 unsigned NumEltBits = VecVT.getScalarSizeInBits();
42722
42723 bool IsAnyOf = CmpOpcode == X86ISD::CMP && CmpVal.isNullValue();
42724 bool IsAllOf = CmpOpcode == X86ISD::SUB && NumElts <= CmpBits &&
42725 CmpVal.isMask(NumElts);
42726 if (!IsAnyOf && !IsAllOf)
42727 return SDValue();
42728
42729 // See if we can peek through to a vector with a wider element type, if the
42730 // signbits extend down to all the sub-elements as well.
42731 // Calling MOVMSK with the wider type, avoiding the bitcast, helps expose
42732 // potential SimplifyDemandedBits/Elts cases.
42733 if (Vec.getOpcode() == ISD::BITCAST) {
42734 SDValue BC = peekThroughBitcasts(Vec);
42735 MVT BCVT = BC.getSimpleValueType();
42736 unsigned BCNumElts = BCVT.getVectorNumElements();
42737 unsigned BCNumEltBits = BCVT.getScalarSizeInBits();
42738 if ((BCNumEltBits == 32 || BCNumEltBits == 64) &&
42739 BCNumEltBits > NumEltBits &&
42740 DAG.ComputeNumSignBits(BC) > (BCNumEltBits - NumEltBits)) {
42741 SDLoc DL(EFLAGS);
42742 unsigned CmpMask = IsAnyOf ? 0 : ((1 << BCNumElts) - 1);
42743 return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
42744 DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, BC),
42745 DAG.getConstant(CmpMask, DL, MVT::i32));
42746 }
42747 }
42748
42749 // MOVMSK(PCMPEQ(X,0)) == -1 -> PTESTZ(X,X).
42750 // MOVMSK(PCMPEQ(X,0)) != -1 -> !PTESTZ(X,X).
42751 if (IsAllOf && Subtarget.hasSSE41()) {
42752 SDValue BC = peekThroughBitcasts(Vec);
42753 if (BC.getOpcode() == X86ISD::PCMPEQ &&
42754 ISD::isBuildVectorAllZeros(BC.getOperand(1).getNode())) {
42755 MVT TestVT = VecVT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
42756 SDValue V = DAG.getBitcast(TestVT, BC.getOperand(0));
42757 return DAG.getNode(X86ISD::PTEST, SDLoc(EFLAGS), MVT::i32, V, V);
42758 }
42759 }
42760
42761 // See if we can avoid a PACKSS by calling MOVMSK on the sources.
42762 // For vXi16 cases we can use a v2Xi8 PMOVMSKB. We must mask out
42763 // sign bits prior to the comparison with zero unless we know that
42764 // the vXi16 splats the sign bit down to the lower i8 half.
42765 // TODO: Handle all_of patterns.
42766 if (Vec.getOpcode() == X86ISD::PACKSS && VecVT == MVT::v16i8) {
42767 SDValue VecOp0 = Vec.getOperand(0);
42768 SDValue VecOp1 = Vec.getOperand(1);
42769 bool SignExt0 = DAG.ComputeNumSignBits(VecOp0) > 8;
42770 bool SignExt1 = DAG.ComputeNumSignBits(VecOp1) > 8;
42771 // PMOVMSKB(PACKSSBW(X, undef)) -> PMOVMSKB(BITCAST_v16i8(X)) & 0xAAAA.
42772 if (IsAnyOf && CmpBits == 8 && VecOp1.isUndef()) {
42773 SDLoc DL(EFLAGS);
42774 SDValue Result = DAG.getBitcast(MVT::v16i8, VecOp0);
42775 Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
42776 Result = DAG.getZExtOrTrunc(Result, DL, MVT::i16);
42777 if (!SignExt0) {
42778 Result = DAG.getNode(ISD::AND, DL, MVT::i16, Result,
42779 DAG.getConstant(0xAAAA, DL, MVT::i16));
42780 }
42781 return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
42782 DAG.getConstant(0, DL, MVT::i16));
42783 }
42784 // PMOVMSKB(PACKSSBW(LO(X), HI(X)))
42785 // -> PMOVMSKB(BITCAST_v32i8(X)) & 0xAAAAAAAA.
42786 if (CmpBits >= 16 && Subtarget.hasInt256() &&
42787 VecOp0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
42788 VecOp1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
42789 VecOp0.getOperand(0) == VecOp1.getOperand(0) &&
42790 VecOp0.getConstantOperandAPInt(1) == 0 &&
42791 VecOp1.getConstantOperandAPInt(1) == 8 &&
42792 (IsAnyOf || (SignExt0 && SignExt1))) {
42793 SDLoc DL(EFLAGS);
42794 SDValue Result = DAG.getBitcast(MVT::v32i8, VecOp0.getOperand(0));
42795 Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
42796 unsigned CmpMask = IsAnyOf ? 0 : 0xFFFFFFFF;
42797 if (!SignExt0 || !SignExt1) {
42798 assert(IsAnyOf && "Only perform v16i16 signmasks for any_of patterns")(static_cast <bool> (IsAnyOf && "Only perform v16i16 signmasks for any_of patterns"
) ? void (0) : __assert_fail ("IsAnyOf && \"Only perform v16i16 signmasks for any_of patterns\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 42798, __extension__ __PRETTY_FUNCTION__))
;
42799 Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
42800 DAG.getConstant(0xAAAAAAAA, DL, MVT::i32));
42801 }
42802 return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
42803 DAG.getConstant(CmpMask, DL, MVT::i32));
42804 }
42805 }
42806
42807 // MOVMSK(SHUFFLE(X,u)) -> MOVMSK(X) iff every element is referenced.
42808 SmallVector<int, 32> ShuffleMask;
42809 SmallVector<SDValue, 2> ShuffleInputs;
42810 if (NumElts <= CmpBits &&
42811 getTargetShuffleInputs(peekThroughBitcasts(Vec), ShuffleInputs,
42812 ShuffleMask, DAG) &&
42813 ShuffleInputs.size() == 1 && !isAnyZeroOrUndef(ShuffleMask) &&
42814 ShuffleInputs[0].getValueSizeInBits() == VecVT.getSizeInBits()) {
42815 unsigned NumShuffleElts = ShuffleMask.size();
42816 APInt DemandedElts = APInt::getNullValue(NumShuffleElts);
42817 for (int M : ShuffleMask) {
42818 assert(0 <= M && M < (int)NumShuffleElts && "Bad unary shuffle index")(static_cast <bool> (0 <= M && M < (int)NumShuffleElts
&& "Bad unary shuffle index") ? void (0) : __assert_fail
("0 <= M && M < (int)NumShuffleElts && \"Bad unary shuffle index\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 42818, __extension__ __PRETTY_FUNCTION__))
;
42819 DemandedElts.setBit(M);
42820 }
42821 if (DemandedElts.isAllOnesValue()) {
42822 SDLoc DL(EFLAGS);
42823 SDValue Result = DAG.getBitcast(VecVT, ShuffleInputs[0]);
42824 Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
42825 Result =
42826 DAG.getZExtOrTrunc(Result, DL, EFLAGS.getOperand(0).getValueType());
42827 return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
42828 EFLAGS.getOperand(1));
42829 }
42830 }
42831
42832 return SDValue();
42833}
42834
42835/// Optimize an EFLAGS definition used according to the condition code \p CC
42836/// into a simpler EFLAGS value, potentially returning a new \p CC and replacing
42837/// uses of chain values.
42838static SDValue combineSetCCEFLAGS(SDValue EFLAGS, X86::CondCode &CC,
42839 SelectionDAG &DAG,
42840 const X86Subtarget &Subtarget) {
42841 if (CC == X86::COND_B)
42842 if (SDValue Flags = combineCarryThroughADD(EFLAGS, DAG))
42843 return Flags;
42844
42845 if (SDValue R = checkBoolTestSetCCCombine(EFLAGS, CC))
42846 return R;
42847
42848 if (SDValue R = combinePTESTCC(EFLAGS, CC, DAG, Subtarget))
42849 return R;
42850
42851 if (SDValue R = combineSetCCMOVMSK(EFLAGS, CC, DAG, Subtarget))
42852 return R;
42853
42854 return combineSetCCAtomicArith(EFLAGS, CC, DAG, Subtarget);
42855}
42856
42857/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
42858static SDValue combineCMov(SDNode *N, SelectionDAG &DAG,
42859 TargetLowering::DAGCombinerInfo &DCI,
42860 const X86Subtarget &Subtarget) {
42861 SDLoc DL(N);
42862
42863 SDValue FalseOp = N->getOperand(0);
42864 SDValue TrueOp = N->getOperand(1);
42865 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
42866 SDValue Cond = N->getOperand(3);
42867
42868 // cmov X, X, ?, ? --> X
42869 if (TrueOp == FalseOp)
42870 return TrueOp;
42871
42872 // Try to simplify the EFLAGS and condition code operands.
42873 // We can't always do this as FCMOV only supports a subset of X86 cond.
42874 if (SDValue Flags = combineSetCCEFLAGS(Cond, CC, DAG, Subtarget)) {
42875 if (!(FalseOp.getValueType() == MVT::f80 ||
42876 (FalseOp.getValueType() == MVT::f64 && !Subtarget.hasSSE2()) ||
42877 (FalseOp.getValueType() == MVT::f32 && !Subtarget.hasSSE1())) ||
42878 !Subtarget.hasCMov() || hasFPCMov(CC)) {
42879 SDValue Ops[] = {FalseOp, TrueOp, DAG.getTargetConstant(CC, DL, MVT::i8),
42880 Flags};
42881 return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
42882 }
42883 }
42884
42885 // If this is a select between two integer constants, try to do some
42886 // optimizations. Note that the operands are ordered the opposite of SELECT
42887 // operands.
42888 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
42889 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
42890 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
42891 // larger than FalseC (the false value).
42892 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
42893 CC = X86::GetOppositeBranchCondition(CC);
42894 std::swap(TrueC, FalseC);
42895 std::swap(TrueOp, FalseOp);
42896 }
42897
42898 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
42899 // This is efficient for any integer data type (including i8/i16) and
42900 // shift amount.
42901 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
42902 Cond = getSETCC(CC, Cond, DL, DAG);
42903
42904 // Zero extend the condition if needed.
42905 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
42906
42907 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
42908 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
42909 DAG.getConstant(ShAmt, DL, MVT::i8));
42910 return Cond;
42911 }
42912
42913 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
42914 // for any integer data type, including i8/i16.
42915 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
42916 Cond = getSETCC(CC, Cond, DL, DAG);
42917
42918 // Zero extend the condition if needed.
42919 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
42920 FalseC->getValueType(0), Cond);
42921 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
42922 SDValue(FalseC, 0));
42923 return Cond;
42924 }
42925
42926 // Optimize cases that will turn into an LEA instruction. This requires
42927 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
42928 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
42929 APInt Diff = TrueC->getAPIntValue() - FalseC->getAPIntValue();
42930 assert(Diff.getBitWidth() == N->getValueType(0).getSizeInBits() &&(static_cast <bool> (Diff.getBitWidth() == N->getValueType
(0).getSizeInBits() && "Implicit constant truncation"
) ? void (0) : __assert_fail ("Diff.getBitWidth() == N->getValueType(0).getSizeInBits() && \"Implicit constant truncation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 42931, __extension__ __PRETTY_FUNCTION__))
42931 "Implicit constant truncation")(static_cast <bool> (Diff.getBitWidth() == N->getValueType
(0).getSizeInBits() && "Implicit constant truncation"
) ? void (0) : __assert_fail ("Diff.getBitWidth() == N->getValueType(0).getSizeInBits() && \"Implicit constant truncation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 42931, __extension__ __PRETTY_FUNCTION__))
;
42932
42933 bool isFastMultiplier = false;
42934 if (Diff.ult(10)) {
42935 switch (Diff.getZExtValue()) {
42936 default: break;
42937 case 1: // result = add base, cond
42938 case 2: // result = lea base( , cond*2)
42939 case 3: // result = lea base(cond, cond*2)
42940 case 4: // result = lea base( , cond*4)
42941 case 5: // result = lea base(cond, cond*4)
42942 case 8: // result = lea base( , cond*8)
42943 case 9: // result = lea base(cond, cond*8)
42944 isFastMultiplier = true;
42945 break;
42946 }
42947 }
42948
42949 if (isFastMultiplier) {
42950 Cond = getSETCC(CC, Cond, DL ,DAG);
42951 // Zero extend the condition if needed.
42952 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
42953 Cond);
42954 // Scale the condition by the difference.
42955 if (Diff != 1)
42956 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
42957 DAG.getConstant(Diff, DL, Cond.getValueType()));
42958
42959 // Add the base if non-zero.
42960 if (FalseC->getAPIntValue() != 0)
42961 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
42962 SDValue(FalseC, 0));
42963 return Cond;
42964 }
42965 }
42966 }
42967 }
42968
42969 // Handle these cases:
42970 // (select (x != c), e, c) -> select (x != c), e, x),
42971 // (select (x == c), c, e) -> select (x == c), x, e)
42972 // where the c is an integer constant, and the "select" is the combination
42973 // of CMOV and CMP.
42974 //
42975 // The rationale for this change is that the conditional-move from a constant
42976 // needs two instructions, however, conditional-move from a register needs
42977 // only one instruction.
42978 //
42979 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
42980 // some instruction-combining opportunities. This opt needs to be
42981 // postponed as late as possible.
42982 //
42983 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
42984 // the DCI.xxxx conditions are provided to postpone the optimization as
42985 // late as possible.
42986
42987 ConstantSDNode *CmpAgainst = nullptr;
42988 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
42989 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
42990 !isa<ConstantSDNode>(Cond.getOperand(0))) {
42991
42992 if (CC == X86::COND_NE &&
42993 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
42994 CC = X86::GetOppositeBranchCondition(CC);
42995 std::swap(TrueOp, FalseOp);
42996 }
42997
42998 if (CC == X86::COND_E &&
42999 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
43000 SDValue Ops[] = {FalseOp, Cond.getOperand(0),
43001 DAG.getTargetConstant(CC, DL, MVT::i8), Cond};
43002 return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
43003 }
43004 }
43005 }
43006
43007 // Fold and/or of setcc's to double CMOV:
43008 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
43009 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
43010 //
43011 // This combine lets us generate:
43012 // cmovcc1 (jcc1 if we don't have CMOV)
43013 // cmovcc2 (same)
43014 // instead of:
43015 // setcc1
43016 // setcc2
43017 // and/or
43018 // cmovne (jne if we don't have CMOV)
43019 // When we can't use the CMOV instruction, it might increase branch
43020 // mispredicts.
43021 // When we can use CMOV, or when there is no mispredict, this improves
43022 // throughput and reduces register pressure.
43023 //
43024 if (CC == X86::COND_NE) {
43025 SDValue Flags;
43026 X86::CondCode CC0, CC1;
43027 bool isAndSetCC;
43028 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
43029 if (isAndSetCC) {
43030 std::swap(FalseOp, TrueOp);
43031 CC0 = X86::GetOppositeBranchCondition(CC0);
43032 CC1 = X86::GetOppositeBranchCondition(CC1);
43033 }
43034
43035 SDValue LOps[] = {FalseOp, TrueOp,
43036 DAG.getTargetConstant(CC0, DL, MVT::i8), Flags};
43037 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), LOps);
43038 SDValue Ops[] = {LCMOV, TrueOp, DAG.getTargetConstant(CC1, DL, MVT::i8),
43039 Flags};
43040 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
43041 return CMOV;
43042 }
43043 }
43044
43045 // Fold (CMOV C1, (ADD (CTTZ X), C2), (X != 0)) ->
43046 // (ADD (CMOV C1-C2, (CTTZ X), (X != 0)), C2)
43047 // Or (CMOV (ADD (CTTZ X), C2), C1, (X == 0)) ->
43048 // (ADD (CMOV (CTTZ X), C1-C2, (X == 0)), C2)
43049 if ((CC == X86::COND_NE || CC == X86::COND_E) &&
43050 Cond.getOpcode() == X86ISD::CMP && isNullConstant(Cond.getOperand(1))) {
43051 SDValue Add = TrueOp;
43052 SDValue Const = FalseOp;
43053 // Canonicalize the condition code for easier matching and output.
43054 if (CC == X86::COND_E)
43055 std::swap(Add, Const);
43056
43057 // We might have replaced the constant in the cmov with the LHS of the
43058 // compare. If so change it to the RHS of the compare.
43059 if (Const == Cond.getOperand(0))
43060 Const = Cond.getOperand(1);
43061
43062 // Ok, now make sure that Add is (add (cttz X), C2) and Const is a constant.
43063 if (isa<ConstantSDNode>(Const) && Add.getOpcode() == ISD::ADD &&
43064 Add.hasOneUse() && isa<ConstantSDNode>(Add.getOperand(1)) &&
43065 (Add.getOperand(0).getOpcode() == ISD::CTTZ_ZERO_UNDEF ||
43066 Add.getOperand(0).getOpcode() == ISD::CTTZ) &&
43067 Add.getOperand(0).getOperand(0) == Cond.getOperand(0)) {
43068 EVT VT = N->getValueType(0);
43069 // This should constant fold.
43070 SDValue Diff = DAG.getNode(ISD::SUB, DL, VT, Const, Add.getOperand(1));
43071 SDValue CMov =
43072 DAG.getNode(X86ISD::CMOV, DL, VT, Diff, Add.getOperand(0),
43073 DAG.getTargetConstant(X86::COND_NE, DL, MVT::i8), Cond);
43074 return DAG.getNode(ISD::ADD, DL, VT, CMov, Add.getOperand(1));
43075 }
43076 }
43077
43078 return SDValue();
43079}
43080
43081/// Different mul shrinking modes.
43082enum class ShrinkMode { MULS8, MULU8, MULS16, MULU16 };
43083
43084static bool canReduceVMulWidth(SDNode *N, SelectionDAG &DAG, ShrinkMode &Mode) {
43085 EVT VT = N->getOperand(0).getValueType();
43086 if (VT.getScalarSizeInBits() != 32)
43087 return false;
43088
43089 assert(N->getNumOperands() == 2 && "NumOperands of Mul are 2")(static_cast <bool> (N->getNumOperands() == 2 &&
"NumOperands of Mul are 2") ? void (0) : __assert_fail ("N->getNumOperands() == 2 && \"NumOperands of Mul are 2\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 43089, __extension__ __PRETTY_FUNCTION__))
;
43090 unsigned SignBits[2] = {1, 1};
43091 bool IsPositive[2] = {false, false};
43092 for (unsigned i = 0; i < 2; i++) {
43093 SDValue Opd = N->getOperand(i);
43094
43095 SignBits[i] = DAG.ComputeNumSignBits(Opd);
43096 IsPositive[i] = DAG.SignBitIsZero(Opd);
43097 }
43098
43099 bool AllPositive = IsPositive[0] && IsPositive[1];
43100 unsigned MinSignBits = std::min(SignBits[0], SignBits[1]);
43101 // When ranges are from -128 ~ 127, use MULS8 mode.
43102 if (MinSignBits >= 25)
43103 Mode = ShrinkMode::MULS8;
43104 // When ranges are from 0 ~ 255, use MULU8 mode.
43105 else if (AllPositive && MinSignBits >= 24)
43106 Mode = ShrinkMode::MULU8;
43107 // When ranges are from -32768 ~ 32767, use MULS16 mode.
43108 else if (MinSignBits >= 17)
43109 Mode = ShrinkMode::MULS16;
43110 // When ranges are from 0 ~ 65535, use MULU16 mode.
43111 else if (AllPositive && MinSignBits >= 16)
43112 Mode = ShrinkMode::MULU16;
43113 else
43114 return false;
43115 return true;
43116}
43117
43118/// When the operands of vector mul are extended from smaller size values,
43119/// like i8 and i16, the type of mul may be shrinked to generate more
43120/// efficient code. Two typical patterns are handled:
43121/// Pattern1:
43122/// %2 = sext/zext <N x i8> %1 to <N x i32>
43123/// %4 = sext/zext <N x i8> %3 to <N x i32>
43124// or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
43125/// %5 = mul <N x i32> %2, %4
43126///
43127/// Pattern2:
43128/// %2 = zext/sext <N x i16> %1 to <N x i32>
43129/// %4 = zext/sext <N x i16> %3 to <N x i32>
43130/// or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
43131/// %5 = mul <N x i32> %2, %4
43132///
43133/// There are four mul shrinking modes:
43134/// If %2 == sext32(trunc8(%2)), i.e., the scalar value range of %2 is
43135/// -128 to 128, and the scalar value range of %4 is also -128 to 128,
43136/// generate pmullw+sext32 for it (MULS8 mode).
43137/// If %2 == zext32(trunc8(%2)), i.e., the scalar value range of %2 is
43138/// 0 to 255, and the scalar value range of %4 is also 0 to 255,
43139/// generate pmullw+zext32 for it (MULU8 mode).
43140/// If %2 == sext32(trunc16(%2)), i.e., the scalar value range of %2 is
43141/// -32768 to 32767, and the scalar value range of %4 is also -32768 to 32767,
43142/// generate pmullw+pmulhw for it (MULS16 mode).
43143/// If %2 == zext32(trunc16(%2)), i.e., the scalar value range of %2 is
43144/// 0 to 65535, and the scalar value range of %4 is also 0 to 65535,
43145/// generate pmullw+pmulhuw for it (MULU16 mode).
43146static SDValue reduceVMULWidth(SDNode *N, SelectionDAG &DAG,
43147 const X86Subtarget &Subtarget) {
43148 // Check for legality
43149 // pmullw/pmulhw are not supported by SSE.
43150 if (!Subtarget.hasSSE2())
43151 return SDValue();
43152
43153 // Check for profitability
43154 // pmulld is supported since SSE41. It is better to use pmulld
43155 // instead of pmullw+pmulhw, except for subtargets where pmulld is slower than
43156 // the expansion.
43157 bool OptForMinSize = DAG.getMachineFunction().getFunction().hasMinSize();
43158 if (Subtarget.hasSSE41() && (OptForMinSize || !Subtarget.isPMULLDSlow()))
43159 return SDValue();
43160
43161 ShrinkMode Mode;
43162 if (!canReduceVMulWidth(N, DAG, Mode))
43163 return SDValue();
43164
43165 SDLoc DL(N);
43166 SDValue N0 = N->getOperand(0);
43167 SDValue N1 = N->getOperand(1);
43168 EVT VT = N->getOperand(0).getValueType();
43169 unsigned NumElts = VT.getVectorNumElements();
43170 if ((NumElts % 2) != 0)
43171 return SDValue();
43172
43173 EVT ReducedVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16, NumElts);
43174
43175 // Shrink the operands of mul.
43176 SDValue NewN0 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N0);
43177 SDValue NewN1 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N1);
43178
43179 // Generate the lower part of mul: pmullw. For MULU8/MULS8, only the
43180 // lower part is needed.
43181 SDValue MulLo = DAG.getNode(ISD::MUL, DL, ReducedVT, NewN0, NewN1);
43182 if (Mode == ShrinkMode::MULU8 || Mode == ShrinkMode::MULS8)
43183 return DAG.getNode((Mode == ShrinkMode::MULU8) ? ISD::ZERO_EXTEND
43184 : ISD::SIGN_EXTEND,
43185 DL, VT, MulLo);
43186
43187 EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts / 2);
43188 // Generate the higher part of mul: pmulhw/pmulhuw. For MULU16/MULS16,
43189 // the higher part is also needed.
43190 SDValue MulHi =
43191 DAG.getNode(Mode == ShrinkMode::MULS16 ? ISD::MULHS : ISD::MULHU, DL,
43192 ReducedVT, NewN0, NewN1);
43193
43194 // Repack the lower part and higher part result of mul into a wider
43195 // result.
43196 // Generate shuffle functioning as punpcklwd.
43197 SmallVector<int, 16> ShuffleMask(NumElts);
43198 for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
43199 ShuffleMask[2 * i] = i;
43200 ShuffleMask[2 * i + 1] = i + NumElts;
43201 }
43202 SDValue ResLo =
43203 DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
43204 ResLo = DAG.getBitcast(ResVT, ResLo);
43205 // Generate shuffle functioning as punpckhwd.
43206 for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
43207 ShuffleMask[2 * i] = i + NumElts / 2;
43208 ShuffleMask[2 * i + 1] = i + NumElts * 3 / 2;
43209 }
43210 SDValue ResHi =
43211 DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
43212 ResHi = DAG.getBitcast(ResVT, ResHi);
43213 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ResLo, ResHi);
43214}
43215
43216static SDValue combineMulSpecial(uint64_t MulAmt, SDNode *N, SelectionDAG &DAG,
43217 EVT VT, const SDLoc &DL) {
43218
43219 auto combineMulShlAddOrSub = [&](int Mult, int Shift, bool isAdd) {
43220 SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
43221 DAG.getConstant(Mult, DL, VT));
43222 Result = DAG.getNode(ISD::SHL, DL, VT, Result,
43223 DAG.getConstant(Shift, DL, MVT::i8));
43224 Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
43225 N->getOperand(0));
43226 return Result;
43227 };
43228
43229 auto combineMulMulAddOrSub = [&](int Mul1, int Mul2, bool isAdd) {
43230 SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
43231 DAG.getConstant(Mul1, DL, VT));
43232 Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, Result,
43233 DAG.getConstant(Mul2, DL, VT));
43234 Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
43235 N->getOperand(0));
43236 return Result;
43237 };
43238
43239 switch (MulAmt) {
43240 default:
43241 break;
43242 case 11:
43243 // mul x, 11 => add ((shl (mul x, 5), 1), x)
43244 return combineMulShlAddOrSub(5, 1, /*isAdd*/ true);
43245 case 21:
43246 // mul x, 21 => add ((shl (mul x, 5), 2), x)
43247 return combineMulShlAddOrSub(5, 2, /*isAdd*/ true);
43248 case 41:
43249 // mul x, 41 => add ((shl (mul x, 5), 3), x)
43250 return combineMulShlAddOrSub(5, 3, /*isAdd*/ true);
43251 case 22:
43252 // mul x, 22 => add (add ((shl (mul x, 5), 2), x), x)
43253 return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
43254 combineMulShlAddOrSub(5, 2, /*isAdd*/ true));
43255 case 19:
43256 // mul x, 19 => add ((shl (mul x, 9), 1), x)
43257 return combineMulShlAddOrSub(9, 1, /*isAdd*/ true);
43258 case 37:
43259 // mul x, 37 => add ((shl (mul x, 9), 2), x)
43260 return combineMulShlAddOrSub(9, 2, /*isAdd*/ true);
43261 case 73:
43262 // mul x, 73 => add ((shl (mul x, 9), 3), x)
43263 return combineMulShlAddOrSub(9, 3, /*isAdd*/ true);
43264 case 13:
43265 // mul x, 13 => add ((shl (mul x, 3), 2), x)
43266 return combineMulShlAddOrSub(3, 2, /*isAdd*/ true);
43267 case 23:
43268 // mul x, 23 => sub ((shl (mul x, 3), 3), x)
43269 return combineMulShlAddOrSub(3, 3, /*isAdd*/ false);
43270 case 26:
43271 // mul x, 26 => add ((mul (mul x, 5), 5), x)
43272 return combineMulMulAddOrSub(5, 5, /*isAdd*/ true);
43273 case 28:
43274 // mul x, 28 => add ((mul (mul x, 9), 3), x)
43275 return combineMulMulAddOrSub(9, 3, /*isAdd*/ true);
43276 case 29:
43277 // mul x, 29 => add (add ((mul (mul x, 9), 3), x), x)
43278 return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
43279 combineMulMulAddOrSub(9, 3, /*isAdd*/ true));
43280 }
43281
43282 // Another trick. If this is a power 2 + 2/4/8, we can use a shift followed
43283 // by a single LEA.
43284 // First check if this a sum of two power of 2s because that's easy. Then
43285 // count how many zeros are up to the first bit.
43286 // TODO: We can do this even without LEA at a cost of two shifts and an add.
43287 if (isPowerOf2_64(MulAmt & (MulAmt - 1))) {
43288 unsigned ScaleShift = countTrailingZeros(MulAmt);
43289 if (ScaleShift >= 1 && ScaleShift < 4) {
43290 unsigned ShiftAmt = Log2_64((MulAmt & (MulAmt - 1)));
43291 SDValue Shift1 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
43292 DAG.getConstant(ShiftAmt, DL, MVT::i8));
43293 SDValue Shift2 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
43294 DAG.getConstant(ScaleShift, DL, MVT::i8));
43295 return DAG.getNode(ISD::ADD, DL, VT, Shift1, Shift2);
43296 }
43297 }
43298
43299 return SDValue();
43300}
43301
43302// If the upper 17 bits of each element are zero then we can use PMADDWD,
43303// which is always at least as quick as PMULLD, except on KNL.
43304static SDValue combineMulToPMADDWD(SDNode *N, SelectionDAG &DAG,
43305 const X86Subtarget &Subtarget) {
43306 if (!Subtarget.hasSSE2())
43307 return SDValue();
43308
43309 if (Subtarget.isPMADDWDSlow())
43310 return SDValue();
43311
43312 EVT VT = N->getValueType(0);
43313
43314 // Only support vXi32 vectors.
43315 if (!VT.isVector() || VT.getVectorElementType() != MVT::i32)
43316 return SDValue();
43317
43318 // Make sure the type is legal or will be widened to a legal type.
43319 if (VT != MVT::v2i32 && !DAG.getTargetLoweringInfo().isTypeLegal(VT))
43320 return SDValue();
43321
43322 MVT WVT = MVT::getVectorVT(MVT::i16, 2 * VT.getVectorNumElements());
43323
43324 // Without BWI, we would need to split v32i16.
43325 if (WVT == MVT::v32i16 && !Subtarget.hasBWI())
43326 return SDValue();
43327
43328 SDValue N0 = N->getOperand(0);
43329 SDValue N1 = N->getOperand(1);
43330
43331 // If we are zero extending two steps without SSE4.1, its better to reduce
43332 // the vmul width instead.
43333 if (!Subtarget.hasSSE41() &&
43334 (N0.getOpcode() == ISD::ZERO_EXTEND &&
43335 N0.getOperand(0).getScalarValueSizeInBits() <= 8) &&
43336 (N1.getOpcode() == ISD::ZERO_EXTEND &&
43337 N1.getOperand(0).getScalarValueSizeInBits() <= 8))
43338 return SDValue();
43339
43340 APInt Mask17 = APInt::getHighBitsSet(32, 17);
43341 if (!DAG.MaskedValueIsZero(N1, Mask17) ||
43342 !DAG.MaskedValueIsZero(N0, Mask17))
43343 return SDValue();
43344
43345 // Use SplitOpsAndApply to handle AVX splitting.
43346 auto PMADDWDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
43347 ArrayRef<SDValue> Ops) {
43348 MVT OpVT = MVT::getVectorVT(MVT::i32, Ops[0].getValueSizeInBits() / 32);
43349 return DAG.getNode(X86ISD::VPMADDWD, DL, OpVT, Ops);
43350 };
43351 return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT,
43352 { DAG.getBitcast(WVT, N0), DAG.getBitcast(WVT, N1) },
43353 PMADDWDBuilder);
43354}
43355
43356static SDValue combineMulToPMULDQ(SDNode *N, SelectionDAG &DAG,
43357 const X86Subtarget &Subtarget) {
43358 if (!Subtarget.hasSSE2())
43359 return SDValue();
43360
43361 EVT VT = N->getValueType(0);
43362
43363 // Only support vXi64 vectors.
43364 if (!VT.isVector() || VT.getVectorElementType() != MVT::i64 ||
43365 VT.getVectorNumElements() < 2 ||
43366 !isPowerOf2_32(VT.getVectorNumElements()))
43367 return SDValue();
43368
43369 SDValue N0 = N->getOperand(0);
43370 SDValue N1 = N->getOperand(1);
43371
43372 // MULDQ returns the 64-bit result of the signed multiplication of the lower
43373 // 32-bits. We can lower with this if the sign bits stretch that far.
43374 if (Subtarget.hasSSE41() && DAG.ComputeNumSignBits(N0) > 32 &&
43375 DAG.ComputeNumSignBits(N1) > 32) {
43376 auto PMULDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
43377 ArrayRef<SDValue> Ops) {
43378 return DAG.getNode(X86ISD::PMULDQ, DL, Ops[0].getValueType(), Ops);
43379 };
43380 return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { N0, N1 },
43381 PMULDQBuilder, /*CheckBWI*/false);
43382 }
43383
43384 // If the upper bits are zero we can use a single pmuludq.
43385 APInt Mask = APInt::getHighBitsSet(64, 32);
43386 if (DAG.MaskedValueIsZero(N0, Mask) && DAG.MaskedValueIsZero(N1, Mask)) {
43387 auto PMULUDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
43388 ArrayRef<SDValue> Ops) {
43389 return DAG.getNode(X86ISD::PMULUDQ, DL, Ops[0].getValueType(), Ops);
43390 };
43391 return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { N0, N1 },
43392 PMULUDQBuilder, /*CheckBWI*/false);
43393 }
43394
43395 return SDValue();
43396}
43397
43398/// Optimize a single multiply with constant into two operations in order to
43399/// implement it with two cheaper instructions, e.g. LEA + SHL, LEA + LEA.
43400static SDValue combineMul(SDNode *N, SelectionDAG &DAG,
43401 TargetLowering::DAGCombinerInfo &DCI,
43402 const X86Subtarget &Subtarget) {
43403 EVT VT = N->getValueType(0);
43404
43405 if (SDValue V = combineMulToPMADDWD(N, DAG, Subtarget))
43406 return V;
43407
43408 if (SDValue V = combineMulToPMULDQ(N, DAG, Subtarget))
43409 return V;
43410
43411 if (DCI.isBeforeLegalize() && VT.isVector())
43412 return reduceVMULWidth(N, DAG, Subtarget);
43413
43414 if (!MulConstantOptimization)
43415 return SDValue();
43416 // An imul is usually smaller than the alternative sequence.
43417 if (DAG.getMachineFunction().getFunction().hasMinSize())
43418 return SDValue();
43419
43420 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
43421 return SDValue();
43422
43423 if (VT != MVT::i64 && VT != MVT::i32)
43424 return SDValue();
43425
43426 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
43427 if (!C)
43428 return SDValue();
43429 if (isPowerOf2_64(C->getZExtValue()))
43430 return SDValue();
43431
43432 int64_t SignMulAmt = C->getSExtValue();
43433 assert(SignMulAmt != INT64_MIN && "Int min should have been handled!")(static_cast <bool> (SignMulAmt != (-9223372036854775807L
-1) && "Int min should have been handled!") ? void (
0) : __assert_fail ("SignMulAmt != INT64_MIN && \"Int min should have been handled!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 43433, __extension__ __PRETTY_FUNCTION__))
;
43434 uint64_t AbsMulAmt = SignMulAmt < 0 ? -SignMulAmt : SignMulAmt;
43435
43436 SDLoc DL(N);
43437 if (AbsMulAmt == 3 || AbsMulAmt == 5 || AbsMulAmt == 9) {
43438 SDValue NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
43439 DAG.getConstant(AbsMulAmt, DL, VT));
43440 if (SignMulAmt < 0)
43441 NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
43442 NewMul);
43443
43444 return NewMul;
43445 }
43446
43447 uint64_t MulAmt1 = 0;
43448 uint64_t MulAmt2 = 0;
43449 if ((AbsMulAmt % 9) == 0) {
43450 MulAmt1 = 9;
43451 MulAmt2 = AbsMulAmt / 9;
43452 } else if ((AbsMulAmt % 5) == 0) {
43453 MulAmt1 = 5;
43454 MulAmt2 = AbsMulAmt / 5;
43455 } else if ((AbsMulAmt % 3) == 0) {
43456 MulAmt1 = 3;
43457 MulAmt2 = AbsMulAmt / 3;
43458 }
43459
43460 SDValue NewMul;
43461 // For negative multiply amounts, only allow MulAmt2 to be a power of 2.
43462 if (MulAmt2 &&
43463 (isPowerOf2_64(MulAmt2) ||
43464 (SignMulAmt >= 0 && (MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)))) {
43465
43466 if (isPowerOf2_64(MulAmt2) &&
43467 !(SignMulAmt >= 0 && N->hasOneUse() &&
43468 N->use_begin()->getOpcode() == ISD::ADD))
43469 // If second multiplifer is pow2, issue it first. We want the multiply by
43470 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
43471 // is an add. Only do this for positive multiply amounts since the
43472 // negate would prevent it from being used as an address mode anyway.
43473 std::swap(MulAmt1, MulAmt2);
43474
43475 if (isPowerOf2_64(MulAmt1))
43476 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
43477 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
43478 else
43479 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
43480 DAG.getConstant(MulAmt1, DL, VT));
43481
43482 if (isPowerOf2_64(MulAmt2))
43483 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
43484 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
43485 else
43486 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
43487 DAG.getConstant(MulAmt2, DL, VT));
43488
43489 // Negate the result.
43490 if (SignMulAmt < 0)
43491 NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
43492 NewMul);
43493 } else if (!Subtarget.slowLEA())
43494 NewMul = combineMulSpecial(C->getZExtValue(), N, DAG, VT, DL);
43495
43496 if (!NewMul) {
43497 assert(C->getZExtValue() != 0 &&(static_cast <bool> (C->getZExtValue() != 0 &&
C->getZExtValue() != (VT == MVT::i64 ? (18446744073709551615UL
) : (4294967295U)) && "Both cases that could cause potential overflows should have "
"already been handled.") ? void (0) : __assert_fail ("C->getZExtValue() != 0 && C->getZExtValue() != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX) && \"Both cases that could cause potential overflows should have \" \"already been handled.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 43500, __extension__ __PRETTY_FUNCTION__))
43498 C->getZExtValue() != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX) &&(static_cast <bool> (C->getZExtValue() != 0 &&
C->getZExtValue() != (VT == MVT::i64 ? (18446744073709551615UL
) : (4294967295U)) && "Both cases that could cause potential overflows should have "
"already been handled.") ? void (0) : __assert_fail ("C->getZExtValue() != 0 && C->getZExtValue() != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX) && \"Both cases that could cause potential overflows should have \" \"already been handled.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 43500, __extension__ __PRETTY_FUNCTION__))
43499 "Both cases that could cause potential overflows should have "(static_cast <bool> (C->getZExtValue() != 0 &&
C->getZExtValue() != (VT == MVT::i64 ? (18446744073709551615UL
) : (4294967295U)) && "Both cases that could cause potential overflows should have "
"already been handled.") ? void (0) : __assert_fail ("C->getZExtValue() != 0 && C->getZExtValue() != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX) && \"Both cases that could cause potential overflows should have \" \"already been handled.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 43500, __extension__ __PRETTY_FUNCTION__))
43500 "already been handled.")(static_cast <bool> (C->getZExtValue() != 0 &&
C->getZExtValue() != (VT == MVT::i64 ? (18446744073709551615UL
) : (4294967295U)) && "Both cases that could cause potential overflows should have "
"already been handled.") ? void (0) : __assert_fail ("C->getZExtValue() != 0 && C->getZExtValue() != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX) && \"Both cases that could cause potential overflows should have \" \"already been handled.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 43500, __extension__ __PRETTY_FUNCTION__))
;
43501 if (isPowerOf2_64(AbsMulAmt - 1)) {
43502 // (mul x, 2^N + 1) => (add (shl x, N), x)
43503 NewMul = DAG.getNode(
43504 ISD::ADD, DL, VT, N->getOperand(0),
43505 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
43506 DAG.getConstant(Log2_64(AbsMulAmt - 1), DL,
43507 MVT::i8)));
43508 // To negate, subtract the number from zero
43509 if (SignMulAmt < 0)
43510 NewMul = DAG.getNode(ISD::SUB, DL, VT,
43511 DAG.getConstant(0, DL, VT), NewMul);
43512 } else if (isPowerOf2_64(AbsMulAmt + 1)) {
43513 // (mul x, 2^N - 1) => (sub (shl x, N), x)
43514 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
43515 DAG.getConstant(Log2_64(AbsMulAmt + 1),
43516 DL, MVT::i8));
43517 // To negate, reverse the operands of the subtract.
43518 if (SignMulAmt < 0)
43519 NewMul = DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), NewMul);
43520 else
43521 NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
43522 } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt - 2)) {
43523 // (mul x, 2^N + 2) => (add (add (shl x, N), x), x)
43524 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
43525 DAG.getConstant(Log2_64(AbsMulAmt - 2),
43526 DL, MVT::i8));
43527 NewMul = DAG.getNode(ISD::ADD, DL, VT, NewMul, N->getOperand(0));
43528 NewMul = DAG.getNode(ISD::ADD, DL, VT, NewMul, N->getOperand(0));
43529 } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt + 2)) {
43530 // (mul x, 2^N - 2) => (sub (sub (shl x, N), x), x)
43531 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
43532 DAG.getConstant(Log2_64(AbsMulAmt + 2),
43533 DL, MVT::i8));
43534 NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
43535 NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
43536 }
43537 }
43538
43539 return NewMul;
43540}
43541
43542// Try to form a MULHU or MULHS node by looking for
43543// (srl (mul ext, ext), 16)
43544// TODO: This is X86 specific because we want to be able to handle wide types
43545// before type legalization. But we can only do it if the vector will be
43546// legalized via widening/splitting. Type legalization can't handle promotion
43547// of a MULHU/MULHS. There isn't a way to convey this to the generic DAG
43548// combiner.
43549static SDValue combineShiftToPMULH(SDNode *N, SelectionDAG &DAG,
43550 const X86Subtarget &Subtarget) {
43551 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&(static_cast <bool> ((N->getOpcode() == ISD::SRL || N
->getOpcode() == ISD::SRA) && "SRL or SRA node is required here!"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && \"SRL or SRA node is required here!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 43552, __extension__ __PRETTY_FUNCTION__))
43552 "SRL or SRA node is required here!")(static_cast <bool> ((N->getOpcode() == ISD::SRL || N
->getOpcode() == ISD::SRA) && "SRL or SRA node is required here!"
) ? void (0) : __assert_fail ("(N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && \"SRL or SRA node is required here!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 43552, __extension__ __PRETTY_FUNCTION__))
;
43553 SDLoc DL(N);
43554
43555 // Only do this with SSE4.1. On earlier targets reduceVMULWidth will expand
43556 // the multiply.
43557 if (!Subtarget.hasSSE41())
43558 return SDValue();
43559
43560 // The operation feeding into the shift must be a multiply.
43561 SDValue ShiftOperand = N->getOperand(0);
43562 if (ShiftOperand.getOpcode() != ISD::MUL || !ShiftOperand.hasOneUse())
43563 return SDValue();
43564
43565 // Input type should be at least vXi32.
43566 EVT VT = N->getValueType(0);
43567 if (!VT.isVector() || VT.getVectorElementType().getSizeInBits() < 32)
43568 return SDValue();
43569
43570 // Need a shift by 16.
43571 APInt ShiftAmt;
43572 if (!ISD::isConstantSplatVector(N->getOperand(1).getNode(), ShiftAmt) ||
43573 ShiftAmt != 16)
43574 return SDValue();
43575
43576 SDValue LHS = ShiftOperand.getOperand(0);
43577 SDValue RHS = ShiftOperand.getOperand(1);
43578
43579 unsigned ExtOpc = LHS.getOpcode();
43580 if ((ExtOpc != ISD::SIGN_EXTEND && ExtOpc != ISD::ZERO_EXTEND) ||
43581 RHS.getOpcode() != ExtOpc)
43582 return SDValue();
43583
43584 // Peek through the extends.
43585 LHS = LHS.getOperand(0);
43586 RHS = RHS.getOperand(0);
43587
43588 // Ensure the input types match.
43589 EVT MulVT = LHS.getValueType();
43590 if (MulVT.getVectorElementType() != MVT::i16 || RHS.getValueType() != MulVT)
43591 return SDValue();
43592
43593 unsigned Opc = ExtOpc == ISD::SIGN_EXTEND ? ISD::MULHS : ISD::MULHU;
43594 SDValue Mulh = DAG.getNode(Opc, DL, MulVT, LHS, RHS);
43595
43596 ExtOpc = N->getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
43597 return DAG.getNode(ExtOpc, DL, VT, Mulh);
43598}
43599
43600static SDValue combineShiftLeft(SDNode *N, SelectionDAG &DAG) {
43601 SDValue N0 = N->getOperand(0);
43602 SDValue N1 = N->getOperand(1);
43603 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
43604 EVT VT = N0.getValueType();
43605
43606 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
43607 // since the result of setcc_c is all zero's or all ones.
43608 if (VT.isInteger() && !VT.isVector() &&
43609 N1C && N0.getOpcode() == ISD::AND &&
43610 N0.getOperand(1).getOpcode() == ISD::Constant) {
43611 SDValue N00 = N0.getOperand(0);
43612 APInt Mask = N0.getConstantOperandAPInt(1);
43613 Mask <<= N1C->getAPIntValue();
43614 bool MaskOK = false;
43615 // We can handle cases concerning bit-widening nodes containing setcc_c if
43616 // we carefully interrogate the mask to make sure we are semantics
43617 // preserving.
43618 // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
43619 // of the underlying setcc_c operation if the setcc_c was zero extended.
43620 // Consider the following example:
43621 // zext(setcc_c) -> i32 0x0000FFFF
43622 // c1 -> i32 0x0000FFFF
43623 // c2 -> i32 0x00000001
43624 // (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
43625 // (and setcc_c, (c1 << c2)) -> i32 0x0000FFFE
43626 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
43627 MaskOK = true;
43628 } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
43629 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
43630 MaskOK = true;
43631 } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
43632 N00.getOpcode() == ISD::ANY_EXTEND) &&
43633 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
43634 MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
43635 }
43636 if (MaskOK && Mask != 0) {
43637 SDLoc DL(N);
43638 return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
43639 }
43640 }
43641
43642 // Hardware support for vector shifts is sparse which makes us scalarize the
43643 // vector operations in many cases. Also, on sandybridge ADD is faster than
43644 // shl.
43645 // (shl V, 1) -> add V,V
43646 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
43647 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
43648 assert(N0.getValueType().isVector() && "Invalid vector shift type")(static_cast <bool> (N0.getValueType().isVector() &&
"Invalid vector shift type") ? void (0) : __assert_fail ("N0.getValueType().isVector() && \"Invalid vector shift type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 43648, __extension__ __PRETTY_FUNCTION__))
;
43649 // We shift all of the values by one. In many cases we do not have
43650 // hardware support for this operation. This is better expressed as an ADD
43651 // of two values.
43652 if (N1SplatC->isOne())
43653 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
43654 }
43655
43656 return SDValue();
43657}
43658
43659static SDValue combineShiftRightArithmetic(SDNode *N, SelectionDAG &DAG,
43660 const X86Subtarget &Subtarget) {
43661 SDValue N0 = N->getOperand(0);
43662 SDValue N1 = N->getOperand(1);
43663 EVT VT = N0.getValueType();
43664 unsigned Size = VT.getSizeInBits();
43665
43666 if (SDValue V = combineShiftToPMULH(N, DAG, Subtarget))
43667 return V;
43668
43669 // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
43670 // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
43671 // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
43672 // depending on sign of (SarConst - [56,48,32,24,16])
43673
43674 // sexts in X86 are MOVs. The MOVs have the same code size
43675 // as above SHIFTs (only SHIFT on 1 has lower code size).
43676 // However the MOVs have 2 advantages to a SHIFT:
43677 // 1. MOVs can write to a register that differs from source
43678 // 2. MOVs accept memory operands
43679
43680 if (VT.isVector() || N1.getOpcode() != ISD::Constant ||
43681 N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
43682 N0.getOperand(1).getOpcode() != ISD::Constant)
43683 return SDValue();
43684
43685 SDValue N00 = N0.getOperand(0);
43686 SDValue N01 = N0.getOperand(1);
43687 APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
43688 APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
43689 EVT CVT = N1.getValueType();
43690
43691 if (SarConst.isNegative())
43692 return SDValue();
43693
43694 for (MVT SVT : { MVT::i8, MVT::i16, MVT::i32 }) {
43695 unsigned ShiftSize = SVT.getSizeInBits();
43696 // skipping types without corresponding sext/zext and
43697 // ShlConst that is not one of [56,48,32,24,16]
43698 if (ShiftSize >= Size || ShlConst != Size - ShiftSize)
43699 continue;
43700 SDLoc DL(N);
43701 SDValue NN =
43702 DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
43703 SarConst = SarConst - (Size - ShiftSize);
43704 if (SarConst == 0)
43705 return NN;
43706 else if (SarConst.isNegative())
43707 return DAG.getNode(ISD::SHL, DL, VT, NN,
43708 DAG.getConstant(-SarConst, DL, CVT));
43709 else
43710 return DAG.getNode(ISD::SRA, DL, VT, NN,
43711 DAG.getConstant(SarConst, DL, CVT));
43712 }
43713 return SDValue();
43714}
43715
43716static SDValue combineShiftRightLogical(SDNode *N, SelectionDAG &DAG,
43717 TargetLowering::DAGCombinerInfo &DCI,
43718 const X86Subtarget &Subtarget) {
43719 SDValue N0 = N->getOperand(0);
43720 SDValue N1 = N->getOperand(1);
43721 EVT VT = N0.getValueType();
43722
43723 if (SDValue V = combineShiftToPMULH(N, DAG, Subtarget))
43724 return V;
43725
43726 // Only do this on the last DAG combine as it can interfere with other
43727 // combines.
43728 if (!DCI.isAfterLegalizeDAG())
43729 return SDValue();
43730
43731 // Try to improve a sequence of srl (and X, C1), C2 by inverting the order.
43732 // TODO: This is a generic DAG combine that became an x86-only combine to
43733 // avoid shortcomings in other folds such as bswap, bit-test ('bt'), and
43734 // and-not ('andn').
43735 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
43736 return SDValue();
43737
43738 auto *ShiftC = dyn_cast<ConstantSDNode>(N1);
43739 auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
43740 if (!ShiftC || !AndC)
43741 return SDValue();
43742
43743 // If we can shrink the constant mask below 8-bits or 32-bits, then this
43744 // transform should reduce code size. It may also enable secondary transforms
43745 // from improved known-bits analysis or instruction selection.
43746 APInt MaskVal = AndC->getAPIntValue();
43747
43748 // If this can be matched by a zero extend, don't optimize.
43749 if (MaskVal.isMask()) {
43750 unsigned TO = MaskVal.countTrailingOnes();
43751 if (TO >= 8 && isPowerOf2_32(TO))
43752 return SDValue();
43753 }
43754
43755 APInt NewMaskVal = MaskVal.lshr(ShiftC->getAPIntValue());
43756 unsigned OldMaskSize = MaskVal.getMinSignedBits();
43757 unsigned NewMaskSize = NewMaskVal.getMinSignedBits();
43758 if ((OldMaskSize > 8 && NewMaskSize <= 8) ||
43759 (OldMaskSize > 32 && NewMaskSize <= 32)) {
43760 // srl (and X, AndC), ShiftC --> and (srl X, ShiftC), (AndC >> ShiftC)
43761 SDLoc DL(N);
43762 SDValue NewMask = DAG.getConstant(NewMaskVal, DL, VT);
43763 SDValue NewShift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), N1);
43764 return DAG.getNode(ISD::AND, DL, VT, NewShift, NewMask);
43765 }
43766 return SDValue();
43767}
43768
43769static SDValue combineHorizOpWithShuffle(SDNode *N, SelectionDAG &DAG,
43770 const X86Subtarget &Subtarget) {
43771 unsigned Opcode = N->getOpcode();
43772 assert(isHorizOp(Opcode) && "Unexpected hadd/hsub/pack opcode")(static_cast <bool> (isHorizOp(Opcode) && "Unexpected hadd/hsub/pack opcode"
) ? void (0) : __assert_fail ("isHorizOp(Opcode) && \"Unexpected hadd/hsub/pack opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 43772, __extension__ __PRETTY_FUNCTION__))
;
43773
43774 SDLoc DL(N);
43775 EVT VT = N->getValueType(0);
43776 SDValue N0 = N->getOperand(0);
43777 SDValue N1 = N->getOperand(1);
43778 EVT SrcVT = N0.getValueType();
43779
43780 SDValue BC0 =
43781 N->isOnlyUserOf(N0.getNode()) ? peekThroughOneUseBitcasts(N0) : N0;
43782 SDValue BC1 =
43783 N->isOnlyUserOf(N1.getNode()) ? peekThroughOneUseBitcasts(N1) : N1;
43784
43785 // Attempt to fold HOP(LOSUBVECTOR(SHUFFLE(X)),HISUBVECTOR(SHUFFLE(X)))
43786 // to SHUFFLE(HOP(LOSUBVECTOR(X),HISUBVECTOR(X))), this is mainly for
43787 // truncation trees that help us avoid lane crossing shuffles.
43788 // TODO: There's a lot more we can do for PACK/HADD style shuffle combines.
43789 // TODO: We don't handle vXf64 shuffles yet.
43790 if (VT.is128BitVector() && SrcVT.getScalarSizeInBits() <= 32 &&
43791 BC0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
43792 BC1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
43793 BC0.getOperand(0) == BC1.getOperand(0) &&
43794 BC0.getOperand(0).getValueType().is256BitVector() &&
43795 BC0.getConstantOperandAPInt(1) == 0 &&
43796 BC1.getConstantOperandAPInt(1) ==
43797 BC0.getValueType().getVectorNumElements()) {
43798 SmallVector<SDValue> ShuffleOps;
43799 SmallVector<int> ShuffleMask, ScaledMask;
43800 SDValue Vec = peekThroughBitcasts(BC0.getOperand(0));
43801 if (getTargetShuffleInputs(Vec, ShuffleOps, ShuffleMask, DAG)) {
43802 resolveTargetShuffleInputsAndMask(ShuffleOps, ShuffleMask);
43803 // To keep the HOP LHS/RHS coherency, we must be able to scale the unary
43804 // shuffle to a v4X64 width - we can probably relax this in the future.
43805 if (!isAnyZero(ShuffleMask) && ShuffleOps.size() == 1 &&
43806 ShuffleOps[0].getValueType().is256BitVector() &&
43807 scaleShuffleElements(ShuffleMask, 4, ScaledMask)) {
43808 SDValue Lo, Hi;
43809 MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f32 : MVT::v4i32;
43810 std::tie(Lo, Hi) = DAG.SplitVector(ShuffleOps[0], DL);
43811 Lo = DAG.getBitcast(SrcVT, Lo);
43812 Hi = DAG.getBitcast(SrcVT, Hi);
43813 SDValue Res = DAG.getNode(Opcode, DL, VT, Lo, Hi);
43814 Res = DAG.getBitcast(ShufVT, Res);
43815 Res = DAG.getVectorShuffle(ShufVT, DL, Res, Res, ScaledMask);
43816 return DAG.getBitcast(VT, Res);
43817 }
43818 }
43819 }
43820
43821 // Attempt to fold HOP(SHUFFLE(X,Y),SHUFFLE(Z,W)) -> SHUFFLE(HOP()).
43822 if (VT.is128BitVector() && SrcVT.getScalarSizeInBits() <= 32) {
43823 // If either/both ops are a shuffle that can scale to v2x64,
43824 // then see if we can perform this as a v4x32 post shuffle.
43825 SmallVector<SDValue> Ops0, Ops1;
43826 SmallVector<int> Mask0, Mask1, ScaledMask0, ScaledMask1;
43827 bool IsShuf0 =
43828 getTargetShuffleInputs(BC0, Ops0, Mask0, DAG) && !isAnyZero(Mask0) &&
43829 scaleShuffleElements(Mask0, 2, ScaledMask0) &&
43830 all_of(Ops0, [](SDValue Op) { return Op.getValueSizeInBits() == 128; });
43831 bool IsShuf1 =
43832 getTargetShuffleInputs(BC1, Ops1, Mask1, DAG) && !isAnyZero(Mask1) &&
43833 scaleShuffleElements(Mask1, 2, ScaledMask1) &&
43834 all_of(Ops1, [](SDValue Op) { return Op.getValueSizeInBits() == 128; });
43835 if (IsShuf0 || IsShuf1) {
43836 if (!IsShuf0) {
43837 Ops0.assign({BC0});
43838 ScaledMask0.assign({0, 1});
43839 }
43840 if (!IsShuf1) {
43841 Ops1.assign({BC1});
43842 ScaledMask1.assign({0, 1});
43843 }
43844
43845 SDValue LHS, RHS;
43846 int PostShuffle[4] = {-1, -1, -1, -1};
43847 auto FindShuffleOpAndIdx = [&](int M, int &Idx, ArrayRef<SDValue> Ops) {
43848 if (M < 0)
43849 return true;
43850 Idx = M % 2;
43851 SDValue Src = Ops[M / 2];
43852 if (!LHS || LHS == Src) {
43853 LHS = Src;
43854 return true;
43855 }
43856 if (!RHS || RHS == Src) {
43857 Idx += 2;
43858 RHS = Src;
43859 return true;
43860 }
43861 return false;
43862 };
43863 if (FindShuffleOpAndIdx(ScaledMask0[0], PostShuffle[0], Ops0) &&
43864 FindShuffleOpAndIdx(ScaledMask0[1], PostShuffle[1], Ops0) &&
43865 FindShuffleOpAndIdx(ScaledMask1[0], PostShuffle[2], Ops1) &&
43866 FindShuffleOpAndIdx(ScaledMask1[1], PostShuffle[3], Ops1)) {
43867 LHS = DAG.getBitcast(SrcVT, LHS);
43868 RHS = DAG.getBitcast(SrcVT, RHS ? RHS : LHS);
43869 MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f32 : MVT::v4i32;
43870 SDValue Res = DAG.getNode(Opcode, DL, VT, LHS, RHS);
43871 Res = DAG.getBitcast(ShufVT, Res);
43872 Res = DAG.getVectorShuffle(ShufVT, DL, Res, Res, PostShuffle);
43873 return DAG.getBitcast(VT, Res);
43874 }
43875 }
43876 }
43877
43878 // Attempt to fold HOP(SHUFFLE(X,Y),SHUFFLE(X,Y)) -> SHUFFLE(HOP(X,Y)).
43879 if (VT.is256BitVector() && Subtarget.hasInt256()) {
43880 SmallVector<int> Mask0, Mask1;
43881 SmallVector<SDValue> Ops0, Ops1;
43882 SmallVector<int, 2> ScaledMask0, ScaledMask1;
43883 if (getTargetShuffleInputs(BC0, Ops0, Mask0, DAG) && !isAnyZero(Mask0) &&
43884 getTargetShuffleInputs(BC1, Ops1, Mask1, DAG) && !isAnyZero(Mask1) &&
43885 !Ops0.empty() && !Ops1.empty() &&
43886 all_of(Ops0,
43887 [](SDValue Op) { return Op.getValueType().is256BitVector(); }) &&
43888 all_of(Ops1,
43889 [](SDValue Op) { return Op.getValueType().is256BitVector(); }) &&
43890 scaleShuffleElements(Mask0, 2, ScaledMask0) &&
43891 scaleShuffleElements(Mask1, 2, ScaledMask1)) {
43892 SDValue Op00 = peekThroughBitcasts(Ops0.front());
43893 SDValue Op10 = peekThroughBitcasts(Ops1.front());
43894 SDValue Op01 = peekThroughBitcasts(Ops0.back());
43895 SDValue Op11 = peekThroughBitcasts(Ops1.back());
43896 if ((Op00 == Op11) && (Op01 == Op10)) {
43897 std::swap(Op10, Op11);
43898 ShuffleVectorSDNode::commuteMask(ScaledMask1);
43899 }
43900 if ((Op00 == Op10) && (Op01 == Op11)) {
43901 const int Map[4] = {0, 2, 1, 3};
43902 SmallVector<int, 4> ShuffleMask(
43903 {Map[ScaledMask0[0]], Map[ScaledMask1[0]], Map[ScaledMask0[1]],
43904 Map[ScaledMask1[1]]});
43905 MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f64 : MVT::v4i64;
43906 SDValue Res = DAG.getNode(Opcode, DL, VT, DAG.getBitcast(SrcVT, Op00),
43907 DAG.getBitcast(SrcVT, Op01));
43908 Res = DAG.getBitcast(ShufVT, Res);
43909 Res = DAG.getVectorShuffle(ShufVT, DL, Res, Res, ShuffleMask);
43910 return DAG.getBitcast(VT, Res);
43911 }
43912 }
43913 }
43914
43915 return SDValue();
43916}
43917
43918static SDValue combineVectorPack(SDNode *N, SelectionDAG &DAG,
43919 TargetLowering::DAGCombinerInfo &DCI,
43920 const X86Subtarget &Subtarget) {
43921 unsigned Opcode = N->getOpcode();
43922 assert((X86ISD::PACKSS == Opcode || X86ISD::PACKUS == Opcode) &&(static_cast <bool> ((X86ISD::PACKSS == Opcode || X86ISD
::PACKUS == Opcode) && "Unexpected pack opcode") ? void
(0) : __assert_fail ("(X86ISD::PACKSS == Opcode || X86ISD::PACKUS == Opcode) && \"Unexpected pack opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 43923, __extension__ __PRETTY_FUNCTION__))
43923 "Unexpected pack opcode")(static_cast <bool> ((X86ISD::PACKSS == Opcode || X86ISD
::PACKUS == Opcode) && "Unexpected pack opcode") ? void
(0) : __assert_fail ("(X86ISD::PACKSS == Opcode || X86ISD::PACKUS == Opcode) && \"Unexpected pack opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 43923, __extension__ __PRETTY_FUNCTION__))
;
43924
43925 EVT VT = N->getValueType(0);
43926 SDValue N0 = N->getOperand(0);
43927 SDValue N1 = N->getOperand(1);
43928 unsigned NumDstElts = VT.getVectorNumElements();
43929 unsigned DstBitsPerElt = VT.getScalarSizeInBits();
43930 unsigned SrcBitsPerElt = 2 * DstBitsPerElt;
43931 assert(N0.getScalarValueSizeInBits() == SrcBitsPerElt &&(static_cast <bool> (N0.getScalarValueSizeInBits() == SrcBitsPerElt
&& N1.getScalarValueSizeInBits() == SrcBitsPerElt &&
"Unexpected PACKSS/PACKUS input type") ? void (0) : __assert_fail
("N0.getScalarValueSizeInBits() == SrcBitsPerElt && N1.getScalarValueSizeInBits() == SrcBitsPerElt && \"Unexpected PACKSS/PACKUS input type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 43933, __extension__ __PRETTY_FUNCTION__))
43932 N1.getScalarValueSizeInBits() == SrcBitsPerElt &&(static_cast <bool> (N0.getScalarValueSizeInBits() == SrcBitsPerElt
&& N1.getScalarValueSizeInBits() == SrcBitsPerElt &&
"Unexpected PACKSS/PACKUS input type") ? void (0) : __assert_fail
("N0.getScalarValueSizeInBits() == SrcBitsPerElt && N1.getScalarValueSizeInBits() == SrcBitsPerElt && \"Unexpected PACKSS/PACKUS input type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 43933, __extension__ __PRETTY_FUNCTION__))
43933 "Unexpected PACKSS/PACKUS input type")(static_cast <bool> (N0.getScalarValueSizeInBits() == SrcBitsPerElt
&& N1.getScalarValueSizeInBits() == SrcBitsPerElt &&
"Unexpected PACKSS/PACKUS input type") ? void (0) : __assert_fail
("N0.getScalarValueSizeInBits() == SrcBitsPerElt && N1.getScalarValueSizeInBits() == SrcBitsPerElt && \"Unexpected PACKSS/PACKUS input type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 43933, __extension__ __PRETTY_FUNCTION__))
;
43934
43935 bool IsSigned = (X86ISD::PACKSS == Opcode);
43936
43937 // Constant Folding.
43938 APInt UndefElts0, UndefElts1;
43939 SmallVector<APInt, 32> EltBits0, EltBits1;
43940 if ((N0.isUndef() || N->isOnlyUserOf(N0.getNode())) &&
43941 (N1.isUndef() || N->isOnlyUserOf(N1.getNode())) &&
43942 getTargetConstantBitsFromNode(N0, SrcBitsPerElt, UndefElts0, EltBits0) &&
43943 getTargetConstantBitsFromNode(N1, SrcBitsPerElt, UndefElts1, EltBits1)) {
43944 unsigned NumLanes = VT.getSizeInBits() / 128;
43945 unsigned NumSrcElts = NumDstElts / 2;
43946 unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
43947 unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
43948
43949 APInt Undefs(NumDstElts, 0);
43950 SmallVector<APInt, 32> Bits(NumDstElts, APInt::getNullValue(DstBitsPerElt));
43951 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
43952 for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
43953 unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
43954 auto &UndefElts = (Elt >= NumSrcEltsPerLane ? UndefElts1 : UndefElts0);
43955 auto &EltBits = (Elt >= NumSrcEltsPerLane ? EltBits1 : EltBits0);
43956
43957 if (UndefElts[SrcIdx]) {
43958 Undefs.setBit(Lane * NumDstEltsPerLane + Elt);
43959 continue;
43960 }
43961
43962 APInt &Val = EltBits[SrcIdx];
43963 if (IsSigned) {
43964 // PACKSS: Truncate signed value with signed saturation.
43965 // Source values less than dst minint are saturated to minint.
43966 // Source values greater than dst maxint are saturated to maxint.
43967 if (Val.isSignedIntN(DstBitsPerElt))
43968 Val = Val.trunc(DstBitsPerElt);
43969 else if (Val.isNegative())
43970 Val = APInt::getSignedMinValue(DstBitsPerElt);
43971 else
43972 Val = APInt::getSignedMaxValue(DstBitsPerElt);
43973 } else {
43974 // PACKUS: Truncate signed value with unsigned saturation.
43975 // Source values less than zero are saturated to zero.
43976 // Source values greater than dst maxuint are saturated to maxuint.
43977 if (Val.isIntN(DstBitsPerElt))
43978 Val = Val.trunc(DstBitsPerElt);
43979 else if (Val.isNegative())
43980 Val = APInt::getNullValue(DstBitsPerElt);
43981 else
43982 Val = APInt::getAllOnesValue(DstBitsPerElt);
43983 }
43984 Bits[Lane * NumDstEltsPerLane + Elt] = Val;
43985 }
43986 }
43987
43988 return getConstVector(Bits, Undefs, VT.getSimpleVT(), DAG, SDLoc(N));
43989 }
43990
43991 // Try to fold PACK(SHUFFLE(),SHUFFLE()) -> SHUFFLE(PACK()).
43992 if (SDValue V = combineHorizOpWithShuffle(N, DAG, Subtarget))
43993 return V;
43994
43995 // Try to combine a PACKUSWB/PACKSSWB implemented truncate with a regular
43996 // truncate to create a larger truncate.
43997 if (Subtarget.hasAVX512() &&
43998 N0.getOpcode() == ISD::TRUNCATE && N1.isUndef() && VT == MVT::v16i8 &&
43999 N0.getOperand(0).getValueType() == MVT::v8i32) {
44000 if ((IsSigned && DAG.ComputeNumSignBits(N0) > 8) ||
44001 (!IsSigned &&
44002 DAG.MaskedValueIsZero(N0, APInt::getHighBitsSet(16, 8)))) {
44003 if (Subtarget.hasVLX())
44004 return DAG.getNode(X86ISD::VTRUNC, SDLoc(N), VT, N0.getOperand(0));
44005
44006 // Widen input to v16i32 so we can truncate that.
44007 SDLoc dl(N);
44008 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i32,
44009 N0.getOperand(0), DAG.getUNDEF(MVT::v8i32));
44010 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Concat);
44011 }
44012 }
44013
44014 // Try to fold PACK(EXTEND(X),EXTEND(Y)) -> CONCAT(X,Y) subvectors.
44015 if (VT.is128BitVector()) {
44016 unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
44017 SDValue Src0, Src1;
44018 if (N0.getOpcode() == ExtOpc &&
44019 N0.getOperand(0).getValueType().is64BitVector() &&
44020 N0.getOperand(0).getScalarValueSizeInBits() == DstBitsPerElt) {
44021 Src0 = N0.getOperand(0);
44022 }
44023 if (N1.getOpcode() == ExtOpc &&
44024 N1.getOperand(0).getValueType().is64BitVector() &&
44025 N1.getOperand(0).getScalarValueSizeInBits() == DstBitsPerElt) {
44026 Src1 = N1.getOperand(0);
44027 }
44028 if ((Src0 || N0.isUndef()) && (Src1 || N1.isUndef())) {
44029 assert((Src0 || Src1) && "Found PACK(UNDEF,UNDEF)")(static_cast <bool> ((Src0 || Src1) && "Found PACK(UNDEF,UNDEF)"
) ? void (0) : __assert_fail ("(Src0 || Src1) && \"Found PACK(UNDEF,UNDEF)\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44029, __extension__ __PRETTY_FUNCTION__))
;
44030 Src0 = Src0 ? Src0 : DAG.getUNDEF(Src1.getValueType());
44031 Src1 = Src1 ? Src1 : DAG.getUNDEF(Src0.getValueType());
44032 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Src0, Src1);
44033 }
44034 }
44035
44036 // Attempt to combine as shuffle.
44037 SDValue Op(N, 0);
44038 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
44039 return Res;
44040
44041 return SDValue();
44042}
44043
44044static SDValue combineVectorHADDSUB(SDNode *N, SelectionDAG &DAG,
44045 TargetLowering::DAGCombinerInfo &DCI,
44046 const X86Subtarget &Subtarget) {
44047 assert((X86ISD::HADD == N->getOpcode() || X86ISD::FHADD == N->getOpcode() ||(static_cast <bool> ((X86ISD::HADD == N->getOpcode()
|| X86ISD::FHADD == N->getOpcode() || X86ISD::HSUB == N->
getOpcode() || X86ISD::FHSUB == N->getOpcode()) &&
"Unexpected horizontal add/sub opcode") ? void (0) : __assert_fail
("(X86ISD::HADD == N->getOpcode() || X86ISD::FHADD == N->getOpcode() || X86ISD::HSUB == N->getOpcode() || X86ISD::FHSUB == N->getOpcode()) && \"Unexpected horizontal add/sub opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44049, __extension__ __PRETTY_FUNCTION__))
44048 X86ISD::HSUB == N->getOpcode() || X86ISD::FHSUB == N->getOpcode()) &&(static_cast <bool> ((X86ISD::HADD == N->getOpcode()
|| X86ISD::FHADD == N->getOpcode() || X86ISD::HSUB == N->
getOpcode() || X86ISD::FHSUB == N->getOpcode()) &&
"Unexpected horizontal add/sub opcode") ? void (0) : __assert_fail
("(X86ISD::HADD == N->getOpcode() || X86ISD::FHADD == N->getOpcode() || X86ISD::HSUB == N->getOpcode() || X86ISD::FHSUB == N->getOpcode()) && \"Unexpected horizontal add/sub opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44049, __extension__ __PRETTY_FUNCTION__))
44049 "Unexpected horizontal add/sub opcode")(static_cast <bool> ((X86ISD::HADD == N->getOpcode()
|| X86ISD::FHADD == N->getOpcode() || X86ISD::HSUB == N->
getOpcode() || X86ISD::FHSUB == N->getOpcode()) &&
"Unexpected horizontal add/sub opcode") ? void (0) : __assert_fail
("(X86ISD::HADD == N->getOpcode() || X86ISD::FHADD == N->getOpcode() || X86ISD::HSUB == N->getOpcode() || X86ISD::FHSUB == N->getOpcode()) && \"Unexpected horizontal add/sub opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44049, __extension__ __PRETTY_FUNCTION__))
;
44050
44051 if (!shouldUseHorizontalOp(true, DAG, Subtarget)) {
44052 // For slow-hop targets, if we have a hop with a single op, see if we already
44053 // have another user that we can reuse and shuffle the result.
44054 MVT VT = N->getSimpleValueType(0);
44055 SDValue LHS = N->getOperand(0);
44056 SDValue RHS = N->getOperand(1);
44057 if (VT.is128BitVector() && LHS == RHS) {
44058 for (SDNode *User : LHS->uses()) {
44059 if (User != N && User->getOpcode() == N->getOpcode()) {
44060 MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f32 : MVT::v4i32;
44061 if (User->getOperand(0) == LHS && !User->getOperand(1).isUndef()) {
44062 return DAG.getBitcast(
44063 VT,
44064 DAG.getVectorShuffle(ShufVT, SDLoc(N),
44065 DAG.getBitcast(ShufVT, SDValue(User, 0)),
44066 DAG.getUNDEF(ShufVT), {0, 1, 0, 1}));
44067 }
44068 if (User->getOperand(1) == LHS && !User->getOperand(0).isUndef()) {
44069 return DAG.getBitcast(
44070 VT,
44071 DAG.getVectorShuffle(ShufVT, SDLoc(N),
44072 DAG.getBitcast(ShufVT, SDValue(User, 0)),
44073 DAG.getUNDEF(ShufVT), {2, 3, 2, 3}));
44074 }
44075 }
44076 }
44077 }
44078
44079 // HOP(HOP'(X,X),HOP'(Y,Y)) -> HOP(PERMUTE(HOP'(X,Y)),PERMUTE(HOP'(X,Y)).
44080 if (LHS != RHS && LHS.getOpcode() == N->getOpcode() &&
44081 LHS.getOpcode() == RHS.getOpcode() &&
44082 LHS.getValueType() == RHS.getValueType()) {
44083 SDValue LHS0 = LHS.getOperand(0);
44084 SDValue RHS0 = LHS.getOperand(1);
44085 SDValue LHS1 = RHS.getOperand(0);
44086 SDValue RHS1 = RHS.getOperand(1);
44087 if ((LHS0 == RHS0 || LHS0.isUndef() || RHS0.isUndef()) &&
44088 (LHS1 == RHS1 || LHS1.isUndef() || RHS1.isUndef())) {
44089 SDLoc DL(N);
44090 SDValue Res = DAG.getNode(LHS.getOpcode(), DL, LHS.getValueType(),
44091 LHS0.isUndef() ? RHS0 : LHS0,
44092 LHS1.isUndef() ? RHS1 : LHS1);
44093 MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
44094 Res = DAG.getBitcast(ShufVT, Res);
44095 SDValue NewLHS =
44096 DAG.getNode(X86ISD::PSHUFD, DL, ShufVT, Res,
44097 getV4X86ShuffleImm8ForMask({0, 1, 0, 1}, DL, DAG));
44098 SDValue NewRHS =
44099 DAG.getNode(X86ISD::PSHUFD, DL, ShufVT, Res,
44100 getV4X86ShuffleImm8ForMask({2, 3, 2, 3}, DL, DAG));
44101 DAG.ReplaceAllUsesOfValueWith(LHS, DAG.getBitcast(VT, NewLHS));
44102 DAG.ReplaceAllUsesOfValueWith(RHS, DAG.getBitcast(VT, NewRHS));
44103 return SDValue(N, 0);
44104 }
44105 }
44106 }
44107
44108 // Try to fold HOP(SHUFFLE(),SHUFFLE()) -> SHUFFLE(HOP()).
44109 if (SDValue V = combineHorizOpWithShuffle(N, DAG, Subtarget))
44110 return V;
44111
44112 return SDValue();
44113}
44114
44115static SDValue combineVectorShiftVar(SDNode *N, SelectionDAG &DAG,
44116 TargetLowering::DAGCombinerInfo &DCI,
44117 const X86Subtarget &Subtarget) {
44118 assert((X86ISD::VSHL == N->getOpcode() || X86ISD::VSRA == N->getOpcode() ||(static_cast <bool> ((X86ISD::VSHL == N->getOpcode()
|| X86ISD::VSRA == N->getOpcode() || X86ISD::VSRL == N->
getOpcode()) && "Unexpected shift opcode") ? void (0)
: __assert_fail ("(X86ISD::VSHL == N->getOpcode() || X86ISD::VSRA == N->getOpcode() || X86ISD::VSRL == N->getOpcode()) && \"Unexpected shift opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44120, __extension__ __PRETTY_FUNCTION__))
44119 X86ISD::VSRL == N->getOpcode()) &&(static_cast <bool> ((X86ISD::VSHL == N->getOpcode()
|| X86ISD::VSRA == N->getOpcode() || X86ISD::VSRL == N->
getOpcode()) && "Unexpected shift opcode") ? void (0)
: __assert_fail ("(X86ISD::VSHL == N->getOpcode() || X86ISD::VSRA == N->getOpcode() || X86ISD::VSRL == N->getOpcode()) && \"Unexpected shift opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44120, __extension__ __PRETTY_FUNCTION__))
44120 "Unexpected shift opcode")(static_cast <bool> ((X86ISD::VSHL == N->getOpcode()
|| X86ISD::VSRA == N->getOpcode() || X86ISD::VSRL == N->
getOpcode()) && "Unexpected shift opcode") ? void (0)
: __assert_fail ("(X86ISD::VSHL == N->getOpcode() || X86ISD::VSRA == N->getOpcode() || X86ISD::VSRL == N->getOpcode()) && \"Unexpected shift opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44120, __extension__ __PRETTY_FUNCTION__))
;
44121 EVT VT = N->getValueType(0);
44122 SDValue N0 = N->getOperand(0);
44123 SDValue N1 = N->getOperand(1);
44124
44125 // Shift zero -> zero.
44126 if (ISD::isBuildVectorAllZeros(N0.getNode()))
44127 return DAG.getConstant(0, SDLoc(N), VT);
44128
44129 // Detect constant shift amounts.
44130 APInt UndefElts;
44131 SmallVector<APInt, 32> EltBits;
44132 if (getTargetConstantBitsFromNode(N1, 64, UndefElts, EltBits, true, false)) {
44133 unsigned X86Opc = getTargetVShiftUniformOpcode(N->getOpcode(), false);
44134 return getTargetVShiftByConstNode(X86Opc, SDLoc(N), VT.getSimpleVT(), N0,
44135 EltBits[0].getZExtValue(), DAG);
44136 }
44137
44138 APInt KnownUndef, KnownZero;
44139 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44140 APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
44141 if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, KnownUndef,
44142 KnownZero, DCI))
44143 return SDValue(N, 0);
44144
44145 return SDValue();
44146}
44147
44148static SDValue combineVectorShiftImm(SDNode *N, SelectionDAG &DAG,
44149 TargetLowering::DAGCombinerInfo &DCI,
44150 const X86Subtarget &Subtarget) {
44151 unsigned Opcode = N->getOpcode();
44152 assert((X86ISD::VSHLI == Opcode || X86ISD::VSRAI == Opcode ||(static_cast <bool> ((X86ISD::VSHLI == Opcode || X86ISD
::VSRAI == Opcode || X86ISD::VSRLI == Opcode) && "Unexpected shift opcode"
) ? void (0) : __assert_fail ("(X86ISD::VSHLI == Opcode || X86ISD::VSRAI == Opcode || X86ISD::VSRLI == Opcode) && \"Unexpected shift opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44154, __extension__ __PRETTY_FUNCTION__))
44153 X86ISD::VSRLI == Opcode) &&(static_cast <bool> ((X86ISD::VSHLI == Opcode || X86ISD
::VSRAI == Opcode || X86ISD::VSRLI == Opcode) && "Unexpected shift opcode"
) ? void (0) : __assert_fail ("(X86ISD::VSHLI == Opcode || X86ISD::VSRAI == Opcode || X86ISD::VSRLI == Opcode) && \"Unexpected shift opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44154, __extension__ __PRETTY_FUNCTION__))
44154 "Unexpected shift opcode")(static_cast <bool> ((X86ISD::VSHLI == Opcode || X86ISD
::VSRAI == Opcode || X86ISD::VSRLI == Opcode) && "Unexpected shift opcode"
) ? void (0) : __assert_fail ("(X86ISD::VSHLI == Opcode || X86ISD::VSRAI == Opcode || X86ISD::VSRLI == Opcode) && \"Unexpected shift opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44154, __extension__ __PRETTY_FUNCTION__))
;
44155 bool LogicalShift = X86ISD::VSHLI == Opcode || X86ISD::VSRLI == Opcode;
44156 EVT VT = N->getValueType(0);
44157 SDValue N0 = N->getOperand(0);
44158 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
44159 assert(VT == N0.getValueType() && (NumBitsPerElt % 8) == 0 &&(static_cast <bool> (VT == N0.getValueType() &&
(NumBitsPerElt % 8) == 0 && "Unexpected value type")
? void (0) : __assert_fail ("VT == N0.getValueType() && (NumBitsPerElt % 8) == 0 && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44160, __extension__ __PRETTY_FUNCTION__))
44160 "Unexpected value type")(static_cast <bool> (VT == N0.getValueType() &&
(NumBitsPerElt % 8) == 0 && "Unexpected value type")
? void (0) : __assert_fail ("VT == N0.getValueType() && (NumBitsPerElt % 8) == 0 && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44160, __extension__ __PRETTY_FUNCTION__))
;
44161 assert(N->getOperand(1).getValueType() == MVT::i8 &&(static_cast <bool> (N->getOperand(1).getValueType()
== MVT::i8 && "Unexpected shift amount type") ? void
(0) : __assert_fail ("N->getOperand(1).getValueType() == MVT::i8 && \"Unexpected shift amount type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44162, __extension__ __PRETTY_FUNCTION__))
44162 "Unexpected shift amount type")(static_cast <bool> (N->getOperand(1).getValueType()
== MVT::i8 && "Unexpected shift amount type") ? void
(0) : __assert_fail ("N->getOperand(1).getValueType() == MVT::i8 && \"Unexpected shift amount type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44162, __extension__ __PRETTY_FUNCTION__))
;
44163
44164 // (shift undef, X) -> 0
44165 if (N0.isUndef())
44166 return DAG.getConstant(0, SDLoc(N), VT);
44167
44168 // Out of range logical bit shifts are guaranteed to be zero.
44169 // Out of range arithmetic bit shifts splat the sign bit.
44170 unsigned ShiftVal = N->getConstantOperandVal(1);
44171 if (ShiftVal >= NumBitsPerElt) {
44172 if (LogicalShift)
44173 return DAG.getConstant(0, SDLoc(N), VT);
44174 ShiftVal = NumBitsPerElt - 1;
44175 }
44176
44177 // (shift X, 0) -> X
44178 if (!ShiftVal)
44179 return N0;
44180
44181 // (shift 0, C) -> 0
44182 if (ISD::isBuildVectorAllZeros(N0.getNode()))
44183 // N0 is all zeros or undef. We guarantee that the bits shifted into the
44184 // result are all zeros, not undef.
44185 return DAG.getConstant(0, SDLoc(N), VT);
44186
44187 // (VSRAI -1, C) -> -1
44188 if (!LogicalShift && ISD::isBuildVectorAllOnes(N0.getNode()))
44189 // N0 is all ones or undef. We guarantee that the bits shifted into the
44190 // result are all ones, not undef.
44191 return DAG.getConstant(-1, SDLoc(N), VT);
44192
44193 // (shift (shift X, C2), C1) -> (shift X, (C1 + C2))
44194 if (Opcode == N0.getOpcode()) {
44195 unsigned ShiftVal2 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
44196 unsigned NewShiftVal = ShiftVal + ShiftVal2;
44197 if (NewShiftVal >= NumBitsPerElt) {
44198 // Out of range logical bit shifts are guaranteed to be zero.
44199 // Out of range arithmetic bit shifts splat the sign bit.
44200 if (LogicalShift)
44201 return DAG.getConstant(0, SDLoc(N), VT);
44202 NewShiftVal = NumBitsPerElt - 1;
44203 }
44204 return DAG.getNode(Opcode, SDLoc(N), VT, N0.getOperand(0),
44205 DAG.getTargetConstant(NewShiftVal, SDLoc(N), MVT::i8));
44206 }
44207
44208 // We can decode 'whole byte' logical bit shifts as shuffles.
44209 if (LogicalShift && (ShiftVal % 8) == 0) {
44210 SDValue Op(N, 0);
44211 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
44212 return Res;
44213 }
44214
44215 // Constant Folding.
44216 APInt UndefElts;
44217 SmallVector<APInt, 32> EltBits;
44218 if (N->isOnlyUserOf(N0.getNode()) &&
44219 getTargetConstantBitsFromNode(N0, NumBitsPerElt, UndefElts, EltBits)) {
44220 assert(EltBits.size() == VT.getVectorNumElements() &&(static_cast <bool> (EltBits.size() == VT.getVectorNumElements
() && "Unexpected shift value type") ? void (0) : __assert_fail
("EltBits.size() == VT.getVectorNumElements() && \"Unexpected shift value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44221, __extension__ __PRETTY_FUNCTION__))
44221 "Unexpected shift value type")(static_cast <bool> (EltBits.size() == VT.getVectorNumElements
() && "Unexpected shift value type") ? void (0) : __assert_fail
("EltBits.size() == VT.getVectorNumElements() && \"Unexpected shift value type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44221, __extension__ __PRETTY_FUNCTION__))
;
44222 // Undef elements need to fold to 0. It's possible SimplifyDemandedBits
44223 // created an undef input due to no input bits being demanded, but user
44224 // still expects 0 in other bits.
44225 for (unsigned i = 0, e = EltBits.size(); i != e; ++i) {
44226 APInt &Elt = EltBits[i];
44227 if (UndefElts[i])
44228 Elt = 0;
44229 else if (X86ISD::VSHLI == Opcode)
44230 Elt <<= ShiftVal;
44231 else if (X86ISD::VSRAI == Opcode)
44232 Elt.ashrInPlace(ShiftVal);
44233 else
44234 Elt.lshrInPlace(ShiftVal);
44235 }
44236 // Reset undef elements since they were zeroed above.
44237 UndefElts = 0;
44238 return getConstVector(EltBits, UndefElts, VT.getSimpleVT(), DAG, SDLoc(N));
44239 }
44240
44241 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44242 if (TLI.SimplifyDemandedBits(SDValue(N, 0),
44243 APInt::getAllOnesValue(NumBitsPerElt), DCI))
44244 return SDValue(N, 0);
44245
44246 return SDValue();
44247}
44248
44249static SDValue combineVectorInsert(SDNode *N, SelectionDAG &DAG,
44250 TargetLowering::DAGCombinerInfo &DCI,
44251 const X86Subtarget &Subtarget) {
44252 EVT VT = N->getValueType(0);
44253 assert(((N->getOpcode() == X86ISD::PINSRB && VT == MVT::v16i8) ||(static_cast <bool> (((N->getOpcode() == X86ISD::PINSRB
&& VT == MVT::v16i8) || (N->getOpcode() == X86ISD
::PINSRW && VT == MVT::v8i16) || N->getOpcode() ==
ISD::INSERT_VECTOR_ELT) && "Unexpected vector insertion"
) ? void (0) : __assert_fail ("((N->getOpcode() == X86ISD::PINSRB && VT == MVT::v16i8) || (N->getOpcode() == X86ISD::PINSRW && VT == MVT::v8i16) || N->getOpcode() == ISD::INSERT_VECTOR_ELT) && \"Unexpected vector insertion\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44256, __extension__ __PRETTY_FUNCTION__))
44254 (N->getOpcode() == X86ISD::PINSRW && VT == MVT::v8i16) ||(static_cast <bool> (((N->getOpcode() == X86ISD::PINSRB
&& VT == MVT::v16i8) || (N->getOpcode() == X86ISD
::PINSRW && VT == MVT::v8i16) || N->getOpcode() ==
ISD::INSERT_VECTOR_ELT) && "Unexpected vector insertion"
) ? void (0) : __assert_fail ("((N->getOpcode() == X86ISD::PINSRB && VT == MVT::v16i8) || (N->getOpcode() == X86ISD::PINSRW && VT == MVT::v8i16) || N->getOpcode() == ISD::INSERT_VECTOR_ELT) && \"Unexpected vector insertion\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44256, __extension__ __PRETTY_FUNCTION__))
44255 N->getOpcode() == ISD::INSERT_VECTOR_ELT) &&(static_cast <bool> (((N->getOpcode() == X86ISD::PINSRB
&& VT == MVT::v16i8) || (N->getOpcode() == X86ISD
::PINSRW && VT == MVT::v8i16) || N->getOpcode() ==
ISD::INSERT_VECTOR_ELT) && "Unexpected vector insertion"
) ? void (0) : __assert_fail ("((N->getOpcode() == X86ISD::PINSRB && VT == MVT::v16i8) || (N->getOpcode() == X86ISD::PINSRW && VT == MVT::v8i16) || N->getOpcode() == ISD::INSERT_VECTOR_ELT) && \"Unexpected vector insertion\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44256, __extension__ __PRETTY_FUNCTION__))
44256 "Unexpected vector insertion")(static_cast <bool> (((N->getOpcode() == X86ISD::PINSRB
&& VT == MVT::v16i8) || (N->getOpcode() == X86ISD
::PINSRW && VT == MVT::v8i16) || N->getOpcode() ==
ISD::INSERT_VECTOR_ELT) && "Unexpected vector insertion"
) ? void (0) : __assert_fail ("((N->getOpcode() == X86ISD::PINSRB && VT == MVT::v16i8) || (N->getOpcode() == X86ISD::PINSRW && VT == MVT::v8i16) || N->getOpcode() == ISD::INSERT_VECTOR_ELT) && \"Unexpected vector insertion\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44256, __extension__ __PRETTY_FUNCTION__))
;
44257
44258 if (N->getOpcode() == X86ISD::PINSRB || N->getOpcode() == X86ISD::PINSRW) {
44259 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
44260 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44261 if (TLI.SimplifyDemandedBits(SDValue(N, 0),
44262 APInt::getAllOnesValue(NumBitsPerElt), DCI))
44263 return SDValue(N, 0);
44264 }
44265
44266 // Attempt to combine insertion patterns to a shuffle.
44267 if (VT.isSimple() && DCI.isAfterLegalizeDAG()) {
44268 SDValue Op(N, 0);
44269 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
44270 return Res;
44271 }
44272
44273 return SDValue();
44274}
44275
44276/// Recognize the distinctive (AND (setcc ...) (setcc ..)) where both setccs
44277/// reference the same FP CMP, and rewrite for CMPEQSS and friends. Likewise for
44278/// OR -> CMPNEQSS.
44279static SDValue combineCompareEqual(SDNode *N, SelectionDAG &DAG,
44280 TargetLowering::DAGCombinerInfo &DCI,
44281 const X86Subtarget &Subtarget) {
44282 unsigned opcode;
44283
44284 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
44285 // we're requiring SSE2 for both.
44286 if (Subtarget.hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
44287 SDValue N0 = N->getOperand(0);
44288 SDValue N1 = N->getOperand(1);
44289 SDValue CMP0 = N0.getOperand(1);
44290 SDValue CMP1 = N1.getOperand(1);
44291 SDLoc DL(N);
44292
44293 // The SETCCs should both refer to the same CMP.
44294 if (CMP0.getOpcode() != X86ISD::FCMP || CMP0 != CMP1)
44295 return SDValue();
44296
44297 SDValue CMP00 = CMP0->getOperand(0);
44298 SDValue CMP01 = CMP0->getOperand(1);
44299 EVT VT = CMP00.getValueType();
44300
44301 if (VT == MVT::f32 || VT == MVT::f64) {
44302 bool ExpectingFlags = false;
44303 // Check for any users that want flags:
44304 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
44305 !ExpectingFlags && UI != UE; ++UI)
44306 switch (UI->getOpcode()) {
44307 default:
44308 case ISD::BR_CC:
44309 case ISD::BRCOND:
44310 case ISD::SELECT:
44311 ExpectingFlags = true;
44312 break;
44313 case ISD::CopyToReg:
44314 case ISD::SIGN_EXTEND:
44315 case ISD::ZERO_EXTEND:
44316 case ISD::ANY_EXTEND:
44317 break;
44318 }
44319
44320 if (!ExpectingFlags) {
44321 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
44322 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
44323
44324 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
44325 X86::CondCode tmp = cc0;
44326 cc0 = cc1;
44327 cc1 = tmp;
44328 }
44329
44330 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
44331 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
44332 // FIXME: need symbolic constants for these magic numbers.
44333 // See X86ATTInstPrinter.cpp:printSSECC().
44334 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
44335 if (Subtarget.hasAVX512()) {
44336 SDValue FSetCC =
44337 DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CMP00, CMP01,
44338 DAG.getTargetConstant(x86cc, DL, MVT::i8));
44339 // Need to fill with zeros to ensure the bitcast will produce zeroes
44340 // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
44341 SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v16i1,
44342 DAG.getConstant(0, DL, MVT::v16i1),
44343 FSetCC, DAG.getIntPtrConstant(0, DL));
44344 return DAG.getZExtOrTrunc(DAG.getBitcast(MVT::i16, Ins), DL,
44345 N->getSimpleValueType(0));
44346 }
44347 SDValue OnesOrZeroesF =
44348 DAG.getNode(X86ISD::FSETCC, DL, CMP00.getValueType(), CMP00,
44349 CMP01, DAG.getTargetConstant(x86cc, DL, MVT::i8));
44350
44351 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
44352 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
44353
44354 if (is64BitFP && !Subtarget.is64Bit()) {
44355 // On a 32-bit target, we cannot bitcast the 64-bit float to a
44356 // 64-bit integer, since that's not a legal type. Since
44357 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
44358 // bits, but can do this little dance to extract the lowest 32 bits
44359 // and work with those going forward.
44360 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
44361 OnesOrZeroesF);
44362 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
44363 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
44364 Vector32, DAG.getIntPtrConstant(0, DL));
44365 IntVT = MVT::i32;
44366 }
44367
44368 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
44369 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
44370 DAG.getConstant(1, DL, IntVT));
44371 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
44372 ANDed);
44373 return OneBitOfTruth;
44374 }
44375 }
44376 }
44377 }
44378 return SDValue();
44379}
44380
44381/// Try to fold: (and (xor X, -1), Y) -> (andnp X, Y).
44382static SDValue combineANDXORWithAllOnesIntoANDNP(SDNode *N, SelectionDAG &DAG) {
44383 assert(N->getOpcode() == ISD::AND)(static_cast <bool> (N->getOpcode() == ISD::AND) ? void
(0) : __assert_fail ("N->getOpcode() == ISD::AND", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44383, __extension__ __PRETTY_FUNCTION__))
;
44384
44385 MVT VT = N->getSimpleValueType(0);
44386 if (!VT.is128BitVector() && !VT.is256BitVector() && !VT.is512BitVector())
44387 return SDValue();
44388
44389 SDValue X, Y;
44390 SDValue N0 = N->getOperand(0);
44391 SDValue N1 = N->getOperand(1);
44392
44393 auto GetNot = [&VT, &DAG](SDValue V) {
44394 // Basic X = NOT(Y) detection.
44395 if (SDValue Not = IsNOT(V, DAG))
44396 return Not;
44397 // Fold BROADCAST(NOT(Y)) -> BROADCAST(Y).
44398 if (V.getOpcode() == X86ISD::VBROADCAST) {
44399 SDValue Src = V.getOperand(0);
44400 EVT SrcVT = Src.getValueType();
44401 if (!SrcVT.isVector())
44402 return SDValue();
44403 if (SDValue Not = IsNOT(Src, DAG))
44404 return DAG.getNode(X86ISD::VBROADCAST, SDLoc(V), VT,
44405 DAG.getBitcast(SrcVT, Not));
44406 }
44407 return SDValue();
44408 };
44409
44410 if (SDValue Not = GetNot(N0)) {
44411 X = Not;
44412 Y = N1;
44413 } else if (SDValue Not = GetNot(N1)) {
44414 X = Not;
44415 Y = N0;
44416 } else
44417 return SDValue();
44418
44419 X = DAG.getBitcast(VT, X);
44420 Y = DAG.getBitcast(VT, Y);
44421 return DAG.getNode(X86ISD::ANDNP, SDLoc(N), VT, X, Y);
44422}
44423
44424// Try to widen AND, OR and XOR nodes to VT in order to remove casts around
44425// logical operations, like in the example below.
44426// or (and (truncate x, truncate y)),
44427// (xor (truncate z, build_vector (constants)))
44428// Given a target type \p VT, we generate
44429// or (and x, y), (xor z, zext(build_vector (constants)))
44430// given x, y and z are of type \p VT. We can do so, if operands are either
44431// truncates from VT types, the second operand is a vector of constants or can
44432// be recursively promoted.
44433static SDValue PromoteMaskArithmetic(SDNode *N, EVT VT, SelectionDAG &DAG,
44434 unsigned Depth) {
44435 // Limit recursion to avoid excessive compile times.
44436 if (Depth >= SelectionDAG::MaxRecursionDepth)
44437 return SDValue();
44438
44439 if (N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND &&
44440 N->getOpcode() != ISD::OR)
44441 return SDValue();
44442
44443 SDValue N0 = N->getOperand(0);
44444 SDValue N1 = N->getOperand(1);
44445 SDLoc DL(N);
44446
44447 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44448 if (!TLI.isOperationLegalOrPromote(N->getOpcode(), VT))
44449 return SDValue();
44450
44451 if (SDValue NN0 = PromoteMaskArithmetic(N0.getNode(), VT, DAG, Depth + 1))
44452 N0 = NN0;
44453 else {
44454 // The Left side has to be a trunc.
44455 if (N0.getOpcode() != ISD::TRUNCATE)
44456 return SDValue();
44457
44458 // The type of the truncated inputs.
44459 if (N0.getOperand(0).getValueType() != VT)
44460 return SDValue();
44461
44462 N0 = N0.getOperand(0);
44463 }
44464
44465 if (SDValue NN1 = PromoteMaskArithmetic(N1.getNode(), VT, DAG, Depth + 1))
44466 N1 = NN1;
44467 else {
44468 // The right side has to be a 'trunc' or a constant vector.
44469 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE &&
44470 N1.getOperand(0).getValueType() == VT;
44471 if (!RHSTrunc && !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()))
44472 return SDValue();
44473
44474 if (RHSTrunc)
44475 N1 = N1.getOperand(0);
44476 else
44477 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N1);
44478 }
44479
44480 return DAG.getNode(N->getOpcode(), DL, VT, N0, N1);
44481}
44482
44483// On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
44484// register. In most cases we actually compare or select YMM-sized registers
44485// and mixing the two types creates horrible code. This method optimizes
44486// some of the transition sequences.
44487// Even with AVX-512 this is still useful for removing casts around logical
44488// operations on vXi1 mask types.
44489static SDValue PromoteMaskArithmetic(SDNode *N, SelectionDAG &DAG,
44490 const X86Subtarget &Subtarget) {
44491 EVT VT = N->getValueType(0);
44492 assert(VT.isVector() && "Expected vector type")(static_cast <bool> (VT.isVector() && "Expected vector type"
) ? void (0) : __assert_fail ("VT.isVector() && \"Expected vector type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44492, __extension__ __PRETTY_FUNCTION__))
;
44493
44494 SDLoc DL(N);
44495 assert((N->getOpcode() == ISD::ANY_EXTEND ||(static_cast <bool> ((N->getOpcode() == ISD::ANY_EXTEND
|| N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode(
) == ISD::SIGN_EXTEND) && "Invalid Node") ? void (0) :
__assert_fail ("(N->getOpcode() == ISD::ANY_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::SIGN_EXTEND) && \"Invalid Node\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44497, __extension__ __PRETTY_FUNCTION__))
44496 N->getOpcode() == ISD::ZERO_EXTEND ||(static_cast <bool> ((N->getOpcode() == ISD::ANY_EXTEND
|| N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode(
) == ISD::SIGN_EXTEND) && "Invalid Node") ? void (0) :
__assert_fail ("(N->getOpcode() == ISD::ANY_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::SIGN_EXTEND) && \"Invalid Node\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44497, __extension__ __PRETTY_FUNCTION__))
44497 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node")(static_cast <bool> ((N->getOpcode() == ISD::ANY_EXTEND
|| N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode(
) == ISD::SIGN_EXTEND) && "Invalid Node") ? void (0) :
__assert_fail ("(N->getOpcode() == ISD::ANY_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::SIGN_EXTEND) && \"Invalid Node\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44497, __extension__ __PRETTY_FUNCTION__))
;
44498
44499 SDValue Narrow = N->getOperand(0);
44500 EVT NarrowVT = Narrow.getValueType();
44501
44502 // Generate the wide operation.
44503 SDValue Op = PromoteMaskArithmetic(Narrow.getNode(), VT, DAG, 0);
44504 if (!Op)
44505 return SDValue();
44506 switch (N->getOpcode()) {
44507 default: llvm_unreachable("Unexpected opcode")::llvm::llvm_unreachable_internal("Unexpected opcode", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44507)
;
44508 case ISD::ANY_EXTEND:
44509 return Op;
44510 case ISD::ZERO_EXTEND:
44511 return DAG.getZeroExtendInReg(Op, DL, NarrowVT);
44512 case ISD::SIGN_EXTEND:
44513 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
44514 Op, DAG.getValueType(NarrowVT));
44515 }
44516}
44517
44518static unsigned convertIntLogicToFPLogicOpcode(unsigned Opcode) {
44519 unsigned FPOpcode;
44520 switch (Opcode) {
44521 default: llvm_unreachable("Unexpected input node for FP logic conversion")::llvm::llvm_unreachable_internal("Unexpected input node for FP logic conversion"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44521)
;
44522 case ISD::AND: FPOpcode = X86ISD::FAND; break;
44523 case ISD::OR: FPOpcode = X86ISD::FOR; break;
44524 case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
44525 }
44526 return FPOpcode;
44527}
44528
44529/// If both input operands of a logic op are being cast from floating point
44530/// types, try to convert this into a floating point logic node to avoid
44531/// unnecessary moves from SSE to integer registers.
44532static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
44533 const X86Subtarget &Subtarget) {
44534 EVT VT = N->getValueType(0);
44535 SDValue N0 = N->getOperand(0);
44536 SDValue N1 = N->getOperand(1);
44537 SDLoc DL(N);
44538
44539 if (N0.getOpcode() != ISD::BITCAST || N1.getOpcode() != ISD::BITCAST)
44540 return SDValue();
44541
44542 SDValue N00 = N0.getOperand(0);
44543 SDValue N10 = N1.getOperand(0);
44544 EVT N00Type = N00.getValueType();
44545 EVT N10Type = N10.getValueType();
44546
44547 // Ensure that both types are the same and are legal scalar fp types.
44548 if (N00Type != N10Type ||
44549 !((Subtarget.hasSSE1() && N00Type == MVT::f32) ||
44550 (Subtarget.hasSSE2() && N00Type == MVT::f64)))
44551 return SDValue();
44552
44553 unsigned FPOpcode = convertIntLogicToFPLogicOpcode(N->getOpcode());
44554 SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
44555 return DAG.getBitcast(VT, FPLogic);
44556}
44557
44558// Attempt to fold BITOP(MOVMSK(X),MOVMSK(Y)) -> MOVMSK(BITOP(X,Y))
44559// to reduce XMM->GPR traffic.
44560static SDValue combineBitOpWithMOVMSK(SDNode *N, SelectionDAG &DAG) {
44561 unsigned Opc = N->getOpcode();
44562 assert((Opc == ISD::OR || Opc == ISD::AND || Opc == ISD::XOR) &&(static_cast <bool> ((Opc == ISD::OR || Opc == ISD::AND
|| Opc == ISD::XOR) && "Unexpected bit opcode") ? void
(0) : __assert_fail ("(Opc == ISD::OR || Opc == ISD::AND || Opc == ISD::XOR) && \"Unexpected bit opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44563, __extension__ __PRETTY_FUNCTION__))
44563 "Unexpected bit opcode")(static_cast <bool> ((Opc == ISD::OR || Opc == ISD::AND
|| Opc == ISD::XOR) && "Unexpected bit opcode") ? void
(0) : __assert_fail ("(Opc == ISD::OR || Opc == ISD::AND || Opc == ISD::XOR) && \"Unexpected bit opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44563, __extension__ __PRETTY_FUNCTION__))
;
44564
44565 SDValue N0 = N->getOperand(0);
44566 SDValue N1 = N->getOperand(1);
44567
44568 // Both operands must be single use MOVMSK.
44569 if (N0.getOpcode() != X86ISD::MOVMSK || !N0.hasOneUse() ||
44570 N1.getOpcode() != X86ISD::MOVMSK || !N1.hasOneUse())
44571 return SDValue();
44572
44573 SDValue Vec0 = N0.getOperand(0);
44574 SDValue Vec1 = N1.getOperand(0);
44575 EVT VecVT0 = Vec0.getValueType();
44576 EVT VecVT1 = Vec1.getValueType();
44577
44578 // Both MOVMSK operands must be from vectors of the same size and same element
44579 // size, but its OK for a fp/int diff.
44580 if (VecVT0.getSizeInBits() != VecVT1.getSizeInBits() ||
44581 VecVT0.getScalarSizeInBits() != VecVT1.getScalarSizeInBits())
44582 return SDValue();
44583
44584 SDLoc DL(N);
44585 unsigned VecOpc =
44586 VecVT0.isFloatingPoint() ? convertIntLogicToFPLogicOpcode(Opc) : Opc;
44587 SDValue Result =
44588 DAG.getNode(VecOpc, DL, VecVT0, Vec0, DAG.getBitcast(VecVT0, Vec1));
44589 return DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
44590}
44591
44592/// If this is a zero/all-bits result that is bitwise-anded with a low bits
44593/// mask. (Mask == 1 for the x86 lowering of a SETCC + ZEXT), replace the 'and'
44594/// with a shift-right to eliminate loading the vector constant mask value.
44595static SDValue combineAndMaskToShift(SDNode *N, SelectionDAG &DAG,
44596 const X86Subtarget &Subtarget) {
44597 SDValue Op0 = peekThroughBitcasts(N->getOperand(0));
44598 SDValue Op1 = peekThroughBitcasts(N->getOperand(1));
44599 EVT VT0 = Op0.getValueType();
44600 EVT VT1 = Op1.getValueType();
44601
44602 if (VT0 != VT1 || !VT0.isSimple() || !VT0.isInteger())
44603 return SDValue();
44604
44605 APInt SplatVal;
44606 if (!ISD::isConstantSplatVector(Op1.getNode(), SplatVal) ||
44607 !SplatVal.isMask())
44608 return SDValue();
44609
44610 // Don't prevent creation of ANDN.
44611 if (isBitwiseNot(Op0))
44612 return SDValue();
44613
44614 if (!SupportedVectorShiftWithImm(VT0.getSimpleVT(), Subtarget, ISD::SRL))
44615 return SDValue();
44616
44617 unsigned EltBitWidth = VT0.getScalarSizeInBits();
44618 if (EltBitWidth != DAG.ComputeNumSignBits(Op0))
44619 return SDValue();
44620
44621 SDLoc DL(N);
44622 unsigned ShiftVal = SplatVal.countTrailingOnes();
44623 SDValue ShAmt = DAG.getTargetConstant(EltBitWidth - ShiftVal, DL, MVT::i8);
44624 SDValue Shift = DAG.getNode(X86ISD::VSRLI, DL, VT0, Op0, ShAmt);
44625 return DAG.getBitcast(N->getValueType(0), Shift);
44626}
44627
44628// Get the index node from the lowered DAG of a GEP IR instruction with one
44629// indexing dimension.
44630static SDValue getIndexFromUnindexedLoad(LoadSDNode *Ld) {
44631 if (Ld->isIndexed())
44632 return SDValue();
44633
44634 SDValue Base = Ld->getBasePtr();
44635
44636 if (Base.getOpcode() != ISD::ADD)
44637 return SDValue();
44638
44639 SDValue ShiftedIndex = Base.getOperand(0);
44640
44641 if (ShiftedIndex.getOpcode() != ISD::SHL)
44642 return SDValue();
44643
44644 return ShiftedIndex.getOperand(0);
44645
44646}
44647
44648static bool hasBZHI(const X86Subtarget &Subtarget, MVT VT) {
44649 if (Subtarget.hasBMI2() && VT.isScalarInteger()) {
44650 switch (VT.getSizeInBits()) {
44651 default: return false;
44652 case 64: return Subtarget.is64Bit() ? true : false;
44653 case 32: return true;
44654 }
44655 }
44656 return false;
44657}
44658
44659// This function recognizes cases where X86 bzhi instruction can replace and
44660// 'and-load' sequence.
44661// In case of loading integer value from an array of constants which is defined
44662// as follows:
44663//
44664// int array[SIZE] = {0x0, 0x1, 0x3, 0x7, 0xF ..., 2^(SIZE-1) - 1}
44665//
44666// then applying a bitwise and on the result with another input.
44667// It's equivalent to performing bzhi (zero high bits) on the input, with the
44668// same index of the load.
44669static SDValue combineAndLoadToBZHI(SDNode *Node, SelectionDAG &DAG,
44670 const X86Subtarget &Subtarget) {
44671 MVT VT = Node->getSimpleValueType(0);
44672 SDLoc dl(Node);
44673
44674 // Check if subtarget has BZHI instruction for the node's type
44675 if (!hasBZHI(Subtarget, VT))
44676 return SDValue();
44677
44678 // Try matching the pattern for both operands.
44679 for (unsigned i = 0; i < 2; i++) {
44680 SDValue N = Node->getOperand(i);
44681 LoadSDNode *Ld = dyn_cast<LoadSDNode>(N.getNode());
44682
44683 // continue if the operand is not a load instruction
44684 if (!Ld)
44685 return SDValue();
44686
44687 const Value *MemOp = Ld->getMemOperand()->getValue();
44688
44689 if (!MemOp)
44690 return SDValue();
44691
44692 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(MemOp)) {
44693 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) {
44694 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
44695
44696 Constant *Init = GV->getInitializer();
44697 Type *Ty = Init->getType();
44698 if (!isa<ConstantDataArray>(Init) ||
44699 !Ty->getArrayElementType()->isIntegerTy() ||
44700 Ty->getArrayElementType()->getScalarSizeInBits() !=
44701 VT.getSizeInBits() ||
44702 Ty->getArrayNumElements() >
44703 Ty->getArrayElementType()->getScalarSizeInBits())
44704 continue;
44705
44706 // Check if the array's constant elements are suitable to our case.
44707 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
44708 bool ConstantsMatch = true;
44709 for (uint64_t j = 0; j < ArrayElementCount; j++) {
44710 auto *Elem = cast<ConstantInt>(Init->getAggregateElement(j));
44711 if (Elem->getZExtValue() != (((uint64_t)1 << j) - 1)) {
44712 ConstantsMatch = false;
44713 break;
44714 }
44715 }
44716 if (!ConstantsMatch)
44717 continue;
44718
44719 // Do the transformation (For 32-bit type):
44720 // -> (and (load arr[idx]), inp)
44721 // <- (and (srl 0xFFFFFFFF, (sub 32, idx)))
44722 // that will be replaced with one bzhi instruction.
44723 SDValue Inp = (i == 0) ? Node->getOperand(1) : Node->getOperand(0);
44724 SDValue SizeC = DAG.getConstant(VT.getSizeInBits(), dl, MVT::i32);
44725
44726 // Get the Node which indexes into the array.
44727 SDValue Index = getIndexFromUnindexedLoad(Ld);
44728 if (!Index)
44729 return SDValue();
44730 Index = DAG.getZExtOrTrunc(Index, dl, MVT::i32);
44731
44732 SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, SizeC, Index);
44733 Sub = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Sub);
44734
44735 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
44736 SDValue LShr = DAG.getNode(ISD::SRL, dl, VT, AllOnes, Sub);
44737
44738 return DAG.getNode(ISD::AND, dl, VT, Inp, LShr);
44739 }
44740 }
44741 }
44742 }
44743 return SDValue();
44744}
44745
44746// Look for (and (bitcast (vXi1 (concat_vectors (vYi1 setcc), undef,))), C)
44747// Where C is a mask containing the same number of bits as the setcc and
44748// where the setcc will freely 0 upper bits of k-register. We can replace the
44749// undef in the concat with 0s and remove the AND. This mainly helps with
44750// v2i1/v4i1 setcc being casted to scalar.
44751static SDValue combineScalarAndWithMaskSetcc(SDNode *N, SelectionDAG &DAG,
44752 const X86Subtarget &Subtarget) {
44753 assert(N->getOpcode() == ISD::AND && "Unexpected opcode!")(static_cast <bool> (N->getOpcode() == ISD::AND &&
"Unexpected opcode!") ? void (0) : __assert_fail ("N->getOpcode() == ISD::AND && \"Unexpected opcode!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44753, __extension__ __PRETTY_FUNCTION__))
;
44754
44755 EVT VT = N->getValueType(0);
44756
44757 // Make sure this is an AND with constant. We will check the value of the
44758 // constant later.
44759 if (!isa<ConstantSDNode>(N->getOperand(1)))
44760 return SDValue();
44761
44762 // This is implied by the ConstantSDNode.
44763 assert(!VT.isVector() && "Expected scalar VT!")(static_cast <bool> (!VT.isVector() && "Expected scalar VT!"
) ? void (0) : __assert_fail ("!VT.isVector() && \"Expected scalar VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44763, __extension__ __PRETTY_FUNCTION__))
;
44764
44765 if (N->getOperand(0).getOpcode() != ISD::BITCAST ||
44766 !N->getOperand(0).hasOneUse() ||
44767 !N->getOperand(0).getOperand(0).hasOneUse())
44768 return SDValue();
44769
44770 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44771 SDValue Src = N->getOperand(0).getOperand(0);
44772 EVT SrcVT = Src.getValueType();
44773 if (!SrcVT.isVector() || SrcVT.getVectorElementType() != MVT::i1 ||
44774 !TLI.isTypeLegal(SrcVT))
44775 return SDValue();
44776
44777 if (Src.getOpcode() != ISD::CONCAT_VECTORS)
44778 return SDValue();
44779
44780 // We only care about the first subvector of the concat, we expect the
44781 // other subvectors to be ignored due to the AND if we make the change.
44782 SDValue SubVec = Src.getOperand(0);
44783 EVT SubVecVT = SubVec.getValueType();
44784
44785 // First subvector should be a setcc with a legal result type. The RHS of the
44786 // AND should be a mask with this many bits.
44787 if (SubVec.getOpcode() != ISD::SETCC || !TLI.isTypeLegal(SubVecVT) ||
44788 !N->getConstantOperandAPInt(1).isMask(SubVecVT.getVectorNumElements()))
44789 return SDValue();
44790
44791 EVT SetccVT = SubVec.getOperand(0).getValueType();
44792 if (!TLI.isTypeLegal(SetccVT) ||
44793 !(Subtarget.hasVLX() || SetccVT.is512BitVector()))
44794 return SDValue();
44795
44796 if (!(Subtarget.hasBWI() || SetccVT.getScalarSizeInBits() >= 32))
44797 return SDValue();
44798
44799 // We passed all the checks. Rebuild the concat_vectors with zeroes
44800 // and cast it back to VT.
44801 SDLoc dl(N);
44802 SmallVector<SDValue, 4> Ops(Src.getNumOperands(),
44803 DAG.getConstant(0, dl, SubVecVT));
44804 Ops[0] = SubVec;
44805 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT,
44806 Ops);
44807 return DAG.getBitcast(VT, Concat);
44808}
44809
44810static SDValue combineAnd(SDNode *N, SelectionDAG &DAG,
44811 TargetLowering::DAGCombinerInfo &DCI,
44812 const X86Subtarget &Subtarget) {
44813 EVT VT = N->getValueType(0);
44814
44815 // If this is SSE1 only convert to FAND to avoid scalarization.
44816 if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
44817 return DAG.getBitcast(
44818 MVT::v4i32, DAG.getNode(X86ISD::FAND, SDLoc(N), MVT::v4f32,
44819 DAG.getBitcast(MVT::v4f32, N->getOperand(0)),
44820 DAG.getBitcast(MVT::v4f32, N->getOperand(1))));
44821 }
44822
44823 // Use a 32-bit and+zext if upper bits known zero.
44824 if (VT == MVT::i64 && Subtarget.is64Bit() &&
44825 !isa<ConstantSDNode>(N->getOperand(1))) {
44826 APInt HiMask = APInt::getHighBitsSet(64, 32);
44827 if (DAG.MaskedValueIsZero(N->getOperand(1), HiMask) ||
44828 DAG.MaskedValueIsZero(N->getOperand(0), HiMask)) {
44829 SDLoc dl(N);
44830 SDValue LHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N->getOperand(0));
44831 SDValue RHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N->getOperand(1));
44832 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64,
44833 DAG.getNode(ISD::AND, dl, MVT::i32, LHS, RHS));
44834 }
44835 }
44836
44837 // Match all-of bool scalar reductions into a bitcast/movmsk + cmp.
44838 // TODO: Support multiple SrcOps.
44839 if (VT == MVT::i1) {
44840 SmallVector<SDValue, 2> SrcOps;
44841 SmallVector<APInt, 2> SrcPartials;
44842 if (matchScalarReduction(SDValue(N, 0), ISD::AND, SrcOps, &SrcPartials) &&
44843 SrcOps.size() == 1) {
44844 SDLoc dl(N);
44845 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44846 unsigned NumElts = SrcOps[0].getValueType().getVectorNumElements();
44847 EVT MaskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
44848 SDValue Mask = combineBitcastvxi1(DAG, MaskVT, SrcOps[0], dl, Subtarget);
44849 if (!Mask && TLI.isTypeLegal(SrcOps[0].getValueType()))
44850 Mask = DAG.getBitcast(MaskVT, SrcOps[0]);
44851 if (Mask) {
44852 assert(SrcPartials[0].getBitWidth() == NumElts &&(static_cast <bool> (SrcPartials[0].getBitWidth() == NumElts
&& "Unexpected partial reduction mask") ? void (0) :
__assert_fail ("SrcPartials[0].getBitWidth() == NumElts && \"Unexpected partial reduction mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44853, __extension__ __PRETTY_FUNCTION__))
44853 "Unexpected partial reduction mask")(static_cast <bool> (SrcPartials[0].getBitWidth() == NumElts
&& "Unexpected partial reduction mask") ? void (0) :
__assert_fail ("SrcPartials[0].getBitWidth() == NumElts && \"Unexpected partial reduction mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44853, __extension__ __PRETTY_FUNCTION__))
;
44854 SDValue PartialBits = DAG.getConstant(SrcPartials[0], dl, MaskVT);
44855 Mask = DAG.getNode(ISD::AND, dl, MaskVT, Mask, PartialBits);
44856 return DAG.getSetCC(dl, MVT::i1, Mask, PartialBits, ISD::SETEQ);
44857 }
44858 }
44859 }
44860
44861 if (SDValue V = combineScalarAndWithMaskSetcc(N, DAG, Subtarget))
44862 return V;
44863
44864 if (SDValue R = combineBitOpWithMOVMSK(N, DAG))
44865 return R;
44866
44867 if (DCI.isBeforeLegalizeOps())
44868 return SDValue();
44869
44870 if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
44871 return R;
44872
44873 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
44874 return FPLogic;
44875
44876 if (SDValue R = combineANDXORWithAllOnesIntoANDNP(N, DAG))
44877 return R;
44878
44879 if (SDValue ShiftRight = combineAndMaskToShift(N, DAG, Subtarget))
44880 return ShiftRight;
44881
44882 if (SDValue R = combineAndLoadToBZHI(N, DAG, Subtarget))
44883 return R;
44884
44885 // Attempt to recursively combine a bitmask AND with shuffles.
44886 if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
44887 SDValue Op(N, 0);
44888 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
44889 return Res;
44890 }
44891
44892 // Attempt to combine a scalar bitmask AND with an extracted shuffle.
44893 if ((VT.getScalarSizeInBits() % 8) == 0 &&
44894 N->getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
44895 isa<ConstantSDNode>(N->getOperand(0).getOperand(1))) {
44896 SDValue BitMask = N->getOperand(1);
44897 SDValue SrcVec = N->getOperand(0).getOperand(0);
44898 EVT SrcVecVT = SrcVec.getValueType();
44899
44900 // Check that the constant bitmask masks whole bytes.
44901 APInt UndefElts;
44902 SmallVector<APInt, 64> EltBits;
44903 if (VT == SrcVecVT.getScalarType() &&
44904 N->getOperand(0)->isOnlyUserOf(SrcVec.getNode()) &&
44905 getTargetConstantBitsFromNode(BitMask, 8, UndefElts, EltBits) &&
44906 llvm::all_of(EltBits, [](const APInt &M) {
44907 return M.isNullValue() || M.isAllOnesValue();
44908 })) {
44909 unsigned NumElts = SrcVecVT.getVectorNumElements();
44910 unsigned Scale = SrcVecVT.getScalarSizeInBits() / 8;
44911 unsigned Idx = N->getOperand(0).getConstantOperandVal(1);
44912
44913 // Create a root shuffle mask from the byte mask and the extracted index.
44914 SmallVector<int, 16> ShuffleMask(NumElts * Scale, SM_SentinelUndef);
44915 for (unsigned i = 0; i != Scale; ++i) {
44916 if (UndefElts[i])
44917 continue;
44918 int VecIdx = Scale * Idx + i;
44919 ShuffleMask[VecIdx] =
44920 EltBits[i].isNullValue() ? SM_SentinelZero : VecIdx;
44921 }
44922
44923 if (SDValue Shuffle = combineX86ShufflesRecursively(
44924 {SrcVec}, 0, SrcVec, ShuffleMask, {}, /*Depth*/ 1,
44925 X86::MaxShuffleCombineDepth,
44926 /*HasVarMask*/ false, /*AllowVarCrossLaneMask*/ true,
44927 /*AllowVarPerLaneMask*/ true, DAG, Subtarget))
44928 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), VT, Shuffle,
44929 N->getOperand(0).getOperand(1));
44930 }
44931 }
44932
44933 return SDValue();
44934}
44935
44936// Canonicalize OR(AND(X,C),AND(Y,~C)) -> OR(AND(X,C),ANDNP(C,Y))
44937static SDValue canonicalizeBitSelect(SDNode *N, SelectionDAG &DAG,
44938 const X86Subtarget &Subtarget) {
44939 assert(N->getOpcode() == ISD::OR && "Unexpected Opcode")(static_cast <bool> (N->getOpcode() == ISD::OR &&
"Unexpected Opcode") ? void (0) : __assert_fail ("N->getOpcode() == ISD::OR && \"Unexpected Opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 44939, __extension__ __PRETTY_FUNCTION__))
;
44940
44941 MVT VT = N->getSimpleValueType(0);
44942 if (!VT.isVector() || (VT.getScalarSizeInBits() % 8) != 0)
44943 return SDValue();
44944
44945 SDValue N0 = peekThroughBitcasts(N->getOperand(0));
44946 SDValue N1 = peekThroughBitcasts(N->getOperand(1));
44947 if (N0.getOpcode() != ISD::AND || N1.getOpcode() != ISD::AND)
44948 return SDValue();
44949
44950 // On XOP we'll lower to PCMOV so accept one use. With AVX512, we can use
44951 // VPTERNLOG. Otherwise only do this if either mask has multiple uses already.
44952 bool UseVPTERNLOG = (Subtarget.hasAVX512() && VT.is512BitVector()) ||
44953 Subtarget.hasVLX();
44954 if (!(Subtarget.hasXOP() || UseVPTERNLOG ||
44955 !N0.getOperand(1).hasOneUse() || !N1.getOperand(1).hasOneUse()))
44956 return SDValue();
44957
44958 // Attempt to extract constant byte masks.
44959 APInt UndefElts0, UndefElts1;
44960 SmallVector<APInt, 32> EltBits0, EltBits1;
44961 if (!getTargetConstantBitsFromNode(N0.getOperand(1), 8, UndefElts0, EltBits0,
44962 false, false))
44963 return SDValue();
44964 if (!getTargetConstantBitsFromNode(N1.getOperand(1), 8, UndefElts1, EltBits1,
44965 false, false))
44966 return SDValue();
44967
44968 for (unsigned i = 0, e = EltBits0.size(); i != e; ++i) {
44969 // TODO - add UNDEF elts support.
44970 if (UndefElts0[i] || UndefElts1[i])
44971 return SDValue();
44972 if (EltBits0[i] != ~EltBits1[i])
44973 return SDValue();
44974 }
44975
44976 SDLoc DL(N);
44977
44978 if (UseVPTERNLOG) {
44979 // Emit a VPTERNLOG node directly.
44980 SDValue A = DAG.getBitcast(VT, N0.getOperand(1));
44981 SDValue B = DAG.getBitcast(VT, N0.getOperand(0));
44982 SDValue C = DAG.getBitcast(VT, N1.getOperand(0));
44983 SDValue Imm = DAG.getTargetConstant(0xCA, DL, MVT::i8);
44984 return DAG.getNode(X86ISD::VPTERNLOG, DL, VT, A, B, C, Imm);
44985 }
44986
44987 SDValue X = N->getOperand(0);
44988 SDValue Y =
44989 DAG.getNode(X86ISD::ANDNP, DL, VT, DAG.getBitcast(VT, N0.getOperand(1)),
44990 DAG.getBitcast(VT, N1.getOperand(0)));
44991 return DAG.getNode(ISD::OR, DL, VT, X, Y);
44992}
44993
44994// Try to match OR(AND(~MASK,X),AND(MASK,Y)) logic pattern.
44995static bool matchLogicBlend(SDNode *N, SDValue &X, SDValue &Y, SDValue &Mask) {
44996 if (N->getOpcode() != ISD::OR)
44997 return false;
44998
44999 SDValue N0 = N->getOperand(0);
45000 SDValue N1 = N->getOperand(1);
45001
45002 // Canonicalize AND to LHS.
45003 if (N1.getOpcode() == ISD::AND)
45004 std::swap(N0, N1);
45005
45006 // Attempt to match OR(AND(M,Y),ANDNP(M,X)).
45007 if (N0.getOpcode() != ISD::AND || N1.getOpcode() != X86ISD::ANDNP)
45008 return false;
45009
45010 Mask = N1.getOperand(0);
45011 X = N1.getOperand(1);
45012
45013 // Check to see if the mask appeared in both the AND and ANDNP.
45014 if (N0.getOperand(0) == Mask)
45015 Y = N0.getOperand(1);
45016 else if (N0.getOperand(1) == Mask)
45017 Y = N0.getOperand(0);
45018 else
45019 return false;
45020
45021 // TODO: Attempt to match against AND(XOR(-1,M),Y) as well, waiting for
45022 // ANDNP combine allows other combines to happen that prevent matching.
45023 return true;
45024}
45025
45026// Try to fold:
45027// (or (and (m, y), (pandn m, x)))
45028// into:
45029// (vselect m, x, y)
45030// As a special case, try to fold:
45031// (or (and (m, (sub 0, x)), (pandn m, x)))
45032// into:
45033// (sub (xor X, M), M)
45034static SDValue combineLogicBlendIntoPBLENDV(SDNode *N, SelectionDAG &DAG,
45035 const X86Subtarget &Subtarget) {
45036 assert(N->getOpcode() == ISD::OR && "Unexpected Opcode")(static_cast <bool> (N->getOpcode() == ISD::OR &&
"Unexpected Opcode") ? void (0) : __assert_fail ("N->getOpcode() == ISD::OR && \"Unexpected Opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 45036, __extension__ __PRETTY_FUNCTION__))
;
45037
45038 EVT VT = N->getValueType(0);
45039 if (!((VT.is128BitVector() && Subtarget.hasSSE2()) ||
45040 (VT.is256BitVector() && Subtarget.hasInt256())))
45041 return SDValue();
45042
45043 SDValue X, Y, Mask;
45044 if (!matchLogicBlend(N, X, Y, Mask))
45045 return SDValue();
45046
45047 // Validate that X, Y, and Mask are bitcasts, and see through them.
45048 Mask = peekThroughBitcasts(Mask);
45049 X = peekThroughBitcasts(X);
45050 Y = peekThroughBitcasts(Y);
45051
45052 EVT MaskVT = Mask.getValueType();
45053 unsigned EltBits = MaskVT.getScalarSizeInBits();
45054
45055 // TODO: Attempt to handle floating point cases as well?
45056 if (!MaskVT.isInteger() || DAG.ComputeNumSignBits(Mask) != EltBits)
45057 return SDValue();
45058
45059 SDLoc DL(N);
45060
45061 // Attempt to combine to conditional negate: (sub (xor X, M), M)
45062 if (SDValue Res = combineLogicBlendIntoConditionalNegate(VT, Mask, X, Y, DL,
45063 DAG, Subtarget))
45064 return Res;
45065
45066 // PBLENDVB is only available on SSE 4.1.
45067 if (!Subtarget.hasSSE41())
45068 return SDValue();
45069
45070 // If we have VPTERNLOG we should prefer that since PBLENDVB is multiple uops.
45071 if (Subtarget.hasVLX())
45072 return SDValue();
45073
45074 MVT BlendVT = VT.is256BitVector() ? MVT::v32i8 : MVT::v16i8;
45075
45076 X = DAG.getBitcast(BlendVT, X);
45077 Y = DAG.getBitcast(BlendVT, Y);
45078 Mask = DAG.getBitcast(BlendVT, Mask);
45079 Mask = DAG.getSelect(DL, BlendVT, Mask, Y, X);
45080 return DAG.getBitcast(VT, Mask);
45081}
45082
45083// Helper function for combineOrCmpEqZeroToCtlzSrl
45084// Transforms:
45085// seteq(cmp x, 0)
45086// into:
45087// srl(ctlz x), log2(bitsize(x))
45088// Input pattern is checked by caller.
45089static SDValue lowerX86CmpEqZeroToCtlzSrl(SDValue Op, EVT ExtTy,
45090 SelectionDAG &DAG) {
45091 SDValue Cmp = Op.getOperand(1);
45092 EVT VT = Cmp.getOperand(0).getValueType();
45093 unsigned Log2b = Log2_32(VT.getSizeInBits());
45094 SDLoc dl(Op);
45095 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Cmp->getOperand(0));
45096 // The result of the shift is true or false, and on X86, the 32-bit
45097 // encoding of shr and lzcnt is more desirable.
45098 SDValue Trunc = DAG.getZExtOrTrunc(Clz, dl, MVT::i32);
45099 SDValue Scc = DAG.getNode(ISD::SRL, dl, MVT::i32, Trunc,
45100 DAG.getConstant(Log2b, dl, MVT::i8));
45101 return DAG.getZExtOrTrunc(Scc, dl, ExtTy);
45102}
45103
45104// Try to transform:
45105// zext(or(setcc(eq, (cmp x, 0)), setcc(eq, (cmp y, 0))))
45106// into:
45107// srl(or(ctlz(x), ctlz(y)), log2(bitsize(x))
45108// Will also attempt to match more generic cases, eg:
45109// zext(or(or(setcc(eq, cmp 0), setcc(eq, cmp 0)), setcc(eq, cmp 0)))
45110// Only applies if the target supports the FastLZCNT feature.
45111static SDValue combineOrCmpEqZeroToCtlzSrl(SDNode *N, SelectionDAG &DAG,
45112 TargetLowering::DAGCombinerInfo &DCI,
45113 const X86Subtarget &Subtarget) {
45114 if (DCI.isBeforeLegalize() || !Subtarget.getTargetLowering()->isCtlzFast())
45115 return SDValue();
45116
45117 auto isORCandidate = [](SDValue N) {
45118 return (N->getOpcode() == ISD::OR && N->hasOneUse());
45119 };
45120
45121 // Check the zero extend is extending to 32-bit or more. The code generated by
45122 // srl(ctlz) for 16-bit or less variants of the pattern would require extra
45123 // instructions to clear the upper bits.
45124 if (!N->hasOneUse() || !N->getSimpleValueType(0).bitsGE(MVT::i32) ||
45125 !isORCandidate(N->getOperand(0)))
45126 return SDValue();
45127
45128 // Check the node matches: setcc(eq, cmp 0)
45129 auto isSetCCCandidate = [](SDValue N) {
45130 return N->getOpcode() == X86ISD::SETCC && N->hasOneUse() &&
45131 X86::CondCode(N->getConstantOperandVal(0)) == X86::COND_E &&
45132 N->getOperand(1).getOpcode() == X86ISD::CMP &&
45133 isNullConstant(N->getOperand(1).getOperand(1)) &&
45134 N->getOperand(1).getValueType().bitsGE(MVT::i32);
45135 };
45136
45137 SDNode *OR = N->getOperand(0).getNode();
45138 SDValue LHS = OR->getOperand(0);
45139 SDValue RHS = OR->getOperand(1);
45140
45141 // Save nodes matching or(or, setcc(eq, cmp 0)).
45142 SmallVector<SDNode *, 2> ORNodes;
45143 while (((isORCandidate(LHS) && isSetCCCandidate(RHS)) ||
45144 (isORCandidate(RHS) && isSetCCCandidate(LHS)))) {
45145 ORNodes.push_back(OR);
45146 OR = (LHS->getOpcode() == ISD::OR) ? LHS.getNode() : RHS.getNode();
45147 LHS = OR->getOperand(0);
45148 RHS = OR->getOperand(1);
45149 }
45150
45151 // The last OR node should match or(setcc(eq, cmp 0), setcc(eq, cmp 0)).
45152 if (!(isSetCCCandidate(LHS) && isSetCCCandidate(RHS)) ||
45153 !isORCandidate(SDValue(OR, 0)))
45154 return SDValue();
45155
45156 // We have a or(setcc(eq, cmp 0), setcc(eq, cmp 0)) pattern, try to lower it
45157 // to
45158 // or(srl(ctlz),srl(ctlz)).
45159 // The dag combiner can then fold it into:
45160 // srl(or(ctlz, ctlz)).
45161 EVT VT = OR->getValueType(0);
45162 SDValue NewLHS = lowerX86CmpEqZeroToCtlzSrl(LHS, VT, DAG);
45163 SDValue Ret, NewRHS;
45164 if (NewLHS && (NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, VT, DAG)))
45165 Ret = DAG.getNode(ISD::OR, SDLoc(OR), VT, NewLHS, NewRHS);
45166
45167 if (!Ret)
45168 return SDValue();
45169
45170 // Try to lower nodes matching the or(or, setcc(eq, cmp 0)) pattern.
45171 while (ORNodes.size() > 0) {
45172 OR = ORNodes.pop_back_val();
45173 LHS = OR->getOperand(0);
45174 RHS = OR->getOperand(1);
45175 // Swap rhs with lhs to match or(setcc(eq, cmp, 0), or).
45176 if (RHS->getOpcode() == ISD::OR)
45177 std::swap(LHS, RHS);
45178 NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, VT, DAG);
45179 if (!NewRHS)
45180 return SDValue();
45181 Ret = DAG.getNode(ISD::OR, SDLoc(OR), VT, Ret, NewRHS);
45182 }
45183
45184 if (Ret)
45185 Ret = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), Ret);
45186
45187 return Ret;
45188}
45189
45190static SDValue combineOr(SDNode *N, SelectionDAG &DAG,
45191 TargetLowering::DAGCombinerInfo &DCI,
45192 const X86Subtarget &Subtarget) {
45193 SDValue N0 = N->getOperand(0);
45194 SDValue N1 = N->getOperand(1);
45195 EVT VT = N->getValueType(0);
45196
45197 // If this is SSE1 only convert to FOR to avoid scalarization.
45198 if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
45199 return DAG.getBitcast(MVT::v4i32,
45200 DAG.getNode(X86ISD::FOR, SDLoc(N), MVT::v4f32,
45201 DAG.getBitcast(MVT::v4f32, N0),
45202 DAG.getBitcast(MVT::v4f32, N1)));
45203 }
45204
45205 // Match any-of bool scalar reductions into a bitcast/movmsk + cmp.
45206 // TODO: Support multiple SrcOps.
45207 if (VT == MVT::i1) {
45208 SmallVector<SDValue, 2> SrcOps;
45209 SmallVector<APInt, 2> SrcPartials;
45210 if (matchScalarReduction(SDValue(N, 0), ISD::OR, SrcOps, &SrcPartials) &&
45211 SrcOps.size() == 1) {
45212 SDLoc dl(N);
45213 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45214 unsigned NumElts = SrcOps[0].getValueType().getVectorNumElements();
45215 EVT MaskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
45216 SDValue Mask = combineBitcastvxi1(DAG, MaskVT, SrcOps[0], dl, Subtarget);
45217 if (!Mask && TLI.isTypeLegal(SrcOps[0].getValueType()))
45218 Mask = DAG.getBitcast(MaskVT, SrcOps[0]);
45219 if (Mask) {
45220 assert(SrcPartials[0].getBitWidth() == NumElts &&(static_cast <bool> (SrcPartials[0].getBitWidth() == NumElts
&& "Unexpected partial reduction mask") ? void (0) :
__assert_fail ("SrcPartials[0].getBitWidth() == NumElts && \"Unexpected partial reduction mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 45221, __extension__ __PRETTY_FUNCTION__))
45221 "Unexpected partial reduction mask")(static_cast <bool> (SrcPartials[0].getBitWidth() == NumElts
&& "Unexpected partial reduction mask") ? void (0) :
__assert_fail ("SrcPartials[0].getBitWidth() == NumElts && \"Unexpected partial reduction mask\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 45221, __extension__ __PRETTY_FUNCTION__))
;
45222 SDValue ZeroBits = DAG.getConstant(0, dl, MaskVT);
45223 SDValue PartialBits = DAG.getConstant(SrcPartials[0], dl, MaskVT);
45224 Mask = DAG.getNode(ISD::AND, dl, MaskVT, Mask, PartialBits);
45225 return DAG.getSetCC(dl, MVT::i1, Mask, ZeroBits, ISD::SETNE);
45226 }
45227 }
45228 }
45229
45230 if (SDValue R = combineBitOpWithMOVMSK(N, DAG))
45231 return R;
45232
45233 if (DCI.isBeforeLegalizeOps())
45234 return SDValue();
45235
45236 if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
45237 return R;
45238
45239 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
45240 return FPLogic;
45241
45242 if (SDValue R = canonicalizeBitSelect(N, DAG, Subtarget))
45243 return R;
45244
45245 if (SDValue R = combineLogicBlendIntoPBLENDV(N, DAG, Subtarget))
45246 return R;
45247
45248 // Combine OR(X,KSHIFTL(Y,Elts/2)) -> CONCAT_VECTORS(X,Y) == KUNPCK(X,Y).
45249 // Combine OR(KSHIFTL(X,Elts/2),Y) -> CONCAT_VECTORS(Y,X) == KUNPCK(Y,X).
45250 // iff the upper elements of the non-shifted arg are zero.
45251 // KUNPCK require 16+ bool vector elements.
45252 if (N0.getOpcode() == X86ISD::KSHIFTL || N1.getOpcode() == X86ISD::KSHIFTL) {
45253 unsigned NumElts = VT.getVectorNumElements();
45254 unsigned HalfElts = NumElts / 2;
45255 APInt UpperElts = APInt::getHighBitsSet(NumElts, HalfElts);
45256 if (NumElts >= 16 && N1.getOpcode() == X86ISD::KSHIFTL &&
45257 N1.getConstantOperandAPInt(1) == HalfElts &&
45258 DAG.MaskedValueIsZero(N0, APInt(1, 1), UpperElts)) {
45259 SDLoc dl(N);
45260 return DAG.getNode(
45261 ISD::CONCAT_VECTORS, dl, VT,
45262 extractSubVector(N0, 0, DAG, dl, HalfElts),
45263 extractSubVector(N1.getOperand(0), 0, DAG, dl, HalfElts));
45264 }
45265 if (NumElts >= 16 && N0.getOpcode() == X86ISD::KSHIFTL &&
45266 N0.getConstantOperandAPInt(1) == HalfElts &&
45267 DAG.MaskedValueIsZero(N1, APInt(1, 1), UpperElts)) {
45268 SDLoc dl(N);
45269 return DAG.getNode(
45270 ISD::CONCAT_VECTORS, dl, VT,
45271 extractSubVector(N1, 0, DAG, dl, HalfElts),
45272 extractSubVector(N0.getOperand(0), 0, DAG, dl, HalfElts));
45273 }
45274 }
45275
45276 // Attempt to recursively combine an OR of shuffles.
45277 if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
45278 SDValue Op(N, 0);
45279 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
45280 return Res;
45281 }
45282
45283 return SDValue();
45284}
45285
45286/// Try to turn tests against the signbit in the form of:
45287/// XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
45288/// into:
45289/// SETGT(X, -1)
45290static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
45291 // This is only worth doing if the output type is i8 or i1.
45292 EVT ResultType = N->getValueType(0);
45293 if (ResultType != MVT::i8 && ResultType != MVT::i1)
45294 return SDValue();
45295
45296 SDValue N0 = N->getOperand(0);
45297 SDValue N1 = N->getOperand(1);
45298
45299 // We should be performing an xor against a truncated shift.
45300 if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
45301 return SDValue();
45302
45303 // Make sure we are performing an xor against one.
45304 if (!isOneConstant(N1))
45305 return SDValue();
45306
45307 // SetCC on x86 zero extends so only act on this if it's a logical shift.
45308 SDValue Shift = N0.getOperand(0);
45309 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
45310 return SDValue();
45311
45312 // Make sure we are truncating from one of i16, i32 or i64.
45313 EVT ShiftTy = Shift.getValueType();
45314 if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
45315 return SDValue();
45316
45317 // Make sure the shift amount extracts the sign bit.
45318 if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
45319 Shift.getConstantOperandAPInt(1) != (ShiftTy.getSizeInBits() - 1))
45320 return SDValue();
45321
45322 // Create a greater-than comparison against -1.
45323 // N.B. Using SETGE against 0 works but we want a canonical looking
45324 // comparison, using SETGT matches up with what TranslateX86CC.
45325 SDLoc DL(N);
45326 SDValue ShiftOp = Shift.getOperand(0);
45327 EVT ShiftOpTy = ShiftOp.getValueType();
45328 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45329 EVT SetCCResultType = TLI.getSetCCResultType(DAG.getDataLayout(),
45330 *DAG.getContext(), ResultType);
45331 SDValue Cond = DAG.getSetCC(DL, SetCCResultType, ShiftOp,
45332 DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
45333 if (SetCCResultType != ResultType)
45334 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, ResultType, Cond);
45335 return Cond;
45336}
45337
45338/// Turn vector tests of the signbit in the form of:
45339/// xor (sra X, elt_size(X)-1), -1
45340/// into:
45341/// pcmpgt X, -1
45342///
45343/// This should be called before type legalization because the pattern may not
45344/// persist after that.
45345static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
45346 const X86Subtarget &Subtarget) {
45347 EVT VT = N->getValueType(0);
45348 if (!VT.isSimple())
45349 return SDValue();
45350
45351 switch (VT.getSimpleVT().SimpleTy) {
45352 default: return SDValue();
45353 case MVT::v16i8:
45354 case MVT::v8i16:
45355 case MVT::v4i32:
45356 case MVT::v2i64: if (!Subtarget.hasSSE2()) return SDValue(); break;
45357 case MVT::v32i8:
45358 case MVT::v16i16:
45359 case MVT::v8i32:
45360 case MVT::v4i64: if (!Subtarget.hasAVX2()) return SDValue(); break;
45361 }
45362
45363 // There must be a shift right algebraic before the xor, and the xor must be a
45364 // 'not' operation.
45365 SDValue Shift = N->getOperand(0);
45366 SDValue Ones = N->getOperand(1);
45367 if (Shift.getOpcode() != ISD::SRA || !Shift.hasOneUse() ||
45368 !ISD::isBuildVectorAllOnes(Ones.getNode()))
45369 return SDValue();
45370
45371 // The shift should be smearing the sign bit across each vector element.
45372 auto *ShiftAmt =
45373 isConstOrConstSplat(Shift.getOperand(1), /*AllowUndefs*/ true);
45374 if (!ShiftAmt ||
45375 ShiftAmt->getAPIntValue() != (Shift.getScalarValueSizeInBits() - 1))
45376 return SDValue();
45377
45378 // Create a greater-than comparison against -1. We don't use the more obvious
45379 // greater-than-or-equal-to-zero because SSE/AVX don't have that instruction.
45380 return DAG.getSetCC(SDLoc(N), VT, Shift.getOperand(0), Ones, ISD::SETGT);
45381}
45382
45383/// Detect patterns of truncation with unsigned saturation:
45384///
45385/// 1. (truncate (umin (x, unsigned_max_of_dest_type)) to dest_type).
45386/// Return the source value x to be truncated or SDValue() if the pattern was
45387/// not matched.
45388///
45389/// 2. (truncate (smin (smax (x, C1), C2)) to dest_type),
45390/// where C1 >= 0 and C2 is unsigned max of destination type.
45391///
45392/// (truncate (smax (smin (x, C2), C1)) to dest_type)
45393/// where C1 >= 0, C2 is unsigned max of destination type and C1 <= C2.
45394///
45395/// These two patterns are equivalent to:
45396/// (truncate (umin (smax(x, C1), unsigned_max_of_dest_type)) to dest_type)
45397/// So return the smax(x, C1) value to be truncated or SDValue() if the
45398/// pattern was not matched.
45399static SDValue detectUSatPattern(SDValue In, EVT VT, SelectionDAG &DAG,
45400 const SDLoc &DL) {
45401 EVT InVT = In.getValueType();
45402
45403 // Saturation with truncation. We truncate from InVT to VT.
45404 assert(InVT.getScalarSizeInBits() > VT.getScalarSizeInBits() &&(static_cast <bool> (InVT.getScalarSizeInBits() > VT
.getScalarSizeInBits() && "Unexpected types for truncate operation"
) ? void (0) : __assert_fail ("InVT.getScalarSizeInBits() > VT.getScalarSizeInBits() && \"Unexpected types for truncate operation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 45405, __extension__ __PRETTY_FUNCTION__))
45405 "Unexpected types for truncate operation")(static_cast <bool> (InVT.getScalarSizeInBits() > VT
.getScalarSizeInBits() && "Unexpected types for truncate operation"
) ? void (0) : __assert_fail ("InVT.getScalarSizeInBits() > VT.getScalarSizeInBits() && \"Unexpected types for truncate operation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 45405, __extension__ __PRETTY_FUNCTION__))
;
45406
45407 // Match min/max and return limit value as a parameter.
45408 auto MatchMinMax = [](SDValue V, unsigned Opcode, APInt &Limit) -> SDValue {
45409 if (V.getOpcode() == Opcode &&
45410 ISD::isConstantSplatVector(V.getOperand(1).getNode(), Limit))
45411 return V.getOperand(0);
45412 return SDValue();
45413 };
45414
45415 APInt C1, C2;
45416 if (SDValue UMin = MatchMinMax(In, ISD::UMIN, C2))
45417 // C2 should be equal to UINT32_MAX / UINT16_MAX / UINT8_MAX according
45418 // the element size of the destination type.
45419 if (C2.isMask(VT.getScalarSizeInBits()))
45420 return UMin;
45421
45422 if (SDValue SMin = MatchMinMax(In, ISD::SMIN, C2))
45423 if (MatchMinMax(SMin, ISD::SMAX, C1))
45424 if (C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()))
45425 return SMin;
45426
45427 if (SDValue SMax = MatchMinMax(In, ISD::SMAX, C1))
45428 if (SDValue SMin = MatchMinMax(SMax, ISD::SMIN, C2))
45429 if (C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()) &&
45430 C2.uge(C1)) {
45431 return DAG.getNode(ISD::SMAX, DL, InVT, SMin, In.getOperand(1));
45432 }
45433
45434 return SDValue();
45435}
45436
45437/// Detect patterns of truncation with signed saturation:
45438/// (truncate (smin ((smax (x, signed_min_of_dest_type)),
45439/// signed_max_of_dest_type)) to dest_type)
45440/// or:
45441/// (truncate (smax ((smin (x, signed_max_of_dest_type)),
45442/// signed_min_of_dest_type)) to dest_type).
45443/// With MatchPackUS, the smax/smin range is [0, unsigned_max_of_dest_type].
45444/// Return the source value to be truncated or SDValue() if the pattern was not
45445/// matched.
45446static SDValue detectSSatPattern(SDValue In, EVT VT, bool MatchPackUS = false) {
45447 unsigned NumDstBits = VT.getScalarSizeInBits();
45448 unsigned NumSrcBits = In.getScalarValueSizeInBits();
45449 assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation")(static_cast <bool> (NumSrcBits > NumDstBits &&
"Unexpected types for truncate operation") ? void (0) : __assert_fail
("NumSrcBits > NumDstBits && \"Unexpected types for truncate operation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 45449, __extension__ __PRETTY_FUNCTION__))
;
45450
45451 auto MatchMinMax = [](SDValue V, unsigned Opcode,
45452 const APInt &Limit) -> SDValue {
45453 APInt C;
45454 if (V.getOpcode() == Opcode &&
45455 ISD::isConstantSplatVector(V.getOperand(1).getNode(), C) && C == Limit)
45456 return V.getOperand(0);
45457 return SDValue();
45458 };
45459
45460 APInt SignedMax, SignedMin;
45461 if (MatchPackUS) {
45462 SignedMax = APInt::getAllOnesValue(NumDstBits).zext(NumSrcBits);
45463 SignedMin = APInt(NumSrcBits, 0);
45464 } else {
45465 SignedMax = APInt::getSignedMaxValue(NumDstBits).sext(NumSrcBits);
45466 SignedMin = APInt::getSignedMinValue(NumDstBits).sext(NumSrcBits);
45467 }
45468
45469 if (SDValue SMin = MatchMinMax(In, ISD::SMIN, SignedMax))
45470 if (SDValue SMax = MatchMinMax(SMin, ISD::SMAX, SignedMin))
45471 return SMax;
45472
45473 if (SDValue SMax = MatchMinMax(In, ISD::SMAX, SignedMin))
45474 if (SDValue SMin = MatchMinMax(SMax, ISD::SMIN, SignedMax))
45475 return SMin;
45476
45477 return SDValue();
45478}
45479
45480static SDValue combineTruncateWithSat(SDValue In, EVT VT, const SDLoc &DL,
45481 SelectionDAG &DAG,
45482 const X86Subtarget &Subtarget) {
45483 if (!Subtarget.hasSSE2() || !VT.isVector())
45484 return SDValue();
45485
45486 EVT SVT = VT.getVectorElementType();
45487 EVT InVT = In.getValueType();
45488 EVT InSVT = InVT.getVectorElementType();
45489
45490 // If we're clamping a signed 32-bit vector to 0-255 and the 32-bit vector is
45491 // split across two registers. We can use a packusdw+perm to clamp to 0-65535
45492 // and concatenate at the same time. Then we can use a final vpmovuswb to
45493 // clip to 0-255.
45494 if (Subtarget.hasBWI() && !Subtarget.useAVX512Regs() &&
45495 InVT == MVT::v16i32 && VT == MVT::v16i8) {
45496 if (auto USatVal = detectSSatPattern(In, VT, true)) {
45497 // Emit a VPACKUSDW+VPERMQ followed by a VPMOVUSWB.
45498 SDValue Mid = truncateVectorWithPACK(X86ISD::PACKUS, MVT::v16i16, USatVal,
45499 DL, DAG, Subtarget);
45500 assert(Mid && "Failed to pack!")(static_cast <bool> (Mid && "Failed to pack!") ?
void (0) : __assert_fail ("Mid && \"Failed to pack!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 45500, __extension__ __PRETTY_FUNCTION__))
;
45501 return DAG.getNode(X86ISD::VTRUNCUS, DL, VT, Mid);
45502 }
45503 }
45504
45505 // vXi32 truncate instructions are available with AVX512F.
45506 // vXi16 truncate instructions are only available with AVX512BW.
45507 // For 256-bit or smaller vectors, we require VLX.
45508 // FIXME: We could widen truncates to 512 to remove the VLX restriction.
45509 // If the result type is 256-bits or larger and we have disable 512-bit
45510 // registers, we should go ahead and use the pack instructions if possible.
45511 bool PreferAVX512 = ((Subtarget.hasAVX512() && InSVT == MVT::i32) ||
45512 (Subtarget.hasBWI() && InSVT == MVT::i16)) &&
45513 (InVT.getSizeInBits() > 128) &&
45514 (Subtarget.hasVLX() || InVT.getSizeInBits() > 256) &&
45515 !(!Subtarget.useAVX512Regs() && VT.getSizeInBits() >= 256);
45516
45517 if (isPowerOf2_32(VT.getVectorNumElements()) && !PreferAVX512 &&
45518 VT.getSizeInBits() >= 64 &&
45519 (SVT == MVT::i8 || SVT == MVT::i16) &&
45520 (InSVT == MVT::i16 || InSVT == MVT::i32)) {
45521 if (auto USatVal = detectSSatPattern(In, VT, true)) {
45522 // vXi32 -> vXi8 must be performed as PACKUSWB(PACKSSDW,PACKSSDW).
45523 // Only do this when the result is at least 64 bits or we'll leaving
45524 // dangling PACKSSDW nodes.
45525 if (SVT == MVT::i8 && InSVT == MVT::i32) {
45526 EVT MidVT = VT.changeVectorElementType(MVT::i16);
45527 SDValue Mid = truncateVectorWithPACK(X86ISD::PACKSS, MidVT, USatVal, DL,
45528 DAG, Subtarget);
45529 assert(Mid && "Failed to pack!")(static_cast <bool> (Mid && "Failed to pack!") ?
void (0) : __assert_fail ("Mid && \"Failed to pack!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 45529, __extension__ __PRETTY_FUNCTION__))
;
45530 SDValue V = truncateVectorWithPACK(X86ISD::PACKUS, VT, Mid, DL, DAG,
45531 Subtarget);
45532 assert(V && "Failed to pack!")(static_cast <bool> (V && "Failed to pack!") ? void
(0) : __assert_fail ("V && \"Failed to pack!\"", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 45532, __extension__ __PRETTY_FUNCTION__))
;
45533 return V;
45534 } else if (SVT == MVT::i8 || Subtarget.hasSSE41())
45535 return truncateVectorWithPACK(X86ISD::PACKUS, VT, USatVal, DL, DAG,
45536 Subtarget);
45537 }
45538 if (auto SSatVal = detectSSatPattern(In, VT))
45539 return truncateVectorWithPACK(X86ISD::PACKSS, VT, SSatVal, DL, DAG,
45540 Subtarget);
45541 }
45542
45543 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45544 if (TLI.isTypeLegal(InVT) && InVT.isVector() && SVT != MVT::i1 &&
45545 Subtarget.hasAVX512() && (InSVT != MVT::i16 || Subtarget.hasBWI()) &&
45546 (SVT == MVT::i32 || SVT == MVT::i16 || SVT == MVT::i8)) {
45547 unsigned TruncOpc = 0;
45548 SDValue SatVal;
45549 if (auto SSatVal = detectSSatPattern(In, VT)) {
45550 SatVal = SSatVal;
45551 TruncOpc = X86ISD::VTRUNCS;
45552 } else if (auto USatVal = detectUSatPattern(In, VT, DAG, DL)) {
45553 SatVal = USatVal;
45554 TruncOpc = X86ISD::VTRUNCUS;
45555 }
45556 if (SatVal) {
45557 unsigned ResElts = VT.getVectorNumElements();
45558 // If the input type is less than 512 bits and we don't have VLX, we need
45559 // to widen to 512 bits.
45560 if (!Subtarget.hasVLX() && !InVT.is512BitVector()) {
45561 unsigned NumConcats = 512 / InVT.getSizeInBits();
45562 ResElts *= NumConcats;
45563 SmallVector<SDValue, 4> ConcatOps(NumConcats, DAG.getUNDEF(InVT));
45564 ConcatOps[0] = SatVal;
45565 InVT = EVT::getVectorVT(*DAG.getContext(), InSVT,
45566 NumConcats * InVT.getVectorNumElements());
45567 SatVal = DAG.getNode(ISD::CONCAT_VECTORS, DL, InVT, ConcatOps);
45568 }
45569 // Widen the result if its narrower than 128 bits.
45570 if (ResElts * SVT.getSizeInBits() < 128)
45571 ResElts = 128 / SVT.getSizeInBits();
45572 EVT TruncVT = EVT::getVectorVT(*DAG.getContext(), SVT, ResElts);
45573 SDValue Res = DAG.getNode(TruncOpc, DL, TruncVT, SatVal);
45574 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
45575 DAG.getIntPtrConstant(0, DL));
45576 }
45577 }
45578
45579 return SDValue();
45580}
45581
45582/// This function detects the AVG pattern between vectors of unsigned i8/i16,
45583/// which is c = (a + b + 1) / 2, and replace this operation with the efficient
45584/// X86ISD::AVG instruction.
45585static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
45586 const X86Subtarget &Subtarget,
45587 const SDLoc &DL) {
45588 if (!VT.isVector())
45589 return SDValue();
45590 EVT InVT = In.getValueType();
45591 unsigned NumElems = VT.getVectorNumElements();
45592
45593 EVT ScalarVT = VT.getVectorElementType();
45594 if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) && NumElems >= 2))
45595 return SDValue();
45596
45597 // InScalarVT is the intermediate type in AVG pattern and it should be greater
45598 // than the original input type (i8/i16).
45599 EVT InScalarVT = InVT.getVectorElementType();
45600 if (InScalarVT.getFixedSizeInBits() <= ScalarVT.getFixedSizeInBits())
45601 return SDValue();
45602
45603 if (!Subtarget.hasSSE2())
45604 return SDValue();
45605
45606 // Detect the following pattern:
45607 //
45608 // %1 = zext <N x i8> %a to <N x i32>
45609 // %2 = zext <N x i8> %b to <N x i32>
45610 // %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
45611 // %4 = add nuw nsw <N x i32> %3, %2
45612 // %5 = lshr <N x i32> %N, <i32 1 x N>
45613 // %6 = trunc <N x i32> %5 to <N x i8>
45614 //
45615 // In AVX512, the last instruction can also be a trunc store.
45616 if (In.getOpcode() != ISD::SRL)
45617 return SDValue();
45618
45619 // A lambda checking the given SDValue is a constant vector and each element
45620 // is in the range [Min, Max].
45621 auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
45622 return ISD::matchUnaryPredicate(V, [Min, Max](ConstantSDNode *C) {
45623 return !(C->getAPIntValue().ult(Min) || C->getAPIntValue().ugt(Max));
45624 });
45625 };
45626
45627 // Check if each element of the vector is right-shifted by one.
45628 SDValue LHS = In.getOperand(0);
45629 SDValue RHS = In.getOperand(1);
45630 if (!IsConstVectorInRange(RHS, 1, 1))
45631 return SDValue();
45632 if (LHS.getOpcode() != ISD::ADD)
45633 return SDValue();
45634
45635 // Detect a pattern of a + b + 1 where the order doesn't matter.
45636 SDValue Operands[3];
45637 Operands[0] = LHS.getOperand(0);
45638 Operands[1] = LHS.getOperand(1);
45639
45640 auto AVGBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
45641 ArrayRef<SDValue> Ops) {
45642 return DAG.getNode(X86ISD::AVG, DL, Ops[0].getValueType(), Ops);
45643 };
45644
45645 auto AVGSplitter = [&](SDValue Op0, SDValue Op1) {
45646 // Pad to a power-of-2 vector, split+apply and extract the original vector.
45647 unsigned NumElemsPow2 = PowerOf2Ceil(NumElems);
45648 EVT Pow2VT = EVT::getVectorVT(*DAG.getContext(), ScalarVT, NumElemsPow2);
45649 if (NumElemsPow2 != NumElems) {
45650 SmallVector<SDValue, 32> Ops0(NumElemsPow2, DAG.getUNDEF(ScalarVT));
45651 SmallVector<SDValue, 32> Ops1(NumElemsPow2, DAG.getUNDEF(ScalarVT));
45652 for (unsigned i = 0; i != NumElems; ++i) {
45653 SDValue Idx = DAG.getIntPtrConstant(i, DL);
45654 Ops0[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, Op0, Idx);
45655 Ops1[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, Op1, Idx);
45656 }
45657 Op0 = DAG.getBuildVector(Pow2VT, DL, Ops0);
45658 Op1 = DAG.getBuildVector(Pow2VT, DL, Ops1);
45659 }
45660 SDValue Res =
45661 SplitOpsAndApply(DAG, Subtarget, DL, Pow2VT, {Op0, Op1}, AVGBuilder);
45662 if (NumElemsPow2 == NumElems)
45663 return Res;
45664 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
45665 DAG.getIntPtrConstant(0, DL));
45666 };
45667
45668 // Take care of the case when one of the operands is a constant vector whose
45669 // element is in the range [1, 256].
45670 if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
45671 Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
45672 Operands[0].getOperand(0).getValueType() == VT) {
45673 // The pattern is detected. Subtract one from the constant vector, then
45674 // demote it and emit X86ISD::AVG instruction.
45675 SDValue VecOnes = DAG.getConstant(1, DL, InVT);
45676 Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], VecOnes);
45677 Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
45678 return AVGSplitter(Operands[0].getOperand(0), Operands[1]);
45679 }
45680
45681 // Matches 'add like' patterns: add(Op0,Op1) + zext(or(Op0,Op1)).
45682 // Match the or case only if its 'add-like' - can be replaced by an add.
45683 auto FindAddLike = [&](SDValue V, SDValue &Op0, SDValue &Op1) {
45684 if (ISD::ADD == V.getOpcode()) {
45685 Op0 = V.getOperand(0);
45686 Op1 = V.getOperand(1);
45687 return true;
45688 }
45689 if (ISD::ZERO_EXTEND != V.getOpcode())
45690 return false;
45691 V = V.getOperand(0);
45692 if (V.getValueType() != VT || ISD::OR != V.getOpcode() ||
45693 !DAG.haveNoCommonBitsSet(V.getOperand(0), V.getOperand(1)))
45694 return false;
45695 Op0 = V.getOperand(0);
45696 Op1 = V.getOperand(1);
45697 return true;
45698 };
45699
45700 SDValue Op0, Op1;
45701 if (FindAddLike(Operands[0], Op0, Op1))
45702 std::swap(Operands[0], Operands[1]);
45703 else if (!FindAddLike(Operands[1], Op0, Op1))
45704 return SDValue();
45705 Operands[2] = Op0;
45706 Operands[1] = Op1;
45707
45708 // Now we have three operands of two additions. Check that one of them is a
45709 // constant vector with ones, and the other two can be promoted from i8/i16.
45710 for (int i = 0; i < 3; ++i) {
45711 if (!IsConstVectorInRange(Operands[i], 1, 1))
45712 continue;
45713 std::swap(Operands[i], Operands[2]);
45714
45715 // Check if Operands[0] and Operands[1] are results of type promotion.
45716 for (int j = 0; j < 2; ++j)
45717 if (Operands[j].getValueType() != VT) {
45718 if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
45719 Operands[j].getOperand(0).getValueType() != VT)
45720 return SDValue();
45721 Operands[j] = Operands[j].getOperand(0);
45722 }
45723
45724 // The pattern is detected, emit X86ISD::AVG instruction(s).
45725 return AVGSplitter(Operands[0], Operands[1]);
45726 }
45727
45728 return SDValue();
45729}
45730
45731static SDValue combineLoad(SDNode *N, SelectionDAG &DAG,
45732 TargetLowering::DAGCombinerInfo &DCI,
45733 const X86Subtarget &Subtarget) {
45734 LoadSDNode *Ld = cast<LoadSDNode>(N);
45735 EVT RegVT = Ld->getValueType(0);
45736 EVT MemVT = Ld->getMemoryVT();
45737 SDLoc dl(Ld);
45738 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45739
45740 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
45741 // into two 16-byte operations. Also split non-temporal aligned loads on
45742 // pre-AVX2 targets as 32-byte loads will lower to regular temporal loads.
45743 ISD::LoadExtType Ext = Ld->getExtensionType();
45744 bool Fast;
45745 if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
45746 Ext == ISD::NON_EXTLOAD &&
45747 ((Ld->isNonTemporal() && !Subtarget.hasInt256() &&
45748 Ld->getAlignment() >= 16) ||
45749 (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
45750 *Ld->getMemOperand(), &Fast) &&
45751 !Fast))) {
45752 unsigned NumElems = RegVT.getVectorNumElements();
45753 if (NumElems < 2)
45754 return SDValue();
45755
45756 unsigned HalfOffset = 16;
45757 SDValue Ptr1 = Ld->getBasePtr();
45758 SDValue Ptr2 =
45759 DAG.getMemBasePlusOffset(Ptr1, TypeSize::Fixed(HalfOffset), dl);
45760 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
45761 NumElems / 2);
45762 SDValue Load1 =
45763 DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr1, Ld->getPointerInfo(),
45764 Ld->getOriginalAlign(),
45765 Ld->getMemOperand()->getFlags());
45766 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr2,
45767 Ld->getPointerInfo().getWithOffset(HalfOffset),
45768 Ld->getOriginalAlign(),
45769 Ld->getMemOperand()->getFlags());
45770 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
45771 Load1.getValue(1), Load2.getValue(1));
45772
45773 SDValue NewVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Load1, Load2);
45774 return DCI.CombineTo(N, NewVec, TF, true);
45775 }
45776
45777 // Bool vector load - attempt to cast to an integer, as we have good
45778 // (vXiY *ext(vXi1 bitcast(iX))) handling.
45779 if (Ext == ISD::NON_EXTLOAD && !Subtarget.hasAVX512() && RegVT.isVector() &&
45780 RegVT.getScalarType() == MVT::i1 && DCI.isBeforeLegalize()) {
45781 unsigned NumElts = RegVT.getVectorNumElements();
45782 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
45783 if (TLI.isTypeLegal(IntVT)) {
45784 SDValue IntLoad = DAG.getLoad(IntVT, dl, Ld->getChain(), Ld->getBasePtr(),
45785 Ld->getPointerInfo(),
45786 Ld->getOriginalAlign(),
45787 Ld->getMemOperand()->getFlags());
45788 SDValue BoolVec = DAG.getBitcast(RegVT, IntLoad);
45789 return DCI.CombineTo(N, BoolVec, IntLoad.getValue(1), true);
45790 }
45791 }
45792
45793 // If we also broadcast this as a subvector to a wider type, then just extract
45794 // the lowest subvector.
45795 if (Ext == ISD::NON_EXTLOAD && Subtarget.hasAVX() && Ld->isSimple() &&
45796 (RegVT.is128BitVector() || RegVT.is256BitVector())) {
45797 SDValue Ptr = Ld->getBasePtr();
45798 SDValue Chain = Ld->getChain();
45799 for (SDNode *User : Ptr->uses()) {
45800 if (User != N && User->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD &&
45801 cast<MemIntrinsicSDNode>(User)->getBasePtr() == Ptr &&
45802 cast<MemIntrinsicSDNode>(User)->getChain() == Chain &&
45803 cast<MemIntrinsicSDNode>(User)->getMemoryVT().getSizeInBits() ==
45804 MemVT.getSizeInBits() &&
45805 !User->hasAnyUseOfValue(1) &&
45806 User->getValueSizeInBits(0).getFixedSize() >
45807 RegVT.getFixedSizeInBits()) {
45808 SDValue Extract = extractSubVector(SDValue(User, 0), 0, DAG, SDLoc(N),
45809 RegVT.getSizeInBits());
45810 Extract = DAG.getBitcast(RegVT, Extract);
45811 return DCI.CombineTo(N, Extract, SDValue(User, 1));
45812 }
45813 }
45814 }
45815
45816 // Cast ptr32 and ptr64 pointers to the default address space before a load.
45817 unsigned AddrSpace = Ld->getAddressSpace();
45818 if (AddrSpace == X86AS::PTR64 || AddrSpace == X86AS::PTR32_SPTR ||
45819 AddrSpace == X86AS::PTR32_UPTR) {
45820 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
45821 if (PtrVT != Ld->getBasePtr().getSimpleValueType()) {
45822 SDValue Cast =
45823 DAG.getAddrSpaceCast(dl, PtrVT, Ld->getBasePtr(), AddrSpace, 0);
45824 return DAG.getLoad(RegVT, dl, Ld->getChain(), Cast, Ld->getPointerInfo(),
45825 Ld->getOriginalAlign(),
45826 Ld->getMemOperand()->getFlags());
45827 }
45828 }
45829
45830 return SDValue();
45831}
45832
45833/// If V is a build vector of boolean constants and exactly one of those
45834/// constants is true, return the operand index of that true element.
45835/// Otherwise, return -1.
45836static int getOneTrueElt(SDValue V) {
45837 // This needs to be a build vector of booleans.
45838 // TODO: Checking for the i1 type matches the IR definition for the mask,
45839 // but the mask check could be loosened to i8 or other types. That might
45840 // also require checking more than 'allOnesValue'; eg, the x86 HW
45841 // instructions only require that the MSB is set for each mask element.
45842 // The ISD::MSTORE comments/definition do not specify how the mask operand
45843 // is formatted.
45844 auto *BV = dyn_cast<BuildVectorSDNode>(V);
45845 if (!BV || BV->getValueType(0).getVectorElementType() != MVT::i1)
45846 return -1;
45847
45848 int TrueIndex = -1;
45849 unsigned NumElts = BV->getValueType(0).getVectorNumElements();
45850 for (unsigned i = 0; i < NumElts; ++i) {
45851 const SDValue &Op = BV->getOperand(i);
45852 if (Op.isUndef())
45853 continue;
45854 auto *ConstNode = dyn_cast<ConstantSDNode>(Op);
45855 if (!ConstNode)
45856 return -1;
45857 if (ConstNode->getAPIntValue().countTrailingOnes() >= 1) {
45858 // If we already found a one, this is too many.
45859 if (TrueIndex >= 0)
45860 return -1;
45861 TrueIndex = i;
45862 }
45863 }
45864 return TrueIndex;
45865}
45866
45867/// Given a masked memory load/store operation, return true if it has one mask
45868/// bit set. If it has one mask bit set, then also return the memory address of
45869/// the scalar element to load/store, the vector index to insert/extract that
45870/// scalar element, and the alignment for the scalar memory access.
45871static bool getParamsForOneTrueMaskedElt(MaskedLoadStoreSDNode *MaskedOp,
45872 SelectionDAG &DAG, SDValue &Addr,
45873 SDValue &Index, Align &Alignment,
45874 unsigned &Offset) {
45875 int TrueMaskElt = getOneTrueElt(MaskedOp->getMask());
45876 if (TrueMaskElt < 0)
45877 return false;
45878
45879 // Get the address of the one scalar element that is specified by the mask
45880 // using the appropriate offset from the base pointer.
45881 EVT EltVT = MaskedOp->getMemoryVT().getVectorElementType();
45882 Offset = 0;
45883 Addr = MaskedOp->getBasePtr();
45884 if (TrueMaskElt != 0) {
45885 Offset = TrueMaskElt * EltVT.getStoreSize();
45886 Addr = DAG.getMemBasePlusOffset(Addr, TypeSize::Fixed(Offset),
45887 SDLoc(MaskedOp));
45888 }
45889
45890 Index = DAG.getIntPtrConstant(TrueMaskElt, SDLoc(MaskedOp));
45891 Alignment = commonAlignment(MaskedOp->getOriginalAlign(),
45892 EltVT.getStoreSize());
45893 return true;
45894}
45895
45896/// If exactly one element of the mask is set for a non-extending masked load,
45897/// it is a scalar load and vector insert.
45898/// Note: It is expected that the degenerate cases of an all-zeros or all-ones
45899/// mask have already been optimized in IR, so we don't bother with those here.
45900static SDValue
45901reduceMaskedLoadToScalarLoad(MaskedLoadSDNode *ML, SelectionDAG &DAG,
45902 TargetLowering::DAGCombinerInfo &DCI,
45903 const X86Subtarget &Subtarget) {
45904 assert(ML->isUnindexed() && "Unexpected indexed masked load!")(static_cast <bool> (ML->isUnindexed() && "Unexpected indexed masked load!"
) ? void (0) : __assert_fail ("ML->isUnindexed() && \"Unexpected indexed masked load!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 45904, __extension__ __PRETTY_FUNCTION__))
;
45905 // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
45906 // However, some target hooks may need to be added to know when the transform
45907 // is profitable. Endianness would also have to be considered.
45908
45909 SDValue Addr, VecIndex;
45910 Align Alignment;
45911 unsigned Offset;
45912 if (!getParamsForOneTrueMaskedElt(ML, DAG, Addr, VecIndex, Alignment, Offset))
45913 return SDValue();
45914
45915 // Load the one scalar element that is specified by the mask using the
45916 // appropriate offset from the base pointer.
45917 SDLoc DL(ML);
45918 EVT VT = ML->getValueType(0);
45919 EVT EltVT = VT.getVectorElementType();
45920
45921 EVT CastVT = VT;
45922 if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
45923 EltVT = MVT::f64;
45924 CastVT = VT.changeVectorElementType(EltVT);
45925 }
45926
45927 SDValue Load =
45928 DAG.getLoad(EltVT, DL, ML->getChain(), Addr,
45929 ML->getPointerInfo().getWithOffset(Offset),
45930 Alignment, ML->getMemOperand()->getFlags());
45931
45932 SDValue PassThru = DAG.getBitcast(CastVT, ML->getPassThru());
45933
45934 // Insert the loaded element into the appropriate place in the vector.
45935 SDValue Insert =
45936 DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, CastVT, PassThru, Load, VecIndex);
45937 Insert = DAG.getBitcast(VT, Insert);
45938 return DCI.CombineTo(ML, Insert, Load.getValue(1), true);
45939}
45940
45941static SDValue
45942combineMaskedLoadConstantMask(MaskedLoadSDNode *ML, SelectionDAG &DAG,
45943 TargetLowering::DAGCombinerInfo &DCI) {
45944 assert(ML->isUnindexed() && "Unexpected indexed masked load!")(static_cast <bool> (ML->isUnindexed() && "Unexpected indexed masked load!"
) ? void (0) : __assert_fail ("ML->isUnindexed() && \"Unexpected indexed masked load!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 45944, __extension__ __PRETTY_FUNCTION__))
;
45945 if (!ISD::isBuildVectorOfConstantSDNodes(ML->getMask().getNode()))
45946 return SDValue();
45947
45948 SDLoc DL(ML);
45949 EVT VT = ML->getValueType(0);
45950
45951 // If we are loading the first and last elements of a vector, it is safe and
45952 // always faster to load the whole vector. Replace the masked load with a
45953 // vector load and select.
45954 unsigned NumElts = VT.getVectorNumElements();
45955 BuildVectorSDNode *MaskBV = cast<BuildVectorSDNode>(ML->getMask());
45956 bool LoadFirstElt = !isNullConstant(MaskBV->getOperand(0));
45957 bool LoadLastElt = !isNullConstant(MaskBV->getOperand(NumElts - 1));
45958 if (LoadFirstElt && LoadLastElt) {
45959 SDValue VecLd = DAG.getLoad(VT, DL, ML->getChain(), ML->getBasePtr(),
45960 ML->getMemOperand());
45961 SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), VecLd,
45962 ML->getPassThru());
45963 return DCI.CombineTo(ML, Blend, VecLd.getValue(1), true);
45964 }
45965
45966 // Convert a masked load with a constant mask into a masked load and a select.
45967 // This allows the select operation to use a faster kind of select instruction
45968 // (for example, vblendvps -> vblendps).
45969
45970 // Don't try this if the pass-through operand is already undefined. That would
45971 // cause an infinite loop because that's what we're about to create.
45972 if (ML->getPassThru().isUndef())
45973 return SDValue();
45974
45975 if (ISD::isBuildVectorAllZeros(ML->getPassThru().getNode()))
45976 return SDValue();
45977
45978 // The new masked load has an undef pass-through operand. The select uses the
45979 // original pass-through operand.
45980 SDValue NewML = DAG.getMaskedLoad(
45981 VT, DL, ML->getChain(), ML->getBasePtr(), ML->getOffset(), ML->getMask(),
45982 DAG.getUNDEF(VT), ML->getMemoryVT(), ML->getMemOperand(),
45983 ML->getAddressingMode(), ML->getExtensionType());
45984 SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), NewML,
45985 ML->getPassThru());
45986
45987 return DCI.CombineTo(ML, Blend, NewML.getValue(1), true);
45988}
45989
45990static SDValue combineMaskedLoad(SDNode *N, SelectionDAG &DAG,
45991 TargetLowering::DAGCombinerInfo &DCI,
45992 const X86Subtarget &Subtarget) {
45993 auto *Mld = cast<MaskedLoadSDNode>(N);
45994
45995 // TODO: Expanding load with constant mask may be optimized as well.
45996 if (Mld->isExpandingLoad())
45997 return SDValue();
45998
45999 if (Mld->getExtensionType() == ISD::NON_EXTLOAD) {
46000 if (SDValue ScalarLoad =
46001 reduceMaskedLoadToScalarLoad(Mld, DAG, DCI, Subtarget))
46002 return ScalarLoad;
46003
46004 // TODO: Do some AVX512 subsets benefit from this transform?
46005 if (!Subtarget.hasAVX512())
46006 if (SDValue Blend = combineMaskedLoadConstantMask(Mld, DAG, DCI))
46007 return Blend;
46008 }
46009
46010 // If the mask value has been legalized to a non-boolean vector, try to
46011 // simplify ops leading up to it. We only demand the MSB of each lane.
46012 SDValue Mask = Mld->getMask();
46013 if (Mask.getScalarValueSizeInBits() != 1) {
46014 EVT VT = Mld->getValueType(0);
46015 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46016 APInt DemandedBits(APInt::getSignMask(VT.getScalarSizeInBits()));
46017 if (TLI.SimplifyDemandedBits(Mask, DemandedBits, DCI)) {
46018 if (N->getOpcode() != ISD::DELETED_NODE)
46019 DCI.AddToWorklist(N);
46020 return SDValue(N, 0);
46021 }
46022 if (SDValue NewMask =
46023 TLI.SimplifyMultipleUseDemandedBits(Mask, DemandedBits, DAG))
46024 return DAG.getMaskedLoad(
46025 VT, SDLoc(N), Mld->getChain(), Mld->getBasePtr(), Mld->getOffset(),
46026 NewMask, Mld->getPassThru(), Mld->getMemoryVT(), Mld->getMemOperand(),
46027 Mld->getAddressingMode(), Mld->getExtensionType());
46028 }
46029
46030 return SDValue();
46031}
46032
46033/// If exactly one element of the mask is set for a non-truncating masked store,
46034/// it is a vector extract and scalar store.
46035/// Note: It is expected that the degenerate cases of an all-zeros or all-ones
46036/// mask have already been optimized in IR, so we don't bother with those here.
46037static SDValue reduceMaskedStoreToScalarStore(MaskedStoreSDNode *MS,
46038 SelectionDAG &DAG,
46039 const X86Subtarget &Subtarget) {
46040 // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
46041 // However, some target hooks may need to be added to know when the transform
46042 // is profitable. Endianness would also have to be considered.
46043
46044 SDValue Addr, VecIndex;
46045 Align Alignment;
46046 unsigned Offset;
46047 if (!getParamsForOneTrueMaskedElt(MS, DAG, Addr, VecIndex, Alignment, Offset))
46048 return SDValue();
46049
46050 // Extract the one scalar element that is actually being stored.
46051 SDLoc DL(MS);
46052 SDValue Value = MS->getValue();
46053 EVT VT = Value.getValueType();
46054 EVT EltVT = VT.getVectorElementType();
46055 if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
46056 EltVT = MVT::f64;
46057 EVT CastVT = VT.changeVectorElementType(EltVT);
46058 Value = DAG.getBitcast(CastVT, Value);
46059 }
46060 SDValue Extract =
46061 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Value, VecIndex);
46062
46063 // Store that element at the appropriate offset from the base pointer.
46064 return DAG.getStore(MS->getChain(), DL, Extract, Addr,
46065 MS->getPointerInfo().getWithOffset(Offset),
46066 Alignment, MS->getMemOperand()->getFlags());
46067}
46068
46069static SDValue combineMaskedStore(SDNode *N, SelectionDAG &DAG,
46070 TargetLowering::DAGCombinerInfo &DCI,
46071 const X86Subtarget &Subtarget) {
46072 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
46073 if (Mst->isCompressingStore())
46074 return SDValue();
46075
46076 EVT VT = Mst->getValue().getValueType();
46077 SDLoc dl(Mst);
46078 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46079
46080 if (Mst->isTruncatingStore())
46081 return SDValue();
46082
46083 if (SDValue ScalarStore = reduceMaskedStoreToScalarStore(Mst, DAG, Subtarget))
46084 return ScalarStore;
46085
46086 // If the mask value has been legalized to a non-boolean vector, try to
46087 // simplify ops leading up to it. We only demand the MSB of each lane.
46088 SDValue Mask = Mst->getMask();
46089 if (Mask.getScalarValueSizeInBits() != 1) {
46090 APInt DemandedBits(APInt::getSignMask(VT.getScalarSizeInBits()));
46091 if (TLI.SimplifyDemandedBits(Mask, DemandedBits, DCI)) {
46092 if (N->getOpcode() != ISD::DELETED_NODE)
46093 DCI.AddToWorklist(N);
46094 return SDValue(N, 0);
46095 }
46096 if (SDValue NewMask =
46097 TLI.SimplifyMultipleUseDemandedBits(Mask, DemandedBits, DAG))
46098 return DAG.getMaskedStore(Mst->getChain(), SDLoc(N), Mst->getValue(),
46099 Mst->getBasePtr(), Mst->getOffset(), NewMask,
46100 Mst->getMemoryVT(), Mst->getMemOperand(),
46101 Mst->getAddressingMode());
46102 }
46103
46104 SDValue Value = Mst->getValue();
46105 if (Value.getOpcode() == ISD::TRUNCATE && Value.getNode()->hasOneUse() &&
46106 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
46107 Mst->getMemoryVT())) {
46108 return DAG.getMaskedStore(Mst->getChain(), SDLoc(N), Value.getOperand(0),
46109 Mst->getBasePtr(), Mst->getOffset(), Mask,
46110 Mst->getMemoryVT(), Mst->getMemOperand(),
46111 Mst->getAddressingMode(), true);
46112 }
46113
46114 return SDValue();
46115}
46116
46117static SDValue combineStore(SDNode *N, SelectionDAG &DAG,
46118 TargetLowering::DAGCombinerInfo &DCI,
46119 const X86Subtarget &Subtarget) {
46120 StoreSDNode *St = cast<StoreSDNode>(N);
46121 EVT StVT = St->getMemoryVT();
46122 SDLoc dl(St);
46123 SDValue StoredVal = St->getValue();
46124 EVT VT = StoredVal.getValueType();
46125 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46126
46127 // Convert a store of vXi1 into a store of iX and a bitcast.
46128 if (!Subtarget.hasAVX512() && VT == StVT && VT.isVector() &&
46129 VT.getVectorElementType() == MVT::i1) {
46130
46131 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), VT.getVectorNumElements());
46132 StoredVal = DAG.getBitcast(NewVT, StoredVal);
46133
46134 return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
46135 St->getPointerInfo(), St->getOriginalAlign(),
46136 St->getMemOperand()->getFlags());
46137 }
46138
46139 // If this is a store of a scalar_to_vector to v1i1, just use a scalar store.
46140 // This will avoid a copy to k-register.
46141 if (VT == MVT::v1i1 && VT == StVT && Subtarget.hasAVX512() &&
46142 StoredVal.getOpcode() == ISD::SCALAR_TO_VECTOR &&
46143 StoredVal.getOperand(0).getValueType() == MVT::i8) {
46144 SDValue Val = StoredVal.getOperand(0);
46145 // We must store zeros to the unused bits.
46146 Val = DAG.getZeroExtendInReg(Val, dl, MVT::i1);
46147 return DAG.getStore(St->getChain(), dl, Val,
46148 St->getBasePtr(), St->getPointerInfo(),
46149 St->getOriginalAlign(),
46150 St->getMemOperand()->getFlags());
46151 }
46152
46153 // Widen v2i1/v4i1 stores to v8i1.
46154 if ((VT == MVT::v1i1 || VT == MVT::v2i1 || VT == MVT::v4i1) && VT == StVT &&
46155 Subtarget.hasAVX512()) {
46156 unsigned NumConcats = 8 / VT.getVectorNumElements();
46157 // We must store zeros to the unused bits.
46158 SmallVector<SDValue, 4> Ops(NumConcats, DAG.getConstant(0, dl, VT));
46159 Ops[0] = StoredVal;
46160 StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
46161 return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
46162 St->getPointerInfo(), St->getOriginalAlign(),
46163 St->getMemOperand()->getFlags());
46164 }
46165
46166 // Turn vXi1 stores of constants into a scalar store.
46167 if ((VT == MVT::v8i1 || VT == MVT::v16i1 || VT == MVT::v32i1 ||
46168 VT == MVT::v64i1) && VT == StVT && TLI.isTypeLegal(VT) &&
46169 ISD::isBuildVectorOfConstantSDNodes(StoredVal.getNode())) {
46170 // If its a v64i1 store without 64-bit support, we need two stores.
46171 if (!DCI.isBeforeLegalize() && VT == MVT::v64i1 && !Subtarget.is64Bit()) {
46172 SDValue Lo = DAG.getBuildVector(MVT::v32i1, dl,
46173 StoredVal->ops().slice(0, 32));
46174 Lo = combinevXi1ConstantToInteger(Lo, DAG);
46175 SDValue Hi = DAG.getBuildVector(MVT::v32i1, dl,
46176 StoredVal->ops().slice(32, 32));
46177 Hi = combinevXi1ConstantToInteger(Hi, DAG);
46178
46179 SDValue Ptr0 = St->getBasePtr();
46180 SDValue Ptr1 = DAG.getMemBasePlusOffset(Ptr0, TypeSize::Fixed(4), dl);
46181
46182 SDValue Ch0 =
46183 DAG.getStore(St->getChain(), dl, Lo, Ptr0, St->getPointerInfo(),
46184 St->getOriginalAlign(),
46185 St->getMemOperand()->getFlags());
46186 SDValue Ch1 =
46187 DAG.getStore(St->getChain(), dl, Hi, Ptr1,
46188 St->getPointerInfo().getWithOffset(4),
46189 St->getOriginalAlign(),
46190 St->getMemOperand()->getFlags());
46191 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
46192 }
46193
46194 StoredVal = combinevXi1ConstantToInteger(StoredVal, DAG);
46195 return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
46196 St->getPointerInfo(), St->getOriginalAlign(),
46197 St->getMemOperand()->getFlags());
46198 }
46199
46200 // If we are saving a 32-byte vector and 32-byte stores are slow, such as on
46201 // Sandy Bridge, perform two 16-byte stores.
46202 bool Fast;
46203 if (VT.is256BitVector() && StVT == VT &&
46204 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
46205 *St->getMemOperand(), &Fast) &&
46206 !Fast) {
46207 unsigned NumElems = VT.getVectorNumElements();
46208 if (NumElems < 2)
46209 return SDValue();
46210
46211 return splitVectorStore(St, DAG);
46212 }
46213
46214 // Split under-aligned vector non-temporal stores.
46215 if (St->isNonTemporal() && StVT == VT &&
46216 St->getAlignment() < VT.getStoreSize()) {
46217 // ZMM/YMM nt-stores - either it can be stored as a series of shorter
46218 // vectors or the legalizer can scalarize it to use MOVNTI.
46219 if (VT.is256BitVector() || VT.is512BitVector()) {
46220 unsigned NumElems = VT.getVectorNumElements();
46221 if (NumElems < 2)
46222 return SDValue();
46223 return splitVectorStore(St, DAG);
46224 }
46225
46226 // XMM nt-stores - scalarize this to f64 nt-stores on SSE4A, else i32/i64
46227 // to use MOVNTI.
46228 if (VT.is128BitVector() && Subtarget.hasSSE2()) {
46229 MVT NTVT = Subtarget.hasSSE4A()
46230 ? MVT::v2f64
46231 : (TLI.isTypeLegal(MVT::i64) ? MVT::v2i64 : MVT::v4i32);
46232 return scalarizeVectorStore(St, NTVT, DAG);
46233 }
46234 }
46235
46236 // Try to optimize v16i16->v16i8 truncating stores when BWI is not
46237 // supported, but avx512f is by extending to v16i32 and truncating.
46238 if (!St->isTruncatingStore() && VT == MVT::v16i8 && !Subtarget.hasBWI() &&
46239 St->getValue().getOpcode() == ISD::TRUNCATE &&
46240 St->getValue().getOperand(0).getValueType() == MVT::v16i16 &&
46241 TLI.isTruncStoreLegal(MVT::v16i32, MVT::v16i8) &&
46242 St->getValue().hasOneUse() && !DCI.isBeforeLegalizeOps()) {
46243 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::v16i32, St->getValue());
46244 return DAG.getTruncStore(St->getChain(), dl, Ext, St->getBasePtr(),
46245 MVT::v16i8, St->getMemOperand());
46246 }
46247
46248 // Try to fold a VTRUNCUS or VTRUNCS into a truncating store.
46249 if (!St->isTruncatingStore() && StoredVal.hasOneUse() &&
46250 (StoredVal.getOpcode() == X86ISD::VTRUNCUS ||
46251 StoredVal.getOpcode() == X86ISD::VTRUNCS) &&
46252 TLI.isTruncStoreLegal(StoredVal.getOperand(0).getValueType(), VT)) {
46253 bool IsSigned = StoredVal.getOpcode() == X86ISD::VTRUNCS;
46254 return EmitTruncSStore(IsSigned, St->getChain(),
46255 dl, StoredVal.getOperand(0), St->getBasePtr(),
46256 VT, St->getMemOperand(), DAG);
46257 }
46258
46259 // Try to fold a extract_element(VTRUNC) pattern into a truncating store.
46260 if (!St->isTruncatingStore() && StoredVal.hasOneUse()) {
46261 auto IsExtractedElement = [](SDValue V) {
46262 if (V.getOpcode() == ISD::TRUNCATE && V.getOperand(0).hasOneUse())
46263 V = V.getOperand(0);
46264 unsigned Opc = V.getOpcode();
46265 if (Opc == ISD::EXTRACT_VECTOR_ELT || Opc == X86ISD::PEXTRW) {
46266 if (V.getOperand(0).hasOneUse() && isNullConstant(V.getOperand(1)))
46267 return V.getOperand(0);
46268 }
46269 return SDValue();
46270 };
46271 if (SDValue Extract = IsExtractedElement(StoredVal)) {
46272 SDValue Trunc = peekThroughOneUseBitcasts(Extract);
46273 if (Trunc.getOpcode() == X86ISD::VTRUNC) {
46274 SDValue Src = Trunc.getOperand(0);
46275 MVT DstVT = Trunc.getSimpleValueType();
46276 MVT SrcVT = Src.getSimpleValueType();
46277 unsigned NumSrcElts = SrcVT.getVectorNumElements();
46278 unsigned NumTruncBits = DstVT.getScalarSizeInBits() * NumSrcElts;
46279 MVT TruncVT = MVT::getVectorVT(DstVT.getScalarType(), NumSrcElts);
46280 if (NumTruncBits == VT.getSizeInBits() &&
46281 TLI.isTruncStoreLegal(SrcVT, TruncVT)) {
46282 return DAG.getTruncStore(St->getChain(), dl, Src, St->getBasePtr(),
46283 TruncVT, St->getMemOperand());
46284 }
46285 }
46286 }
46287 }
46288
46289 // Optimize trunc store (of multiple scalars) to shuffle and store.
46290 // First, pack all of the elements in one place. Next, store to memory
46291 // in fewer chunks.
46292 if (St->isTruncatingStore() && VT.isVector()) {
46293 // Check if we can detect an AVG pattern from the truncation. If yes,
46294 // replace the trunc store by a normal store with the result of X86ISD::AVG
46295 // instruction.
46296 if (DCI.isBeforeLegalize() || TLI.isTypeLegal(St->getMemoryVT()))
46297 if (SDValue Avg = detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG,
46298 Subtarget, dl))
46299 return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
46300 St->getPointerInfo(), St->getOriginalAlign(),
46301 St->getMemOperand()->getFlags());
46302
46303 if (TLI.isTruncStoreLegal(VT, StVT)) {
46304 if (SDValue Val = detectSSatPattern(St->getValue(), St->getMemoryVT()))
46305 return EmitTruncSStore(true /* Signed saturation */, St->getChain(),
46306 dl, Val, St->getBasePtr(),
46307 St->getMemoryVT(), St->getMemOperand(), DAG);
46308 if (SDValue Val = detectUSatPattern(St->getValue(), St->getMemoryVT(),
46309 DAG, dl))
46310 return EmitTruncSStore(false /* Unsigned saturation */, St->getChain(),
46311 dl, Val, St->getBasePtr(),
46312 St->getMemoryVT(), St->getMemOperand(), DAG);
46313 }
46314
46315 return SDValue();
46316 }
46317
46318 // Cast ptr32 and ptr64 pointers to the default address space before a store.
46319 unsigned AddrSpace = St->getAddressSpace();
46320 if (AddrSpace == X86AS::PTR64 || AddrSpace == X86AS::PTR32_SPTR ||
46321 AddrSpace == X86AS::PTR32_UPTR) {
46322 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
46323 if (PtrVT != St->getBasePtr().getSimpleValueType()) {
46324 SDValue Cast =
46325 DAG.getAddrSpaceCast(dl, PtrVT, St->getBasePtr(), AddrSpace, 0);
46326 return DAG.getStore(St->getChain(), dl, StoredVal, Cast,
46327 St->getPointerInfo(), St->getOriginalAlign(),
46328 St->getMemOperand()->getFlags(), St->getAAInfo());
46329 }
46330 }
46331
46332 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
46333 // the FP state in cases where an emms may be missing.
46334 // A preferable solution to the general problem is to figure out the right
46335 // places to insert EMMS. This qualifies as a quick hack.
46336
46337 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
46338 if (VT.getSizeInBits() != 64)
46339 return SDValue();
46340
46341 const Function &F = DAG.getMachineFunction().getFunction();
46342 bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
46343 bool F64IsLegal =
46344 !Subtarget.useSoftFloat() && !NoImplicitFloatOps && Subtarget.hasSSE2();
46345 if ((VT == MVT::i64 && F64IsLegal && !Subtarget.is64Bit()) &&
46346 isa<LoadSDNode>(St->getValue()) &&
46347 cast<LoadSDNode>(St->getValue())->isSimple() &&
46348 St->getChain().hasOneUse() && St->isSimple()) {
46349 LoadSDNode *Ld = cast<LoadSDNode>(St->getValue().getNode());
46350
46351 if (!ISD::isNormalLoad(Ld))
46352 return SDValue();
46353
46354 // Avoid the transformation if there are multiple uses of the loaded value.
46355 if (!Ld->hasNUsesOfValue(1, 0))
46356 return SDValue();
46357
46358 SDLoc LdDL(Ld);
46359 SDLoc StDL(N);
46360 // Lower to a single movq load/store pair.
46361 SDValue NewLd = DAG.getLoad(MVT::f64, LdDL, Ld->getChain(),
46362 Ld->getBasePtr(), Ld->getMemOperand());
46363
46364 // Make sure new load is placed in same chain order.
46365 DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
46366 return DAG.getStore(St->getChain(), StDL, NewLd, St->getBasePtr(),
46367 St->getMemOperand());
46368 }
46369
46370 // This is similar to the above case, but here we handle a scalar 64-bit
46371 // integer store that is extracted from a vector on a 32-bit target.
46372 // If we have SSE2, then we can treat it like a floating-point double
46373 // to get past legalization. The execution dependencies fixup pass will
46374 // choose the optimal machine instruction for the store if this really is
46375 // an integer or v2f32 rather than an f64.
46376 if (VT == MVT::i64 && F64IsLegal && !Subtarget.is64Bit() &&
46377 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
46378 SDValue OldExtract = St->getOperand(1);
46379 SDValue ExtOp0 = OldExtract.getOperand(0);
46380 unsigned VecSize = ExtOp0.getValueSizeInBits();
46381 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
46382 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
46383 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
46384 BitCast, OldExtract.getOperand(1));
46385 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
46386 St->getPointerInfo(), St->getOriginalAlign(),
46387 St->getMemOperand()->getFlags());
46388 }
46389
46390 return SDValue();
46391}
46392
46393static SDValue combineVEXTRACT_STORE(SDNode *N, SelectionDAG &DAG,
46394 TargetLowering::DAGCombinerInfo &DCI,
46395 const X86Subtarget &Subtarget) {
46396 auto *St = cast<MemIntrinsicSDNode>(N);
46397
46398 SDValue StoredVal = N->getOperand(1);
46399 MVT VT = StoredVal.getSimpleValueType();
46400 EVT MemVT = St->getMemoryVT();
46401
46402 // Figure out which elements we demand.
46403 unsigned StElts = MemVT.getSizeInBits() / VT.getScalarSizeInBits();
46404 APInt DemandedElts = APInt::getLowBitsSet(VT.getVectorNumElements(), StElts);
46405
46406 APInt KnownUndef, KnownZero;
46407 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46408 if (TLI.SimplifyDemandedVectorElts(StoredVal, DemandedElts, KnownUndef,
46409 KnownZero, DCI)) {
46410 if (N->getOpcode() != ISD::DELETED_NODE)
46411 DCI.AddToWorklist(N);
46412 return SDValue(N, 0);
46413 }
46414
46415 return SDValue();
46416}
46417
46418/// Return 'true' if this vector operation is "horizontal"
46419/// and return the operands for the horizontal operation in LHS and RHS. A
46420/// horizontal operation performs the binary operation on successive elements
46421/// of its first operand, then on successive elements of its second operand,
46422/// returning the resulting values in a vector. For example, if
46423/// A = < float a0, float a1, float a2, float a3 >
46424/// and
46425/// B = < float b0, float b1, float b2, float b3 >
46426/// then the result of doing a horizontal operation on A and B is
46427/// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
46428/// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
46429/// A horizontal-op B, for some already available A and B, and if so then LHS is
46430/// set to A, RHS to B, and the routine returns 'true'.
46431static bool isHorizontalBinOp(unsigned HOpcode, SDValue &LHS, SDValue &RHS,
46432 SelectionDAG &DAG, const X86Subtarget &Subtarget,
46433 bool IsCommutative,
46434 SmallVectorImpl<int> &PostShuffleMask) {
46435 // If either operand is undef, bail out. The binop should be simplified.
46436 if (LHS.isUndef() || RHS.isUndef())
46437 return false;
46438
46439 // Look for the following pattern:
46440 // A = < float a0, float a1, float a2, float a3 >
46441 // B = < float b0, float b1, float b2, float b3 >
46442 // and
46443 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
46444 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
46445 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
46446 // which is A horizontal-op B.
46447
46448 MVT VT = LHS.getSimpleValueType();
46449 assert((VT.is128BitVector() || VT.is256BitVector()) &&(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
()) && "Unsupported vector type for horizontal add/sub"
) ? void (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector()) && \"Unsupported vector type for horizontal add/sub\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 46450, __extension__ __PRETTY_FUNCTION__))
46450 "Unsupported vector type for horizontal add/sub")(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
()) && "Unsupported vector type for horizontal add/sub"
) ? void (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector()) && \"Unsupported vector type for horizontal add/sub\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 46450, __extension__ __PRETTY_FUNCTION__))
;
46451 unsigned NumElts = VT.getVectorNumElements();
46452
46453 auto GetShuffle = [&](SDValue Op, SDValue &N0, SDValue &N1,
46454 SmallVectorImpl<int> &ShuffleMask) {
46455 bool UseSubVector = false;
46456 if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
46457 Op.getOperand(0).getValueType().is256BitVector() &&
46458 llvm::isNullConstant(Op.getOperand(1))) {
46459 Op = Op.getOperand(0);
46460 UseSubVector = true;
46461 }
46462 SmallVector<SDValue, 2> SrcOps;
46463 SmallVector<int, 16> SrcMask, ScaledMask;
46464 SDValue BC = peekThroughBitcasts(Op);
46465 if (getTargetShuffleInputs(BC, SrcOps, SrcMask, DAG) &&
46466 !isAnyZero(SrcMask) && all_of(SrcOps, [BC](SDValue Op) {
46467 return Op.getValueSizeInBits() == BC.getValueSizeInBits();
46468 })) {
46469 resolveTargetShuffleInputsAndMask(SrcOps, SrcMask);
46470 if (!UseSubVector && SrcOps.size() <= 2 &&
46471 scaleShuffleElements(SrcMask, NumElts, ScaledMask)) {
46472 N0 = SrcOps.size() > 0 ? SrcOps[0] : SDValue();
46473 N1 = SrcOps.size() > 1 ? SrcOps[1] : SDValue();
46474 ShuffleMask.assign(ScaledMask.begin(), ScaledMask.end());
46475 }
46476 if (UseSubVector && SrcOps.size() == 1 &&
46477 scaleShuffleElements(SrcMask, 2 * NumElts, ScaledMask)) {
46478 std::tie(N0, N1) = DAG.SplitVector(SrcOps[0], SDLoc(Op));
46479 ArrayRef<int> Mask = ArrayRef<int>(ScaledMask).slice(0, NumElts);
46480 ShuffleMask.assign(Mask.begin(), Mask.end());
46481 }
46482 }
46483 };
46484
46485 // View LHS in the form
46486 // LHS = VECTOR_SHUFFLE A, B, LMask
46487 // If LHS is not a shuffle, then pretend it is the identity shuffle:
46488 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
46489 // NOTE: A default initialized SDValue represents an UNDEF of type VT.
46490 SDValue A, B;
46491 SmallVector<int, 16> LMask;
46492 GetShuffle(LHS, A, B, LMask);
46493
46494 // Likewise, view RHS in the form
46495 // RHS = VECTOR_SHUFFLE C, D, RMask
46496 SDValue C, D;
46497 SmallVector<int, 16> RMask;
46498 GetShuffle(RHS, C, D, RMask);
46499
46500 // At least one of the operands should be a vector shuffle.
46501 unsigned NumShuffles = (LMask.empty() ? 0 : 1) + (RMask.empty() ? 0 : 1);
46502 if (NumShuffles == 0)
46503 return false;
46504
46505 if (LMask.empty()) {
46506 A = LHS;
46507 for (unsigned i = 0; i != NumElts; ++i)
46508 LMask.push_back(i);
46509 }
46510
46511 if (RMask.empty()) {
46512 C = RHS;
46513 for (unsigned i = 0; i != NumElts; ++i)
46514 RMask.push_back(i);
46515 }
46516
46517 // If we have an unary mask, ensure the other op is set to null.
46518 if (isUndefOrInRange(LMask, 0, NumElts))
46519 B = SDValue();
46520 else if (isUndefOrInRange(LMask, NumElts, NumElts * 2))
46521 A = SDValue();
46522
46523 if (isUndefOrInRange(RMask, 0, NumElts))
46524 D = SDValue();
46525 else if (isUndefOrInRange(RMask, NumElts, NumElts * 2))
46526 C = SDValue();
46527
46528 // If A and B occur in reverse order in RHS, then canonicalize by commuting
46529 // RHS operands and shuffle mask.
46530 if (A != C) {
46531 std::swap(C, D);
46532 ShuffleVectorSDNode::commuteMask(RMask);
46533 }
46534 // Check that the shuffles are both shuffling the same vectors.
46535 if (!(A == C && B == D))
46536 return false;
46537
46538 PostShuffleMask.clear();
46539 PostShuffleMask.append(NumElts, SM_SentinelUndef);
46540
46541 // LHS and RHS are now:
46542 // LHS = shuffle A, B, LMask
46543 // RHS = shuffle A, B, RMask
46544 // Check that the masks correspond to performing a horizontal operation.
46545 // AVX defines horizontal add/sub to operate independently on 128-bit lanes,
46546 // so we just repeat the inner loop if this is a 256-bit op.
46547 unsigned Num128BitChunks = VT.getSizeInBits() / 128;
46548 unsigned NumEltsPer128BitChunk = NumElts / Num128BitChunks;
46549 unsigned NumEltsPer64BitChunk = NumEltsPer128BitChunk / 2;
46550 assert((NumEltsPer128BitChunk % 2 == 0) &&(static_cast <bool> ((NumEltsPer128BitChunk % 2 == 0) &&
"Vector type should have an even number of elements in each lane"
) ? void (0) : __assert_fail ("(NumEltsPer128BitChunk % 2 == 0) && \"Vector type should have an even number of elements in each lane\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 46551, __extension__ __PRETTY_FUNCTION__))
46551 "Vector type should have an even number of elements in each lane")(static_cast <bool> ((NumEltsPer128BitChunk % 2 == 0) &&
"Vector type should have an even number of elements in each lane"
) ? void (0) : __assert_fail ("(NumEltsPer128BitChunk % 2 == 0) && \"Vector type should have an even number of elements in each lane\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 46551, __extension__ __PRETTY_FUNCTION__))
;
46552 for (unsigned j = 0; j != NumElts; j += NumEltsPer128BitChunk) {
46553 for (unsigned i = 0; i != NumEltsPer128BitChunk; ++i) {
46554 // Ignore undefined components.
46555 int LIdx = LMask[i + j], RIdx = RMask[i + j];
46556 if (LIdx < 0 || RIdx < 0 ||
46557 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
46558 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
46559 continue;
46560
46561 // Check that successive odd/even elements are being operated on. If not,
46562 // this is not a horizontal operation.
46563 if (!((RIdx & 1) == 1 && (LIdx + 1) == RIdx) &&
46564 !((LIdx & 1) == 1 && (RIdx + 1) == LIdx && IsCommutative))
46565 return false;
46566
46567 // Compute the post-shuffle mask index based on where the element
46568 // is stored in the HOP result, and where it needs to be moved to.
46569 int Base = LIdx & ~1u;
46570 int Index = ((Base % NumEltsPer128BitChunk) / 2) +
46571 ((Base % NumElts) & ~(NumEltsPer128BitChunk - 1));
46572
46573 // The low half of the 128-bit result must choose from A.
46574 // The high half of the 128-bit result must choose from B,
46575 // unless B is undef. In that case, we are always choosing from A.
46576 if ((B && Base >= (int)NumElts) || (!B && i >= NumEltsPer64BitChunk))
46577 Index += NumEltsPer64BitChunk;
46578 PostShuffleMask[i + j] = Index;
46579 }
46580 }
46581
46582 SDValue NewLHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
46583 SDValue NewRHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
46584
46585 bool IsIdentityPostShuffle =
46586 isSequentialOrUndefInRange(PostShuffleMask, 0, NumElts, 0);
46587 if (IsIdentityPostShuffle)
46588 PostShuffleMask.clear();
46589
46590 // Avoid 128-bit multi lane shuffles if pre-AVX2 and FP (integer will split).
46591 if (!IsIdentityPostShuffle && !Subtarget.hasAVX2() && VT.isFloatingPoint() &&
46592 isMultiLaneShuffleMask(128, VT.getScalarSizeInBits(), PostShuffleMask))
46593 return false;
46594
46595 // If the source nodes are already used in HorizOps then always accept this.
46596 // Shuffle folding should merge these back together.
46597 bool FoundHorizLHS = llvm::any_of(NewLHS->uses(), [&](SDNode *User) {
46598 return User->getOpcode() == HOpcode && User->getValueType(0) == VT;
46599 });
46600 bool FoundHorizRHS = llvm::any_of(NewRHS->uses(), [&](SDNode *User) {
46601 return User->getOpcode() == HOpcode && User->getValueType(0) == VT;
46602 });
46603 bool ForceHorizOp = FoundHorizLHS && FoundHorizRHS;
46604
46605 // Assume a SingleSource HOP if we only shuffle one input and don't need to
46606 // shuffle the result.
46607 if (!ForceHorizOp &&
46608 !shouldUseHorizontalOp(NewLHS == NewRHS &&
46609 (NumShuffles < 2 || !IsIdentityPostShuffle),
46610 DAG, Subtarget))
46611 return false;
46612
46613 LHS = DAG.getBitcast(VT, NewLHS);
46614 RHS = DAG.getBitcast(VT, NewRHS);
46615 return true;
46616}
46617
46618// Try to synthesize horizontal (f)hadd/hsub from (f)adds/subs of shuffles.
46619static SDValue combineToHorizontalAddSub(SDNode *N, SelectionDAG &DAG,
46620 const X86Subtarget &Subtarget) {
46621 EVT VT = N->getValueType(0);
46622 unsigned Opcode = N->getOpcode();
46623 bool IsAdd = (Opcode == ISD::FADD) || (Opcode == ISD::ADD);
46624 SmallVector<int, 8> PostShuffleMask;
46625
46626 switch (Opcode) {
46627 case ISD::FADD:
46628 case ISD::FSUB:
46629 if ((Subtarget.hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
46630 (Subtarget.hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
46631 SDValue LHS = N->getOperand(0);
46632 SDValue RHS = N->getOperand(1);
46633 auto HorizOpcode = IsAdd ? X86ISD::FHADD : X86ISD::FHSUB;
46634 if (isHorizontalBinOp(HorizOpcode, LHS, RHS, DAG, Subtarget, IsAdd,
46635 PostShuffleMask)) {
46636 SDValue HorizBinOp = DAG.getNode(HorizOpcode, SDLoc(N), VT, LHS, RHS);
46637 if (!PostShuffleMask.empty())
46638 HorizBinOp = DAG.getVectorShuffle(VT, SDLoc(HorizBinOp), HorizBinOp,
46639 DAG.getUNDEF(VT), PostShuffleMask);
46640 return HorizBinOp;
46641 }
46642 }
46643 break;
46644 case ISD::ADD:
46645 case ISD::SUB:
46646 if (Subtarget.hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32 ||
46647 VT == MVT::v16i16 || VT == MVT::v8i32)) {
46648 SDValue LHS = N->getOperand(0);
46649 SDValue RHS = N->getOperand(1);
46650 auto HorizOpcode = IsAdd ? X86ISD::HADD : X86ISD::HSUB;
46651 if (isHorizontalBinOp(HorizOpcode, LHS, RHS, DAG, Subtarget, IsAdd,
46652 PostShuffleMask)) {
46653 auto HOpBuilder = [HorizOpcode](SelectionDAG &DAG, const SDLoc &DL,
46654 ArrayRef<SDValue> Ops) {
46655 return DAG.getNode(HorizOpcode, DL, Ops[0].getValueType(), Ops);
46656 };
46657 SDValue HorizBinOp = SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT,
46658 {LHS, RHS}, HOpBuilder);
46659 if (!PostShuffleMask.empty())
46660 HorizBinOp = DAG.getVectorShuffle(VT, SDLoc(HorizBinOp), HorizBinOp,
46661 DAG.getUNDEF(VT), PostShuffleMask);
46662 return HorizBinOp;
46663 }
46664 }
46665 break;
46666 }
46667
46668 return SDValue();
46669}
46670
46671/// Do target-specific dag combines on floating-point adds/subs.
46672static SDValue combineFaddFsub(SDNode *N, SelectionDAG &DAG,
46673 const X86Subtarget &Subtarget) {
46674 if (SDValue HOp = combineToHorizontalAddSub(N, DAG, Subtarget))
46675 return HOp;
46676 return SDValue();
46677}
46678
46679/// Attempt to pre-truncate inputs to arithmetic ops if it will simplify
46680/// the codegen.
46681/// e.g. TRUNC( BINOP( X, Y ) ) --> BINOP( TRUNC( X ), TRUNC( Y ) )
46682/// TODO: This overlaps with the generic combiner's visitTRUNCATE. Remove
46683/// anything that is guaranteed to be transformed by DAGCombiner.
46684static SDValue combineTruncatedArithmetic(SDNode *N, SelectionDAG &DAG,
46685 const X86Subtarget &Subtarget,
46686 const SDLoc &DL) {
46687 assert(N->getOpcode() == ISD::TRUNCATE && "Wrong opcode")(static_cast <bool> (N->getOpcode() == ISD::TRUNCATE
&& "Wrong opcode") ? void (0) : __assert_fail ("N->getOpcode() == ISD::TRUNCATE && \"Wrong opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 46687, __extension__ __PRETTY_FUNCTION__))
;
46688 SDValue Src = N->getOperand(0);
46689 unsigned SrcOpcode = Src.getOpcode();
46690 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46691
46692 EVT VT = N->getValueType(0);
46693 EVT SrcVT = Src.getValueType();
46694
46695 auto IsFreeTruncation = [VT](SDValue Op) {
46696 unsigned TruncSizeInBits = VT.getScalarSizeInBits();
46697
46698 // See if this has been extended from a smaller/equal size to
46699 // the truncation size, allowing a truncation to combine with the extend.
46700 unsigned Opcode = Op.getOpcode();
46701 if ((Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND ||
46702 Opcode == ISD::ZERO_EXTEND) &&
46703 Op.getOperand(0).getScalarValueSizeInBits() <= TruncSizeInBits)
46704 return true;
46705
46706 // See if this is a single use constant which can be constant folded.
46707 // NOTE: We don't peek throught bitcasts here because there is currently
46708 // no support for constant folding truncate+bitcast+vector_of_constants. So
46709 // we'll just send up with a truncate on both operands which will
46710 // get turned back into (truncate (binop)) causing an infinite loop.
46711 return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
46712 };
46713
46714 auto TruncateArithmetic = [&](SDValue N0, SDValue N1) {
46715 SDValue Trunc0 = DAG.getNode(ISD::TRUNCATE, DL, VT, N0);
46716 SDValue Trunc1 = DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
46717 return DAG.getNode(SrcOpcode, DL, VT, Trunc0, Trunc1);
46718 };
46719
46720 // Don't combine if the operation has other uses.
46721 if (!Src.hasOneUse())
46722 return SDValue();
46723
46724 // Only support vector truncation for now.
46725 // TODO: i64 scalar math would benefit as well.
46726 if (!VT.isVector())
46727 return SDValue();
46728
46729 // In most cases its only worth pre-truncating if we're only facing the cost
46730 // of one truncation.
46731 // i.e. if one of the inputs will constant fold or the input is repeated.
46732 switch (SrcOpcode) {
46733 case ISD::MUL:
46734 // X86 is rubbish at scalar and vector i64 multiplies (until AVX512DQ) - its
46735 // better to truncate if we have the chance.
46736 if (SrcVT.getScalarType() == MVT::i64 &&
46737 TLI.isOperationLegal(SrcOpcode, VT) &&
46738 !TLI.isOperationLegal(SrcOpcode, SrcVT))
46739 return TruncateArithmetic(Src.getOperand(0), Src.getOperand(1));
46740 LLVM_FALLTHROUGH[[gnu::fallthrough]];
46741 case ISD::AND:
46742 case ISD::XOR:
46743 case ISD::OR:
46744 case ISD::ADD:
46745 case ISD::SUB: {
46746 SDValue Op0 = Src.getOperand(0);
46747 SDValue Op1 = Src.getOperand(1);
46748 if (TLI.isOperationLegal(SrcOpcode, VT) &&
46749 (Op0 == Op1 || IsFreeTruncation(Op0) || IsFreeTruncation(Op1)))
46750 return TruncateArithmetic(Op0, Op1);
46751 break;
46752 }
46753 }
46754
46755 return SDValue();
46756}
46757
46758/// Truncate using ISD::AND mask and X86ISD::PACKUS.
46759/// e.g. trunc <8 x i32> X to <8 x i16> -->
46760/// MaskX = X & 0xffff (clear high bits to prevent saturation)
46761/// packus (extract_subv MaskX, 0), (extract_subv MaskX, 1)
46762static SDValue combineVectorTruncationWithPACKUS(SDNode *N, const SDLoc &DL,
46763 const X86Subtarget &Subtarget,
46764 SelectionDAG &DAG) {
46765 SDValue In = N->getOperand(0);
46766 EVT InVT = In.getValueType();
46767 EVT OutVT = N->getValueType(0);
46768
46769 APInt Mask = APInt::getLowBitsSet(InVT.getScalarSizeInBits(),
46770 OutVT.getScalarSizeInBits());
46771 In = DAG.getNode(ISD::AND, DL, InVT, In, DAG.getConstant(Mask, DL, InVT));
46772 return truncateVectorWithPACK(X86ISD::PACKUS, OutVT, In, DL, DAG, Subtarget);
46773}
46774
46775/// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
46776static SDValue combineVectorTruncationWithPACKSS(SDNode *N, const SDLoc &DL,
46777 const X86Subtarget &Subtarget,
46778 SelectionDAG &DAG) {
46779 SDValue In = N->getOperand(0);
46780 EVT InVT = In.getValueType();
46781 EVT OutVT = N->getValueType(0);
46782 In = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, InVT, In,
46783 DAG.getValueType(OutVT));
46784 return truncateVectorWithPACK(X86ISD::PACKSS, OutVT, In, DL, DAG, Subtarget);
46785}
46786
46787/// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
46788/// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
46789/// legalization the truncation will be translated into a BUILD_VECTOR with each
46790/// element that is extracted from a vector and then truncated, and it is
46791/// difficult to do this optimization based on them.
46792static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
46793 const X86Subtarget &Subtarget) {
46794 EVT OutVT = N->getValueType(0);
46795 if (!OutVT.isVector())
46796 return SDValue();
46797
46798 SDValue In = N->getOperand(0);
46799 if (!In.getValueType().isSimple())
46800 return SDValue();
46801
46802 EVT InVT = In.getValueType();
46803 unsigned NumElems = OutVT.getVectorNumElements();
46804
46805 // AVX512 provides fast truncate ops.
46806 if (!Subtarget.hasSSE2() || Subtarget.hasAVX512())
46807 return SDValue();
46808
46809 EVT OutSVT = OutVT.getVectorElementType();
46810 EVT InSVT = InVT.getVectorElementType();
46811 if (!((InSVT == MVT::i16 || InSVT == MVT::i32 || InSVT == MVT::i64) &&
46812 (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
46813 NumElems >= 8))
46814 return SDValue();
46815
46816 // SSSE3's pshufb results in less instructions in the cases below.
46817 if (Subtarget.hasSSSE3() && NumElems == 8 && InSVT != MVT::i64)
46818 return SDValue();
46819
46820 SDLoc DL(N);
46821 // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PACKUS
46822 // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
46823 // truncate 2 x v4i32 to v8i16.
46824 if (Subtarget.hasSSE41() || OutSVT == MVT::i8)
46825 return combineVectorTruncationWithPACKUS(N, DL, Subtarget, DAG);
46826 if (InSVT == MVT::i32)
46827 return combineVectorTruncationWithPACKSS(N, DL, Subtarget, DAG);
46828
46829 return SDValue();
46830}
46831
46832/// This function transforms vector truncation of 'extended sign-bits' or
46833/// 'extended zero-bits' values.
46834/// vXi16/vXi32/vXi64 to vXi8/vXi16/vXi32 into X86ISD::PACKSS/PACKUS operations.
46835static SDValue combineVectorSignBitsTruncation(SDNode *N, const SDLoc &DL,
46836 SelectionDAG &DAG,
46837 const X86Subtarget &Subtarget) {
46838 // Requires SSE2.
46839 if (!Subtarget.hasSSE2())
46840 return SDValue();
46841
46842 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple())
46843 return SDValue();
46844
46845 SDValue In = N->getOperand(0);
46846 if (!In.getValueType().isSimple())
46847 return SDValue();
46848
46849 MVT VT = N->getValueType(0).getSimpleVT();
46850 MVT SVT = VT.getScalarType();
46851
46852 MVT InVT = In.getValueType().getSimpleVT();
46853 MVT InSVT = InVT.getScalarType();
46854
46855 // Check we have a truncation suited for PACKSS/PACKUS.
46856 if (!isPowerOf2_32(VT.getVectorNumElements()))
46857 return SDValue();
46858 if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32)
46859 return SDValue();
46860 if (InSVT != MVT::i16 && InSVT != MVT::i32 && InSVT != MVT::i64)
46861 return SDValue();
46862
46863 // Truncation to sub-128bit vXi32 can be better handled with shuffles.
46864 if (SVT == MVT::i32 && VT.getSizeInBits() < 128)
46865 return SDValue();
46866
46867 // AVX512 has fast truncate, but if the input is already going to be split,
46868 // there's no harm in trying pack.
46869 if (Subtarget.hasAVX512() &&
46870 !(!Subtarget.useAVX512Regs() && VT.is256BitVector() &&
46871 InVT.is512BitVector())) {
46872 // PACK should still be worth it for 128-bit vectors if the sources were
46873 // originally concatenated from subvectors.
46874 SmallVector<SDValue> ConcatOps;
46875 if (VT.getSizeInBits() > 128 || !collectConcatOps(In.getNode(), ConcatOps))
46876 return SDValue();
46877 }
46878
46879 unsigned NumPackedSignBits = std::min<unsigned>(SVT.getSizeInBits(), 16);
46880 unsigned NumPackedZeroBits = Subtarget.hasSSE41() ? NumPackedSignBits : 8;
46881
46882 // Use PACKUS if the input has zero-bits that extend all the way to the
46883 // packed/truncated value. e.g. masks, zext_in_reg, etc.
46884 KnownBits Known = DAG.computeKnownBits(In);
46885 unsigned NumLeadingZeroBits = Known.countMinLeadingZeros();
46886 if (NumLeadingZeroBits >= (InSVT.getSizeInBits() - NumPackedZeroBits))
46887 return truncateVectorWithPACK(X86ISD::PACKUS, VT, In, DL, DAG, Subtarget);
46888
46889 // Use PACKSS if the input has sign-bits that extend all the way to the
46890 // packed/truncated value. e.g. Comparison result, sext_in_reg, etc.
46891 unsigned NumSignBits = DAG.ComputeNumSignBits(In);
46892
46893 // Don't use PACKSS for vXi64 -> vXi32 truncations unless we're dealing with
46894 // a sign splat. ComputeNumSignBits struggles to see through BITCASTs later
46895 // on and combines/simplifications can't then use it.
46896 if (SVT == MVT::i32 && NumSignBits != InSVT.getSizeInBits())
46897 return SDValue();
46898
46899 unsigned MinSignBits = InSVT.getSizeInBits() - NumPackedSignBits;
46900 if (NumSignBits > MinSignBits)
46901 return truncateVectorWithPACK(X86ISD::PACKSS, VT, In, DL, DAG, Subtarget);
46902
46903 // If we have a srl that only generates signbits that we will discard in
46904 // the truncation then we can use PACKSS by converting the srl to a sra.
46905 // SimplifyDemandedBits often relaxes sra to srl so we need to reverse it.
46906 if (In.getOpcode() == ISD::SRL && N->isOnlyUserOf(In.getNode()))
46907 if (const APInt *ShAmt = DAG.getValidShiftAmountConstant(
46908 In, APInt::getAllOnesValue(VT.getVectorNumElements()))) {
46909 if (*ShAmt == MinSignBits) {
46910 SDValue NewIn = DAG.getNode(ISD::SRA, DL, InVT, In->ops());
46911 return truncateVectorWithPACK(X86ISD::PACKSS, VT, NewIn, DL, DAG,
46912 Subtarget);
46913 }
46914 }
46915
46916 return SDValue();
46917}
46918
46919// Try to form a MULHU or MULHS node by looking for
46920// (trunc (srl (mul ext, ext), 16))
46921// TODO: This is X86 specific because we want to be able to handle wide types
46922// before type legalization. But we can only do it if the vector will be
46923// legalized via widening/splitting. Type legalization can't handle promotion
46924// of a MULHU/MULHS. There isn't a way to convey this to the generic DAG
46925// combiner.
46926static SDValue combinePMULH(SDValue Src, EVT VT, const SDLoc &DL,
46927 SelectionDAG &DAG, const X86Subtarget &Subtarget) {
46928 // First instruction should be a right shift of a multiply.
46929 if (Src.getOpcode() != ISD::SRL ||
46930 Src.getOperand(0).getOpcode() != ISD::MUL)
46931 return SDValue();
46932
46933 if (!Subtarget.hasSSE2())
46934 return SDValue();
46935
46936 // Only handle vXi16 types that are at least 128-bits unless they will be
46937 // widened.
46938 if (!VT.isVector() || VT.getVectorElementType() != MVT::i16)
46939 return SDValue();
46940
46941 // Input type should be at least vXi32.
46942 EVT InVT = Src.getValueType();
46943 if (InVT.getVectorElementType().getSizeInBits() < 32)
46944 return SDValue();
46945
46946 // Need a shift by 16.
46947 APInt ShiftAmt;
46948 if (!ISD::isConstantSplatVector(Src.getOperand(1).getNode(), ShiftAmt) ||
46949 ShiftAmt != 16)
46950 return SDValue();
46951
46952 SDValue LHS = Src.getOperand(0).getOperand(0);
46953 SDValue RHS = Src.getOperand(0).getOperand(1);
46954
46955 unsigned ExtOpc = LHS.getOpcode();
46956 if ((ExtOpc != ISD::SIGN_EXTEND && ExtOpc != ISD::ZERO_EXTEND) ||
46957 RHS.getOpcode() != ExtOpc)
46958 return SDValue();
46959
46960 // Peek through the extends.
46961 LHS = LHS.getOperand(0);
46962 RHS = RHS.getOperand(0);
46963
46964 // Ensure the input types match.
46965 if (LHS.getValueType() != VT || RHS.getValueType() != VT)
46966 return SDValue();
46967
46968 unsigned Opc = ExtOpc == ISD::SIGN_EXTEND ? ISD::MULHS : ISD::MULHU;
46969 return DAG.getNode(Opc, DL, VT, LHS, RHS);
46970}
46971
46972// Attempt to match PMADDUBSW, which multiplies corresponding unsigned bytes
46973// from one vector with signed bytes from another vector, adds together
46974// adjacent pairs of 16-bit products, and saturates the result before
46975// truncating to 16-bits.
46976//
46977// Which looks something like this:
46978// (i16 (ssat (add (mul (zext (even elts (i8 A))), (sext (even elts (i8 B)))),
46979// (mul (zext (odd elts (i8 A)), (sext (odd elts (i8 B))))))))
46980static SDValue detectPMADDUBSW(SDValue In, EVT VT, SelectionDAG &DAG,
46981 const X86Subtarget &Subtarget,
46982 const SDLoc &DL) {
46983 if (!VT.isVector() || !Subtarget.hasSSSE3())
46984 return SDValue();
46985
46986 unsigned NumElems = VT.getVectorNumElements();
46987 EVT ScalarVT = VT.getVectorElementType();
46988 if (ScalarVT != MVT::i16 || NumElems < 8 || !isPowerOf2_32(NumElems))
46989 return SDValue();
46990
46991 SDValue SSatVal = detectSSatPattern(In, VT);
46992 if (!SSatVal || SSatVal.getOpcode() != ISD::ADD)
46993 return SDValue();
46994
46995 // Ok this is a signed saturation of an ADD. See if this ADD is adding pairs
46996 // of multiplies from even/odd elements.
46997 SDValue N0 = SSatVal.getOperand(0);
46998 SDValue N1 = SSatVal.getOperand(1);
46999
47000 if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
47001 return SDValue();
47002
47003 SDValue N00 = N0.getOperand(0);
47004 SDValue N01 = N0.getOperand(1);
47005 SDValue N10 = N1.getOperand(0);
47006 SDValue N11 = N1.getOperand(1);
47007
47008 // TODO: Handle constant vectors and use knownbits/computenumsignbits?
47009 // Canonicalize zero_extend to LHS.
47010 if (N01.getOpcode() == ISD::ZERO_EXTEND)
47011 std::swap(N00, N01);
47012 if (N11.getOpcode() == ISD::ZERO_EXTEND)
47013 std::swap(N10, N11);
47014
47015 // Ensure we have a zero_extend and a sign_extend.
47016 if (N00.getOpcode() != ISD::ZERO_EXTEND ||
47017 N01.getOpcode() != ISD::SIGN_EXTEND ||
47018 N10.getOpcode() != ISD::ZERO_EXTEND ||
47019 N11.getOpcode() != ISD::SIGN_EXTEND)
47020 return SDValue();
47021
47022 // Peek through the extends.
47023 N00 = N00.getOperand(0);
47024 N01 = N01.getOperand(0);
47025 N10 = N10.getOperand(0);
47026 N11 = N11.getOperand(0);
47027
47028 // Ensure the extend is from vXi8.
47029 if (N00.getValueType().getVectorElementType() != MVT::i8 ||
47030 N01.getValueType().getVectorElementType() != MVT::i8 ||
47031 N10.getValueType().getVectorElementType() != MVT::i8 ||
47032 N11.getValueType().getVectorElementType() != MVT::i8)
47033 return SDValue();
47034
47035 // All inputs should be build_vectors.
47036 if (N00.getOpcode() != ISD::BUILD_VECTOR ||
47037 N01.getOpcode() != ISD::BUILD_VECTOR ||
47038 N10.getOpcode() != ISD::BUILD_VECTOR ||
47039 N11.getOpcode() != ISD::BUILD_VECTOR)
47040 return SDValue();
47041
47042 // N00/N10 are zero extended. N01/N11 are sign extended.
47043
47044 // For each element, we need to ensure we have an odd element from one vector
47045 // multiplied by the odd element of another vector and the even element from
47046 // one of the same vectors being multiplied by the even element from the
47047 // other vector. So we need to make sure for each element i, this operator
47048 // is being performed:
47049 // A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
47050 SDValue ZExtIn, SExtIn;
47051 for (unsigned i = 0; i != NumElems; ++i) {
47052 SDValue N00Elt = N00.getOperand(i);
47053 SDValue N01Elt = N01.getOperand(i);
47054 SDValue N10Elt = N10.getOperand(i);
47055 SDValue N11Elt = N11.getOperand(i);
47056 // TODO: Be more tolerant to undefs.
47057 if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
47058 N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
47059 N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
47060 N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
47061 return SDValue();
47062 auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
47063 auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
47064 auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
47065 auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
47066 if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
47067 return SDValue();
47068 unsigned IdxN00 = ConstN00Elt->getZExtValue();
47069 unsigned IdxN01 = ConstN01Elt->getZExtValue();
47070 unsigned IdxN10 = ConstN10Elt->getZExtValue();
47071 unsigned IdxN11 = ConstN11Elt->getZExtValue();
47072 // Add is commutative so indices can be reordered.
47073 if (IdxN00 > IdxN10) {
47074 std::swap(IdxN00, IdxN10);
47075 std::swap(IdxN01, IdxN11);
47076 }
47077 // N0 indices be the even element. N1 indices must be the next odd element.
47078 if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
47079 IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
47080 return SDValue();
47081 SDValue N00In = N00Elt.getOperand(0);
47082 SDValue N01In = N01Elt.getOperand(0);
47083 SDValue N10In = N10Elt.getOperand(0);
47084 SDValue N11In = N11Elt.getOperand(0);
47085 // First time we find an input capture it.
47086 if (!ZExtIn) {
47087 ZExtIn = N00In;
47088 SExtIn = N01In;
47089 }
47090 if (ZExtIn != N00In || SExtIn != N01In ||
47091 ZExtIn != N10In || SExtIn != N11In)
47092 return SDValue();
47093 }
47094
47095 auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
47096 ArrayRef<SDValue> Ops) {
47097 // Shrink by adding truncate nodes and let DAGCombine fold with the
47098 // sources.
47099 EVT InVT = Ops[0].getValueType();
47100 assert(InVT.getScalarType() == MVT::i8 &&(static_cast <bool> (InVT.getScalarType() == MVT::i8 &&
"Unexpected scalar element type") ? void (0) : __assert_fail
("InVT.getScalarType() == MVT::i8 && \"Unexpected scalar element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 47101, __extension__ __PRETTY_FUNCTION__))
47101 "Unexpected scalar element type")(static_cast <bool> (InVT.getScalarType() == MVT::i8 &&
"Unexpected scalar element type") ? void (0) : __assert_fail
("InVT.getScalarType() == MVT::i8 && \"Unexpected scalar element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 47101, __extension__ __PRETTY_FUNCTION__))
;
47102 assert(InVT == Ops[1].getValueType() && "Operands' types mismatch")(static_cast <bool> (InVT == Ops[1].getValueType() &&
"Operands' types mismatch") ? void (0) : __assert_fail ("InVT == Ops[1].getValueType() && \"Operands' types mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 47102, __extension__ __PRETTY_FUNCTION__))
;
47103 EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
47104 InVT.getVectorNumElements() / 2);
47105 return DAG.getNode(X86ISD::VPMADDUBSW, DL, ResVT, Ops[0], Ops[1]);
47106 };
47107 return SplitOpsAndApply(DAG, Subtarget, DL, VT, { ZExtIn, SExtIn },
47108 PMADDBuilder);
47109}
47110
47111static SDValue combineTruncate(SDNode *N, SelectionDAG &DAG,
47112 const X86Subtarget &Subtarget) {
47113 EVT VT = N->getValueType(0);
47114 SDValue Src = N->getOperand(0);
47115 SDLoc DL(N);
47116
47117 // Attempt to pre-truncate inputs to arithmetic ops instead.
47118 if (SDValue V = combineTruncatedArithmetic(N, DAG, Subtarget, DL))
47119 return V;
47120
47121 // Try to detect AVG pattern first.
47122 if (SDValue Avg = detectAVGPattern(Src, VT, DAG, Subtarget, DL))
47123 return Avg;
47124
47125 // Try to detect PMADD
47126 if (SDValue PMAdd = detectPMADDUBSW(Src, VT, DAG, Subtarget, DL))
47127 return PMAdd;
47128
47129 // Try to combine truncation with signed/unsigned saturation.
47130 if (SDValue Val = combineTruncateWithSat(Src, VT, DL, DAG, Subtarget))
47131 return Val;
47132
47133 // Try to combine PMULHUW/PMULHW for vXi16.
47134 if (SDValue V = combinePMULH(Src, VT, DL, DAG, Subtarget))
47135 return V;
47136
47137 // The bitcast source is a direct mmx result.
47138 // Detect bitcasts between i32 to x86mmx
47139 if (Src.getOpcode() == ISD::BITCAST && VT == MVT::i32) {
47140 SDValue BCSrc = Src.getOperand(0);
47141 if (BCSrc.getValueType() == MVT::x86mmx)
47142 return DAG.getNode(X86ISD::MMX_MOVD2W, DL, MVT::i32, BCSrc);
47143 }
47144
47145 // Try to truncate extended sign/zero bits with PACKSS/PACKUS.
47146 if (SDValue V = combineVectorSignBitsTruncation(N, DL, DAG, Subtarget))
47147 return V;
47148
47149 return combineVectorTruncation(N, DAG, Subtarget);
47150}
47151
47152static SDValue combineVTRUNC(SDNode *N, SelectionDAG &DAG,
47153 TargetLowering::DAGCombinerInfo &DCI) {
47154 EVT VT = N->getValueType(0);
47155 SDValue In = N->getOperand(0);
47156 SDLoc DL(N);
47157
47158 if (auto SSatVal = detectSSatPattern(In, VT))
47159 return DAG.getNode(X86ISD::VTRUNCS, DL, VT, SSatVal);
47160 if (auto USatVal = detectUSatPattern(In, VT, DAG, DL))
47161 return DAG.getNode(X86ISD::VTRUNCUS, DL, VT, USatVal);
47162
47163 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47164 APInt DemandedMask(APInt::getAllOnesValue(VT.getScalarSizeInBits()));
47165 if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
47166 return SDValue(N, 0);
47167
47168 return SDValue();
47169}
47170
47171/// Returns the negated value if the node \p N flips sign of FP value.
47172///
47173/// FP-negation node may have different forms: FNEG(x), FXOR (x, 0x80000000)
47174/// or FSUB(0, x)
47175/// AVX512F does not have FXOR, so FNEG is lowered as
47176/// (bitcast (xor (bitcast x), (bitcast ConstantFP(0x80000000)))).
47177/// In this case we go though all bitcasts.
47178/// This also recognizes splat of a negated value and returns the splat of that
47179/// value.
47180static SDValue isFNEG(SelectionDAG &DAG, SDNode *N, unsigned Depth = 0) {
47181 if (N->getOpcode() == ISD::FNEG)
47182 return N->getOperand(0);
47183
47184 // Don't recurse exponentially.
47185 if (Depth > SelectionDAG::MaxRecursionDepth)
47186 return SDValue();
47187
47188 unsigned ScalarSize = N->getValueType(0).getScalarSizeInBits();
47189
47190 SDValue Op = peekThroughBitcasts(SDValue(N, 0));
47191 EVT VT = Op->getValueType(0);
47192
47193 // Make sure the element size doesn't change.
47194 if (VT.getScalarSizeInBits() != ScalarSize)
47195 return SDValue();
47196
47197 unsigned Opc = Op.getOpcode();
47198 switch (Opc) {
47199 case ISD::VECTOR_SHUFFLE: {
47200 // For a VECTOR_SHUFFLE(VEC1, VEC2), if the VEC2 is undef, then the negate
47201 // of this is VECTOR_SHUFFLE(-VEC1, UNDEF). The mask can be anything here.
47202 if (!Op.getOperand(1).isUndef())
47203 return SDValue();
47204 if (SDValue NegOp0 = isFNEG(DAG, Op.getOperand(0).getNode(), Depth + 1))
47205 if (NegOp0.getValueType() == VT) // FIXME: Can we do better?
47206 return DAG.getVectorShuffle(VT, SDLoc(Op), NegOp0, DAG.getUNDEF(VT),
47207 cast<ShuffleVectorSDNode>(Op)->getMask());
47208 break;
47209 }
47210 case ISD::INSERT_VECTOR_ELT: {
47211 // Negate of INSERT_VECTOR_ELT(UNDEF, V, INDEX) is INSERT_VECTOR_ELT(UNDEF,
47212 // -V, INDEX).
47213 SDValue InsVector = Op.getOperand(0);
47214 SDValue InsVal = Op.getOperand(1);
47215 if (!InsVector.isUndef())
47216 return SDValue();
47217 if (SDValue NegInsVal = isFNEG(DAG, InsVal.getNode(), Depth + 1))
47218 if (NegInsVal.getValueType() == VT.getVectorElementType()) // FIXME
47219 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Op), VT, InsVector,
47220 NegInsVal, Op.getOperand(2));
47221 break;
47222 }
47223 case ISD::FSUB:
47224 case ISD::XOR:
47225 case X86ISD::FXOR: {
47226 SDValue Op1 = Op.getOperand(1);
47227 SDValue Op0 = Op.getOperand(0);
47228
47229 // For XOR and FXOR, we want to check if constant
47230 // bits of Op1 are sign bit masks. For FSUB, we
47231 // have to check if constant bits of Op0 are sign
47232 // bit masks and hence we swap the operands.
47233 if (Opc == ISD::FSUB)
47234 std::swap(Op0, Op1);
47235
47236 APInt UndefElts;
47237 SmallVector<APInt, 16> EltBits;
47238 // Extract constant bits and see if they are all
47239 // sign bit masks. Ignore the undef elements.
47240 if (getTargetConstantBitsFromNode(Op1, ScalarSize, UndefElts, EltBits,
47241 /* AllowWholeUndefs */ true,
47242 /* AllowPartialUndefs */ false)) {
47243 for (unsigned I = 0, E = EltBits.size(); I < E; I++)
47244 if (!UndefElts[I] && !EltBits[I].isSignMask())
47245 return SDValue();
47246
47247 return peekThroughBitcasts(Op0);
47248 }
47249 }
47250 }
47251
47252 return SDValue();
47253}
47254
47255static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc,
47256 bool NegRes) {
47257 if (NegMul) {
47258 switch (Opcode) {
47259 default: llvm_unreachable("Unexpected opcode")::llvm::llvm_unreachable_internal("Unexpected opcode", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 47259)
;
47260 case ISD::FMA: Opcode = X86ISD::FNMADD; break;
47261 case ISD::STRICT_FMA: Opcode = X86ISD::STRICT_FNMADD; break;
47262 case X86ISD::FMADD_RND: Opcode = X86ISD::FNMADD_RND; break;
47263 case X86ISD::FMSUB: Opcode = X86ISD::FNMSUB; break;
47264 case X86ISD::STRICT_FMSUB: Opcode = X86ISD::STRICT_FNMSUB; break;
47265 case X86ISD::FMSUB_RND: Opcode = X86ISD::FNMSUB_RND; break;
47266 case X86ISD::FNMADD: Opcode = ISD::FMA; break;
47267 case X86ISD::STRICT_FNMADD: Opcode = ISD::STRICT_FMA; break;
47268 case X86ISD::FNMADD_RND: Opcode = X86ISD::FMADD_RND; break;
47269 case X86ISD::FNMSUB: Opcode = X86ISD::FMSUB; break;
47270 case X86ISD::STRICT_FNMSUB: Opcode = X86ISD::STRICT_FMSUB; break;
47271 case X86ISD::FNMSUB_RND: Opcode = X86ISD::FMSUB_RND; break;
47272 }
47273 }
47274
47275 if (NegAcc) {
47276 switch (Opcode) {
47277 default: llvm_unreachable("Unexpected opcode")::llvm::llvm_unreachable_internal("Unexpected opcode", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 47277)
;
47278 case ISD::FMA: Opcode = X86ISD::FMSUB; break;
47279 case ISD::STRICT_FMA: Opcode = X86ISD::STRICT_FMSUB; break;
47280 case X86ISD::FMADD_RND: Opcode = X86ISD::FMSUB_RND; break;
47281 case X86ISD::FMSUB: Opcode = ISD::FMA; break;
47282 case X86ISD::STRICT_FMSUB: Opcode = ISD::STRICT_FMA; break;
47283 case X86ISD::FMSUB_RND: Opcode = X86ISD::FMADD_RND; break;
47284 case X86ISD::FNMADD: Opcode = X86ISD::FNMSUB; break;
47285 case X86ISD::STRICT_FNMADD: Opcode = X86ISD::STRICT_FNMSUB; break;
47286 case X86ISD::FNMADD_RND: Opcode = X86ISD::FNMSUB_RND; break;
47287 case X86ISD::FNMSUB: Opcode = X86ISD::FNMADD; break;
47288 case X86ISD::STRICT_FNMSUB: Opcode = X86ISD::STRICT_FNMADD; break;
47289 case X86ISD::FNMSUB_RND: Opcode = X86ISD::FNMADD_RND; break;
47290 case X86ISD::FMADDSUB: Opcode = X86ISD::FMSUBADD; break;
47291 case X86ISD::FMADDSUB_RND: Opcode = X86ISD::FMSUBADD_RND; break;
47292 case X86ISD::FMSUBADD: Opcode = X86ISD::FMADDSUB; break;
47293 case X86ISD::FMSUBADD_RND: Opcode = X86ISD::FMADDSUB_RND; break;
47294 }
47295 }
47296
47297 if (NegRes) {
47298 switch (Opcode) {
47299 // For accuracy reason, we never combine fneg and fma under strict FP.
47300 default: llvm_unreachable("Unexpected opcode")::llvm::llvm_unreachable_internal("Unexpected opcode", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 47300)
;
47301 case ISD::FMA: Opcode = X86ISD::FNMSUB; break;
47302 case X86ISD::FMADD_RND: Opcode = X86ISD::FNMSUB_RND; break;
47303 case X86ISD::FMSUB: Opcode = X86ISD::FNMADD; break;
47304 case X86ISD::FMSUB_RND: Opcode = X86ISD::FNMADD_RND; break;
47305 case X86ISD::FNMADD: Opcode = X86ISD::FMSUB; break;
47306 case X86ISD::FNMADD_RND: Opcode = X86ISD::FMSUB_RND; break;
47307 case X86ISD::FNMSUB: Opcode = ISD::FMA; break;
47308 case X86ISD::FNMSUB_RND: Opcode = X86ISD::FMADD_RND; break;
47309 }
47310 }
47311
47312 return Opcode;
47313}
47314
47315/// Do target-specific dag combines on floating point negations.
47316static SDValue combineFneg(SDNode *N, SelectionDAG &DAG,
47317 TargetLowering::DAGCombinerInfo &DCI,
47318 const X86Subtarget &Subtarget) {
47319 EVT OrigVT = N->getValueType(0);
47320 SDValue Arg = isFNEG(DAG, N);
47321 if (!Arg)
47322 return SDValue();
47323
47324 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47325 EVT VT = Arg.getValueType();
47326 EVT SVT = VT.getScalarType();
47327 SDLoc DL(N);
47328
47329 // Let legalize expand this if it isn't a legal type yet.
47330 if (!TLI.isTypeLegal(VT))
47331 return SDValue();
47332
47333 // If we're negating a FMUL node on a target with FMA, then we can avoid the
47334 // use of a constant by performing (-0 - A*B) instead.
47335 // FIXME: Check rounding control flags as well once it becomes available.
47336 if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
47337 Arg->getFlags().hasNoSignedZeros() && Subtarget.hasAnyFMA()) {
47338 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
47339 SDValue NewNode = DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
47340 Arg.getOperand(1), Zero);
47341 return DAG.getBitcast(OrigVT, NewNode);
47342 }
47343
47344 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
47345 bool LegalOperations = !DCI.isBeforeLegalizeOps();
47346 if (SDValue NegArg =
47347 TLI.getNegatedExpression(Arg, DAG, LegalOperations, CodeSize))
47348 return DAG.getBitcast(OrigVT, NegArg);
47349
47350 return SDValue();
47351}
47352
47353SDValue X86TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
47354 bool LegalOperations,
47355 bool ForCodeSize,
47356 NegatibleCost &Cost,
47357 unsigned Depth) const {
47358 // fneg patterns are removable even if they have multiple uses.
47359 if (SDValue Arg = isFNEG(DAG, Op.getNode(), Depth)) {
47360 Cost = NegatibleCost::Cheaper;
47361 return DAG.getBitcast(Op.getValueType(), Arg);
47362 }
47363
47364 EVT VT = Op.getValueType();
47365 EVT SVT = VT.getScalarType();
47366 unsigned Opc = Op.getOpcode();
47367 SDNodeFlags Flags = Op.getNode()->getFlags();
47368 switch (Opc) {
47369 case ISD::FMA:
47370 case X86ISD::FMSUB:
47371 case X86ISD::FNMADD:
47372 case X86ISD::FNMSUB:
47373 case X86ISD::FMADD_RND:
47374 case X86ISD::FMSUB_RND:
47375 case X86ISD::FNMADD_RND:
47376 case X86ISD::FNMSUB_RND: {
47377 if (!Op.hasOneUse() || !Subtarget.hasAnyFMA() || !isTypeLegal(VT) ||
47378 !(SVT == MVT::f32 || SVT == MVT::f64) ||
47379 !isOperationLegal(ISD::FMA, VT))
47380 break;
47381
47382 // Don't fold (fneg (fma (fneg x), y, (fneg z))) to (fma x, y, z)
47383 // if it may have signed zeros.
47384 if (!Flags.hasNoSignedZeros())
47385 break;
47386
47387 // This is always negatible for free but we might be able to remove some
47388 // extra operand negations as well.
47389 SmallVector<SDValue, 4> NewOps(Op.getNumOperands(), SDValue());
47390 for (int i = 0; i != 3; ++i)
47391 NewOps[i] = getCheaperNegatedExpression(
47392 Op.getOperand(i), DAG, LegalOperations, ForCodeSize, Depth + 1);
47393
47394 bool NegA = !!NewOps[0];
47395 bool NegB = !!NewOps[1];
47396 bool NegC = !!NewOps[2];
47397 unsigned NewOpc = negateFMAOpcode(Opc, NegA != NegB, NegC, true);
47398
47399 Cost = (NegA || NegB || NegC) ? NegatibleCost::Cheaper
47400 : NegatibleCost::Neutral;
47401
47402 // Fill in the non-negated ops with the original values.
47403 for (int i = 0, e = Op.getNumOperands(); i != e; ++i)
47404 if (!NewOps[i])
47405 NewOps[i] = Op.getOperand(i);
47406 return DAG.getNode(NewOpc, SDLoc(Op), VT, NewOps);
47407 }
47408 case X86ISD::FRCP:
47409 if (SDValue NegOp0 =
47410 getNegatedExpression(Op.getOperand(0), DAG, LegalOperations,
47411 ForCodeSize, Cost, Depth + 1))
47412 return DAG.getNode(Opc, SDLoc(Op), VT, NegOp0);
47413 break;
47414 }
47415
47416 return TargetLowering::getNegatedExpression(Op, DAG, LegalOperations,
47417 ForCodeSize, Cost, Depth);
47418}
47419
47420static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
47421 const X86Subtarget &Subtarget) {
47422 MVT VT = N->getSimpleValueType(0);
47423 // If we have integer vector types available, use the integer opcodes.
47424 if (!VT.isVector() || !Subtarget.hasSSE2())
47425 return SDValue();
47426
47427 SDLoc dl(N);
47428
47429 unsigned IntBits = VT.getScalarSizeInBits();
47430 MVT IntSVT = MVT::getIntegerVT(IntBits);
47431 MVT IntVT = MVT::getVectorVT(IntSVT, VT.getSizeInBits() / IntBits);
47432
47433 SDValue Op0 = DAG.getBitcast(IntVT, N->getOperand(0));
47434 SDValue Op1 = DAG.getBitcast(IntVT, N->getOperand(1));
47435 unsigned IntOpcode;
47436 switch (N->getOpcode()) {
47437 default: llvm_unreachable("Unexpected FP logic op")::llvm::llvm_unreachable_internal("Unexpected FP logic op", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 47437)
;
47438 case X86ISD::FOR: IntOpcode = ISD::OR; break;
47439 case X86ISD::FXOR: IntOpcode = ISD::XOR; break;
47440 case X86ISD::FAND: IntOpcode = ISD::AND; break;
47441 case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
47442 }
47443 SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
47444 return DAG.getBitcast(VT, IntOp);
47445}
47446
47447
47448/// Fold a xor(setcc cond, val), 1 --> setcc (inverted(cond), val)
47449static SDValue foldXor1SetCC(SDNode *N, SelectionDAG &DAG) {
47450 if (N->getOpcode() != ISD::XOR)
47451 return SDValue();
47452
47453 SDValue LHS = N->getOperand(0);
47454 if (!isOneConstant(N->getOperand(1)) || LHS->getOpcode() != X86ISD::SETCC)
47455 return SDValue();
47456
47457 X86::CondCode NewCC = X86::GetOppositeBranchCondition(
47458 X86::CondCode(LHS->getConstantOperandVal(0)));
47459 SDLoc DL(N);
47460 return getSETCC(NewCC, LHS->getOperand(1), DL, DAG);
47461}
47462
47463static SDValue combineXor(SDNode *N, SelectionDAG &DAG,
47464 TargetLowering::DAGCombinerInfo &DCI,
47465 const X86Subtarget &Subtarget) {
47466 SDValue N0 = N->getOperand(0);
47467 SDValue N1 = N->getOperand(1);
47468 EVT VT = N->getValueType(0);
47469
47470 // If this is SSE1 only convert to FXOR to avoid scalarization.
47471 if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
47472 return DAG.getBitcast(MVT::v4i32,
47473 DAG.getNode(X86ISD::FXOR, SDLoc(N), MVT::v4f32,
47474 DAG.getBitcast(MVT::v4f32, N0),
47475 DAG.getBitcast(MVT::v4f32, N1)));
47476 }
47477
47478 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
47479 return Cmp;
47480
47481 if (SDValue R = combineBitOpWithMOVMSK(N, DAG))
47482 return R;
47483
47484 if (DCI.isBeforeLegalizeOps())
47485 return SDValue();
47486
47487 if (SDValue SetCC = foldXor1SetCC(N, DAG))
47488 return SetCC;
47489
47490 if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
47491 return RV;
47492
47493 // Fold not(iX bitcast(vXi1)) -> (iX bitcast(not(vec))) for legal boolvecs.
47494 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47495 if (llvm::isAllOnesConstant(N1) && N0.getOpcode() == ISD::BITCAST &&
47496 N0.getOperand(0).getValueType().isVector() &&
47497 N0.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
47498 TLI.isTypeLegal(N0.getOperand(0).getValueType()) && N0.hasOneUse()) {
47499 return DAG.getBitcast(VT, DAG.getNOT(SDLoc(N), N0.getOperand(0),
47500 N0.getOperand(0).getValueType()));
47501 }
47502
47503 // Handle AVX512 mask widening.
47504 // Fold not(insert_subvector(undef,sub)) -> insert_subvector(undef,not(sub))
47505 if (ISD::isBuildVectorAllOnes(N1.getNode()) && VT.isVector() &&
47506 VT.getVectorElementType() == MVT::i1 &&
47507 N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.getOperand(0).isUndef() &&
47508 TLI.isTypeLegal(N0.getOperand(1).getValueType())) {
47509 return DAG.getNode(
47510 ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
47511 DAG.getNOT(SDLoc(N), N0.getOperand(1), N0.getOperand(1).getValueType()),
47512 N0.getOperand(2));
47513 }
47514
47515 // Fold xor(zext(xor(x,c1)),c2) -> xor(zext(x),xor(zext(c1),c2))
47516 // Fold xor(truncate(xor(x,c1)),c2) -> xor(truncate(x),xor(truncate(c1),c2))
47517 // TODO: Under what circumstances could this be performed in DAGCombine?
47518 if ((N0.getOpcode() == ISD::TRUNCATE || N0.getOpcode() == ISD::ZERO_EXTEND) &&
47519 N0.getOperand(0).getOpcode() == N->getOpcode()) {
47520 SDValue TruncExtSrc = N0.getOperand(0);
47521 auto *N1C = dyn_cast<ConstantSDNode>(N1);
47522 auto *N001C = dyn_cast<ConstantSDNode>(TruncExtSrc.getOperand(1));
47523 if (N1C && !N1C->isOpaque() && N001C && !N001C->isOpaque()) {
47524 SDLoc DL(N);
47525 SDValue LHS = DAG.getZExtOrTrunc(TruncExtSrc.getOperand(0), DL, VT);
47526 SDValue RHS = DAG.getZExtOrTrunc(TruncExtSrc.getOperand(1), DL, VT);
47527 return DAG.getNode(ISD::XOR, DL, VT, LHS,
47528 DAG.getNode(ISD::XOR, DL, VT, RHS, N1));
47529 }
47530 }
47531
47532 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
47533 return FPLogic;
47534
47535 return combineFneg(N, DAG, DCI, Subtarget);
47536}
47537
47538static SDValue combineBEXTR(SDNode *N, SelectionDAG &DAG,
47539 TargetLowering::DAGCombinerInfo &DCI,
47540 const X86Subtarget &Subtarget) {
47541 EVT VT = N->getValueType(0);
47542 unsigned NumBits = VT.getSizeInBits();
47543
47544 // TODO - Constant Folding.
47545
47546 // Simplify the inputs.
47547 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47548 APInt DemandedMask(APInt::getAllOnesValue(NumBits));
47549 if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
47550 return SDValue(N, 0);
47551
47552 return SDValue();
47553}
47554
47555static bool isNullFPScalarOrVectorConst(SDValue V) {
47556 return isNullFPConstant(V) || ISD::isBuildVectorAllZeros(V.getNode());
47557}
47558
47559/// If a value is a scalar FP zero or a vector FP zero (potentially including
47560/// undefined elements), return a zero constant that may be used to fold away
47561/// that value. In the case of a vector, the returned constant will not contain
47562/// undefined elements even if the input parameter does. This makes it suitable
47563/// to be used as a replacement operand with operations (eg, bitwise-and) where
47564/// an undef should not propagate.
47565static SDValue getNullFPConstForNullVal(SDValue V, SelectionDAG &DAG,
47566 const X86Subtarget &Subtarget) {
47567 if (!isNullFPScalarOrVectorConst(V))
47568 return SDValue();
47569
47570 if (V.getValueType().isVector())
47571 return getZeroVector(V.getSimpleValueType(), Subtarget, DAG, SDLoc(V));
47572
47573 return V;
47574}
47575
47576static SDValue combineFAndFNotToFAndn(SDNode *N, SelectionDAG &DAG,
47577 const X86Subtarget &Subtarget) {
47578 SDValue N0 = N->getOperand(0);
47579 SDValue N1 = N->getOperand(1);
47580 EVT VT = N->getValueType(0);
47581 SDLoc DL(N);
47582
47583 // Vector types are handled in combineANDXORWithAllOnesIntoANDNP().
47584 if (!((VT == MVT::f32 && Subtarget.hasSSE1()) ||
47585 (VT == MVT::f64 && Subtarget.hasSSE2()) ||
47586 (VT == MVT::v4f32 && Subtarget.hasSSE1() && !Subtarget.hasSSE2())))
47587 return SDValue();
47588
47589 auto isAllOnesConstantFP = [](SDValue V) {
47590 if (V.getSimpleValueType().isVector())
47591 return ISD::isBuildVectorAllOnes(V.getNode());
47592 auto *C = dyn_cast<ConstantFPSDNode>(V);
47593 return C && C->getConstantFPValue()->isAllOnesValue();
47594 };
47595
47596 // fand (fxor X, -1), Y --> fandn X, Y
47597 if (N0.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N0.getOperand(1)))
47598 return DAG.getNode(X86ISD::FANDN, DL, VT, N0.getOperand(0), N1);
47599
47600 // fand X, (fxor Y, -1) --> fandn Y, X
47601 if (N1.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N1.getOperand(1)))
47602 return DAG.getNode(X86ISD::FANDN, DL, VT, N1.getOperand(0), N0);
47603
47604 return SDValue();
47605}
47606
47607/// Do target-specific dag combines on X86ISD::FAND nodes.
47608static SDValue combineFAnd(SDNode *N, SelectionDAG &DAG,
47609 const X86Subtarget &Subtarget) {
47610 // FAND(0.0, x) -> 0.0
47611 if (SDValue V = getNullFPConstForNullVal(N->getOperand(0), DAG, Subtarget))
47612 return V;
47613
47614 // FAND(x, 0.0) -> 0.0
47615 if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
47616 return V;
47617
47618 if (SDValue V = combineFAndFNotToFAndn(N, DAG, Subtarget))
47619 return V;
47620
47621 return lowerX86FPLogicOp(N, DAG, Subtarget);
47622}
47623
47624/// Do target-specific dag combines on X86ISD::FANDN nodes.
47625static SDValue combineFAndn(SDNode *N, SelectionDAG &DAG,
47626 const X86Subtarget &Subtarget) {
47627 // FANDN(0.0, x) -> x
47628 if (isNullFPScalarOrVectorConst(N->getOperand(0)))
47629 return N->getOperand(1);
47630
47631 // FANDN(x, 0.0) -> 0.0
47632 if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
47633 return V;
47634
47635 return lowerX86FPLogicOp(N, DAG, Subtarget);
47636}
47637
47638/// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
47639static SDValue combineFOr(SDNode *N, SelectionDAG &DAG,
47640 TargetLowering::DAGCombinerInfo &DCI,
47641 const X86Subtarget &Subtarget) {
47642 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR)(static_cast <bool> (N->getOpcode() == X86ISD::FOR ||
N->getOpcode() == X86ISD::FXOR) ? void (0) : __assert_fail
("N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 47642, __extension__ __PRETTY_FUNCTION__))
;
47643
47644 // F[X]OR(0.0, x) -> x
47645 if (isNullFPScalarOrVectorConst(N->getOperand(0)))
47646 return N->getOperand(1);
47647
47648 // F[X]OR(x, 0.0) -> x
47649 if (isNullFPScalarOrVectorConst(N->getOperand(1)))
47650 return N->getOperand(0);
47651
47652 if (SDValue NewVal = combineFneg(N, DAG, DCI, Subtarget))
47653 return NewVal;
47654
47655 return lowerX86FPLogicOp(N, DAG, Subtarget);
47656}
47657
47658/// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
47659static SDValue combineFMinFMax(SDNode *N, SelectionDAG &DAG) {
47660 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX)(static_cast <bool> (N->getOpcode() == X86ISD::FMIN ||
N->getOpcode() == X86ISD::FMAX) ? void (0) : __assert_fail
("N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 47660, __extension__ __PRETTY_FUNCTION__))
;
47661
47662 // FMIN/FMAX are commutative if no NaNs and no negative zeros are allowed.
47663 if (!DAG.getTarget().Options.NoNaNsFPMath ||
47664 !DAG.getTarget().Options.NoSignedZerosFPMath)
47665 return SDValue();
47666
47667 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
47668 // into FMINC and FMAXC, which are Commutative operations.
47669 unsigned NewOp = 0;
47670 switch (N->getOpcode()) {
47671 default: llvm_unreachable("unknown opcode")::llvm::llvm_unreachable_internal("unknown opcode", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 47671)
;
47672 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
47673 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
47674 }
47675
47676 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
47677 N->getOperand(0), N->getOperand(1));
47678}
47679
47680static SDValue combineFMinNumFMaxNum(SDNode *N, SelectionDAG &DAG,
47681 const X86Subtarget &Subtarget) {
47682 if (Subtarget.useSoftFloat())
47683 return SDValue();
47684
47685 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47686
47687 EVT VT = N->getValueType(0);
47688 if (!((Subtarget.hasSSE1() && VT == MVT::f32) ||
47689 (Subtarget.hasSSE2() && VT == MVT::f64) ||
47690 (VT.isVector() && TLI.isTypeLegal(VT))))
47691 return SDValue();
47692
47693 SDValue Op0 = N->getOperand(0);
47694 SDValue Op1 = N->getOperand(1);
47695 SDLoc DL(N);
47696 auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
47697
47698 // If we don't have to respect NaN inputs, this is a direct translation to x86
47699 // min/max instructions.
47700 if (DAG.getTarget().Options.NoNaNsFPMath || N->getFlags().hasNoNaNs())
47701 return DAG.getNode(MinMaxOp, DL, VT, Op0, Op1, N->getFlags());
47702
47703 // If one of the operands is known non-NaN use the native min/max instructions
47704 // with the non-NaN input as second operand.
47705 if (DAG.isKnownNeverNaN(Op1))
47706 return DAG.getNode(MinMaxOp, DL, VT, Op0, Op1, N->getFlags());
47707 if (DAG.isKnownNeverNaN(Op0))
47708 return DAG.getNode(MinMaxOp, DL, VT, Op1, Op0, N->getFlags());
47709
47710 // If we have to respect NaN inputs, this takes at least 3 instructions.
47711 // Favor a library call when operating on a scalar and minimizing code size.
47712 if (!VT.isVector() && DAG.getMachineFunction().getFunction().hasMinSize())
47713 return SDValue();
47714
47715 EVT SetCCType = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
47716 VT);
47717
47718 // There are 4 possibilities involving NaN inputs, and these are the required
47719 // outputs:
47720 // Op1
47721 // Num NaN
47722 // ----------------
47723 // Num | Max | Op0 |
47724 // Op0 ----------------
47725 // NaN | Op1 | NaN |
47726 // ----------------
47727 //
47728 // The SSE FP max/min instructions were not designed for this case, but rather
47729 // to implement:
47730 // Min = Op1 < Op0 ? Op1 : Op0
47731 // Max = Op1 > Op0 ? Op1 : Op0
47732 //
47733 // So they always return Op0 if either input is a NaN. However, we can still
47734 // use those instructions for fmaxnum by selecting away a NaN input.
47735
47736 // If either operand is NaN, the 2nd source operand (Op0) is passed through.
47737 SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
47738 SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType, Op0, Op0, ISD::SETUO);
47739
47740 // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
47741 // are NaN, the NaN value of Op1 is the result.
47742 return DAG.getSelect(DL, VT, IsOp0Nan, Op1, MinOrMax);
47743}
47744
47745static SDValue combineX86INT_TO_FP(SDNode *N, SelectionDAG &DAG,
47746 TargetLowering::DAGCombinerInfo &DCI) {
47747 EVT VT = N->getValueType(0);
47748 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47749
47750 APInt KnownUndef, KnownZero;
47751 APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
47752 if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, KnownUndef,
47753 KnownZero, DCI))
47754 return SDValue(N, 0);
47755
47756 // Convert a full vector load into vzload when not all bits are needed.
47757 SDValue In = N->getOperand(0);
47758 MVT InVT = In.getSimpleValueType();
47759 if (VT.getVectorNumElements() < InVT.getVectorNumElements() &&
47760 ISD::isNormalLoad(In.getNode()) && In.hasOneUse()) {
47761 assert(InVT.is128BitVector() && "Expected 128-bit input vector")(static_cast <bool> (InVT.is128BitVector() && "Expected 128-bit input vector"
) ? void (0) : __assert_fail ("InVT.is128BitVector() && \"Expected 128-bit input vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 47761, __extension__ __PRETTY_FUNCTION__))
;
47762 LoadSDNode *LN = cast<LoadSDNode>(N->getOperand(0));
47763 unsigned NumBits = InVT.getScalarSizeInBits() * VT.getVectorNumElements();
47764 MVT MemVT = MVT::getIntegerVT(NumBits);
47765 MVT LoadVT = MVT::getVectorVT(MemVT, 128 / NumBits);
47766 if (SDValue VZLoad = narrowLoadToVZLoad(LN, MemVT, LoadVT, DAG)) {
47767 SDLoc dl(N);
47768 SDValue Convert = DAG.getNode(N->getOpcode(), dl, VT,
47769 DAG.getBitcast(InVT, VZLoad));
47770 DCI.CombineTo(N, Convert);
47771 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
47772 DCI.recursivelyDeleteUnusedNodes(LN);
47773 return SDValue(N, 0);
47774 }
47775 }
47776
47777 return SDValue();
47778}
47779
47780static SDValue combineCVTP2I_CVTTP2I(SDNode *N, SelectionDAG &DAG,
47781 TargetLowering::DAGCombinerInfo &DCI) {
47782 bool IsStrict = N->isTargetStrictFPOpcode();
47783 EVT VT = N->getValueType(0);
47784
47785 // Convert a full vector load into vzload when not all bits are needed.
47786 SDValue In = N->getOperand(IsStrict ? 1 : 0);
47787 MVT InVT = In.getSimpleValueType();
47788 if (VT.getVectorNumElements() < InVT.getVectorNumElements() &&
47789 ISD::isNormalLoad(In.getNode()) && In.hasOneUse()) {
47790 assert(InVT.is128BitVector() && "Expected 128-bit input vector")(static_cast <bool> (InVT.is128BitVector() && "Expected 128-bit input vector"
) ? void (0) : __assert_fail ("InVT.is128BitVector() && \"Expected 128-bit input vector\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 47790, __extension__ __PRETTY_FUNCTION__))
;
47791 LoadSDNode *LN = cast<LoadSDNode>(In);
47792 unsigned NumBits = InVT.getScalarSizeInBits() * VT.getVectorNumElements();
47793 MVT MemVT = MVT::getFloatingPointVT(NumBits);
47794 MVT LoadVT = MVT::getVectorVT(MemVT, 128 / NumBits);
47795 if (SDValue VZLoad = narrowLoadToVZLoad(LN, MemVT, LoadVT, DAG)) {
47796 SDLoc dl(N);
47797 if (IsStrict) {
47798 SDValue Convert =
47799 DAG.getNode(N->getOpcode(), dl, {VT, MVT::Other},
47800 {N->getOperand(0), DAG.getBitcast(InVT, VZLoad)});
47801 DCI.CombineTo(N, Convert, Convert.getValue(1));
47802 } else {
47803 SDValue Convert =
47804 DAG.getNode(N->getOpcode(), dl, VT, DAG.getBitcast(InVT, VZLoad));
47805 DCI.CombineTo(N, Convert);
47806 }
47807 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
47808 DCI.recursivelyDeleteUnusedNodes(LN);
47809 return SDValue(N, 0);
47810 }
47811 }
47812
47813 return SDValue();
47814}
47815
47816/// Do target-specific dag combines on X86ISD::ANDNP nodes.
47817static SDValue combineAndnp(SDNode *N, SelectionDAG &DAG,
47818 TargetLowering::DAGCombinerInfo &DCI,
47819 const X86Subtarget &Subtarget) {
47820 MVT VT = N->getSimpleValueType(0);
47821
47822 // ANDNP(0, x) -> x
47823 if (ISD::isBuildVectorAllZeros(N->getOperand(0).getNode()))
47824 return N->getOperand(1);
47825
47826 // ANDNP(x, 0) -> 0
47827 if (ISD::isBuildVectorAllZeros(N->getOperand(1).getNode()))
47828 return DAG.getConstant(0, SDLoc(N), VT);
47829
47830 // Turn ANDNP back to AND if input is inverted.
47831 if (SDValue Not = IsNOT(N->getOperand(0), DAG))
47832 return DAG.getNode(ISD::AND, SDLoc(N), VT, DAG.getBitcast(VT, Not),
47833 N->getOperand(1));
47834
47835 // Attempt to recursively combine a bitmask ANDNP with shuffles.
47836 if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
47837 SDValue Op(N, 0);
47838 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
47839 return Res;
47840 }
47841
47842 return SDValue();
47843}
47844
47845static SDValue combineBT(SDNode *N, SelectionDAG &DAG,
47846 TargetLowering::DAGCombinerInfo &DCI) {
47847 SDValue N1 = N->getOperand(1);
47848
47849 // BT ignores high bits in the bit index operand.
47850 unsigned BitWidth = N1.getValueSizeInBits();
47851 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
47852 if (DAG.getTargetLoweringInfo().SimplifyDemandedBits(N1, DemandedMask, DCI)) {
47853 if (N->getOpcode() != ISD::DELETED_NODE)
47854 DCI.AddToWorklist(N);
47855 return SDValue(N, 0);
47856 }
47857
47858 return SDValue();
47859}
47860
47861static SDValue combineCVTPH2PS(SDNode *N, SelectionDAG &DAG,
47862 TargetLowering::DAGCombinerInfo &DCI) {
47863 bool IsStrict = N->getOpcode() == X86ISD::STRICT_CVTPH2PS;
47864 SDValue Src = N->getOperand(IsStrict ? 1 : 0);
47865
47866 if (N->getValueType(0) == MVT::v4f32 && Src.getValueType() == MVT::v8i16) {
47867 APInt KnownUndef, KnownZero;
47868 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47869 APInt DemandedElts = APInt::getLowBitsSet(8, 4);
47870 if (TLI.SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, KnownZero,
47871 DCI)) {
47872 if (N->getOpcode() != ISD::DELETED_NODE)
47873 DCI.AddToWorklist(N);
47874 return SDValue(N, 0);
47875 }
47876
47877 // Convert a full vector load into vzload when not all bits are needed.
47878 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
47879 LoadSDNode *LN = cast<LoadSDNode>(N->getOperand(IsStrict ? 1 : 0));
47880 if (SDValue VZLoad = narrowLoadToVZLoad(LN, MVT::i64, MVT::v2i64, DAG)) {
47881 SDLoc dl(N);
47882 if (IsStrict) {
47883 SDValue Convert = DAG.getNode(
47884 N->getOpcode(), dl, {MVT::v4f32, MVT::Other},
47885 {N->getOperand(0), DAG.getBitcast(MVT::v8i16, VZLoad)});
47886 DCI.CombineTo(N, Convert, Convert.getValue(1));
47887 } else {
47888 SDValue Convert = DAG.getNode(N->getOpcode(), dl, MVT::v4f32,
47889 DAG.getBitcast(MVT::v8i16, VZLoad));
47890 DCI.CombineTo(N, Convert);
47891 }
47892
47893 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
47894 DCI.recursivelyDeleteUnusedNodes(LN);
47895 return SDValue(N, 0);
47896 }
47897 }
47898 }
47899
47900 return SDValue();
47901}
47902
47903// Try to combine sext_in_reg of a cmov of constants by extending the constants.
47904static SDValue combineSextInRegCmov(SDNode *N, SelectionDAG &DAG) {
47905 assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG)(static_cast <bool> (N->getOpcode() == ISD::SIGN_EXTEND_INREG
) ? void (0) : __assert_fail ("N->getOpcode() == ISD::SIGN_EXTEND_INREG"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 47905, __extension__ __PRETTY_FUNCTION__))
;
47906
47907 EVT DstVT = N->getValueType(0);
47908
47909 SDValue N0 = N->getOperand(0);
47910 SDValue N1 = N->getOperand(1);
47911 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
47912
47913 if (ExtraVT != MVT::i8 && ExtraVT != MVT::i16)
47914 return SDValue();
47915
47916 // Look through single use any_extends / truncs.
47917 SDValue IntermediateBitwidthOp;
47918 if ((N0.getOpcode() == ISD::ANY_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
47919 N0.hasOneUse()) {
47920 IntermediateBitwidthOp = N0;
47921 N0 = N0.getOperand(0);
47922 }
47923
47924 // See if we have a single use cmov.
47925 if (N0.getOpcode() != X86ISD::CMOV || !N0.hasOneUse())
47926 return SDValue();
47927
47928 SDValue CMovOp0 = N0.getOperand(0);
47929 SDValue CMovOp1 = N0.getOperand(1);
47930
47931 // Make sure both operands are constants.
47932 if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
47933 !isa<ConstantSDNode>(CMovOp1.getNode()))
47934 return SDValue();
47935
47936 SDLoc DL(N);
47937
47938 // If we looked through an any_extend/trunc above, add one to the constants.
47939 if (IntermediateBitwidthOp) {
47940 unsigned IntermediateOpc = IntermediateBitwidthOp.getOpcode();
47941 CMovOp0 = DAG.getNode(IntermediateOpc, DL, DstVT, CMovOp0);
47942 CMovOp1 = DAG.getNode(IntermediateOpc, DL, DstVT, CMovOp1);
47943 }
47944
47945 CMovOp0 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, DstVT, CMovOp0, N1);
47946 CMovOp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, DstVT, CMovOp1, N1);
47947
47948 EVT CMovVT = DstVT;
47949 // We do not want i16 CMOV's. Promote to i32 and truncate afterwards.
47950 if (DstVT == MVT::i16) {
47951 CMovVT = MVT::i32;
47952 CMovOp0 = DAG.getNode(ISD::ZERO_EXTEND, DL, CMovVT, CMovOp0);
47953 CMovOp1 = DAG.getNode(ISD::ZERO_EXTEND, DL, CMovVT, CMovOp1);
47954 }
47955
47956 SDValue CMov = DAG.getNode(X86ISD::CMOV, DL, CMovVT, CMovOp0, CMovOp1,
47957 N0.getOperand(2), N0.getOperand(3));
47958
47959 if (CMovVT != DstVT)
47960 CMov = DAG.getNode(ISD::TRUNCATE, DL, DstVT, CMov);
47961
47962 return CMov;
47963}
47964
47965static SDValue combineSignExtendInReg(SDNode *N, SelectionDAG &DAG,
47966 const X86Subtarget &Subtarget) {
47967 assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG)(static_cast <bool> (N->getOpcode() == ISD::SIGN_EXTEND_INREG
) ? void (0) : __assert_fail ("N->getOpcode() == ISD::SIGN_EXTEND_INREG"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 47967, __extension__ __PRETTY_FUNCTION__))
;
47968
47969 if (SDValue V = combineSextInRegCmov(N, DAG))
47970 return V;
47971
47972 EVT VT = N->getValueType(0);
47973 SDValue N0 = N->getOperand(0);
47974 SDValue N1 = N->getOperand(1);
47975 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
47976 SDLoc dl(N);
47977
47978 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
47979 // both SSE and AVX2 since there is no sign-extended shift right
47980 // operation on a vector with 64-bit elements.
47981 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
47982 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
47983 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
47984 N0.getOpcode() == ISD::SIGN_EXTEND)) {
47985 SDValue N00 = N0.getOperand(0);
47986
47987 // EXTLOAD has a better solution on AVX2,
47988 // it may be replaced with X86ISD::VSEXT node.
47989 if (N00.getOpcode() == ISD::LOAD && Subtarget.hasInt256())
47990 if (!ISD::isNormalLoad(N00.getNode()))
47991 return SDValue();
47992
47993 // Attempt to promote any comparison mask ops before moving the
47994 // SIGN_EXTEND_INREG in the way.
47995 if (SDValue Promote = PromoteMaskArithmetic(N0.getNode(), DAG, Subtarget))
47996 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Promote, N1);
47997
47998 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
47999 SDValue Tmp =
48000 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, N00, N1);
48001 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
48002 }
48003 }
48004 return SDValue();
48005}
48006
48007/// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
48008/// zext(add_nuw(x, C)) --> add(zext(x), C_zext)
48009/// Promoting a sign/zero extension ahead of a no overflow 'add' exposes
48010/// opportunities to combine math ops, use an LEA, or use a complex addressing
48011/// mode. This can eliminate extend, add, and shift instructions.
48012static SDValue promoteExtBeforeAdd(SDNode *Ext, SelectionDAG &DAG,
48013 const X86Subtarget &Subtarget) {
48014 if (Ext->getOpcode() != ISD::SIGN_EXTEND &&
48015 Ext->getOpcode() != ISD::ZERO_EXTEND)
48016 return SDValue();
48017
48018 // TODO: This should be valid for other integer types.
48019 EVT VT = Ext->getValueType(0);
48020 if (VT != MVT::i64)
48021 return SDValue();
48022
48023 SDValue Add = Ext->getOperand(0);
48024 if (Add.getOpcode() != ISD::ADD)
48025 return SDValue();
48026
48027 bool Sext = Ext->getOpcode() == ISD::SIGN_EXTEND;
48028 bool NSW = Add->getFlags().hasNoSignedWrap();
48029 bool NUW = Add->getFlags().hasNoUnsignedWrap();
48030
48031 // We need an 'add nsw' feeding into the 'sext' or 'add nuw' feeding
48032 // into the 'zext'
48033 if ((Sext && !NSW) || (!Sext && !NUW))
48034 return SDValue();
48035
48036 // Having a constant operand to the 'add' ensures that we are not increasing
48037 // the instruction count because the constant is extended for free below.
48038 // A constant operand can also become the displacement field of an LEA.
48039 auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
48040 if (!AddOp1)
48041 return SDValue();
48042
48043 // Don't make the 'add' bigger if there's no hope of combining it with some
48044 // other 'add' or 'shl' instruction.
48045 // TODO: It may be profitable to generate simpler LEA instructions in place
48046 // of single 'add' instructions, but the cost model for selecting an LEA
48047 // currently has a high threshold.
48048 bool HasLEAPotential = false;
48049 for (auto *User : Ext->uses()) {
48050 if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
48051 HasLEAPotential = true;
48052 break;
48053 }
48054 }
48055 if (!HasLEAPotential)
48056 return SDValue();
48057
48058 // Everything looks good, so pull the '{s|z}ext' ahead of the 'add'.
48059 int64_t AddConstant = Sext ? AddOp1->getSExtValue() : AddOp1->getZExtValue();
48060 SDValue AddOp0 = Add.getOperand(0);
48061 SDValue NewExt = DAG.getNode(Ext->getOpcode(), SDLoc(Ext), VT, AddOp0);
48062 SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
48063
48064 // The wider add is guaranteed to not wrap because both operands are
48065 // sign-extended.
48066 SDNodeFlags Flags;
48067 Flags.setNoSignedWrap(NSW);
48068 Flags.setNoUnsignedWrap(NUW);
48069 return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewExt, NewConstant, Flags);
48070}
48071
48072// If we face {ANY,SIGN,ZERO}_EXTEND that is applied to a CMOV with constant
48073// operands and the result of CMOV is not used anywhere else - promote CMOV
48074// itself instead of promoting its result. This could be beneficial, because:
48075// 1) X86TargetLowering::EmitLoweredSelect later can do merging of two
48076// (or more) pseudo-CMOVs only when they go one-after-another and
48077// getting rid of result extension code after CMOV will help that.
48078// 2) Promotion of constant CMOV arguments is free, hence the
48079// {ANY,SIGN,ZERO}_EXTEND will just be deleted.
48080// 3) 16-bit CMOV encoding is 4 bytes, 32-bit CMOV is 3-byte, so this
48081// promotion is also good in terms of code-size.
48082// (64-bit CMOV is 4-bytes, that's why we don't do 32-bit => 64-bit
48083// promotion).
48084static SDValue combineToExtendCMOV(SDNode *Extend, SelectionDAG &DAG) {
48085 SDValue CMovN = Extend->getOperand(0);
48086 if (CMovN.getOpcode() != X86ISD::CMOV || !CMovN.hasOneUse())
48087 return SDValue();
48088
48089 EVT TargetVT = Extend->getValueType(0);
48090 unsigned ExtendOpcode = Extend->getOpcode();
48091 SDLoc DL(Extend);
48092
48093 EVT VT = CMovN.getValueType();
48094 SDValue CMovOp0 = CMovN.getOperand(0);
48095 SDValue CMovOp1 = CMovN.getOperand(1);
48096
48097 if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
48098 !isa<ConstantSDNode>(CMovOp1.getNode()))
48099 return SDValue();
48100
48101 // Only extend to i32 or i64.
48102 if (TargetVT != MVT::i32 && TargetVT != MVT::i64)
48103 return SDValue();
48104
48105 // Only extend from i16 unless its a sign_extend from i32. Zext/aext from i32
48106 // are free.
48107 if (VT != MVT::i16 && !(ExtendOpcode == ISD::SIGN_EXTEND && VT == MVT::i32))
48108 return SDValue();
48109
48110 // If this a zero extend to i64, we should only extend to i32 and use a free
48111 // zero extend to finish.
48112 EVT ExtendVT = TargetVT;
48113 if (TargetVT == MVT::i64 && ExtendOpcode != ISD::SIGN_EXTEND)
48114 ExtendVT = MVT::i32;
48115
48116 CMovOp0 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp0);
48117 CMovOp1 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp1);
48118
48119 SDValue Res = DAG.getNode(X86ISD::CMOV, DL, ExtendVT, CMovOp0, CMovOp1,
48120 CMovN.getOperand(2), CMovN.getOperand(3));
48121
48122 // Finish extending if needed.
48123 if (ExtendVT != TargetVT)
48124 Res = DAG.getNode(ExtendOpcode, DL, TargetVT, Res);
48125
48126 return Res;
48127}
48128
48129// Convert (vXiY *ext(vXi1 bitcast(iX))) to extend_in_reg(broadcast(iX)).
48130// This is more or less the reverse of combineBitcastvxi1.
48131static SDValue
48132combineToExtendBoolVectorInReg(SDNode *N, SelectionDAG &DAG,
48133 TargetLowering::DAGCombinerInfo &DCI,
48134 const X86Subtarget &Subtarget) {
48135 unsigned Opcode = N->getOpcode();
48136 if (Opcode != ISD::SIGN_EXTEND && Opcode != ISD::ZERO_EXTEND &&
48137 Opcode != ISD::ANY_EXTEND)
48138 return SDValue();
48139 if (!DCI.isBeforeLegalizeOps())
48140 return SDValue();
48141 if (!Subtarget.hasSSE2() || Subtarget.hasAVX512())
48142 return SDValue();
48143
48144 SDValue N0 = N->getOperand(0);
48145 EVT VT = N->getValueType(0);
48146 EVT SVT = VT.getScalarType();
48147 EVT InSVT = N0.getValueType().getScalarType();
48148 unsigned EltSizeInBits = SVT.getSizeInBits();
48149
48150 // Input type must be extending a bool vector (bit-casted from a scalar
48151 // integer) to legal integer types.
48152 if (!VT.isVector())
48153 return SDValue();
48154 if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16 && SVT != MVT::i8)
48155 return SDValue();
48156 if (InSVT != MVT::i1 || N0.getOpcode() != ISD::BITCAST)
48157 return SDValue();
48158
48159 SDValue N00 = N0.getOperand(0);
48160 EVT SclVT = N0.getOperand(0).getValueType();
48161 if (!SclVT.isScalarInteger())
48162 return SDValue();
48163
48164 SDLoc DL(N);
48165 SDValue Vec;
48166 SmallVector<int, 32> ShuffleMask;
48167 unsigned NumElts = VT.getVectorNumElements();
48168 assert(NumElts == SclVT.getSizeInBits() && "Unexpected bool vector size")(static_cast <bool> (NumElts == SclVT.getSizeInBits() &&
"Unexpected bool vector size") ? void (0) : __assert_fail ("NumElts == SclVT.getSizeInBits() && \"Unexpected bool vector size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 48168, __extension__ __PRETTY_FUNCTION__))
;
48169
48170 // Broadcast the scalar integer to the vector elements.
48171 if (NumElts > EltSizeInBits) {
48172 // If the scalar integer is greater than the vector element size, then we
48173 // must split it down into sub-sections for broadcasting. For example:
48174 // i16 -> v16i8 (i16 -> v8i16 -> v16i8) with 2 sub-sections.
48175 // i32 -> v32i8 (i32 -> v8i32 -> v32i8) with 4 sub-sections.
48176 assert((NumElts % EltSizeInBits) == 0 && "Unexpected integer scale")(static_cast <bool> ((NumElts % EltSizeInBits) == 0 &&
"Unexpected integer scale") ? void (0) : __assert_fail ("(NumElts % EltSizeInBits) == 0 && \"Unexpected integer scale\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 48176, __extension__ __PRETTY_FUNCTION__))
;
48177 unsigned Scale = NumElts / EltSizeInBits;
48178 EVT BroadcastVT =
48179 EVT::getVectorVT(*DAG.getContext(), SclVT, EltSizeInBits);
48180 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, BroadcastVT, N00);
48181 Vec = DAG.getBitcast(VT, Vec);
48182
48183 for (unsigned i = 0; i != Scale; ++i)
48184 ShuffleMask.append(EltSizeInBits, i);
48185 Vec = DAG.getVectorShuffle(VT, DL, Vec, Vec, ShuffleMask);
48186 } else if (Subtarget.hasAVX2() && NumElts < EltSizeInBits &&
48187 (SclVT == MVT::i8 || SclVT == MVT::i16 || SclVT == MVT::i32)) {
48188 // If we have register broadcast instructions, use the scalar size as the
48189 // element type for the shuffle. Then cast to the wider element type. The
48190 // widened bits won't be used, and this might allow the use of a broadcast
48191 // load.
48192 assert((EltSizeInBits % NumElts) == 0 && "Unexpected integer scale")(static_cast <bool> ((EltSizeInBits % NumElts) == 0 &&
"Unexpected integer scale") ? void (0) : __assert_fail ("(EltSizeInBits % NumElts) == 0 && \"Unexpected integer scale\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 48192, __extension__ __PRETTY_FUNCTION__))
;
48193 unsigned Scale = EltSizeInBits / NumElts;
48194 EVT BroadcastVT =
48195 EVT::getVectorVT(*DAG.getContext(), SclVT, NumElts * Scale);
48196 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, BroadcastVT, N00);
48197 ShuffleMask.append(NumElts * Scale, 0);
48198 Vec = DAG.getVectorShuffle(BroadcastVT, DL, Vec, Vec, ShuffleMask);
48199 Vec = DAG.getBitcast(VT, Vec);
48200 } else {
48201 // For smaller scalar integers, we can simply any-extend it to the vector
48202 // element size (we don't care about the upper bits) and broadcast it to all
48203 // elements.
48204 SDValue Scl = DAG.getAnyExtOrTrunc(N00, DL, SVT);
48205 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Scl);
48206 ShuffleMask.append(NumElts, 0);
48207 Vec = DAG.getVectorShuffle(VT, DL, Vec, Vec, ShuffleMask);
48208 }
48209
48210 // Now, mask the relevant bit in each element.
48211 SmallVector<SDValue, 32> Bits;
48212 for (unsigned i = 0; i != NumElts; ++i) {
48213 int BitIdx = (i % EltSizeInBits);
48214 APInt Bit = APInt::getBitsSet(EltSizeInBits, BitIdx, BitIdx + 1);
48215 Bits.push_back(DAG.getConstant(Bit, DL, SVT));
48216 }
48217 SDValue BitMask = DAG.getBuildVector(VT, DL, Bits);
48218 Vec = DAG.getNode(ISD::AND, DL, VT, Vec, BitMask);
48219
48220 // Compare against the bitmask and extend the result.
48221 EVT CCVT = VT.changeVectorElementType(MVT::i1);
48222 Vec = DAG.getSetCC(DL, CCVT, Vec, BitMask, ISD::SETEQ);
48223 Vec = DAG.getSExtOrTrunc(Vec, DL, VT);
48224
48225 // For SEXT, this is now done, otherwise shift the result down for
48226 // zero-extension.
48227 if (Opcode == ISD::SIGN_EXTEND)
48228 return Vec;
48229 return DAG.getNode(ISD::SRL, DL, VT, Vec,
48230 DAG.getConstant(EltSizeInBits - 1, DL, VT));
48231}
48232
48233// Attempt to combine a (sext/zext (setcc)) to a setcc with a xmm/ymm/zmm
48234// result type.
48235static SDValue combineExtSetcc(SDNode *N, SelectionDAG &DAG,
48236 const X86Subtarget &Subtarget) {
48237 SDValue N0 = N->getOperand(0);
48238 EVT VT = N->getValueType(0);
48239 SDLoc dl(N);
48240
48241 // Only do this combine with AVX512 for vector extends.
48242 if (!Subtarget.hasAVX512() || !VT.isVector() || N0.getOpcode() != ISD::SETCC)
48243 return SDValue();
48244
48245 // Only combine legal element types.
48246 EVT SVT = VT.getVectorElementType();
48247 if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32 &&
48248 SVT != MVT::i64 && SVT != MVT::f32 && SVT != MVT::f64)
48249 return SDValue();
48250
48251 // We can only do this if the vector size in 256 bits or less.
48252 unsigned Size = VT.getSizeInBits();
48253 if (Size > 256 && Subtarget.useAVX512Regs())
48254 return SDValue();
48255
48256 // Don't fold if the condition code can't be handled by PCMPEQ/PCMPGT since
48257 // that's the only integer compares with we have.
48258 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
48259 if (ISD::isUnsignedIntSetCC(CC))
48260 return SDValue();
48261
48262 // Only do this combine if the extension will be fully consumed by the setcc.
48263 EVT N00VT = N0.getOperand(0).getValueType();
48264 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
48265 if (Size != MatchingVecType.getSizeInBits())
48266 return SDValue();
48267
48268 SDValue Res = DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
48269
48270 if (N->getOpcode() == ISD::ZERO_EXTEND)
48271 Res = DAG.getZeroExtendInReg(Res, dl, N0.getValueType());
48272
48273 return Res;
48274}
48275
48276static SDValue combineSext(SDNode *N, SelectionDAG &DAG,
48277 TargetLowering::DAGCombinerInfo &DCI,
48278 const X86Subtarget &Subtarget) {
48279 SDValue N0 = N->getOperand(0);
48280 EVT VT = N->getValueType(0);
48281 SDLoc DL(N);
48282
48283 // (i32 (sext (i8 (x86isd::setcc_carry)))) -> (i32 (x86isd::setcc_carry))
48284 if (!DCI.isBeforeLegalizeOps() &&
48285 N0.getOpcode() == X86ISD::SETCC_CARRY) {
48286 SDValue Setcc = DAG.getNode(X86ISD::SETCC_CARRY, DL, VT, N0->getOperand(0),
48287 N0->getOperand(1));
48288 bool ReplaceOtherUses = !N0.hasOneUse();
48289 DCI.CombineTo(N, Setcc);
48290 // Replace other uses with a truncate of the widened setcc_carry.
48291 if (ReplaceOtherUses) {
48292 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
48293 N0.getValueType(), Setcc);
48294 DCI.CombineTo(N0.getNode(), Trunc);
48295 }
48296
48297 return SDValue(N, 0);
48298 }
48299
48300 if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
48301 return NewCMov;
48302
48303 if (!DCI.isBeforeLegalizeOps())
48304 return SDValue();
48305
48306 if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
48307 return V;
48308
48309 if (SDValue V = combineToExtendBoolVectorInReg(N, DAG, DCI, Subtarget))
48310 return V;
48311
48312 if (VT.isVector()) {
48313 if (SDValue R = PromoteMaskArithmetic(N, DAG, Subtarget))
48314 return R;
48315
48316 if (N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG)
48317 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0));
48318 }
48319
48320 if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
48321 return NewAdd;
48322
48323 return SDValue();
48324}
48325
48326static SDValue combineFMA(SDNode *N, SelectionDAG &DAG,
48327 TargetLowering::DAGCombinerInfo &DCI,
48328 const X86Subtarget &Subtarget) {
48329 SDLoc dl(N);
48330 EVT VT = N->getValueType(0);
48331 bool IsStrict = N->isStrictFPOpcode() || N->isTargetStrictFPOpcode();
48332
48333 // Let legalize expand this if it isn't a legal type yet.
48334 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48335 if (!TLI.isTypeLegal(VT))
48336 return SDValue();
48337
48338 SDValue A = N->getOperand(IsStrict ? 1 : 0);
48339 SDValue B = N->getOperand(IsStrict ? 2 : 1);
48340 SDValue C = N->getOperand(IsStrict ? 3 : 2);
48341
48342 // If the operation allows fast-math and the target does not support FMA,
48343 // split this into mul+add to avoid libcall(s).
48344 SDNodeFlags Flags = N->getFlags();
48345 if (!IsStrict && Flags.hasAllowReassociation() &&
48346 TLI.isOperationExpand(ISD::FMA, VT)) {
48347 SDValue Fmul = DAG.getNode(ISD::FMUL, dl, VT, A, B, Flags);
48348 return DAG.getNode(ISD::FADD, dl, VT, Fmul, C, Flags);
48349 }
48350
48351 EVT ScalarVT = VT.getScalarType();
48352 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget.hasAnyFMA())
48353 return SDValue();
48354
48355 auto invertIfNegative = [&DAG, &TLI, &DCI](SDValue &V) {
48356 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
48357 bool LegalOperations = !DCI.isBeforeLegalizeOps();
48358 if (SDValue NegV = TLI.getCheaperNegatedExpression(V, DAG, LegalOperations,
48359 CodeSize)) {
48360 V = NegV;
48361 return true;
48362 }
48363 // Look through extract_vector_elts. If it comes from an FNEG, create a
48364 // new extract from the FNEG input.
48365 if (V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
48366 isNullConstant(V.getOperand(1))) {
48367 SDValue Vec = V.getOperand(0);
48368 if (SDValue NegV = TLI.getCheaperNegatedExpression(
48369 Vec, DAG, LegalOperations, CodeSize)) {
48370 V = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), V.getValueType(),
48371 NegV, V.getOperand(1));
48372 return true;
48373 }
48374 }
48375
48376 return false;
48377 };
48378
48379 // Do not convert the passthru input of scalar intrinsics.
48380 // FIXME: We could allow negations of the lower element only.
48381 bool NegA = invertIfNegative(A);
48382 bool NegB = invertIfNegative(B);
48383 bool NegC = invertIfNegative(C);
48384
48385 if (!NegA && !NegB && !NegC)
48386 return SDValue();
48387
48388 unsigned NewOpcode =
48389 negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC, false);
48390
48391 // Propagate fast-math-flags to new FMA node.
48392 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
48393 if (IsStrict) {
48394 assert(N->getNumOperands() == 4 && "Shouldn't be greater than 4")(static_cast <bool> (N->getNumOperands() == 4 &&
"Shouldn't be greater than 4") ? void (0) : __assert_fail ("N->getNumOperands() == 4 && \"Shouldn't be greater than 4\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 48394, __extension__ __PRETTY_FUNCTION__))
;
48395 return DAG.getNode(NewOpcode, dl, {VT, MVT::Other},
48396 {N->getOperand(0), A, B, C});
48397 } else {
48398 if (N->getNumOperands() == 4)
48399 return DAG.getNode(NewOpcode, dl, VT, A, B, C, N->getOperand(3));
48400 return DAG.getNode(NewOpcode, dl, VT, A, B, C);
48401 }
48402}
48403
48404// Combine FMADDSUB(A, B, FNEG(C)) -> FMSUBADD(A, B, C)
48405// Combine FMSUBADD(A, B, FNEG(C)) -> FMADDSUB(A, B, C)
48406static SDValue combineFMADDSUB(SDNode *N, SelectionDAG &DAG,
48407 TargetLowering::DAGCombinerInfo &DCI) {
48408 SDLoc dl(N);
48409 EVT VT = N->getValueType(0);
48410 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48411 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
48412 bool LegalOperations = !DCI.isBeforeLegalizeOps();
48413
48414 SDValue N2 = N->getOperand(2);
48415
48416 SDValue NegN2 =
48417 TLI.getCheaperNegatedExpression(N2, DAG, LegalOperations, CodeSize);
48418 if (!NegN2)
48419 return SDValue();
48420 unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), false, true, false);
48421
48422 if (N->getNumOperands() == 4)
48423 return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
48424 NegN2, N->getOperand(3));
48425 return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
48426 NegN2);
48427}
48428
48429static SDValue combineZext(SDNode *N, SelectionDAG &DAG,
48430 TargetLowering::DAGCombinerInfo &DCI,
48431 const X86Subtarget &Subtarget) {
48432 SDLoc dl(N);
48433 SDValue N0 = N->getOperand(0);
48434 EVT VT = N->getValueType(0);
48435
48436 // (i32 (aext (i8 (x86isd::setcc_carry)))) -> (i32 (x86isd::setcc_carry))
48437 // FIXME: Is this needed? We don't seem to have any tests for it.
48438 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ANY_EXTEND &&
48439 N0.getOpcode() == X86ISD::SETCC_CARRY) {
48440 SDValue Setcc = DAG.getNode(X86ISD::SETCC_CARRY, dl, VT, N0->getOperand(0),
48441 N0->getOperand(1));
48442 bool ReplaceOtherUses = !N0.hasOneUse();
48443 DCI.CombineTo(N, Setcc);
48444 // Replace other uses with a truncate of the widened setcc_carry.
48445 if (ReplaceOtherUses) {
48446 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
48447 N0.getValueType(), Setcc);
48448 DCI.CombineTo(N0.getNode(), Trunc);
48449 }
48450
48451 return SDValue(N, 0);
48452 }
48453
48454 if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
48455 return NewCMov;
48456
48457 if (DCI.isBeforeLegalizeOps())
48458 if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
48459 return V;
48460
48461 if (SDValue V = combineToExtendBoolVectorInReg(N, DAG, DCI, Subtarget))
48462 return V;
48463
48464 if (VT.isVector())
48465 if (SDValue R = PromoteMaskArithmetic(N, DAG, Subtarget))
48466 return R;
48467
48468 if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
48469 return NewAdd;
48470
48471 if (SDValue R = combineOrCmpEqZeroToCtlzSrl(N, DAG, DCI, Subtarget))
48472 return R;
48473
48474 // TODO: Combine with any target/faux shuffle.
48475 if (N0.getOpcode() == X86ISD::PACKUS && N0.getValueSizeInBits() == 128 &&
48476 VT.getScalarSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits()) {
48477 SDValue N00 = N0.getOperand(0);
48478 SDValue N01 = N0.getOperand(1);
48479 unsigned NumSrcEltBits = N00.getScalarValueSizeInBits();
48480 APInt ZeroMask = APInt::getHighBitsSet(NumSrcEltBits, NumSrcEltBits / 2);
48481 if ((N00.isUndef() || DAG.MaskedValueIsZero(N00, ZeroMask)) &&
48482 (N01.isUndef() || DAG.MaskedValueIsZero(N01, ZeroMask))) {
48483 return concatSubVectors(N00, N01, DAG, dl);
48484 }
48485 }
48486
48487 return SDValue();
48488}
48489
48490/// Recursive helper for combineVectorSizedSetCCEquality() to see if we have a
48491/// recognizable memcmp expansion.
48492static bool isOrXorXorTree(SDValue X, bool Root = true) {
48493 if (X.getOpcode() == ISD::OR)
48494 return isOrXorXorTree(X.getOperand(0), false) &&
48495 isOrXorXorTree(X.getOperand(1), false);
48496 if (Root)
48497 return false;
48498 return X.getOpcode() == ISD::XOR;
48499}
48500
48501/// Recursive helper for combineVectorSizedSetCCEquality() to emit the memcmp
48502/// expansion.
48503template<typename F>
48504static SDValue emitOrXorXorTree(SDValue X, SDLoc &DL, SelectionDAG &DAG,
48505 EVT VecVT, EVT CmpVT, bool HasPT, F SToV) {
48506 SDValue Op0 = X.getOperand(0);
48507 SDValue Op1 = X.getOperand(1);
48508 if (X.getOpcode() == ISD::OR) {
48509 SDValue A = emitOrXorXorTree(Op0, DL, DAG, VecVT, CmpVT, HasPT, SToV);
48510 SDValue B = emitOrXorXorTree(Op1, DL, DAG, VecVT, CmpVT, HasPT, SToV);
48511 if (VecVT != CmpVT)
48512 return DAG.getNode(ISD::OR, DL, CmpVT, A, B);
48513 if (HasPT)
48514 return DAG.getNode(ISD::OR, DL, VecVT, A, B);
48515 return DAG.getNode(ISD::AND, DL, CmpVT, A, B);
48516 } else if (X.getOpcode() == ISD::XOR) {
48517 SDValue A = SToV(Op0);
48518 SDValue B = SToV(Op1);
48519 if (VecVT != CmpVT)
48520 return DAG.getSetCC(DL, CmpVT, A, B, ISD::SETNE);
48521 if (HasPT)
48522 return DAG.getNode(ISD::XOR, DL, VecVT, A, B);
48523 return DAG.getSetCC(DL, CmpVT, A, B, ISD::SETEQ);
48524 }
48525 llvm_unreachable("Impossible")::llvm::llvm_unreachable_internal("Impossible", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 48525)
;
48526}
48527
48528/// Try to map a 128-bit or larger integer comparison to vector instructions
48529/// before type legalization splits it up into chunks.
48530static SDValue combineVectorSizedSetCCEquality(SDNode *SetCC, SelectionDAG &DAG,
48531 const X86Subtarget &Subtarget) {
48532 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
48533 assert((CC == ISD::SETNE || CC == ISD::SETEQ) && "Bad comparison predicate")(static_cast <bool> ((CC == ISD::SETNE || CC == ISD::SETEQ
) && "Bad comparison predicate") ? void (0) : __assert_fail
("(CC == ISD::SETNE || CC == ISD::SETEQ) && \"Bad comparison predicate\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 48533, __extension__ __PRETTY_FUNCTION__))
;
48534
48535 // We're looking for an oversized integer equality comparison.
48536 SDValue X = SetCC->getOperand(0);
48537 SDValue Y = SetCC->getOperand(1);
48538 EVT OpVT = X.getValueType();
48539 unsigned OpSize = OpVT.getSizeInBits();
48540 if (!OpVT.isScalarInteger() || OpSize < 128)
48541 return SDValue();
48542
48543 // Ignore a comparison with zero because that gets special treatment in
48544 // EmitTest(). But make an exception for the special case of a pair of
48545 // logically-combined vector-sized operands compared to zero. This pattern may
48546 // be generated by the memcmp expansion pass with oversized integer compares
48547 // (see PR33325).
48548 bool IsOrXorXorTreeCCZero = isNullConstant(Y) && isOrXorXorTree(X);
48549 if (isNullConstant(Y) && !IsOrXorXorTreeCCZero)
48550 return SDValue();
48551
48552 // Don't perform this combine if constructing the vector will be expensive.
48553 auto IsVectorBitCastCheap = [](SDValue X) {
48554 X = peekThroughBitcasts(X);
48555 return isa<ConstantSDNode>(X) || X.getValueType().isVector() ||
48556 X.getOpcode() == ISD::LOAD;
48557 };
48558 if ((!IsVectorBitCastCheap(X) || !IsVectorBitCastCheap(Y)) &&
48559 !IsOrXorXorTreeCCZero)
48560 return SDValue();
48561
48562 EVT VT = SetCC->getValueType(0);
48563 SDLoc DL(SetCC);
48564
48565 // Use XOR (plus OR) and PTEST after SSE4.1 for 128/256-bit operands.
48566 // Use PCMPNEQ (plus OR) and KORTEST for 512-bit operands.
48567 // Otherwise use PCMPEQ (plus AND) and mask testing.
48568 if ((OpSize == 128 && Subtarget.hasSSE2()) ||
48569 (OpSize == 256 && Subtarget.hasAVX()) ||
48570 (OpSize == 512 && Subtarget.useAVX512Regs())) {
48571 bool HasPT = Subtarget.hasSSE41();
48572
48573 // PTEST and MOVMSK are slow on Knights Landing and Knights Mill and widened
48574 // vector registers are essentially free. (Technically, widening registers
48575 // prevents load folding, but the tradeoff is worth it.)
48576 bool PreferKOT = Subtarget.preferMaskRegisters();
48577 bool NeedZExt = PreferKOT && !Subtarget.hasVLX() && OpSize != 512;
48578
48579 EVT VecVT = MVT::v16i8;
48580 EVT CmpVT = PreferKOT ? MVT::v16i1 : VecVT;
48581 if (OpSize == 256) {
48582 VecVT = MVT::v32i8;
48583 CmpVT = PreferKOT ? MVT::v32i1 : VecVT;
48584 }
48585 EVT CastVT = VecVT;
48586 bool NeedsAVX512FCast = false;
48587 if (OpSize == 512 || NeedZExt) {
48588 if (Subtarget.hasBWI()) {
48589 VecVT = MVT::v64i8;
48590 CmpVT = MVT::v64i1;
48591 if (OpSize == 512)
48592 CastVT = VecVT;
48593 } else {
48594 VecVT = MVT::v16i32;
48595 CmpVT = MVT::v16i1;
48596 CastVT = OpSize == 512 ? VecVT :
48597 OpSize == 256 ? MVT::v8i32 : MVT::v4i32;
48598 NeedsAVX512FCast = true;
48599 }
48600 }
48601
48602 auto ScalarToVector = [&](SDValue X) -> SDValue {
48603 bool TmpZext = false;
48604 EVT TmpCastVT = CastVT;
48605 if (X.getOpcode() == ISD::ZERO_EXTEND) {
48606 SDValue OrigX = X.getOperand(0);
48607 unsigned OrigSize = OrigX.getScalarValueSizeInBits();
48608 if (OrigSize < OpSize) {
48609 if (OrigSize == 128) {
48610 TmpCastVT = NeedsAVX512FCast ? MVT::v4i32 : MVT::v16i8;
48611 X = OrigX;
48612 TmpZext = true;
48613 } else if (OrigSize == 256) {
48614 TmpCastVT = NeedsAVX512FCast ? MVT::v8i32 : MVT::v32i8;
48615 X = OrigX;
48616 TmpZext = true;
48617 }
48618 }
48619 }
48620 X = DAG.getBitcast(TmpCastVT, X);
48621 if (!NeedZExt && !TmpZext)
48622 return X;
48623 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT,
48624 DAG.getConstant(0, DL, VecVT), X,
48625 DAG.getVectorIdxConstant(0, DL));
48626 };
48627
48628 SDValue Cmp;
48629 if (IsOrXorXorTreeCCZero) {
48630 // This is a bitwise-combined equality comparison of 2 pairs of vectors:
48631 // setcc i128 (or (xor A, B), (xor C, D)), 0, eq|ne
48632 // Use 2 vector equality compares and 'and' the results before doing a
48633 // MOVMSK.
48634 Cmp = emitOrXorXorTree(X, DL, DAG, VecVT, CmpVT, HasPT, ScalarToVector);
48635 } else {
48636 SDValue VecX = ScalarToVector(X);
48637 SDValue VecY = ScalarToVector(Y);
48638 if (VecVT != CmpVT) {
48639 Cmp = DAG.getSetCC(DL, CmpVT, VecX, VecY, ISD::SETNE);
48640 } else if (HasPT) {
48641 Cmp = DAG.getNode(ISD::XOR, DL, VecVT, VecX, VecY);
48642 } else {
48643 Cmp = DAG.getSetCC(DL, CmpVT, VecX, VecY, ISD::SETEQ);
48644 }
48645 }
48646 // AVX512 should emit a setcc that will lower to kortest.
48647 if (VecVT != CmpVT) {
48648 EVT KRegVT = CmpVT == MVT::v64i1 ? MVT::i64 :
48649 CmpVT == MVT::v32i1 ? MVT::i32 : MVT::i16;
48650 return DAG.getSetCC(DL, VT, DAG.getBitcast(KRegVT, Cmp),
48651 DAG.getConstant(0, DL, KRegVT), CC);
48652 }
48653 if (HasPT) {
48654 SDValue BCCmp = DAG.getBitcast(OpSize == 256 ? MVT::v4i64 : MVT::v2i64,
48655 Cmp);
48656 SDValue PT = DAG.getNode(X86ISD::PTEST, DL, MVT::i32, BCCmp, BCCmp);
48657 X86::CondCode X86CC = CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE;
48658 SDValue X86SetCC = getSETCC(X86CC, PT, DL, DAG);
48659 return DAG.getNode(ISD::TRUNCATE, DL, VT, X86SetCC.getValue(0));
48660 }
48661 // If all bytes match (bitmask is 0x(FFFF)FFFF), that's equality.
48662 // setcc i128 X, Y, eq --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, eq
48663 // setcc i128 X, Y, ne --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, ne
48664 assert(Cmp.getValueType() == MVT::v16i8 &&(static_cast <bool> (Cmp.getValueType() == MVT::v16i8 &&
"Non 128-bit vector on pre-SSE41 target") ? void (0) : __assert_fail
("Cmp.getValueType() == MVT::v16i8 && \"Non 128-bit vector on pre-SSE41 target\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 48665, __extension__ __PRETTY_FUNCTION__))
48665 "Non 128-bit vector on pre-SSE41 target")(static_cast <bool> (Cmp.getValueType() == MVT::v16i8 &&
"Non 128-bit vector on pre-SSE41 target") ? void (0) : __assert_fail
("Cmp.getValueType() == MVT::v16i8 && \"Non 128-bit vector on pre-SSE41 target\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 48665, __extension__ __PRETTY_FUNCTION__))
;
48666 SDValue MovMsk = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Cmp);
48667 SDValue FFFFs = DAG.getConstant(0xFFFF, DL, MVT::i32);
48668 return DAG.getSetCC(DL, VT, MovMsk, FFFFs, CC);
48669 }
48670
48671 return SDValue();
48672}
48673
48674static SDValue combineSetCC(SDNode *N, SelectionDAG &DAG,
48675 TargetLowering::DAGCombinerInfo &DCI,
48676 const X86Subtarget &Subtarget) {
48677 const ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
48678 const SDValue LHS = N->getOperand(0);
48679 const SDValue RHS = N->getOperand(1);
48680 EVT VT = N->getValueType(0);
48681 EVT OpVT = LHS.getValueType();
48682 SDLoc DL(N);
48683
48684 if (CC == ISD::SETNE || CC == ISD::SETEQ) {
48685 if (SDValue V = combineVectorSizedSetCCEquality(N, DAG, Subtarget))
48686 return V;
48687
48688 if (VT == MVT::i1 && isNullConstant(RHS)) {
48689 SDValue X86CC;
48690 if (SDValue V =
48691 MatchVectorAllZeroTest(LHS, CC, DL, Subtarget, DAG, X86CC))
48692 return DAG.getNode(ISD::TRUNCATE, DL, VT,
48693 DAG.getNode(X86ISD::SETCC, DL, MVT::i8, X86CC, V));
48694 }
48695
48696 if (OpVT.isScalarInteger()) {
48697 // cmpeq(or(X,Y),X) --> cmpeq(and(~X,Y),0)
48698 // cmpne(or(X,Y),X) --> cmpne(and(~X,Y),0)
48699 auto MatchOrCmpEq = [&](SDValue N0, SDValue N1) {
48700 if (N0.getOpcode() == ISD::OR && N0->hasOneUse()) {
48701 if (N0.getOperand(0) == N1)
48702 return DAG.getNode(ISD::AND, DL, OpVT, DAG.getNOT(DL, N1, OpVT),
48703 N0.getOperand(1));
48704 if (N0.getOperand(1) == N1)
48705 return DAG.getNode(ISD::AND, DL, OpVT, DAG.getNOT(DL, N1, OpVT),
48706 N0.getOperand(0));
48707 }
48708 return SDValue();
48709 };
48710 if (SDValue AndN = MatchOrCmpEq(LHS, RHS))
48711 return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
48712 if (SDValue AndN = MatchOrCmpEq(RHS, LHS))
48713 return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
48714
48715 // cmpeq(and(X,Y),Y) --> cmpeq(and(~X,Y),0)
48716 // cmpne(and(X,Y),Y) --> cmpne(and(~X,Y),0)
48717 auto MatchAndCmpEq = [&](SDValue N0, SDValue N1) {
48718 if (N0.getOpcode() == ISD::AND && N0->hasOneUse()) {
48719 if (N0.getOperand(0) == N1)
48720 return DAG.getNode(ISD::AND, DL, OpVT, N1,
48721 DAG.getNOT(DL, N0.getOperand(1), OpVT));
48722 if (N0.getOperand(1) == N1)
48723 return DAG.getNode(ISD::AND, DL, OpVT, N1,
48724 DAG.getNOT(DL, N0.getOperand(0), OpVT));
48725 }
48726 return SDValue();
48727 };
48728 if (SDValue AndN = MatchAndCmpEq(LHS, RHS))
48729 return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
48730 if (SDValue AndN = MatchAndCmpEq(RHS, LHS))
48731 return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
48732
48733 // cmpeq(trunc(x),0) --> cmpeq(x,0)
48734 // cmpne(trunc(x),0) --> cmpne(x,0)
48735 // iff x upper bits are zero.
48736 // TODO: Add support for RHS to be truncate as well?
48737 if (LHS.getOpcode() == ISD::TRUNCATE &&
48738 LHS.getOperand(0).getScalarValueSizeInBits() >= 32 &&
48739 isNullConstant(RHS) && !DCI.isBeforeLegalize()) {
48740 EVT SrcVT = LHS.getOperand(0).getValueType();
48741 APInt UpperBits = APInt::getBitsSetFrom(SrcVT.getScalarSizeInBits(),
48742 OpVT.getScalarSizeInBits());
48743 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48744 if (DAG.MaskedValueIsZero(LHS.getOperand(0), UpperBits) &&
48745 TLI.isTypeLegal(LHS.getOperand(0).getValueType()))
48746 return DAG.getSetCC(DL, VT, LHS.getOperand(0),
48747 DAG.getConstant(0, DL, SrcVT), CC);
48748 }
48749 }
48750 }
48751
48752 if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
48753 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
48754 // Using temporaries to avoid messing up operand ordering for later
48755 // transformations if this doesn't work.
48756 SDValue Op0 = LHS;
48757 SDValue Op1 = RHS;
48758 ISD::CondCode TmpCC = CC;
48759 // Put build_vector on the right.
48760 if (Op0.getOpcode() == ISD::BUILD_VECTOR) {
48761 std::swap(Op0, Op1);
48762 TmpCC = ISD::getSetCCSwappedOperands(TmpCC);
48763 }
48764
48765 bool IsSEXT0 =
48766 (Op0.getOpcode() == ISD::SIGN_EXTEND) &&
48767 (Op0.getOperand(0).getValueType().getVectorElementType() == MVT::i1);
48768 bool IsVZero1 = ISD::isBuildVectorAllZeros(Op1.getNode());
48769
48770 if (IsSEXT0 && IsVZero1) {
48771 assert(VT == Op0.getOperand(0).getValueType() &&(static_cast <bool> (VT == Op0.getOperand(0).getValueType
() && "Unexpected operand type") ? void (0) : __assert_fail
("VT == Op0.getOperand(0).getValueType() && \"Unexpected operand type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 48772, __extension__ __PRETTY_FUNCTION__))
48772 "Unexpected operand type")(static_cast <bool> (VT == Op0.getOperand(0).getValueType
() && "Unexpected operand type") ? void (0) : __assert_fail
("VT == Op0.getOperand(0).getValueType() && \"Unexpected operand type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 48772, __extension__ __PRETTY_FUNCTION__))
;
48773 if (TmpCC == ISD::SETGT)
48774 return DAG.getConstant(0, DL, VT);
48775 if (TmpCC == ISD::SETLE)
48776 return DAG.getConstant(1, DL, VT);
48777 if (TmpCC == ISD::SETEQ || TmpCC == ISD::SETGE)
48778 return DAG.getNOT(DL, Op0.getOperand(0), VT);
48779
48780 assert((TmpCC == ISD::SETNE || TmpCC == ISD::SETLT) &&(static_cast <bool> ((TmpCC == ISD::SETNE || TmpCC == ISD
::SETLT) && "Unexpected condition code!") ? void (0) :
__assert_fail ("(TmpCC == ISD::SETNE || TmpCC == ISD::SETLT) && \"Unexpected condition code!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 48781, __extension__ __PRETTY_FUNCTION__))
48781 "Unexpected condition code!")(static_cast <bool> ((TmpCC == ISD::SETNE || TmpCC == ISD
::SETLT) && "Unexpected condition code!") ? void (0) :
__assert_fail ("(TmpCC == ISD::SETNE || TmpCC == ISD::SETLT) && \"Unexpected condition code!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 48781, __extension__ __PRETTY_FUNCTION__))
;
48782 return Op0.getOperand(0);
48783 }
48784 }
48785
48786 // If we have AVX512, but not BWI and this is a vXi16/vXi8 setcc, just
48787 // pre-promote its result type since vXi1 vectors don't get promoted
48788 // during type legalization.
48789 // NOTE: The element count check is to ignore operand types that need to
48790 // go through type promotion to a 128-bit vector.
48791 if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && VT.isVector() &&
48792 VT.getVectorElementType() == MVT::i1 &&
48793 (OpVT.getVectorElementType() == MVT::i8 ||
48794 OpVT.getVectorElementType() == MVT::i16)) {
48795 SDValue Setcc = DAG.getSetCC(DL, OpVT, LHS, RHS, CC);
48796 return DAG.getNode(ISD::TRUNCATE, DL, VT, Setcc);
48797 }
48798
48799 // For an SSE1-only target, lower a comparison of v4f32 to X86ISD::CMPP early
48800 // to avoid scalarization via legalization because v4i32 is not a legal type.
48801 if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32 &&
48802 LHS.getValueType() == MVT::v4f32)
48803 return LowerVSETCC(SDValue(N, 0), Subtarget, DAG);
48804
48805 return SDValue();
48806}
48807
48808static SDValue combineMOVMSK(SDNode *N, SelectionDAG &DAG,
48809 TargetLowering::DAGCombinerInfo &DCI,
48810 const X86Subtarget &Subtarget) {
48811 SDValue Src = N->getOperand(0);
48812 MVT SrcVT = Src.getSimpleValueType();
48813 MVT VT = N->getSimpleValueType(0);
48814 unsigned NumBits = VT.getScalarSizeInBits();
48815 unsigned NumElts = SrcVT.getVectorNumElements();
48816
48817 // Perform constant folding.
48818 if (ISD::isBuildVectorOfConstantSDNodes(Src.getNode())) {
48819 assert(VT == MVT::i32 && "Unexpected result type")(static_cast <bool> (VT == MVT::i32 && "Unexpected result type"
) ? void (0) : __assert_fail ("VT == MVT::i32 && \"Unexpected result type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 48819, __extension__ __PRETTY_FUNCTION__))
;
48820 APInt Imm(32, 0);
48821 for (unsigned Idx = 0, e = Src.getNumOperands(); Idx < e; ++Idx) {
48822 if (!Src.getOperand(Idx).isUndef() &&
48823 Src.getConstantOperandAPInt(Idx).isNegative())
48824 Imm.setBit(Idx);
48825 }
48826 return DAG.getConstant(Imm, SDLoc(N), VT);
48827 }
48828
48829 // Look through int->fp bitcasts that don't change the element width.
48830 unsigned EltWidth = SrcVT.getScalarSizeInBits();
48831 if (Subtarget.hasSSE2() && Src.getOpcode() == ISD::BITCAST &&
48832 Src.getOperand(0).getScalarValueSizeInBits() == EltWidth)
48833 return DAG.getNode(X86ISD::MOVMSK, SDLoc(N), VT, Src.getOperand(0));
48834
48835 // Fold movmsk(not(x)) -> not(movmsk(x)) to improve folding of movmsk results
48836 // with scalar comparisons.
48837 if (SDValue NotSrc = IsNOT(Src, DAG)) {
48838 SDLoc DL(N);
48839 APInt NotMask = APInt::getLowBitsSet(NumBits, NumElts);
48840 NotSrc = DAG.getBitcast(SrcVT, NotSrc);
48841 return DAG.getNode(ISD::XOR, DL, VT,
48842 DAG.getNode(X86ISD::MOVMSK, DL, VT, NotSrc),
48843 DAG.getConstant(NotMask, DL, VT));
48844 }
48845
48846 // Fold movmsk(icmp_sgt(x,-1)) -> not(movmsk(x)) to improve folding of movmsk
48847 // results with scalar comparisons.
48848 if (Src.getOpcode() == X86ISD::PCMPGT &&
48849 ISD::isBuildVectorAllOnes(Src.getOperand(1).getNode())) {
48850 SDLoc DL(N);
48851 APInt NotMask = APInt::getLowBitsSet(NumBits, NumElts);
48852 return DAG.getNode(ISD::XOR, DL, VT,
48853 DAG.getNode(X86ISD::MOVMSK, DL, VT, Src.getOperand(0)),
48854 DAG.getConstant(NotMask, DL, VT));
48855 }
48856
48857 // Simplify the inputs.
48858 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48859 APInt DemandedMask(APInt::getAllOnesValue(NumBits));
48860 if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
48861 return SDValue(N, 0);
48862
48863 return SDValue();
48864}
48865
48866static SDValue combineX86GatherScatter(SDNode *N, SelectionDAG &DAG,
48867 TargetLowering::DAGCombinerInfo &DCI) {
48868 // With vector masks we only demand the upper bit of the mask.
48869 SDValue Mask = cast<X86MaskedGatherScatterSDNode>(N)->getMask();
48870 if (Mask.getScalarValueSizeInBits() != 1) {
48871 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48872 APInt DemandedMask(APInt::getSignMask(Mask.getScalarValueSizeInBits()));
48873 if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI)) {
48874 if (N->getOpcode() != ISD::DELETED_NODE)
48875 DCI.AddToWorklist(N);
48876 return SDValue(N, 0);
48877 }
48878 }
48879
48880 return SDValue();
48881}
48882
48883static SDValue rebuildGatherScatter(MaskedGatherScatterSDNode *GorS,
48884 SDValue Index, SDValue Base, SDValue Scale,
48885 SelectionDAG &DAG) {
48886 SDLoc DL(GorS);
48887
48888 if (auto *Gather = dyn_cast<MaskedGatherSDNode>(GorS)) {
48889 SDValue Ops[] = { Gather->getChain(), Gather->getPassThru(),
48890 Gather->getMask(), Base, Index, Scale } ;
48891 return DAG.getMaskedGather(Gather->getVTList(),
48892 Gather->getMemoryVT(), DL, Ops,
48893 Gather->getMemOperand(),
48894 Gather->getIndexType(),
48895 Gather->getExtensionType());
48896 }
48897 auto *Scatter = cast<MaskedScatterSDNode>(GorS);
48898 SDValue Ops[] = { Scatter->getChain(), Scatter->getValue(),
48899 Scatter->getMask(), Base, Index, Scale };
48900 return DAG.getMaskedScatter(Scatter->getVTList(),
48901 Scatter->getMemoryVT(), DL,
48902 Ops, Scatter->getMemOperand(),
48903 Scatter->getIndexType(),
48904 Scatter->isTruncatingStore());
48905}
48906
48907static SDValue combineGatherScatter(SDNode *N, SelectionDAG &DAG,
48908 TargetLowering::DAGCombinerInfo &DCI) {
48909 SDLoc DL(N);
48910 auto *GorS = cast<MaskedGatherScatterSDNode>(N);
48911 SDValue Index = GorS->getIndex();
48912 SDValue Base = GorS->getBasePtr();
48913 SDValue Scale = GorS->getScale();
48914
48915 if (DCI.isBeforeLegalize()) {
48916 unsigned IndexWidth = Index.getScalarValueSizeInBits();
48917
48918 // Shrink constant indices if they are larger than 32-bits.
48919 // Only do this before legalize types since v2i64 could become v2i32.
48920 // FIXME: We could check that the type is legal if we're after legalize
48921 // types, but then we would need to construct test cases where that happens.
48922 // FIXME: We could support more than just constant vectors, but we need to
48923 // careful with costing. A truncate that can be optimized out would be fine.
48924 // Otherwise we might only want to create a truncate if it avoids a split.
48925 if (auto *BV = dyn_cast<BuildVectorSDNode>(Index)) {
48926 if (BV->isConstant() && IndexWidth > 32 &&
48927 DAG.ComputeNumSignBits(Index) > (IndexWidth - 32)) {
48928 EVT NewVT = Index.getValueType().changeVectorElementType(MVT::i32);
48929 Index = DAG.getNode(ISD::TRUNCATE, DL, NewVT, Index);
48930 return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
48931 }
48932 }
48933
48934 // Shrink any sign/zero extends from 32 or smaller to larger than 32 if
48935 // there are sufficient sign bits. Only do this before legalize types to
48936 // avoid creating illegal types in truncate.
48937 if ((Index.getOpcode() == ISD::SIGN_EXTEND ||
48938 Index.getOpcode() == ISD::ZERO_EXTEND) &&
48939 IndexWidth > 32 &&
48940 Index.getOperand(0).getScalarValueSizeInBits() <= 32 &&
48941 DAG.ComputeNumSignBits(Index) > (IndexWidth - 32)) {
48942 EVT NewVT = Index.getValueType().changeVectorElementType(MVT::i32);
48943 Index = DAG.getNode(ISD::TRUNCATE, DL, NewVT, Index);
48944 return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
48945 }
48946 }
48947
48948 if (DCI.isBeforeLegalizeOps()) {
48949 unsigned IndexWidth = Index.getScalarValueSizeInBits();
48950
48951 // Make sure the index is either i32 or i64
48952 if (IndexWidth != 32 && IndexWidth != 64) {
48953 MVT EltVT = IndexWidth > 32 ? MVT::i64 : MVT::i32;
48954 EVT IndexVT = Index.getValueType().changeVectorElementType(EltVT);
48955 Index = DAG.getSExtOrTrunc(Index, DL, IndexVT);
48956 return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
48957 }
48958 }
48959
48960 // With vector masks we only demand the upper bit of the mask.
48961 SDValue Mask = GorS->getMask();
48962 if (Mask.getScalarValueSizeInBits() != 1) {
48963 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48964 APInt DemandedMask(APInt::getSignMask(Mask.getScalarValueSizeInBits()));
48965 if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI)) {
48966 if (N->getOpcode() != ISD::DELETED_NODE)
48967 DCI.AddToWorklist(N);
48968 return SDValue(N, 0);
48969 }
48970 }
48971
48972 return SDValue();
48973}
48974
48975// Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
48976static SDValue combineX86SetCC(SDNode *N, SelectionDAG &DAG,
48977 const X86Subtarget &Subtarget) {
48978 SDLoc DL(N);
48979 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
48980 SDValue EFLAGS = N->getOperand(1);
48981
48982 // Try to simplify the EFLAGS and condition code operands.
48983 if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget))
48984 return getSETCC(CC, Flags, DL, DAG);
48985
48986 return SDValue();
48987}
48988
48989/// Optimize branch condition evaluation.
48990static SDValue combineBrCond(SDNode *N, SelectionDAG &DAG,
48991 const X86Subtarget &Subtarget) {
48992 SDLoc DL(N);
48993 SDValue EFLAGS = N->getOperand(3);
48994 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
48995
48996 // Try to simplify the EFLAGS and condition code operands.
48997 // Make sure to not keep references to operands, as combineSetCCEFLAGS can
48998 // RAUW them under us.
48999 if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget)) {
49000 SDValue Cond = DAG.getTargetConstant(CC, DL, MVT::i8);
49001 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), N->getOperand(0),
49002 N->getOperand(1), Cond, Flags);
49003 }
49004
49005 return SDValue();
49006}
49007
49008// TODO: Could we move this to DAGCombine?
49009static SDValue combineVectorCompareAndMaskUnaryOp(SDNode *N,
49010 SelectionDAG &DAG) {
49011 // Take advantage of vector comparisons (etc.) producing 0 or -1 in each lane
49012 // to optimize away operation when it's from a constant.
49013 //
49014 // The general transformation is:
49015 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
49016 // AND(VECTOR_CMP(x,y), constant2)
49017 // constant2 = UNARYOP(constant)
49018
49019 // Early exit if this isn't a vector operation, the operand of the
49020 // unary operation isn't a bitwise AND, or if the sizes of the operations
49021 // aren't the same.
49022 EVT VT = N->getValueType(0);
49023 bool IsStrict = N->isStrictFPOpcode();
49024 unsigned NumEltBits = VT.getScalarSizeInBits();
49025 SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
49026 if (!VT.isVector() || Op0.getOpcode() != ISD::AND ||
49027 DAG.ComputeNumSignBits(Op0.getOperand(0)) != NumEltBits ||
49028 VT.getSizeInBits() != Op0.getValueSizeInBits())
49029 return SDValue();
49030
49031 // Now check that the other operand of the AND is a constant. We could
49032 // make the transformation for non-constant splats as well, but it's unclear
49033 // that would be a benefit as it would not eliminate any operations, just
49034 // perform one more step in scalar code before moving to the vector unit.
49035 if (auto *BV = dyn_cast<BuildVectorSDNode>(Op0.getOperand(1))) {
49036 // Bail out if the vector isn't a constant.
49037 if (!BV->isConstant())
49038 return SDValue();
49039
49040 // Everything checks out. Build up the new and improved node.
49041 SDLoc DL(N);
49042 EVT IntVT = BV->getValueType(0);
49043 // Create a new constant of the appropriate type for the transformed
49044 // DAG.
49045 SDValue SourceConst;
49046 if (IsStrict)
49047 SourceConst = DAG.getNode(N->getOpcode(), DL, {VT, MVT::Other},
49048 {N->getOperand(0), SDValue(BV, 0)});
49049 else
49050 SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
49051 // The AND node needs bitcasts to/from an integer vector type around it.
49052 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
49053 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, Op0->getOperand(0),
49054 MaskConst);
49055 SDValue Res = DAG.getBitcast(VT, NewAnd);
49056 if (IsStrict)
49057 return DAG.getMergeValues({Res, SourceConst.getValue(1)}, DL);
49058 return Res;
49059 }
49060
49061 return SDValue();
49062}
49063
49064/// If we are converting a value to floating-point, try to replace scalar
49065/// truncate of an extracted vector element with a bitcast. This tries to keep
49066/// the sequence on XMM registers rather than moving between vector and GPRs.
49067static SDValue combineToFPTruncExtElt(SDNode *N, SelectionDAG &DAG) {
49068 // TODO: This is currently only used by combineSIntToFP, but it is generalized
49069 // to allow being called by any similar cast opcode.
49070 // TODO: Consider merging this into lowering: vectorizeExtractedCast().
49071 SDValue Trunc = N->getOperand(0);
49072 if (!Trunc.hasOneUse() || Trunc.getOpcode() != ISD::TRUNCATE)
49073 return SDValue();
49074
49075 SDValue ExtElt = Trunc.getOperand(0);
49076 if (!ExtElt.hasOneUse() || ExtElt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
49077 !isNullConstant(ExtElt.getOperand(1)))
49078 return SDValue();
49079
49080 EVT TruncVT = Trunc.getValueType();
49081 EVT SrcVT = ExtElt.getValueType();
49082 unsigned DestWidth = TruncVT.getSizeInBits();
49083 unsigned SrcWidth = SrcVT.getSizeInBits();
49084 if (SrcWidth % DestWidth != 0)
49085 return SDValue();
49086
49087 // inttofp (trunc (extelt X, 0)) --> inttofp (extelt (bitcast X), 0)
49088 EVT SrcVecVT = ExtElt.getOperand(0).getValueType();
49089 unsigned VecWidth = SrcVecVT.getSizeInBits();
49090 unsigned NumElts = VecWidth / DestWidth;
49091 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), TruncVT, NumElts);
49092 SDValue BitcastVec = DAG.getBitcast(BitcastVT, ExtElt.getOperand(0));
49093 SDLoc DL(N);
49094 SDValue NewExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TruncVT,
49095 BitcastVec, ExtElt.getOperand(1));
49096 return DAG.getNode(N->getOpcode(), DL, N->getValueType(0), NewExtElt);
49097}
49098
49099static SDValue combineUIntToFP(SDNode *N, SelectionDAG &DAG,
49100 const X86Subtarget &Subtarget) {
49101 bool IsStrict = N->isStrictFPOpcode();
49102 SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
49103 EVT VT = N->getValueType(0);
49104 EVT InVT = Op0.getValueType();
49105
49106 // UINT_TO_FP(vXi1) -> SINT_TO_FP(ZEXT(vXi1 to vXi32))
49107 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
49108 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
49109 if (InVT.isVector() && InVT.getScalarSizeInBits() < 32) {
49110 SDLoc dl(N);
49111 EVT DstVT = InVT.changeVectorElementType(MVT::i32);
49112 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
49113
49114 // UINT_TO_FP isn't legal without AVX512 so use SINT_TO_FP.
49115 if (IsStrict)
49116 return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
49117 {N->getOperand(0), P});
49118 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
49119 }
49120
49121 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
49122 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
49123 // the optimization here.
49124 if (DAG.SignBitIsZero(Op0)) {
49125 if (IsStrict)
49126 return DAG.getNode(ISD::STRICT_SINT_TO_FP, SDLoc(N), {VT, MVT::Other},
49127 {N->getOperand(0), Op0});
49128 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, Op0);
49129 }
49130
49131 return SDValue();
49132}
49133
49134static SDValue combineSIntToFP(SDNode *N, SelectionDAG &DAG,
49135 TargetLowering::DAGCombinerInfo &DCI,
49136 const X86Subtarget &Subtarget) {
49137 // First try to optimize away the conversion entirely when it's
49138 // conditionally from a constant. Vectors only.
49139 bool IsStrict = N->isStrictFPOpcode();
49140 if (SDValue Res = combineVectorCompareAndMaskUnaryOp(N, DAG))
49141 return Res;
49142
49143 // Now move on to more general possibilities.
49144 SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
49145 EVT VT = N->getValueType(0);
49146 EVT InVT = Op0.getValueType();
49147
49148 // SINT_TO_FP(vXi1) -> SINT_TO_FP(SEXT(vXi1 to vXi32))
49149 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
49150 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
49151 if (InVT.isVector() && InVT.getScalarSizeInBits() < 32) {
49152 SDLoc dl(N);
49153 EVT DstVT = InVT.changeVectorElementType(MVT::i32);
49154 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
49155 if (IsStrict)
49156 return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
49157 {N->getOperand(0), P});
49158 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
49159 }
49160
49161 // Without AVX512DQ we only support i64 to float scalar conversion. For both
49162 // vectors and scalars, see if we know that the upper bits are all the sign
49163 // bit, in which case we can truncate the input to i32 and convert from that.
49164 if (InVT.getScalarSizeInBits() > 32 && !Subtarget.hasDQI()) {
49165 unsigned BitWidth = InVT.getScalarSizeInBits();
49166 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0);
49167 if (NumSignBits >= (BitWidth - 31)) {
49168 EVT TruncVT = MVT::i32;
49169 if (InVT.isVector())
49170 TruncVT = InVT.changeVectorElementType(TruncVT);
49171 SDLoc dl(N);
49172 if (DCI.isBeforeLegalize() || TruncVT != MVT::v2i32) {
49173 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Op0);
49174 if (IsStrict)
49175 return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
49176 {N->getOperand(0), Trunc});
49177 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Trunc);
49178 }
49179 // If we're after legalize and the type is v2i32 we need to shuffle and
49180 // use CVTSI2P.
49181 assert(InVT == MVT::v2i64 && "Unexpected VT!")(static_cast <bool> (InVT == MVT::v2i64 && "Unexpected VT!"
) ? void (0) : __assert_fail ("InVT == MVT::v2i64 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 49181, __extension__ __PRETTY_FUNCTION__))
;
49182 SDValue Cast = DAG.getBitcast(MVT::v4i32, Op0);
49183 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Cast, Cast,
49184 { 0, 2, -1, -1 });
49185 if (IsStrict)
49186 return DAG.getNode(X86ISD::STRICT_CVTSI2P, dl, {VT, MVT::Other},
49187 {N->getOperand(0), Shuf});
49188 return DAG.getNode(X86ISD::CVTSI2P, dl, VT, Shuf);
49189 }
49190 }
49191
49192 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
49193 // a 32-bit target where SSE doesn't support i64->FP operations.
49194 if (!Subtarget.useSoftFloat() && Subtarget.hasX87() &&
49195 Op0.getOpcode() == ISD::LOAD) {
49196 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
49197
49198 // This transformation is not supported if the result type is f16 or f128.
49199 if (VT == MVT::f16 || VT == MVT::f128)
49200 return SDValue();
49201
49202 // If we have AVX512DQ we can use packed conversion instructions unless
49203 // the VT is f80.
49204 if (Subtarget.hasDQI() && VT != MVT::f80)
49205 return SDValue();
49206
49207 if (Ld->isSimple() && !VT.isVector() && ISD::isNormalLoad(Op0.getNode()) &&
49208 Op0.hasOneUse() && !Subtarget.is64Bit() && InVT == MVT::i64) {
49209 std::pair<SDValue, SDValue> Tmp =
49210 Subtarget.getTargetLowering()->BuildFILD(
49211 VT, InVT, SDLoc(N), Ld->getChain(), Ld->getBasePtr(),
49212 Ld->getPointerInfo(), Ld->getOriginalAlign(), DAG);
49213 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Tmp.second);
49214 return Tmp.first;
49215 }
49216 }
49217
49218 if (IsStrict)
49219 return SDValue();
49220
49221 if (SDValue V = combineToFPTruncExtElt(N, DAG))
49222 return V;
49223
49224 return SDValue();
49225}
49226
49227static bool needCarryOrOverflowFlag(SDValue Flags) {
49228 assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!")(static_cast <bool> (Flags.getValueType() == MVT::i32 &&
"Unexpected VT!") ? void (0) : __assert_fail ("Flags.getValueType() == MVT::i32 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 49228, __extension__ __PRETTY_FUNCTION__))
;
49229
49230 for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
49231 UI != UE; ++UI) {
49232 SDNode *User = *UI;
49233
49234 X86::CondCode CC;
49235 switch (User->getOpcode()) {
49236 default:
49237 // Be conservative.
49238 return true;
49239 case X86ISD::SETCC:
49240 case X86ISD::SETCC_CARRY:
49241 CC = (X86::CondCode)User->getConstantOperandVal(0);
49242 break;
49243 case X86ISD::BRCOND:
49244 CC = (X86::CondCode)User->getConstantOperandVal(2);
49245 break;
49246 case X86ISD::CMOV:
49247 CC = (X86::CondCode)User->getConstantOperandVal(2);
49248 break;
49249 }
49250
49251 switch (CC) {
49252 default: break;
49253 case X86::COND_A: case X86::COND_AE:
49254 case X86::COND_B: case X86::COND_BE:
49255 case X86::COND_O: case X86::COND_NO:
49256 case X86::COND_G: case X86::COND_GE:
49257 case X86::COND_L: case X86::COND_LE:
49258 return true;
49259 }
49260 }
49261
49262 return false;
49263}
49264
49265static bool onlyZeroFlagUsed(SDValue Flags) {
49266 assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!")(static_cast <bool> (Flags.getValueType() == MVT::i32 &&
"Unexpected VT!") ? void (0) : __assert_fail ("Flags.getValueType() == MVT::i32 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 49266, __extension__ __PRETTY_FUNCTION__))
;
49267
49268 for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
49269 UI != UE; ++UI) {
49270 SDNode *User = *UI;
49271
49272 unsigned CCOpNo;
49273 switch (User->getOpcode()) {
49274 default:
49275 // Be conservative.
49276 return false;
49277 case X86ISD::SETCC: CCOpNo = 0; break;
49278 case X86ISD::SETCC_CARRY: CCOpNo = 0; break;
49279 case X86ISD::BRCOND: CCOpNo = 2; break;
49280 case X86ISD::CMOV: CCOpNo = 2; break;
49281 }
49282
49283 X86::CondCode CC = (X86::CondCode)User->getConstantOperandVal(CCOpNo);
49284 if (CC != X86::COND_E && CC != X86::COND_NE)
49285 return false;
49286 }
49287
49288 return true;
49289}
49290
49291static SDValue combineCMP(SDNode *N, SelectionDAG &DAG) {
49292 // Only handle test patterns.
49293 if (!isNullConstant(N->getOperand(1)))
49294 return SDValue();
49295
49296 // If we have a CMP of a truncated binop, see if we can make a smaller binop
49297 // and use its flags directly.
49298 // TODO: Maybe we should try promoting compares that only use the zero flag
49299 // first if we can prove the upper bits with computeKnownBits?
49300 SDLoc dl(N);
49301 SDValue Op = N->getOperand(0);
49302 EVT VT = Op.getValueType();
49303
49304 // If we have a constant logical shift that's only used in a comparison
49305 // against zero turn it into an equivalent AND. This allows turning it into
49306 // a TEST instruction later.
49307 if ((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) &&
49308 Op.hasOneUse() && isa<ConstantSDNode>(Op.getOperand(1)) &&
49309 onlyZeroFlagUsed(SDValue(N, 0))) {
49310 unsigned BitWidth = VT.getSizeInBits();
49311 const APInt &ShAmt = Op.getConstantOperandAPInt(1);
49312 if (ShAmt.ult(BitWidth)) { // Avoid undefined shifts.
49313 unsigned MaskBits = BitWidth - ShAmt.getZExtValue();
49314 APInt Mask = Op.getOpcode() == ISD::SRL
49315 ? APInt::getHighBitsSet(BitWidth, MaskBits)
49316 : APInt::getLowBitsSet(BitWidth, MaskBits);
49317 if (Mask.isSignedIntN(32)) {
49318 Op = DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0),
49319 DAG.getConstant(Mask, dl, VT));
49320 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
49321 DAG.getConstant(0, dl, VT));
49322 }
49323 }
49324 }
49325
49326 // Look for a truncate.
49327 if (Op.getOpcode() != ISD::TRUNCATE)
49328 return SDValue();
49329
49330 SDValue Trunc = Op;
49331 Op = Op.getOperand(0);
49332
49333 // See if we can compare with zero against the truncation source,
49334 // which should help using the Z flag from many ops. Only do this for
49335 // i32 truncated op to prevent partial-reg compares of promoted ops.
49336 EVT OpVT = Op.getValueType();
49337 APInt UpperBits =
49338 APInt::getBitsSetFrom(OpVT.getSizeInBits(), VT.getSizeInBits());
49339 if (OpVT == MVT::i32 && DAG.MaskedValueIsZero(Op, UpperBits) &&
49340 onlyZeroFlagUsed(SDValue(N, 0))) {
49341 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
49342 DAG.getConstant(0, dl, OpVT));
49343 }
49344
49345 // After this the truncate and arithmetic op must have a single use.
49346 if (!Trunc.hasOneUse() || !Op.hasOneUse())
49347 return SDValue();
49348
49349 unsigned NewOpc;
49350 switch (Op.getOpcode()) {
49351 default: return SDValue();
49352 case ISD::AND:
49353 // Skip and with constant. We have special handling for and with immediate
49354 // during isel to generate test instructions.
49355 if (isa<ConstantSDNode>(Op.getOperand(1)))
49356 return SDValue();
49357 NewOpc = X86ISD::AND;
49358 break;
49359 case ISD::OR: NewOpc = X86ISD::OR; break;
49360 case ISD::XOR: NewOpc = X86ISD::XOR; break;
49361 case ISD::ADD:
49362 // If the carry or overflow flag is used, we can't truncate.
49363 if (needCarryOrOverflowFlag(SDValue(N, 0)))
49364 return SDValue();
49365 NewOpc = X86ISD::ADD;
49366 break;
49367 case ISD::SUB:
49368 // If the carry or overflow flag is used, we can't truncate.
49369 if (needCarryOrOverflowFlag(SDValue(N, 0)))
49370 return SDValue();
49371 NewOpc = X86ISD::SUB;
49372 break;
49373 }
49374
49375 // We found an op we can narrow. Truncate its inputs.
49376 SDValue Op0 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(0));
49377 SDValue Op1 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(1));
49378
49379 // Use a X86 specific opcode to avoid DAG combine messing with it.
49380 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
49381 Op = DAG.getNode(NewOpc, dl, VTs, Op0, Op1);
49382
49383 // For AND, keep a CMP so that we can match the test pattern.
49384 if (NewOpc == X86ISD::AND)
49385 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
49386 DAG.getConstant(0, dl, VT));
49387
49388 // Return the flags.
49389 return Op.getValue(1);
49390}
49391
49392static SDValue combineX86AddSub(SDNode *N, SelectionDAG &DAG,
49393 TargetLowering::DAGCombinerInfo &DCI) {
49394 assert((X86ISD::ADD == N->getOpcode() || X86ISD::SUB == N->getOpcode()) &&(static_cast <bool> ((X86ISD::ADD == N->getOpcode() ||
X86ISD::SUB == N->getOpcode()) && "Expected X86ISD::ADD or X86ISD::SUB"
) ? void (0) : __assert_fail ("(X86ISD::ADD == N->getOpcode() || X86ISD::SUB == N->getOpcode()) && \"Expected X86ISD::ADD or X86ISD::SUB\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 49395, __extension__ __PRETTY_FUNCTION__))
49395 "Expected X86ISD::ADD or X86ISD::SUB")(static_cast <bool> ((X86ISD::ADD == N->getOpcode() ||
X86ISD::SUB == N->getOpcode()) && "Expected X86ISD::ADD or X86ISD::SUB"
) ? void (0) : __assert_fail ("(X86ISD::ADD == N->getOpcode() || X86ISD::SUB == N->getOpcode()) && \"Expected X86ISD::ADD or X86ISD::SUB\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 49395, __extension__ __PRETTY_FUNCTION__))
;
49396
49397 SDLoc DL(N);
49398 SDValue LHS = N->getOperand(0);
49399 SDValue RHS = N->getOperand(1);
49400 MVT VT = LHS.getSimpleValueType();
49401 unsigned GenericOpc = X86ISD::ADD == N->getOpcode() ? ISD::ADD : ISD::SUB;
49402
49403 // If we don't use the flag result, simplify back to a generic ADD/SUB.
49404 if (!N->hasAnyUseOfValue(1)) {
49405 SDValue Res = DAG.getNode(GenericOpc, DL, VT, LHS, RHS);
49406 return DAG.getMergeValues({Res, DAG.getConstant(0, DL, MVT::i32)}, DL);
49407 }
49408
49409 // Fold any similar generic ADD/SUB opcodes to reuse this node.
49410 auto MatchGeneric = [&](SDValue N0, SDValue N1, bool Negate) {
49411 SDValue Ops[] = {N0, N1};
49412 SDVTList VTs = DAG.getVTList(N->getValueType(0));
49413 if (SDNode *GenericAddSub = DAG.getNodeIfExists(GenericOpc, VTs, Ops)) {
49414 SDValue Op(N, 0);
49415 if (Negate)
49416 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
49417 DCI.CombineTo(GenericAddSub, Op);
49418 }
49419 };
49420 MatchGeneric(LHS, RHS, false);
49421 MatchGeneric(RHS, LHS, X86ISD::SUB == N->getOpcode());
49422
49423 return SDValue();
49424}
49425
49426static SDValue combineSBB(SDNode *N, SelectionDAG &DAG) {
49427 if (SDValue Flags = combineCarryThroughADD(N->getOperand(2), DAG)) {
49428 MVT VT = N->getSimpleValueType(0);
49429 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
49430 return DAG.getNode(X86ISD::SBB, SDLoc(N), VTs,
49431 N->getOperand(0), N->getOperand(1),
49432 Flags);
49433 }
49434
49435 // Fold SBB(SUB(X,Y),0,Carry) -> SBB(X,Y,Carry)
49436 // iff the flag result is dead.
49437 SDValue Op0 = N->getOperand(0);
49438 SDValue Op1 = N->getOperand(1);
49439 if (Op0.getOpcode() == ISD::SUB && isNullConstant(Op1) &&
49440 !N->hasAnyUseOfValue(1))
49441 return DAG.getNode(X86ISD::SBB, SDLoc(N), N->getVTList(), Op0.getOperand(0),
49442 Op0.getOperand(1), N->getOperand(2));
49443
49444 return SDValue();
49445}
49446
49447// Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
49448static SDValue combineADC(SDNode *N, SelectionDAG &DAG,
49449 TargetLowering::DAGCombinerInfo &DCI) {
49450 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
49451 // the result is either zero or one (depending on the input carry bit).
49452 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
49453 if (X86::isZeroNode(N->getOperand(0)) &&
49454 X86::isZeroNode(N->getOperand(1)) &&
49455 // We don't have a good way to replace an EFLAGS use, so only do this when
49456 // dead right now.
49457 SDValue(N, 1).use_empty()) {
49458 SDLoc DL(N);
49459 EVT VT = N->getValueType(0);
49460 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
49461 SDValue Res1 =
49462 DAG.getNode(ISD::AND, DL, VT,
49463 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
49464 DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
49465 N->getOperand(2)),
49466 DAG.getConstant(1, DL, VT));
49467 return DCI.CombineTo(N, Res1, CarryOut);
49468 }
49469
49470 if (SDValue Flags = combineCarryThroughADD(N->getOperand(2), DAG)) {
49471 MVT VT = N->getSimpleValueType(0);
49472 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
49473 return DAG.getNode(X86ISD::ADC, SDLoc(N), VTs,
49474 N->getOperand(0), N->getOperand(1),
49475 Flags);
49476 }
49477
49478 return SDValue();
49479}
49480
49481/// If this is an add or subtract where one operand is produced by a cmp+setcc,
49482/// then try to convert it to an ADC or SBB. This replaces TEST+SET+{ADD/SUB}
49483/// with CMP+{ADC, SBB}.
49484static SDValue combineAddOrSubToADCOrSBB(SDNode *N, SelectionDAG &DAG) {
49485 bool IsSub = N->getOpcode() == ISD::SUB;
49486 SDValue X = N->getOperand(0);
49487 SDValue Y = N->getOperand(1);
49488
49489 // If this is an add, canonicalize a zext operand to the RHS.
49490 // TODO: Incomplete? What if both sides are zexts?
49491 if (!IsSub && X.getOpcode() == ISD::ZERO_EXTEND &&
49492 Y.getOpcode() != ISD::ZERO_EXTEND)
49493 std::swap(X, Y);
49494
49495 // Look through a one-use zext.
49496 bool PeekedThroughZext = false;
49497 if (Y.getOpcode() == ISD::ZERO_EXTEND && Y.hasOneUse()) {
49498 Y = Y.getOperand(0);
49499 PeekedThroughZext = true;
49500 }
49501
49502 // If this is an add, canonicalize a setcc operand to the RHS.
49503 // TODO: Incomplete? What if both sides are setcc?
49504 // TODO: Should we allow peeking through a zext of the other operand?
49505 if (!IsSub && !PeekedThroughZext && X.getOpcode() == X86ISD::SETCC &&
49506 Y.getOpcode() != X86ISD::SETCC)
49507 std::swap(X, Y);
49508
49509 if (Y.getOpcode() != X86ISD::SETCC || !Y.hasOneUse())
49510 return SDValue();
49511
49512 SDLoc DL(N);
49513 EVT VT = N->getValueType(0);
49514 X86::CondCode CC = (X86::CondCode)Y.getConstantOperandVal(0);
49515
49516 // If X is -1 or 0, then we have an opportunity to avoid constants required in
49517 // the general case below.
49518 auto *ConstantX = dyn_cast<ConstantSDNode>(X);
49519 if (ConstantX) {
49520 if ((!IsSub && CC == X86::COND_AE && ConstantX->isAllOnesValue()) ||
49521 (IsSub && CC == X86::COND_B && ConstantX->isNullValue())) {
49522 // This is a complicated way to get -1 or 0 from the carry flag:
49523 // -1 + SETAE --> -1 + (!CF) --> CF ? -1 : 0 --> SBB %eax, %eax
49524 // 0 - SETB --> 0 - (CF) --> CF ? -1 : 0 --> SBB %eax, %eax
49525 return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
49526 DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
49527 Y.getOperand(1));
49528 }
49529
49530 if ((!IsSub && CC == X86::COND_BE && ConstantX->isAllOnesValue()) ||
49531 (IsSub && CC == X86::COND_A && ConstantX->isNullValue())) {
49532 SDValue EFLAGS = Y->getOperand(1);
49533 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
49534 EFLAGS.getValueType().isInteger() &&
49535 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
49536 // Swap the operands of a SUB, and we have the same pattern as above.
49537 // -1 + SETBE (SUB A, B) --> -1 + SETAE (SUB B, A) --> SUB + SBB
49538 // 0 - SETA (SUB A, B) --> 0 - SETB (SUB B, A) --> SUB + SBB
49539 SDValue NewSub = DAG.getNode(
49540 X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
49541 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
49542 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
49543 return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
49544 DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
49545 NewEFLAGS);
49546 }
49547 }
49548 }
49549
49550 if (CC == X86::COND_B) {
49551 // X + SETB Z --> adc X, 0
49552 // X - SETB Z --> sbb X, 0
49553 return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
49554 DAG.getVTList(VT, MVT::i32), X,
49555 DAG.getConstant(0, DL, VT), Y.getOperand(1));
49556 }
49557
49558 if (CC == X86::COND_A) {
49559 SDValue EFLAGS = Y.getOperand(1);
49560 // Try to convert COND_A into COND_B in an attempt to facilitate
49561 // materializing "setb reg".
49562 //
49563 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
49564 // cannot take an immediate as its first operand.
49565 //
49566 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.getNode()->hasOneUse() &&
49567 EFLAGS.getValueType().isInteger() &&
49568 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
49569 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
49570 EFLAGS.getNode()->getVTList(),
49571 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
49572 SDValue NewEFLAGS = NewSub.getValue(EFLAGS.getResNo());
49573 return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
49574 DAG.getVTList(VT, MVT::i32), X,
49575 DAG.getConstant(0, DL, VT), NewEFLAGS);
49576 }
49577 }
49578
49579 if (CC == X86::COND_AE) {
49580 // X + SETAE --> sbb X, -1
49581 // X - SETAE --> adc X, -1
49582 return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL,
49583 DAG.getVTList(VT, MVT::i32), X,
49584 DAG.getConstant(-1, DL, VT), Y.getOperand(1));
49585 }
49586
49587 if (CC == X86::COND_BE) {
49588 // X + SETBE --> sbb X, -1
49589 // X - SETBE --> adc X, -1
49590 SDValue EFLAGS = Y.getOperand(1);
49591 // Try to convert COND_BE into COND_AE in an attempt to facilitate
49592 // materializing "setae reg".
49593 //
49594 // Do not flip "e <= c", where "c" is a constant, because Cmp instruction
49595 // cannot take an immediate as its first operand.
49596 //
49597 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.getNode()->hasOneUse() &&
49598 EFLAGS.getValueType().isInteger() &&
49599 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
49600 SDValue NewSub = DAG.getNode(
49601 X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
49602 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
49603 SDValue NewEFLAGS = NewSub.getValue(EFLAGS.getResNo());
49604 return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL,
49605 DAG.getVTList(VT, MVT::i32), X,
49606 DAG.getConstant(-1, DL, VT), NewEFLAGS);
49607 }
49608 }
49609
49610 if (CC != X86::COND_E && CC != X86::COND_NE)
49611 return SDValue();
49612
49613 SDValue Cmp = Y.getOperand(1);
49614 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
49615 !X86::isZeroNode(Cmp.getOperand(1)) ||
49616 !Cmp.getOperand(0).getValueType().isInteger())
49617 return SDValue();
49618
49619 SDValue Z = Cmp.getOperand(0);
49620 EVT ZVT = Z.getValueType();
49621
49622 // If X is -1 or 0, then we have an opportunity to avoid constants required in
49623 // the general case below.
49624 if (ConstantX) {
49625 // 'neg' sets the carry flag when Z != 0, so create 0 or -1 using 'sbb' with
49626 // fake operands:
49627 // 0 - (Z != 0) --> sbb %eax, %eax, (neg Z)
49628 // -1 + (Z == 0) --> sbb %eax, %eax, (neg Z)
49629 if ((IsSub && CC == X86::COND_NE && ConstantX->isNullValue()) ||
49630 (!IsSub && CC == X86::COND_E && ConstantX->isAllOnesValue())) {
49631 SDValue Zero = DAG.getConstant(0, DL, ZVT);
49632 SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
49633 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Zero, Z);
49634 return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
49635 DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
49636 SDValue(Neg.getNode(), 1));
49637 }
49638
49639 // cmp with 1 sets the carry flag when Z == 0, so create 0 or -1 using 'sbb'
49640 // with fake operands:
49641 // 0 - (Z == 0) --> sbb %eax, %eax, (cmp Z, 1)
49642 // -1 + (Z != 0) --> sbb %eax, %eax, (cmp Z, 1)
49643 if ((IsSub && CC == X86::COND_E && ConstantX->isNullValue()) ||
49644 (!IsSub && CC == X86::COND_NE && ConstantX->isAllOnesValue())) {
49645 SDValue One = DAG.getConstant(1, DL, ZVT);
49646 SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
49647 SDValue Cmp1 = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Z, One);
49648 return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
49649 DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
49650 Cmp1.getValue(1));
49651 }
49652 }
49653
49654 // (cmp Z, 1) sets the carry flag if Z is 0.
49655 SDValue One = DAG.getConstant(1, DL, ZVT);
49656 SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
49657 SDValue Cmp1 = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Z, One);
49658
49659 // Add the flags type for ADC/SBB nodes.
49660 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
49661
49662 // X - (Z != 0) --> sub X, (zext(setne Z, 0)) --> adc X, -1, (cmp Z, 1)
49663 // X + (Z != 0) --> add X, (zext(setne Z, 0)) --> sbb X, -1, (cmp Z, 1)
49664 if (CC == X86::COND_NE)
49665 return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL, VTs, X,
49666 DAG.getConstant(-1ULL, DL, VT), Cmp1.getValue(1));
49667
49668 // X - (Z == 0) --> sub X, (zext(sete Z, 0)) --> sbb X, 0, (cmp Z, 1)
49669 // X + (Z == 0) --> add X, (zext(sete Z, 0)) --> adc X, 0, (cmp Z, 1)
49670 return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL, VTs, X,
49671 DAG.getConstant(0, DL, VT), Cmp1.getValue(1));
49672}
49673
49674static SDValue matchPMADDWD(SelectionDAG &DAG, SDValue Op0, SDValue Op1,
49675 const SDLoc &DL, EVT VT,
49676 const X86Subtarget &Subtarget) {
49677 // Example of pattern we try to detect:
49678 // t := (v8i32 mul (sext (v8i16 x0), (sext (v8i16 x1))))
49679 //(add (build_vector (extract_elt t, 0),
49680 // (extract_elt t, 2),
49681 // (extract_elt t, 4),
49682 // (extract_elt t, 6)),
49683 // (build_vector (extract_elt t, 1),
49684 // (extract_elt t, 3),
49685 // (extract_elt t, 5),
49686 // (extract_elt t, 7)))
49687
49688 if (!Subtarget.hasSSE2())
49689 return SDValue();
49690
49691 if (Op0.getOpcode() != ISD::BUILD_VECTOR ||
49692 Op1.getOpcode() != ISD::BUILD_VECTOR)
49693 return SDValue();
49694
49695 if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
49696 VT.getVectorNumElements() < 4 ||
49697 !isPowerOf2_32(VT.getVectorNumElements()))
49698 return SDValue();
49699
49700 // Check if one of Op0,Op1 is of the form:
49701 // (build_vector (extract_elt Mul, 0),
49702 // (extract_elt Mul, 2),
49703 // (extract_elt Mul, 4),
49704 // ...
49705 // the other is of the form:
49706 // (build_vector (extract_elt Mul, 1),
49707 // (extract_elt Mul, 3),
49708 // (extract_elt Mul, 5),
49709 // ...
49710 // and identify Mul.
49711 SDValue Mul;
49712 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; i += 2) {
49713 SDValue Op0L = Op0->getOperand(i), Op1L = Op1->getOperand(i),
49714 Op0H = Op0->getOperand(i + 1), Op1H = Op1->getOperand(i + 1);
49715 // TODO: Be more tolerant to undefs.
49716 if (Op0L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
49717 Op1L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
49718 Op0H.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
49719 Op1H.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
49720 return SDValue();
49721 auto *Const0L = dyn_cast<ConstantSDNode>(Op0L->getOperand(1));
49722 auto *Const1L = dyn_cast<ConstantSDNode>(Op1L->getOperand(1));
49723 auto *Const0H = dyn_cast<ConstantSDNode>(Op0H->getOperand(1));
49724 auto *Const1H = dyn_cast<ConstantSDNode>(Op1H->getOperand(1));
49725 if (!Const0L || !Const1L || !Const0H || !Const1H)
49726 return SDValue();
49727 unsigned Idx0L = Const0L->getZExtValue(), Idx1L = Const1L->getZExtValue(),
49728 Idx0H = Const0H->getZExtValue(), Idx1H = Const1H->getZExtValue();
49729 // Commutativity of mul allows factors of a product to reorder.
49730 if (Idx0L > Idx1L)
49731 std::swap(Idx0L, Idx1L);
49732 if (Idx0H > Idx1H)
49733 std::swap(Idx0H, Idx1H);
49734 // Commutativity of add allows pairs of factors to reorder.
49735 if (Idx0L > Idx0H) {
49736 std::swap(Idx0L, Idx0H);
49737 std::swap(Idx1L, Idx1H);
49738 }
49739 if (Idx0L != 2 * i || Idx1L != 2 * i + 1 || Idx0H != 2 * i + 2 ||
49740 Idx1H != 2 * i + 3)
49741 return SDValue();
49742 if (!Mul) {
49743 // First time an extract_elt's source vector is visited. Must be a MUL
49744 // with 2X number of vector elements than the BUILD_VECTOR.
49745 // Both extracts must be from same MUL.
49746 Mul = Op0L->getOperand(0);
49747 if (Mul->getOpcode() != ISD::MUL ||
49748 Mul.getValueType().getVectorNumElements() != 2 * e)
49749 return SDValue();
49750 }
49751 // Check that the extract is from the same MUL previously seen.
49752 if (Mul != Op0L->getOperand(0) || Mul != Op1L->getOperand(0) ||
49753 Mul != Op0H->getOperand(0) || Mul != Op1H->getOperand(0))
49754 return SDValue();
49755 }
49756
49757 // Check if the Mul source can be safely shrunk.
49758 ShrinkMode Mode;
49759 if (!canReduceVMulWidth(Mul.getNode(), DAG, Mode) ||
49760 Mode == ShrinkMode::MULU16)
49761 return SDValue();
49762
49763 EVT TruncVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
49764 VT.getVectorNumElements() * 2);
49765 SDValue N0 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Mul.getOperand(0));
49766 SDValue N1 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Mul.getOperand(1));
49767
49768 auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
49769 ArrayRef<SDValue> Ops) {
49770 EVT InVT = Ops[0].getValueType();
49771 assert(InVT == Ops[1].getValueType() && "Operands' types mismatch")(static_cast <bool> (InVT == Ops[1].getValueType() &&
"Operands' types mismatch") ? void (0) : __assert_fail ("InVT == Ops[1].getValueType() && \"Operands' types mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 49771, __extension__ __PRETTY_FUNCTION__))
;
49772 EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
49773 InVT.getVectorNumElements() / 2);
49774 return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT, Ops[0], Ops[1]);
49775 };
49776 return SplitOpsAndApply(DAG, Subtarget, DL, VT, { N0, N1 }, PMADDBuilder);
49777}
49778
49779// Attempt to turn this pattern into PMADDWD.
49780// (add (mul (sext (build_vector)), (sext (build_vector))),
49781// (mul (sext (build_vector)), (sext (build_vector)))
49782static SDValue matchPMADDWD_2(SelectionDAG &DAG, SDValue N0, SDValue N1,
49783 const SDLoc &DL, EVT VT,
49784 const X86Subtarget &Subtarget) {
49785 if (!Subtarget.hasSSE2())
49786 return SDValue();
49787
49788 if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
49789 return SDValue();
49790
49791 if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
49792 VT.getVectorNumElements() < 4 ||
49793 !isPowerOf2_32(VT.getVectorNumElements()))
49794 return SDValue();
49795
49796 SDValue N00 = N0.getOperand(0);
49797 SDValue N01 = N0.getOperand(1);
49798 SDValue N10 = N1.getOperand(0);
49799 SDValue N11 = N1.getOperand(1);
49800
49801 // All inputs need to be sign extends.
49802 // TODO: Support ZERO_EXTEND from known positive?
49803 if (N00.getOpcode() != ISD::SIGN_EXTEND ||
49804 N01.getOpcode() != ISD::SIGN_EXTEND ||
49805 N10.getOpcode() != ISD::SIGN_EXTEND ||
49806 N11.getOpcode() != ISD::SIGN_EXTEND)
49807 return SDValue();
49808
49809 // Peek through the extends.
49810 N00 = N00.getOperand(0);
49811 N01 = N01.getOperand(0);
49812 N10 = N10.getOperand(0);
49813 N11 = N11.getOperand(0);
49814
49815 // Must be extending from vXi16.
49816 EVT InVT = N00.getValueType();
49817 if (InVT.getVectorElementType() != MVT::i16 || N01.getValueType() != InVT ||
49818 N10.getValueType() != InVT || N11.getValueType() != InVT)
49819 return SDValue();
49820
49821 // All inputs should be build_vectors.
49822 if (N00.getOpcode() != ISD::BUILD_VECTOR ||
49823 N01.getOpcode() != ISD::BUILD_VECTOR ||
49824 N10.getOpcode() != ISD::BUILD_VECTOR ||
49825 N11.getOpcode() != ISD::BUILD_VECTOR)
49826 return SDValue();
49827
49828 // For each element, we need to ensure we have an odd element from one vector
49829 // multiplied by the odd element of another vector and the even element from
49830 // one of the same vectors being multiplied by the even element from the
49831 // other vector. So we need to make sure for each element i, this operator
49832 // is being performed:
49833 // A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
49834 SDValue In0, In1;
49835 for (unsigned i = 0; i != N00.getNumOperands(); ++i) {
49836 SDValue N00Elt = N00.getOperand(i);
49837 SDValue N01Elt = N01.getOperand(i);
49838 SDValue N10Elt = N10.getOperand(i);
49839 SDValue N11Elt = N11.getOperand(i);
49840 // TODO: Be more tolerant to undefs.
49841 if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
49842 N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
49843 N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
49844 N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
49845 return SDValue();
49846 auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
49847 auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
49848 auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
49849 auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
49850 if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
49851 return SDValue();
49852 unsigned IdxN00 = ConstN00Elt->getZExtValue();
49853 unsigned IdxN01 = ConstN01Elt->getZExtValue();
49854 unsigned IdxN10 = ConstN10Elt->getZExtValue();
49855 unsigned IdxN11 = ConstN11Elt->getZExtValue();
49856 // Add is commutative so indices can be reordered.
49857 if (IdxN00 > IdxN10) {
49858 std::swap(IdxN00, IdxN10);
49859 std::swap(IdxN01, IdxN11);
49860 }
49861 // N0 indices be the even element. N1 indices must be the next odd element.
49862 if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
49863 IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
49864 return SDValue();
49865 SDValue N00In = N00Elt.getOperand(0);
49866 SDValue N01In = N01Elt.getOperand(0);
49867 SDValue N10In = N10Elt.getOperand(0);
49868 SDValue N11In = N11Elt.getOperand(0);
49869
49870 // First time we find an input capture it.
49871 if (!In0) {
49872 In0 = N00In;
49873 In1 = N01In;
49874
49875 // The input vectors must be at least as wide as the output.
49876 // If they are larger than the output, we extract subvector below.
49877 if (In0.getValueSizeInBits() < VT.getSizeInBits() ||
49878 In1.getValueSizeInBits() < VT.getSizeInBits())
49879 return SDValue();
49880 }
49881 // Mul is commutative so the input vectors can be in any order.
49882 // Canonicalize to make the compares easier.
49883 if (In0 != N00In)
49884 std::swap(N00In, N01In);
49885 if (In0 != N10In)
49886 std::swap(N10In, N11In);
49887 if (In0 != N00In || In1 != N01In || In0 != N10In || In1 != N11In)
49888 return SDValue();
49889 }
49890
49891 auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
49892 ArrayRef<SDValue> Ops) {
49893 EVT OpVT = Ops[0].getValueType();
49894 assert(OpVT.getScalarType() == MVT::i16 &&(static_cast <bool> (OpVT.getScalarType() == MVT::i16 &&
"Unexpected scalar element type") ? void (0) : __assert_fail
("OpVT.getScalarType() == MVT::i16 && \"Unexpected scalar element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 49895, __extension__ __PRETTY_FUNCTION__))
49895 "Unexpected scalar element type")(static_cast <bool> (OpVT.getScalarType() == MVT::i16 &&
"Unexpected scalar element type") ? void (0) : __assert_fail
("OpVT.getScalarType() == MVT::i16 && \"Unexpected scalar element type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 49895, __extension__ __PRETTY_FUNCTION__))
;
49896 assert(OpVT == Ops[1].getValueType() && "Operands' types mismatch")(static_cast <bool> (OpVT == Ops[1].getValueType() &&
"Operands' types mismatch") ? void (0) : __assert_fail ("OpVT == Ops[1].getValueType() && \"Operands' types mismatch\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 49896, __extension__ __PRETTY_FUNCTION__))
;
49897 EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
49898 OpVT.getVectorNumElements() / 2);
49899 return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT, Ops[0], Ops[1]);
49900 };
49901
49902 // If the output is narrower than an input, extract the low part of the input
49903 // vector.
49904 EVT OutVT16 = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
49905 VT.getVectorNumElements() * 2);
49906 if (OutVT16.bitsLT(In0.getValueType())) {
49907 In0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT16, In0,
49908 DAG.getIntPtrConstant(0, DL));
49909 }
49910 if (OutVT16.bitsLT(In1.getValueType())) {
49911 In1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT16, In1,
49912 DAG.getIntPtrConstant(0, DL));
49913 }
49914 return SplitOpsAndApply(DAG, Subtarget, DL, VT, { In0, In1 },
49915 PMADDBuilder);
49916}
49917
49918/// CMOV of constants requires materializing constant operands in registers.
49919/// Try to fold those constants into an 'add' instruction to reduce instruction
49920/// count. We do this with CMOV rather the generic 'select' because there are
49921/// earlier folds that may be used to turn select-of-constants into logic hacks.
49922static SDValue pushAddIntoCmovOfConsts(SDNode *N, SelectionDAG &DAG) {
49923 // If an operand is zero, add-of-0 gets simplified away, so that's clearly
49924 // better because we eliminate 1-2 instructions. This transform is still
49925 // an improvement without zero operands because we trade 2 move constants and
49926 // 1 add for 2 adds (LEA) as long as the constants can be represented as
49927 // immediate asm operands (fit in 32-bits).
49928 auto isSuitableCmov = [](SDValue V) {
49929 if (V.getOpcode() != X86ISD::CMOV || !V.hasOneUse())
49930 return false;
49931 if (!isa<ConstantSDNode>(V.getOperand(0)) ||
49932 !isa<ConstantSDNode>(V.getOperand(1)))
49933 return false;
49934 return isNullConstant(V.getOperand(0)) || isNullConstant(V.getOperand(1)) ||
49935 (V.getConstantOperandAPInt(0).isSignedIntN(32) &&
49936 V.getConstantOperandAPInt(1).isSignedIntN(32));
49937 };
49938
49939 // Match an appropriate CMOV as the first operand of the add.
49940 SDValue Cmov = N->getOperand(0);
49941 SDValue OtherOp = N->getOperand(1);
49942 if (!isSuitableCmov(Cmov))
49943 std::swap(Cmov, OtherOp);
49944 if (!isSuitableCmov(Cmov))
49945 return SDValue();
49946
49947 // add (cmov C, 0), OtherOp --> cmov (add OtherOp, C), OtherOp
49948 // add (cmov 0, C), OtherOp --> cmov OtherOp, (add OtherOp, C)
49949 SDLoc DL(N);
49950 SDValue FalseOp = Cmov.getOperand(0);
49951 SDValue TrueOp = Cmov.getOperand(1);
49952 EVT VT = N->getValueType(0);
49953 FalseOp = DAG.getNode(ISD::ADD, DL, VT, OtherOp, FalseOp);
49954 TrueOp = DAG.getNode(ISD::ADD, DL, VT, OtherOp, TrueOp);
49955 return DAG.getNode(X86ISD::CMOV, DL, VT, FalseOp, TrueOp, Cmov.getOperand(2),
49956 Cmov.getOperand(3));
49957}
49958
49959static SDValue combineAdd(SDNode *N, SelectionDAG &DAG,
49960 TargetLowering::DAGCombinerInfo &DCI,
49961 const X86Subtarget &Subtarget) {
49962 EVT VT = N->getValueType(0);
49963 SDValue Op0 = N->getOperand(0);
49964 SDValue Op1 = N->getOperand(1);
49965
49966 if (SDValue Select = pushAddIntoCmovOfConsts(N, DAG))
49967 return Select;
49968
49969 if (SDValue MAdd = matchPMADDWD(DAG, Op0, Op1, SDLoc(N), VT, Subtarget))
49970 return MAdd;
49971 if (SDValue MAdd = matchPMADDWD_2(DAG, Op0, Op1, SDLoc(N), VT, Subtarget))
49972 return MAdd;
49973
49974 // Try to synthesize horizontal adds from adds of shuffles.
49975 if (SDValue V = combineToHorizontalAddSub(N, DAG, Subtarget))
49976 return V;
49977
49978 // If vectors of i1 are legal, turn (add (zext (vXi1 X)), Y) into
49979 // (sub Y, (sext (vXi1 X))).
49980 // FIXME: We have the (sub Y, (zext (vXi1 X))) -> (add (sext (vXi1 X)), Y) in
49981 // generic DAG combine without a legal type check, but adding this there
49982 // caused regressions.
49983 if (VT.isVector()) {
49984 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49985 if (Op0.getOpcode() == ISD::ZERO_EXTEND &&
49986 Op0.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
49987 TLI.isTypeLegal(Op0.getOperand(0).getValueType())) {
49988 SDLoc DL(N);
49989 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op0.getOperand(0));
49990 return DAG.getNode(ISD::SUB, DL, VT, Op1, SExt);
49991 }
49992
49993 if (Op1.getOpcode() == ISD::ZERO_EXTEND &&
49994 Op1.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
49995 TLI.isTypeLegal(Op1.getOperand(0).getValueType())) {
49996 SDLoc DL(N);
49997 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op1.getOperand(0));
49998 return DAG.getNode(ISD::SUB, DL, VT, Op0, SExt);
49999 }
50000 }
50001
50002 return combineAddOrSubToADCOrSBB(N, DAG);
50003}
50004
50005static SDValue combineSub(SDNode *N, SelectionDAG &DAG,
50006 TargetLowering::DAGCombinerInfo &DCI,
50007 const X86Subtarget &Subtarget) {
50008 SDValue Op0 = N->getOperand(0);
50009 SDValue Op1 = N->getOperand(1);
50010
50011 // TODO: Add NoOpaque handling to isConstantIntBuildVectorOrConstantInt.
50012 auto IsNonOpaqueConstant = [&](SDValue Op) {
50013 if (SDNode *C = DAG.isConstantIntBuildVectorOrConstantInt(Op)) {
50014 if (auto *Cst = dyn_cast<ConstantSDNode>(C))
50015 return !Cst->isOpaque();
50016 return true;
50017 }
50018 return false;
50019 };
50020
50021 // X86 can't encode an immediate LHS of a sub. See if we can push the
50022 // negation into a preceding instruction. If the RHS of the sub is a XOR with
50023 // one use and a constant, invert the immediate, saving one register.
50024 // sub(C1, xor(X, C2)) -> add(xor(X, ~C2), C1+1)
50025 if (Op1.getOpcode() == ISD::XOR && IsNonOpaqueConstant(Op0) &&
50026 IsNonOpaqueConstant(Op1.getOperand(1)) && Op1->hasOneUse()) {
50027 SDLoc DL(N);
50028 EVT VT = Op0.getValueType();
50029 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT, Op1.getOperand(0),
50030 DAG.getNOT(SDLoc(Op1), Op1.getOperand(1), VT));
50031 SDValue NewAdd =
50032 DAG.getNode(ISD::ADD, DL, VT, Op0, DAG.getConstant(1, DL, VT));
50033 return DAG.getNode(ISD::ADD, DL, VT, NewXor, NewAdd);
50034 }
50035
50036 // Try to synthesize horizontal subs from subs of shuffles.
50037 if (SDValue V = combineToHorizontalAddSub(N, DAG, Subtarget))
50038 return V;
50039
50040 return combineAddOrSubToADCOrSBB(N, DAG);
50041}
50042
50043static SDValue combineVectorCompare(SDNode *N, SelectionDAG &DAG,
50044 const X86Subtarget &Subtarget) {
50045 MVT VT = N->getSimpleValueType(0);
50046 SDLoc DL(N);
50047
50048 if (N->getOperand(0) == N->getOperand(1)) {
50049 if (N->getOpcode() == X86ISD::PCMPEQ)
50050 return DAG.getConstant(-1, DL, VT);
50051 if (N->getOpcode() == X86ISD::PCMPGT)
50052 return DAG.getConstant(0, DL, VT);
50053 }
50054
50055 return SDValue();
50056}
50057
50058/// Helper that combines an array of subvector ops as if they were the operands
50059/// of a ISD::CONCAT_VECTORS node, but may have come from another source (e.g.
50060/// ISD::INSERT_SUBVECTOR). The ops are assumed to be of the same type.
50061static SDValue combineConcatVectorOps(const SDLoc &DL, MVT VT,
50062 ArrayRef<SDValue> Ops, SelectionDAG &DAG,
50063 TargetLowering::DAGCombinerInfo &DCI,
50064 const X86Subtarget &Subtarget) {
50065 assert(Subtarget.hasAVX() && "AVX assumed for concat_vectors")(static_cast <bool> (Subtarget.hasAVX() && "AVX assumed for concat_vectors"
) ? void (0) : __assert_fail ("Subtarget.hasAVX() && \"AVX assumed for concat_vectors\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 50065, __extension__ __PRETTY_FUNCTION__))
;
50066 unsigned EltSizeInBits = VT.getScalarSizeInBits();
50067
50068 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
50069 return DAG.getUNDEF(VT);
50070
50071 if (llvm::all_of(Ops, [](SDValue Op) {
50072 return ISD::isBuildVectorAllZeros(Op.getNode());
50073 }))
50074 return getZeroVector(VT, Subtarget, DAG, DL);
50075
50076 SDValue Op0 = Ops[0];
50077 bool IsSplat = llvm::all_of(Ops, [&Op0](SDValue Op) { return Op == Op0; });
50078
50079 // Repeated subvectors.
50080 if (IsSplat &&
50081 (VT.is256BitVector() || (VT.is512BitVector() && Subtarget.hasAVX512()))) {
50082 // If this broadcast is inserted into both halves, use a larger broadcast.
50083 if (Op0.getOpcode() == X86ISD::VBROADCAST)
50084 return DAG.getNode(Op0.getOpcode(), DL, VT, Op0.getOperand(0));
50085
50086 // If this simple subvector or scalar/subvector broadcast_load is inserted
50087 // into both halves, use a larger broadcast_load. Update other uses to use
50088 // an extracted subvector.
50089 if (Op0.getOpcode() == ISD::LOAD ||
50090 Op0.getOpcode() == X86ISD::VBROADCAST_LOAD ||
50091 Op0.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) {
50092 auto *Mem = cast<MemSDNode>(Op0);
50093 unsigned Opcode = Op0.getOpcode() == X86ISD::VBROADCAST_LOAD
50094 ? X86ISD::VBROADCAST_LOAD
50095 : X86ISD::SUBV_BROADCAST_LOAD;
50096 if (SDValue BcastLd = getBROADCAST_LOAD(
50097 Opcode, DL, VT, Mem->getMemoryVT(), Mem, 0, DAG)) {
50098 DAG.ReplaceAllUsesOfValueWith(
50099 Op0,
50100 extractSubVector(BcastLd, 0, DAG, DL, Op0.getValueSizeInBits()));
50101 return BcastLd;
50102 }
50103 }
50104
50105 // concat_vectors(movddup(x),movddup(x)) -> broadcast(x)
50106 if (Op0.getOpcode() == X86ISD::MOVDDUP && VT == MVT::v4f64 &&
50107 (Subtarget.hasAVX2() || MayFoldLoad(Op0.getOperand(0))))
50108 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
50109 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f64,
50110 Op0.getOperand(0),
50111 DAG.getIntPtrConstant(0, DL)));
50112
50113 // concat_vectors(scalar_to_vector(x),scalar_to_vector(x)) -> broadcast(x)
50114 if (Op0.getOpcode() == ISD::SCALAR_TO_VECTOR &&
50115 (Subtarget.hasAVX2() ||
50116 (EltSizeInBits >= 32 && MayFoldLoad(Op0.getOperand(0)))) &&
50117 Op0.getOperand(0).getValueType() == VT.getScalarType())
50118 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Op0.getOperand(0));
50119
50120 // concat_vectors(extract_subvector(broadcast(x)),
50121 // extract_subvector(broadcast(x))) -> broadcast(x)
50122 if (Op0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
50123 Op0.getOperand(0).getValueType() == VT) {
50124 if (Op0.getOperand(0).getOpcode() == X86ISD::VBROADCAST ||
50125 Op0.getOperand(0).getOpcode() == X86ISD::VBROADCAST_LOAD)
50126 return Op0.getOperand(0);
50127 }
50128 }
50129
50130 // concat(extract_subvector(v0,c0), extract_subvector(v1,c1)) -> vperm2x128.
50131 // Only concat of subvector high halves which vperm2x128 is best at.
50132 // TODO: This should go in combineX86ShufflesRecursively eventually.
50133 if (VT.is256BitVector() && Ops.size() == 2) {
50134 SDValue Src0 = peekThroughBitcasts(Ops[0]);
50135 SDValue Src1 = peekThroughBitcasts(Ops[1]);
50136 if (Src0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
50137 Src1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
50138 EVT SrcVT0 = Src0.getOperand(0).getValueType();
50139 EVT SrcVT1 = Src1.getOperand(0).getValueType();
50140 unsigned NumSrcElts0 = SrcVT0.getVectorNumElements();
50141 unsigned NumSrcElts1 = SrcVT1.getVectorNumElements();
50142 if (SrcVT0.is256BitVector() && SrcVT1.is256BitVector() &&
50143 Src0.getConstantOperandAPInt(1) == (NumSrcElts0 / 2) &&
50144 Src1.getConstantOperandAPInt(1) == (NumSrcElts1 / 2)) {
50145 return DAG.getNode(X86ISD::VPERM2X128, DL, VT,
50146 DAG.getBitcast(VT, Src0.getOperand(0)),
50147 DAG.getBitcast(VT, Src1.getOperand(0)),
50148 DAG.getTargetConstant(0x31, DL, MVT::i8));
50149 }
50150 }
50151 }
50152
50153 // Repeated opcode.
50154 // TODO - combineX86ShufflesRecursively should handle shuffle concatenation
50155 // but it currently struggles with different vector widths.
50156 if (llvm::all_of(Ops, [Op0](SDValue Op) {
50157 return Op.getOpcode() == Op0.getOpcode();
50158 })) {
50159 auto ConcatSubOperand = [&](MVT VT, ArrayRef<SDValue> SubOps, unsigned I) {
50160 SmallVector<SDValue> Subs;
50161 for (SDValue SubOp : SubOps)
50162 Subs.push_back(SubOp.getOperand(I));
50163 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
50164 };
50165
50166 unsigned NumOps = Ops.size();
50167 switch (Op0.getOpcode()) {
50168 case X86ISD::SHUFP: {
50169 // Add SHUFPD support if/when necessary.
50170 if (!IsSplat && VT.getScalarType() == MVT::f32 &&
50171 llvm::all_of(Ops, [Op0](SDValue Op) {
50172 return Op.getOperand(2) == Op0.getOperand(2);
50173 })) {
50174 return DAG.getNode(Op0.getOpcode(), DL, VT,
50175 ConcatSubOperand(VT, Ops, 0),
50176 ConcatSubOperand(VT, Ops, 1), Op0.getOperand(2));
50177 }
50178 break;
50179 }
50180 case X86ISD::PSHUFHW:
50181 case X86ISD::PSHUFLW:
50182 case X86ISD::PSHUFD:
50183 if (!IsSplat && NumOps == 2 && VT.is256BitVector() &&
50184 Subtarget.hasInt256() && Op0.getOperand(1) == Ops[1].getOperand(1)) {
50185 return DAG.getNode(Op0.getOpcode(), DL, VT,
50186 ConcatSubOperand(VT, Ops, 0), Op0.getOperand(1));
50187 }
50188 LLVM_FALLTHROUGH[[gnu::fallthrough]];
50189 case X86ISD::VPERMILPI:
50190 // TODO - add support for vXf64/vXi64 shuffles.
50191 if (!IsSplat && NumOps == 2 && (VT == MVT::v8f32 || VT == MVT::v8i32) &&
50192 Subtarget.hasAVX() && Op0.getOperand(1) == Ops[1].getOperand(1)) {
50193 SDValue Res = DAG.getBitcast(MVT::v8f32, ConcatSubOperand(VT, Ops, 0));
50194 Res = DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, Res,
50195 Op0.getOperand(1));
50196 return DAG.getBitcast(VT, Res);
50197 }
50198 break;
50199 case X86ISD::VPERMV3:
50200 if (!IsSplat && NumOps == 2 && VT.is512BitVector()) {
50201 MVT OpVT = Op0.getSimpleValueType();
50202 int NumSrcElts = OpVT.getVectorNumElements();
50203 SmallVector<int, 64> ConcatMask;
50204 for (unsigned i = 0; i != NumOps; ++i) {
50205 SmallVector<int, 64> SubMask;
50206 SmallVector<SDValue, 2> SubOps;
50207 if (!getTargetShuffleMask(Ops[i].getNode(), OpVT, false, SubOps,
50208 SubMask))
50209 break;
50210 for (int M : SubMask) {
50211 if (0 <= M) {
50212 M += M < NumSrcElts ? 0 : NumSrcElts;
50213 M += i * NumSrcElts;
50214 }
50215 ConcatMask.push_back(M);
50216 }
50217 }
50218 if (ConcatMask.size() == (NumOps * NumSrcElts)) {
50219 SDValue Src0 = concatSubVectors(Ops[0].getOperand(0),
50220 Ops[1].getOperand(0), DAG, DL);
50221 SDValue Src1 = concatSubVectors(Ops[0].getOperand(2),
50222 Ops[1].getOperand(2), DAG, DL);
50223 MVT IntMaskSVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
50224 MVT IntMaskVT = MVT::getVectorVT(IntMaskSVT, NumOps * NumSrcElts);
50225 SDValue Mask = getConstVector(ConcatMask, IntMaskVT, DAG, DL, true);
50226 return DAG.getNode(X86ISD::VPERMV3, DL, VT, Src0, Mask, Src1);
50227 }
50228 }
50229 break;
50230 case X86ISD::VSHLI:
50231 case X86ISD::VSRLI:
50232 // Special case: SHL/SRL AVX1 V4i64 by 32-bits can lower as a shuffle.
50233 // TODO: Move this to LowerScalarImmediateShift?
50234 if (VT == MVT::v4i64 && !Subtarget.hasInt256() &&
50235 llvm::all_of(Ops, [](SDValue Op) {
50236 return Op.getConstantOperandAPInt(1) == 32;
50237 })) {
50238 SDValue Res = DAG.getBitcast(MVT::v8i32, ConcatSubOperand(VT, Ops, 0));
50239 SDValue Zero = getZeroVector(MVT::v8i32, Subtarget, DAG, DL);
50240 if (Op0.getOpcode() == X86ISD::VSHLI) {
50241 Res = DAG.getVectorShuffle(MVT::v8i32, DL, Res, Zero,
50242 {8, 0, 8, 2, 8, 4, 8, 6});
50243 } else {
50244 Res = DAG.getVectorShuffle(MVT::v8i32, DL, Res, Zero,
50245 {1, 8, 3, 8, 5, 8, 7, 8});
50246 }
50247 return DAG.getBitcast(VT, Res);
50248 }
50249 LLVM_FALLTHROUGH[[gnu::fallthrough]];
50250 case X86ISD::VSRAI:
50251 if (((VT.is256BitVector() && Subtarget.hasInt256()) ||
50252 (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
50253 (EltSizeInBits >= 32 || Subtarget.useBWIRegs()))) &&
50254 llvm::all_of(Ops, [Op0](SDValue Op) {
50255 return Op0.getOperand(1) == Op.getOperand(1);
50256 })) {
50257 return DAG.getNode(Op0.getOpcode(), DL, VT,
50258 ConcatSubOperand(VT, Ops, 0), Op0.getOperand(1));
50259 }
50260 break;
50261 case X86ISD::VPERMI:
50262 case X86ISD::VROTLI:
50263 case X86ISD::VROTRI:
50264 if (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
50265 llvm::all_of(Ops, [Op0](SDValue Op) {
50266 return Op0.getOperand(1) == Op.getOperand(1);
50267 })) {
50268 return DAG.getNode(Op0.getOpcode(), DL, VT,
50269 ConcatSubOperand(VT, Ops, 0), Op0.getOperand(1));
50270 }
50271 break;
50272 case ISD::AND:
50273 case ISD::OR:
50274 case ISD::XOR:
50275 case X86ISD::ANDNP:
50276 // TODO: Add 256-bit support.
50277 if (!IsSplat && VT.is512BitVector()) {
50278 MVT SrcVT = Op0.getOperand(0).getSimpleValueType();
50279 SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
50280 NumOps * SrcVT.getVectorNumElements());
50281 return DAG.getNode(Op0.getOpcode(), DL, VT,
50282 ConcatSubOperand(SrcVT, Ops, 0),
50283 ConcatSubOperand(SrcVT, Ops, 1));
50284 }
50285 break;
50286 case X86ISD::HADD:
50287 case X86ISD::HSUB:
50288 case X86ISD::FHADD:
50289 case X86ISD::FHSUB:
50290 case X86ISD::PACKSS:
50291 case X86ISD::PACKUS:
50292 if (!IsSplat && VT.is256BitVector() &&
50293 (VT.isFloatingPoint() || Subtarget.hasInt256())) {
50294 MVT SrcVT = Op0.getOperand(0).getSimpleValueType();
50295 SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
50296 NumOps * SrcVT.getVectorNumElements());
50297 return DAG.getNode(Op0.getOpcode(), DL, VT,
50298 ConcatSubOperand(SrcVT, Ops, 0),
50299 ConcatSubOperand(SrcVT, Ops, 1));
50300 }
50301 break;
50302 case X86ISD::PALIGNR:
50303 if (!IsSplat &&
50304 ((VT.is256BitVector() && Subtarget.hasInt256()) ||
50305 (VT.is512BitVector() && Subtarget.useBWIRegs())) &&
50306 llvm::all_of(Ops, [Op0](SDValue Op) {
50307 return Op0.getOperand(2) == Op.getOperand(2);
50308 })) {
50309 return DAG.getNode(Op0.getOpcode(), DL, VT,
50310 ConcatSubOperand(VT, Ops, 0),
50311 ConcatSubOperand(VT, Ops, 1), Op0.getOperand(2));
50312 }
50313 break;
50314 }
50315 }
50316
50317 // Fold subvector loads into one.
50318 // If needed, look through bitcasts to get to the load.
50319 if (auto *FirstLd = dyn_cast<LoadSDNode>(peekThroughBitcasts(Op0))) {
50320 bool Fast;
50321 const X86TargetLowering *TLI = Subtarget.getTargetLowering();
50322 if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
50323 *FirstLd->getMemOperand(), &Fast) &&
50324 Fast) {
50325 if (SDValue Ld =
50326 EltsFromConsecutiveLoads(VT, Ops, DL, DAG, Subtarget, false))
50327 return Ld;
50328 }
50329 }
50330
50331 return SDValue();
50332}
50333
50334static SDValue combineConcatVectors(SDNode *N, SelectionDAG &DAG,
50335 TargetLowering::DAGCombinerInfo &DCI,
50336 const X86Subtarget &Subtarget) {
50337 EVT VT = N->getValueType(0);
50338 EVT SrcVT = N->getOperand(0).getValueType();
50339 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50340
50341 // Don't do anything for i1 vectors.
50342 if (VT.getVectorElementType() == MVT::i1)
50343 return SDValue();
50344
50345 if (Subtarget.hasAVX() && TLI.isTypeLegal(VT) && TLI.isTypeLegal(SrcVT)) {
50346 SmallVector<SDValue, 4> Ops(N->op_begin(), N->op_end());
50347 if (SDValue R = combineConcatVectorOps(SDLoc(N), VT.getSimpleVT(), Ops, DAG,
50348 DCI, Subtarget))
50349 return R;
50350 }
50351
50352 return SDValue();
50353}
50354
50355static SDValue combineInsertSubvector(SDNode *N, SelectionDAG &DAG,
50356 TargetLowering::DAGCombinerInfo &DCI,
50357 const X86Subtarget &Subtarget) {
50358 if (DCI.isBeforeLegalizeOps())
50359 return SDValue();
50360
50361 MVT OpVT = N->getSimpleValueType(0);
50362
50363 bool IsI1Vector = OpVT.getVectorElementType() == MVT::i1;
50364
50365 SDLoc dl(N);
50366 SDValue Vec = N->getOperand(0);
50367 SDValue SubVec = N->getOperand(1);
50368
50369 uint64_t IdxVal = N->getConstantOperandVal(2);
50370 MVT SubVecVT = SubVec.getSimpleValueType();
50371
50372 if (Vec.isUndef() && SubVec.isUndef())
50373 return DAG.getUNDEF(OpVT);
50374
50375 // Inserting undefs/zeros into zeros/undefs is a zero vector.
50376 if ((Vec.isUndef() || ISD::isBuildVectorAllZeros(Vec.getNode())) &&
50377 (SubVec.isUndef() || ISD::isBuildVectorAllZeros(SubVec.getNode())))
50378 return getZeroVector(OpVT, Subtarget, DAG, dl);
50379
50380 if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
50381 // If we're inserting into a zero vector and then into a larger zero vector,
50382 // just insert into the larger zero vector directly.
50383 if (SubVec.getOpcode() == ISD::INSERT_SUBVECTOR &&
50384 ISD::isBuildVectorAllZeros(SubVec.getOperand(0).getNode())) {
50385 uint64_t Idx2Val = SubVec.getConstantOperandVal(2);
50386 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
50387 getZeroVector(OpVT, Subtarget, DAG, dl),
50388 SubVec.getOperand(1),
50389 DAG.getIntPtrConstant(IdxVal + Idx2Val, dl));
50390 }
50391
50392 // If we're inserting into a zero vector and our input was extracted from an
50393 // insert into a zero vector of the same type and the extraction was at
50394 // least as large as the original insertion. Just insert the original
50395 // subvector into a zero vector.
50396 if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR && IdxVal == 0 &&
50397 isNullConstant(SubVec.getOperand(1)) &&
50398 SubVec.getOperand(0).getOpcode() == ISD::INSERT_SUBVECTOR) {
50399 SDValue Ins = SubVec.getOperand(0);
50400 if (isNullConstant(Ins.getOperand(2)) &&
50401 ISD::isBuildVectorAllZeros(Ins.getOperand(0).getNode()) &&
50402 Ins.getOperand(1).getValueSizeInBits().getFixedSize() <=
50403 SubVecVT.getFixedSizeInBits())
50404 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
50405 getZeroVector(OpVT, Subtarget, DAG, dl),
50406 Ins.getOperand(1), N->getOperand(2));
50407 }
50408 }
50409
50410 // Stop here if this is an i1 vector.
50411 if (IsI1Vector)
50412 return SDValue();
50413
50414 // If this is an insert of an extract, combine to a shuffle. Don't do this
50415 // if the insert or extract can be represented with a subregister operation.
50416 if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
50417 SubVec.getOperand(0).getSimpleValueType() == OpVT &&
50418 (IdxVal != 0 ||
50419 !(Vec.isUndef() || ISD::isBuildVectorAllZeros(Vec.getNode())))) {
50420 int ExtIdxVal = SubVec.getConstantOperandVal(1);
50421 if (ExtIdxVal != 0) {
50422 int VecNumElts = OpVT.getVectorNumElements();
50423 int SubVecNumElts = SubVecVT.getVectorNumElements();
50424 SmallVector<int, 64> Mask(VecNumElts);
50425 // First create an identity shuffle mask.
50426 for (int i = 0; i != VecNumElts; ++i)
50427 Mask[i] = i;
50428 // Now insert the extracted portion.
50429 for (int i = 0; i != SubVecNumElts; ++i)
50430 Mask[i + IdxVal] = i + ExtIdxVal + VecNumElts;
50431
50432 return DAG.getVectorShuffle(OpVT, dl, Vec, SubVec.getOperand(0), Mask);
50433 }
50434 }
50435
50436 // Match concat_vector style patterns.
50437 SmallVector<SDValue, 2> SubVectorOps;
50438 if (collectConcatOps(N, SubVectorOps)) {
50439 if (SDValue Fold =
50440 combineConcatVectorOps(dl, OpVT, SubVectorOps, DAG, DCI, Subtarget))
50441 return Fold;
50442
50443 // If we're inserting all zeros into the upper half, change this to
50444 // a concat with zero. We will match this to a move
50445 // with implicit upper bit zeroing during isel.
50446 // We do this here because we don't want combineConcatVectorOps to
50447 // create INSERT_SUBVECTOR from CONCAT_VECTORS.
50448 if (SubVectorOps.size() == 2 &&
50449 ISD::isBuildVectorAllZeros(SubVectorOps[1].getNode()))
50450 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
50451 getZeroVector(OpVT, Subtarget, DAG, dl),
50452 SubVectorOps[0], DAG.getIntPtrConstant(0, dl));
50453 }
50454
50455 // If this is a broadcast insert into an upper undef, use a larger broadcast.
50456 if (Vec.isUndef() && IdxVal != 0 && SubVec.getOpcode() == X86ISD::VBROADCAST)
50457 return DAG.getNode(X86ISD::VBROADCAST, dl, OpVT, SubVec.getOperand(0));
50458
50459 // If this is a broadcast load inserted into an upper undef, use a larger
50460 // broadcast load.
50461 if (Vec.isUndef() && IdxVal != 0 && SubVec.hasOneUse() &&
50462 SubVec.getOpcode() == X86ISD::VBROADCAST_LOAD) {
50463 auto *MemIntr = cast<MemIntrinsicSDNode>(SubVec);
50464 return getBROADCAST_LOAD(X86ISD::VBROADCAST_LOAD, dl, OpVT,
50465 MemIntr->getMemoryVT(), MemIntr, 0, DAG);
50466 }
50467
50468 // If we're splatting the lower half subvector of a full vector load into the
50469 // upper half, attempt to create a subvector broadcast.
50470 if (IdxVal == (OpVT.getVectorNumElements() / 2) && SubVec.hasOneUse() &&
50471 Vec.getValueSizeInBits() == (2 * SubVec.getValueSizeInBits())) {
50472 auto *VecLd = dyn_cast<LoadSDNode>(Vec);
50473 auto *SubLd = dyn_cast<LoadSDNode>(SubVec);
50474 if (VecLd && SubLd &&
50475 DAG.areNonVolatileConsecutiveLoads(SubLd, VecLd,
50476 SubVec.getValueSizeInBits() / 8, 0))
50477 return getBROADCAST_LOAD(X86ISD::SUBV_BROADCAST_LOAD, dl, OpVT, SubVecVT,
50478 SubLd, 0, DAG);
50479 }
50480
50481 return SDValue();
50482}
50483
50484/// If we are extracting a subvector of a vector select and the select condition
50485/// is composed of concatenated vectors, try to narrow the select width. This
50486/// is a common pattern for AVX1 integer code because 256-bit selects may be
50487/// legal, but there is almost no integer math/logic available for 256-bit.
50488/// This function should only be called with legal types (otherwise, the calls
50489/// to get simple value types will assert).
50490static SDValue narrowExtractedVectorSelect(SDNode *Ext, SelectionDAG &DAG) {
50491 SDValue Sel = peekThroughBitcasts(Ext->getOperand(0));
50492 SmallVector<SDValue, 4> CatOps;
50493 if (Sel.getOpcode() != ISD::VSELECT ||
50494 !collectConcatOps(Sel.getOperand(0).getNode(), CatOps))
50495 return SDValue();
50496
50497 // Note: We assume simple value types because this should only be called with
50498 // legal operations/types.
50499 // TODO: This can be extended to handle extraction to 256-bits.
50500 MVT VT = Ext->getSimpleValueType(0);
50501 if (!VT.is128BitVector())
50502 return SDValue();
50503
50504 MVT SelCondVT = Sel.getOperand(0).getSimpleValueType();
50505 if (!SelCondVT.is256BitVector() && !SelCondVT.is512BitVector())
50506 return SDValue();
50507
50508 MVT WideVT = Ext->getOperand(0).getSimpleValueType();
50509 MVT SelVT = Sel.getSimpleValueType();
50510 assert((SelVT.is256BitVector() || SelVT.is512BitVector()) &&(static_cast <bool> ((SelVT.is256BitVector() || SelVT.is512BitVector
()) && "Unexpected vector type with legal operations"
) ? void (0) : __assert_fail ("(SelVT.is256BitVector() || SelVT.is512BitVector()) && \"Unexpected vector type with legal operations\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 50511, __extension__ __PRETTY_FUNCTION__))
50511 "Unexpected vector type with legal operations")(static_cast <bool> ((SelVT.is256BitVector() || SelVT.is512BitVector
()) && "Unexpected vector type with legal operations"
) ? void (0) : __assert_fail ("(SelVT.is256BitVector() || SelVT.is512BitVector()) && \"Unexpected vector type with legal operations\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 50511, __extension__ __PRETTY_FUNCTION__))
;
50512
50513 unsigned SelElts = SelVT.getVectorNumElements();
50514 unsigned CastedElts = WideVT.getVectorNumElements();
50515 unsigned ExtIdx = Ext->getConstantOperandVal(1);
50516 if (SelElts % CastedElts == 0) {
50517 // The select has the same or more (narrower) elements than the extract
50518 // operand. The extraction index gets scaled by that factor.
50519 ExtIdx *= (SelElts / CastedElts);
50520 } else if (CastedElts % SelElts == 0) {
50521 // The select has less (wider) elements than the extract operand. Make sure
50522 // that the extraction index can be divided evenly.
50523 unsigned IndexDivisor = CastedElts / SelElts;
50524 if (ExtIdx % IndexDivisor != 0)
50525 return SDValue();
50526 ExtIdx /= IndexDivisor;
50527 } else {
50528 llvm_unreachable("Element count of simple vector types are not divisible?")::llvm::llvm_unreachable_internal("Element count of simple vector types are not divisible?"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 50528)
;
50529 }
50530
50531 unsigned NarrowingFactor = WideVT.getSizeInBits() / VT.getSizeInBits();
50532 unsigned NarrowElts = SelElts / NarrowingFactor;
50533 MVT NarrowSelVT = MVT::getVectorVT(SelVT.getVectorElementType(), NarrowElts);
50534 SDLoc DL(Ext);
50535 SDValue ExtCond = extract128BitVector(Sel.getOperand(0), ExtIdx, DAG, DL);
50536 SDValue ExtT = extract128BitVector(Sel.getOperand(1), ExtIdx, DAG, DL);
50537 SDValue ExtF = extract128BitVector(Sel.getOperand(2), ExtIdx, DAG, DL);
50538 SDValue NarrowSel = DAG.getSelect(DL, NarrowSelVT, ExtCond, ExtT, ExtF);
50539 return DAG.getBitcast(VT, NarrowSel);
50540}
50541
50542static SDValue combineExtractSubvector(SDNode *N, SelectionDAG &DAG,
50543 TargetLowering::DAGCombinerInfo &DCI,
50544 const X86Subtarget &Subtarget) {
50545 // For AVX1 only, if we are extracting from a 256-bit and+not (which will
50546 // eventually get combined/lowered into ANDNP) with a concatenated operand,
50547 // split the 'and' into 128-bit ops to avoid the concatenate and extract.
50548 // We let generic combining take over from there to simplify the
50549 // insert/extract and 'not'.
50550 // This pattern emerges during AVX1 legalization. We handle it before lowering
50551 // to avoid complications like splitting constant vector loads.
50552
50553 // Capture the original wide type in the likely case that we need to bitcast
50554 // back to this type.
50555 if (!N->getValueType(0).isSimple())
50556 return SDValue();
50557
50558 MVT VT = N->getSimpleValueType(0);
50559 SDValue InVec = N->getOperand(0);
50560 unsigned IdxVal = N->getConstantOperandVal(1);
50561 SDValue InVecBC = peekThroughBitcasts(InVec);
50562 EVT InVecVT = InVec.getValueType();
50563 unsigned SizeInBits = VT.getSizeInBits();
50564 unsigned InSizeInBits = InVecVT.getSizeInBits();
50565 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50566
50567 if (Subtarget.hasAVX() && !Subtarget.hasAVX2() &&
50568 TLI.isTypeLegal(InVecVT) &&
50569 InSizeInBits == 256 && InVecBC.getOpcode() == ISD::AND) {
50570 auto isConcatenatedNot = [](SDValue V) {
50571 V = peekThroughBitcasts(V);
50572 if (!isBitwiseNot(V))
50573 return false;
50574 SDValue NotOp = V->getOperand(0);
50575 return peekThroughBitcasts(NotOp).getOpcode() == ISD::CONCAT_VECTORS;
50576 };
50577 if (isConcatenatedNot(InVecBC.getOperand(0)) ||
50578 isConcatenatedNot(InVecBC.getOperand(1))) {
50579 // extract (and v4i64 X, (not (concat Y1, Y2))), n -> andnp v2i64 X(n), Y1
50580 SDValue Concat = splitVectorIntBinary(InVecBC, DAG);
50581 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), VT,
50582 DAG.getBitcast(InVecVT, Concat), N->getOperand(1));
50583 }
50584 }
50585
50586 if (DCI.isBeforeLegalizeOps())
50587 return SDValue();
50588
50589 if (SDValue V = narrowExtractedVectorSelect(N, DAG))
50590 return V;
50591
50592 if (ISD::isBuildVectorAllZeros(InVec.getNode()))
50593 return getZeroVector(VT, Subtarget, DAG, SDLoc(N));
50594
50595 if (ISD::isBuildVectorAllOnes(InVec.getNode())) {
50596 if (VT.getScalarType() == MVT::i1)
50597 return DAG.getConstant(1, SDLoc(N), VT);
50598 return getOnesVector(VT, DAG, SDLoc(N));
50599 }
50600
50601 if (InVec.getOpcode() == ISD::BUILD_VECTOR)
50602 return DAG.getBuildVector(
50603 VT, SDLoc(N),
50604 InVec.getNode()->ops().slice(IdxVal, VT.getVectorNumElements()));
50605
50606 // If we are extracting from an insert into a zero vector, replace with a
50607 // smaller insert into zero if we don't access less than the original
50608 // subvector. Don't do this for i1 vectors.
50609 if (VT.getVectorElementType() != MVT::i1 &&
50610 InVec.getOpcode() == ISD::INSERT_SUBVECTOR && IdxVal == 0 &&
50611 InVec.hasOneUse() && isNullConstant(InVec.getOperand(2)) &&
50612 ISD::isBuildVectorAllZeros(InVec.getOperand(0).getNode()) &&
50613 InVec.getOperand(1).getValueSizeInBits() <= SizeInBits) {
50614 SDLoc DL(N);
50615 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
50616 getZeroVector(VT, Subtarget, DAG, DL),
50617 InVec.getOperand(1), InVec.getOperand(2));
50618 }
50619
50620 // If we're extracting an upper subvector from a broadcast we should just
50621 // extract the lowest subvector instead which should allow
50622 // SimplifyDemandedVectorElts do more simplifications.
50623 if (IdxVal != 0 && (InVec.getOpcode() == X86ISD::VBROADCAST ||
50624 InVec.getOpcode() == X86ISD::VBROADCAST_LOAD ||
50625 DAG.isSplatValue(InVec, /*AllowUndefs*/ false)))
50626 return extractSubVector(InVec, 0, DAG, SDLoc(N), SizeInBits);
50627
50628 // If we're extracting a broadcasted subvector, just use the lowest subvector.
50629 if (IdxVal != 0 && InVec.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD &&
50630 cast<MemIntrinsicSDNode>(InVec)->getMemoryVT() == VT)
50631 return extractSubVector(InVec, 0, DAG, SDLoc(N), SizeInBits);
50632
50633 // Attempt to extract from the source of a shuffle vector.
50634 if ((InSizeInBits % SizeInBits) == 0 &&
50635 (IdxVal % VT.getVectorNumElements()) == 0) {
50636 SmallVector<int, 32> ShuffleMask;
50637 SmallVector<int, 32> ScaledMask;
50638 SmallVector<SDValue, 2> ShuffleInputs;
50639 unsigned NumSubVecs = InSizeInBits / SizeInBits;
50640 // Decode the shuffle mask and scale it so its shuffling subvectors.
50641 if (getTargetShuffleInputs(InVecBC, ShuffleInputs, ShuffleMask, DAG) &&
50642 scaleShuffleElements(ShuffleMask, NumSubVecs, ScaledMask)) {
50643 unsigned SubVecIdx = IdxVal / VT.getVectorNumElements();
50644 if (ScaledMask[SubVecIdx] == SM_SentinelUndef)
50645 return DAG.getUNDEF(VT);
50646 if (ScaledMask[SubVecIdx] == SM_SentinelZero)
50647 return getZeroVector(VT, Subtarget, DAG, SDLoc(N));
50648 SDValue Src = ShuffleInputs[ScaledMask[SubVecIdx] / NumSubVecs];
50649 if (Src.getValueSizeInBits() == InSizeInBits) {
50650 unsigned SrcSubVecIdx = ScaledMask[SubVecIdx] % NumSubVecs;
50651 unsigned SrcEltIdx = SrcSubVecIdx * VT.getVectorNumElements();
50652 return extractSubVector(DAG.getBitcast(InVecVT, Src), SrcEltIdx, DAG,
50653 SDLoc(N), SizeInBits);
50654 }
50655 }
50656 }
50657
50658 // If we're extracting the lowest subvector and we're the only user,
50659 // we may be able to perform this with a smaller vector width.
50660 unsigned InOpcode = InVec.getOpcode();
50661 if (IdxVal == 0 && InVec.hasOneUse()) {
50662 if (VT == MVT::v2f64 && InVecVT == MVT::v4f64) {
50663 // v2f64 CVTDQ2PD(v4i32).
50664 if (InOpcode == ISD::SINT_TO_FP &&
50665 InVec.getOperand(0).getValueType() == MVT::v4i32) {
50666 return DAG.getNode(X86ISD::CVTSI2P, SDLoc(N), VT, InVec.getOperand(0));
50667 }
50668 // v2f64 CVTUDQ2PD(v4i32).
50669 if (InOpcode == ISD::UINT_TO_FP && Subtarget.hasVLX() &&
50670 InVec.getOperand(0).getValueType() == MVT::v4i32) {
50671 return DAG.getNode(X86ISD::CVTUI2P, SDLoc(N), VT, InVec.getOperand(0));
50672 }
50673 // v2f64 CVTPS2PD(v4f32).
50674 if (InOpcode == ISD::FP_EXTEND &&
50675 InVec.getOperand(0).getValueType() == MVT::v4f32) {
50676 return DAG.getNode(X86ISD::VFPEXT, SDLoc(N), VT, InVec.getOperand(0));
50677 }
50678 }
50679 if ((InOpcode == ISD::ANY_EXTEND ||
50680 InOpcode == ISD::ANY_EXTEND_VECTOR_INREG ||
50681 InOpcode == ISD::ZERO_EXTEND ||
50682 InOpcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
50683 InOpcode == ISD::SIGN_EXTEND ||
50684 InOpcode == ISD::SIGN_EXTEND_VECTOR_INREG) &&
50685 (SizeInBits == 128 || SizeInBits == 256) &&
50686 InVec.getOperand(0).getValueSizeInBits() >= SizeInBits) {
50687 SDLoc DL(N);
50688 SDValue Ext = InVec.getOperand(0);
50689 if (Ext.getValueSizeInBits() > SizeInBits)
50690 Ext = extractSubVector(Ext, 0, DAG, DL, SizeInBits);
50691 unsigned ExtOp = getOpcode_EXTEND_VECTOR_INREG(InOpcode);
50692 return DAG.getNode(ExtOp, DL, VT, Ext);
50693 }
50694 if (InOpcode == ISD::VSELECT &&
50695 InVec.getOperand(0).getValueType().is256BitVector() &&
50696 InVec.getOperand(1).getValueType().is256BitVector() &&
50697 InVec.getOperand(2).getValueType().is256BitVector()) {
50698 SDLoc DL(N);
50699 SDValue Ext0 = extractSubVector(InVec.getOperand(0), 0, DAG, DL, 128);
50700 SDValue Ext1 = extractSubVector(InVec.getOperand(1), 0, DAG, DL, 128);
50701 SDValue Ext2 = extractSubVector(InVec.getOperand(2), 0, DAG, DL, 128);
50702 return DAG.getNode(InOpcode, DL, VT, Ext0, Ext1, Ext2);
50703 }
50704 if (InOpcode == ISD::TRUNCATE && Subtarget.hasVLX() &&
50705 (VT.is128BitVector() || VT.is256BitVector())) {
50706 SDLoc DL(N);
50707 SDValue InVecSrc = InVec.getOperand(0);
50708 unsigned Scale = InVecSrc.getValueSizeInBits() / InSizeInBits;
50709 SDValue Ext = extractSubVector(InVecSrc, 0, DAG, DL, Scale * SizeInBits);
50710 return DAG.getNode(InOpcode, DL, VT, Ext);
50711 }
50712 }
50713
50714 // Always split vXi64 logical shifts where we're extracting the upper 32-bits
50715 // as this is very likely to fold into a shuffle/truncation.
50716 if ((InOpcode == X86ISD::VSHLI || InOpcode == X86ISD::VSRLI) &&
50717 InVecVT.getScalarSizeInBits() == 64 &&
50718 InVec.getConstantOperandAPInt(1) == 32) {
50719 SDLoc DL(N);
50720 SDValue Ext =
50721 extractSubVector(InVec.getOperand(0), IdxVal, DAG, DL, SizeInBits);
50722 return DAG.getNode(InOpcode, DL, VT, Ext, InVec.getOperand(1));
50723 }
50724
50725 return SDValue();
50726}
50727
50728static SDValue combineScalarToVector(SDNode *N, SelectionDAG &DAG) {
50729 EVT VT = N->getValueType(0);
50730 SDValue Src = N->getOperand(0);
50731 SDLoc DL(N);
50732
50733 // If this is a scalar to vector to v1i1 from an AND with 1, bypass the and.
50734 // This occurs frequently in our masked scalar intrinsic code and our
50735 // floating point select lowering with AVX512.
50736 // TODO: SimplifyDemandedBits instead?
50737 if (VT == MVT::v1i1 && Src.getOpcode() == ISD::AND && Src.hasOneUse())
50738 if (auto *C = dyn_cast<ConstantSDNode>(Src.getOperand(1)))
50739 if (C->getAPIntValue().isOneValue())
50740 return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1,
50741 Src.getOperand(0));
50742
50743 // Combine scalar_to_vector of an extract_vector_elt into an extract_subvec.
50744 if (VT == MVT::v1i1 && Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
50745 Src.hasOneUse() && Src.getOperand(0).getValueType().isVector() &&
50746 Src.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
50747 if (auto *C = dyn_cast<ConstantSDNode>(Src.getOperand(1)))
50748 if (C->isNullValue())
50749 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src.getOperand(0),
50750 Src.getOperand(1));
50751
50752 // Reduce v2i64 to v4i32 if we don't need the upper bits.
50753 // TODO: Move to DAGCombine/SimplifyDemandedBits?
50754 if (VT == MVT::v2i64 || VT == MVT::v2f64) {
50755 auto IsAnyExt64 = [](SDValue Op) {
50756 if (Op.getValueType() != MVT::i64 || !Op.hasOneUse())
50757 return SDValue();
50758 if (Op.getOpcode() == ISD::ANY_EXTEND &&
50759 Op.getOperand(0).getScalarValueSizeInBits() <= 32)
50760 return Op.getOperand(0);
50761 if (auto *Ld = dyn_cast<LoadSDNode>(Op))
50762 if (Ld->getExtensionType() == ISD::EXTLOAD &&
50763 Ld->getMemoryVT().getScalarSizeInBits() <= 32)
50764 return Op;
50765 return SDValue();
50766 };
50767 if (SDValue ExtSrc = IsAnyExt64(peekThroughOneUseBitcasts(Src)))
50768 return DAG.getBitcast(
50769 VT, DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32,
50770 DAG.getAnyExtOrTrunc(ExtSrc, DL, MVT::i32)));
50771 }
50772
50773 // Combine (v2i64 (scalar_to_vector (i64 (bitconvert (mmx))))) to MOVQ2DQ.
50774 if (VT == MVT::v2i64 && Src.getOpcode() == ISD::BITCAST &&
50775 Src.getOperand(0).getValueType() == MVT::x86mmx)
50776 return DAG.getNode(X86ISD::MOVQ2DQ, DL, VT, Src.getOperand(0));
50777
50778 // See if we're broadcasting the scalar value, in which case just reuse that.
50779 // Ensure the same SDValue from the SDNode use is being used.
50780 if (VT.getScalarType() == Src.getValueType())
50781 for (SDNode *User : Src->uses())
50782 if (User->getOpcode() == X86ISD::VBROADCAST &&
50783 Src == User->getOperand(0)) {
50784 unsigned SizeInBits = VT.getFixedSizeInBits();
50785 unsigned BroadcastSizeInBits =
50786 User->getValueSizeInBits(0).getFixedSize();
50787 if (BroadcastSizeInBits == SizeInBits)
50788 return SDValue(User, 0);
50789 if (BroadcastSizeInBits > SizeInBits)
50790 return extractSubVector(SDValue(User, 0), 0, DAG, DL, SizeInBits);
50791 // TODO: Handle BroadcastSizeInBits < SizeInBits when we have test
50792 // coverage.
50793 }
50794
50795 return SDValue();
50796}
50797
50798// Simplify PMULDQ and PMULUDQ operations.
50799static SDValue combinePMULDQ(SDNode *N, SelectionDAG &DAG,
50800 TargetLowering::DAGCombinerInfo &DCI,
50801 const X86Subtarget &Subtarget) {
50802 SDValue LHS = N->getOperand(0);
50803 SDValue RHS = N->getOperand(1);
50804
50805 // Canonicalize constant to RHS.
50806 if (DAG.isConstantIntBuildVectorOrConstantInt(LHS) &&
50807 !DAG.isConstantIntBuildVectorOrConstantInt(RHS))
50808 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), RHS, LHS);
50809
50810 // Multiply by zero.
50811 // Don't return RHS as it may contain UNDEFs.
50812 if (ISD::isBuildVectorAllZeros(RHS.getNode()))
50813 return DAG.getConstant(0, SDLoc(N), N->getValueType(0));
50814
50815 // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
50816 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50817 if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnesValue(64), DCI))
50818 return SDValue(N, 0);
50819
50820 // If the input is an extend_invec and the SimplifyDemandedBits call didn't
50821 // convert it to any_extend_invec, due to the LegalOperations check, do the
50822 // conversion directly to a vector shuffle manually. This exposes combine
50823 // opportunities missed by combineEXTEND_VECTOR_INREG not calling
50824 // combineX86ShufflesRecursively on SSE4.1 targets.
50825 // FIXME: This is basically a hack around several other issues related to
50826 // ANY_EXTEND_VECTOR_INREG.
50827 if (N->getValueType(0) == MVT::v2i64 && LHS.hasOneUse() &&
50828 (LHS.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG ||
50829 LHS.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG) &&
50830 LHS.getOperand(0).getValueType() == MVT::v4i32) {
50831 SDLoc dl(N);
50832 LHS = DAG.getVectorShuffle(MVT::v4i32, dl, LHS.getOperand(0),
50833 LHS.getOperand(0), { 0, -1, 1, -1 });
50834 LHS = DAG.getBitcast(MVT::v2i64, LHS);
50835 return DAG.getNode(N->getOpcode(), dl, MVT::v2i64, LHS, RHS);
50836 }
50837 if (N->getValueType(0) == MVT::v2i64 && RHS.hasOneUse() &&
50838 (RHS.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG ||
50839 RHS.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG) &&
50840 RHS.getOperand(0).getValueType() == MVT::v4i32) {
50841 SDLoc dl(N);
50842 RHS = DAG.getVectorShuffle(MVT::v4i32, dl, RHS.getOperand(0),
50843 RHS.getOperand(0), { 0, -1, 1, -1 });
50844 RHS = DAG.getBitcast(MVT::v2i64, RHS);
50845 return DAG.getNode(N->getOpcode(), dl, MVT::v2i64, LHS, RHS);
50846 }
50847
50848 return SDValue();
50849}
50850
50851static SDValue combineEXTEND_VECTOR_INREG(SDNode *N, SelectionDAG &DAG,
50852 TargetLowering::DAGCombinerInfo &DCI,
50853 const X86Subtarget &Subtarget) {
50854 EVT VT = N->getValueType(0);
50855 SDValue In = N->getOperand(0);
50856 unsigned Opcode = N->getOpcode();
50857 unsigned InOpcode = In.getOpcode();
50858 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50859
50860 // Try to merge vector loads and extend_inreg to an extload.
50861 if (!DCI.isBeforeLegalizeOps() && ISD::isNormalLoad(In.getNode()) &&
50862 In.hasOneUse()) {
50863 auto *Ld = cast<LoadSDNode>(In);
50864 if (Ld->isSimple()) {
50865 MVT SVT = In.getSimpleValueType().getVectorElementType();
50866 ISD::LoadExtType Ext = Opcode == ISD::SIGN_EXTEND_VECTOR_INREG
50867 ? ISD::SEXTLOAD
50868 : ISD::ZEXTLOAD;
50869 EVT MemVT = VT.changeVectorElementType(SVT);
50870 if (TLI.isLoadExtLegal(Ext, VT, MemVT)) {
50871 SDValue Load =
50872 DAG.getExtLoad(Ext, SDLoc(N), VT, Ld->getChain(), Ld->getBasePtr(),
50873 Ld->getPointerInfo(), MemVT, Ld->getOriginalAlign(),
50874 Ld->getMemOperand()->getFlags());
50875 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
50876 return Load;
50877 }
50878 }
50879 }
50880
50881 // Fold EXTEND_VECTOR_INREG(EXTEND_VECTOR_INREG(X)) -> EXTEND_VECTOR_INREG(X).
50882 if (Opcode == InOpcode)
50883 return DAG.getNode(Opcode, SDLoc(N), VT, In.getOperand(0));
50884
50885 // Fold EXTEND_VECTOR_INREG(EXTRACT_SUBVECTOR(EXTEND(X),0))
50886 // -> EXTEND_VECTOR_INREG(X).
50887 // TODO: Handle non-zero subvector indices.
50888 if (InOpcode == ISD::EXTRACT_SUBVECTOR && In.getConstantOperandVal(1) == 0 &&
50889 In.getOperand(0).getOpcode() == getOpcode_EXTEND(Opcode) &&
50890 In.getOperand(0).getOperand(0).getValueSizeInBits() ==
50891 In.getValueSizeInBits())
50892 return DAG.getNode(Opcode, SDLoc(N), VT, In.getOperand(0).getOperand(0));
50893
50894 // Attempt to combine as a shuffle.
50895 // TODO: General ZERO_EXTEND_VECTOR_INREG support.
50896 if (Opcode == ISD::ANY_EXTEND_VECTOR_INREG ||
50897 (Opcode == ISD::ZERO_EXTEND_VECTOR_INREG && Subtarget.hasSSE41())) {
50898 SDValue Op(N, 0);
50899 if (TLI.isTypeLegal(VT) && TLI.isTypeLegal(In.getValueType()))
50900 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
50901 return Res;
50902 }
50903
50904 return SDValue();
50905}
50906
50907static SDValue combineKSHIFT(SDNode *N, SelectionDAG &DAG,
50908 TargetLowering::DAGCombinerInfo &DCI) {
50909 EVT VT = N->getValueType(0);
50910
50911 if (ISD::isBuildVectorAllZeros(N->getOperand(0).getNode()))
50912 return DAG.getConstant(0, SDLoc(N), VT);
50913
50914 APInt KnownUndef, KnownZero;
50915 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50916 APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
50917 if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, KnownUndef,
50918 KnownZero, DCI))
50919 return SDValue(N, 0);
50920
50921 return SDValue();
50922}
50923
50924// Optimize (fp16_to_fp (fp_to_fp16 X)) to VCVTPS2PH followed by VCVTPH2PS.
50925// Done as a combine because the lowering for fp16_to_fp and fp_to_fp16 produce
50926// extra instructions between the conversion due to going to scalar and back.
50927static SDValue combineFP16_TO_FP(SDNode *N, SelectionDAG &DAG,
50928 const X86Subtarget &Subtarget) {
50929 if (Subtarget.useSoftFloat() || !Subtarget.hasF16C())
50930 return SDValue();
50931
50932 if (N->getOperand(0).getOpcode() != ISD::FP_TO_FP16)
50933 return SDValue();
50934
50935 if (N->getValueType(0) != MVT::f32 ||
50936 N->getOperand(0).getOperand(0).getValueType() != MVT::f32)
50937 return SDValue();
50938
50939 SDLoc dl(N);
50940 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32,
50941 N->getOperand(0).getOperand(0));
50942 Res = DAG.getNode(X86ISD::CVTPS2PH, dl, MVT::v8i16, Res,
50943 DAG.getTargetConstant(4, dl, MVT::i32));
50944 Res = DAG.getNode(X86ISD::CVTPH2PS, dl, MVT::v4f32, Res);
50945 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
50946 DAG.getIntPtrConstant(0, dl));
50947}
50948
50949static SDValue combineFP_EXTEND(SDNode *N, SelectionDAG &DAG,
50950 const X86Subtarget &Subtarget) {
50951 if (!Subtarget.hasF16C() || Subtarget.useSoftFloat())
50952 return SDValue();
50953
50954 bool IsStrict = N->isStrictFPOpcode();
50955 EVT VT = N->getValueType(0);
50956 SDValue Src = N->getOperand(IsStrict ? 1 : 0);
50957 EVT SrcVT = Src.getValueType();
50958
50959 if (!SrcVT.isVector() || SrcVT.getVectorElementType() != MVT::f16)
50960 return SDValue();
50961
50962 if (VT.getVectorElementType() != MVT::f32 &&
50963 VT.getVectorElementType() != MVT::f64)
50964 return SDValue();
50965
50966 unsigned NumElts = VT.getVectorNumElements();
50967 if (NumElts == 1 || !isPowerOf2_32(NumElts))
50968 return SDValue();
50969
50970 SDLoc dl(N);
50971
50972 // Convert the input to vXi16.
50973 EVT IntVT = SrcVT.changeVectorElementTypeToInteger();
50974 Src = DAG.getBitcast(IntVT, Src);
50975
50976 // Widen to at least 8 input elements.
50977 if (NumElts < 8) {
50978 unsigned NumConcats = 8 / NumElts;
50979 SDValue Fill = NumElts == 4 ? DAG.getUNDEF(IntVT)
50980 : DAG.getConstant(0, dl, IntVT);
50981 SmallVector<SDValue, 4> Ops(NumConcats, Fill);
50982 Ops[0] = Src;
50983 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, Ops);
50984 }
50985
50986 // Destination is vXf32 with at least 4 elements.
50987 EVT CvtVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32,
50988 std::max(4U, NumElts));
50989 SDValue Cvt, Chain;
50990 if (IsStrict) {
50991 Cvt = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {CvtVT, MVT::Other},
50992 {N->getOperand(0), Src});
50993 Chain = Cvt.getValue(1);
50994 } else {
50995 Cvt = DAG.getNode(X86ISD::CVTPH2PS, dl, CvtVT, Src);
50996 }
50997
50998 if (NumElts < 4) {
50999 assert(NumElts == 2 && "Unexpected size")(static_cast <bool> (NumElts == 2 && "Unexpected size"
) ? void (0) : __assert_fail ("NumElts == 2 && \"Unexpected size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 50999, __extension__ __PRETTY_FUNCTION__))
;
51000 Cvt = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2f32, Cvt,
51001 DAG.getIntPtrConstant(0, dl));
51002 }
51003
51004 if (IsStrict) {
51005 // Extend to the original VT if necessary.
51006 if (Cvt.getValueType() != VT) {
51007 Cvt = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {VT, MVT::Other},
51008 {Chain, Cvt});
51009 Chain = Cvt.getValue(1);
51010 }
51011 return DAG.getMergeValues({Cvt, Chain}, dl);
51012 }
51013
51014 // Extend to the original VT if necessary.
51015 return DAG.getNode(ISD::FP_EXTEND, dl, VT, Cvt);
51016}
51017
51018// Try to find a larger VBROADCAST_LOAD/SUBV_BROADCAST_LOAD that we can extract
51019// from. Limit this to cases where the loads have the same input chain and the
51020// output chains are unused. This avoids any memory ordering issues.
51021static SDValue combineBROADCAST_LOAD(SDNode *N, SelectionDAG &DAG,
51022 TargetLowering::DAGCombinerInfo &DCI) {
51023 assert((N->getOpcode() == X86ISD::VBROADCAST_LOAD ||(static_cast <bool> ((N->getOpcode() == X86ISD::VBROADCAST_LOAD
|| N->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) &&
"Unknown broadcast load type") ? void (0) : __assert_fail ("(N->getOpcode() == X86ISD::VBROADCAST_LOAD || N->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) && \"Unknown broadcast load type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 51025, __extension__ __PRETTY_FUNCTION__))
51024 N->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) &&(static_cast <bool> ((N->getOpcode() == X86ISD::VBROADCAST_LOAD
|| N->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) &&
"Unknown broadcast load type") ? void (0) : __assert_fail ("(N->getOpcode() == X86ISD::VBROADCAST_LOAD || N->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) && \"Unknown broadcast load type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 51025, __extension__ __PRETTY_FUNCTION__))
51025 "Unknown broadcast load type")(static_cast <bool> ((N->getOpcode() == X86ISD::VBROADCAST_LOAD
|| N->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) &&
"Unknown broadcast load type") ? void (0) : __assert_fail ("(N->getOpcode() == X86ISD::VBROADCAST_LOAD || N->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) && \"Unknown broadcast load type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 51025, __extension__ __PRETTY_FUNCTION__))
;
51026
51027 // Only do this if the chain result is unused.
51028 if (N->hasAnyUseOfValue(1))
51029 return SDValue();
51030
51031 auto *MemIntrin = cast<MemIntrinsicSDNode>(N);
51032
51033 SDValue Ptr = MemIntrin->getBasePtr();
51034 SDValue Chain = MemIntrin->getChain();
51035 EVT VT = N->getSimpleValueType(0);
51036 EVT MemVT = MemIntrin->getMemoryVT();
51037
51038 // Look at other users of our base pointer and try to find a wider broadcast.
51039 // The input chain and the size of the memory VT must match.
51040 for (SDNode *User : Ptr->uses())
51041 if (User != N && User->getOpcode() == N->getOpcode() &&
51042 cast<MemIntrinsicSDNode>(User)->getBasePtr() == Ptr &&
51043 cast<MemIntrinsicSDNode>(User)->getChain() == Chain &&
51044 cast<MemIntrinsicSDNode>(User)->getMemoryVT().getSizeInBits() ==
51045 MemVT.getSizeInBits() &&
51046 !User->hasAnyUseOfValue(1) &&
51047 User->getValueSizeInBits(0).getFixedSize() > VT.getFixedSizeInBits()) {
51048 SDValue Extract = extractSubVector(SDValue(User, 0), 0, DAG, SDLoc(N),
51049 VT.getSizeInBits());
51050 Extract = DAG.getBitcast(VT, Extract);
51051 return DCI.CombineTo(N, Extract, SDValue(User, 1));
51052 }
51053
51054 return SDValue();
51055}
51056
51057static SDValue combineFP_ROUND(SDNode *N, SelectionDAG &DAG,
51058 const X86Subtarget &Subtarget) {
51059 if (!Subtarget.hasF16C() || Subtarget.useSoftFloat())
51060 return SDValue();
51061
51062 EVT VT = N->getValueType(0);
51063 SDValue Src = N->getOperand(0);
51064 EVT SrcVT = Src.getValueType();
51065
51066 if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
51067 SrcVT.getVectorElementType() != MVT::f32)
51068 return SDValue();
51069
51070 unsigned NumElts = VT.getVectorNumElements();
51071 if (NumElts == 1 || !isPowerOf2_32(NumElts))
51072 return SDValue();
51073
51074 SDLoc dl(N);
51075
51076 // Widen to at least 4 input elements.
51077 if (NumElts < 4)
51078 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
51079 DAG.getConstantFP(0.0, dl, SrcVT));
51080
51081 // Destination is v8i16 with at least 8 elements.
51082 EVT CvtVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
51083 std::max(8U, NumElts));
51084 SDValue Cvt = DAG.getNode(X86ISD::CVTPS2PH, dl, CvtVT, Src,
51085 DAG.getTargetConstant(4, dl, MVT::i32));
51086
51087 // Extract down to real number of elements.
51088 if (NumElts < 8) {
51089 EVT IntVT = VT.changeVectorElementTypeToInteger();
51090 Cvt = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, IntVT, Cvt,
51091 DAG.getIntPtrConstant(0, dl));
51092 }
51093
51094 return DAG.getBitcast(VT, Cvt);
51095}
51096
51097static SDValue combineMOVDQ2Q(SDNode *N, SelectionDAG &DAG) {
51098 SDValue Src = N->getOperand(0);
51099
51100 // Turn MOVDQ2Q+simple_load into an mmx load.
51101 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
51102 LoadSDNode *LN = cast<LoadSDNode>(Src.getNode());
51103
51104 if (LN->isSimple()) {
51105 SDValue NewLd = DAG.getLoad(MVT::x86mmx, SDLoc(N), LN->getChain(),
51106 LN->getBasePtr(),
51107 LN->getPointerInfo(),
51108 LN->getOriginalAlign(),
51109 LN->getMemOperand()->getFlags());
51110 DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), NewLd.getValue(1));
51111 return NewLd;
51112 }
51113 }
51114
51115 return SDValue();
51116}
51117
51118static SDValue combinePDEP(SDNode *N, SelectionDAG &DAG,
51119 TargetLowering::DAGCombinerInfo &DCI) {
51120 unsigned NumBits = N->getSimpleValueType(0).getSizeInBits();
51121 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
51122 if (TLI.SimplifyDemandedBits(SDValue(N, 0),
51123 APInt::getAllOnesValue(NumBits), DCI))
51124 return SDValue(N, 0);
51125
51126 return SDValue();
51127}
51128
51129SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
51130 DAGCombinerInfo &DCI) const {
51131 SelectionDAG &DAG = DCI.DAG;
51132 switch (N->getOpcode()) {
51133 default: break;
51134 case ISD::SCALAR_TO_VECTOR:
51135 return combineScalarToVector(N, DAG);
51136 case ISD::EXTRACT_VECTOR_ELT:
51137 case X86ISD::PEXTRW:
51138 case X86ISD::PEXTRB:
51139 return combineExtractVectorElt(N, DAG, DCI, Subtarget);
51140 case ISD::CONCAT_VECTORS:
51141 return combineConcatVectors(N, DAG, DCI, Subtarget);
51142 case ISD::INSERT_SUBVECTOR:
51143 return combineInsertSubvector(N, DAG, DCI, Subtarget);
51144 case ISD::EXTRACT_SUBVECTOR:
51145 return combineExtractSubvector(N, DAG, DCI, Subtarget);
51146 case ISD::VSELECT:
51147 case ISD::SELECT:
51148 case X86ISD::BLENDV: return combineSelect(N, DAG, DCI, Subtarget);
51149 case ISD::BITCAST: return combineBitcast(N, DAG, DCI, Subtarget);
51150 case X86ISD::CMOV: return combineCMov(N, DAG, DCI, Subtarget);
51151 case X86ISD::CMP: return combineCMP(N, DAG);
51152 case ISD::ADD: return combineAdd(N, DAG, DCI, Subtarget);
51153 case ISD::SUB: return combineSub(N, DAG, DCI, Subtarget);
51154 case X86ISD::ADD:
51155 case X86ISD::SUB: return combineX86AddSub(N, DAG, DCI);
51156 case X86ISD::SBB: return combineSBB(N, DAG);
51157 case X86ISD::ADC: return combineADC(N, DAG, DCI);
51158 case ISD::MUL: return combineMul(N, DAG, DCI, Subtarget);
51159 case ISD::SHL: return combineShiftLeft(N, DAG);
51160 case ISD::SRA: return combineShiftRightArithmetic(N, DAG, Subtarget);
51161 case ISD::SRL: return combineShiftRightLogical(N, DAG, DCI, Subtarget);
51162 case ISD::AND: return combineAnd(N, DAG, DCI, Subtarget);
51163 case ISD::OR: return combineOr(N, DAG, DCI, Subtarget);
51164 case ISD::XOR: return combineXor(N, DAG, DCI, Subtarget);
51165 case X86ISD::BEXTR:
51166 case X86ISD::BEXTRI: return combineBEXTR(N, DAG, DCI, Subtarget);
51167 case ISD::LOAD: return combineLoad(N, DAG, DCI, Subtarget);
51168 case ISD::MLOAD: return combineMaskedLoad(N, DAG, DCI, Subtarget);
51169 case ISD::STORE: return combineStore(N, DAG, DCI, Subtarget);
51170 case ISD::MSTORE: return combineMaskedStore(N, DAG, DCI, Subtarget);
51171 case X86ISD::VEXTRACT_STORE:
51172 return combineVEXTRACT_STORE(N, DAG, DCI, Subtarget);
51173 case ISD::SINT_TO_FP:
51174 case ISD::STRICT_SINT_TO_FP:
51175 return combineSIntToFP(N, DAG, DCI, Subtarget);
51176 case ISD::UINT_TO_FP:
51177 case ISD::STRICT_UINT_TO_FP:
51178 return combineUIntToFP(N, DAG, Subtarget);
51179 case ISD::FADD:
51180 case ISD::FSUB: return combineFaddFsub(N, DAG, Subtarget);
51181 case ISD::FNEG: return combineFneg(N, DAG, DCI, Subtarget);
51182 case ISD::TRUNCATE: return combineTruncate(N, DAG, Subtarget);
51183 case X86ISD::VTRUNC: return combineVTRUNC(N, DAG, DCI);
51184 case X86ISD::ANDNP: return combineAndnp(N, DAG, DCI, Subtarget);
51185 case X86ISD::FAND: return combineFAnd(N, DAG, Subtarget);
51186 case X86ISD::FANDN: return combineFAndn(N, DAG, Subtarget);
51187 case X86ISD::FXOR:
51188 case X86ISD::FOR: return combineFOr(N, DAG, DCI, Subtarget);
51189 case X86ISD::FMIN:
51190 case X86ISD::FMAX: return combineFMinFMax(N, DAG);
51191 case ISD::FMINNUM:
51192 case ISD::FMAXNUM: return combineFMinNumFMaxNum(N, DAG, Subtarget);
51193 case X86ISD::CVTSI2P:
51194 case X86ISD::CVTUI2P: return combineX86INT_TO_FP(N, DAG, DCI);
51195 case X86ISD::CVTP2SI:
51196 case X86ISD::CVTP2UI:
51197 case X86ISD::STRICT_CVTTP2SI:
51198 case X86ISD::CVTTP2SI:
51199 case X86ISD::STRICT_CVTTP2UI:
51200 case X86ISD::CVTTP2UI:
51201 return combineCVTP2I_CVTTP2I(N, DAG, DCI);
51202 case X86ISD::STRICT_CVTPH2PS:
51203 case X86ISD::CVTPH2PS: return combineCVTPH2PS(N, DAG, DCI);
51204 case X86ISD::BT: return combineBT(N, DAG, DCI);
51205 case ISD::ANY_EXTEND:
51206 case ISD::ZERO_EXTEND: return combineZext(N, DAG, DCI, Subtarget);
51207 case ISD::SIGN_EXTEND: return combineSext(N, DAG, DCI, Subtarget);
51208 case ISD::SIGN_EXTEND_INREG: return combineSignExtendInReg(N, DAG, Subtarget);
51209 case ISD::ANY_EXTEND_VECTOR_INREG:
51210 case ISD::SIGN_EXTEND_VECTOR_INREG:
51211 case ISD::ZERO_EXTEND_VECTOR_INREG:
51212 return combineEXTEND_VECTOR_INREG(N, DAG, DCI, Subtarget);
51213 case ISD::SETCC: return combineSetCC(N, DAG, DCI, Subtarget);
51214 case X86ISD::SETCC: return combineX86SetCC(N, DAG, Subtarget);
51215 case X86ISD::BRCOND: return combineBrCond(N, DAG, Subtarget);
51216 case X86ISD::PACKSS:
51217 case X86ISD::PACKUS: return combineVectorPack(N, DAG, DCI, Subtarget);
51218 case X86ISD::HADD:
51219 case X86ISD::HSUB:
51220 case X86ISD::FHADD:
51221 case X86ISD::FHSUB: return combineVectorHADDSUB(N, DAG, DCI, Subtarget);
51222 case X86ISD::VSHL:
51223 case X86ISD::VSRA:
51224 case X86ISD::VSRL:
51225 return combineVectorShiftVar(N, DAG, DCI, Subtarget);
51226 case X86ISD::VSHLI:
51227 case X86ISD::VSRAI:
51228 case X86ISD::VSRLI:
51229 return combineVectorShiftImm(N, DAG, DCI, Subtarget);
51230 case ISD::INSERT_VECTOR_ELT:
51231 case X86ISD::PINSRB:
51232 case X86ISD::PINSRW: return combineVectorInsert(N, DAG, DCI, Subtarget);
51233 case X86ISD::SHUFP: // Handle all target specific shuffles
51234 case X86ISD::INSERTPS:
51235 case X86ISD::EXTRQI:
51236 case X86ISD::INSERTQI:
51237 case X86ISD::VALIGN:
51238 case X86ISD::PALIGNR:
51239 case X86ISD::VSHLDQ:
51240 case X86ISD::VSRLDQ:
51241 case X86ISD::BLENDI:
51242 case X86ISD::UNPCKH:
51243 case X86ISD::UNPCKL:
51244 case X86ISD::MOVHLPS:
51245 case X86ISD::MOVLHPS:
51246 case X86ISD::PSHUFB:
51247 case X86ISD::PSHUFD:
51248 case X86ISD::PSHUFHW:
51249 case X86ISD::PSHUFLW:
51250 case X86ISD::MOVSHDUP:
51251 case X86ISD::MOVSLDUP:
51252 case X86ISD::MOVDDUP:
51253 case X86ISD::MOVSS:
51254 case X86ISD::MOVSD:
51255 case X86ISD::VBROADCAST:
51256 case X86ISD::VPPERM:
51257 case X86ISD::VPERMI:
51258 case X86ISD::VPERMV:
51259 case X86ISD::VPERMV3:
51260 case X86ISD::VPERMIL2:
51261 case X86ISD::VPERMILPI:
51262 case X86ISD::VPERMILPV:
51263 case X86ISD::VPERM2X128:
51264 case X86ISD::SHUF128:
51265 case X86ISD::VZEXT_MOVL:
51266 case ISD::VECTOR_SHUFFLE: return combineShuffle(N, DAG, DCI,Subtarget);
51267 case X86ISD::FMADD_RND:
51268 case X86ISD::FMSUB:
51269 case X86ISD::STRICT_FMSUB:
51270 case X86ISD::FMSUB_RND:
51271 case X86ISD::FNMADD:
51272 case X86ISD::STRICT_FNMADD:
51273 case X86ISD::FNMADD_RND:
51274 case X86ISD::FNMSUB:
51275 case X86ISD::STRICT_FNMSUB:
51276 case X86ISD::FNMSUB_RND:
51277 case ISD::FMA:
51278 case ISD::STRICT_FMA: return combineFMA(N, DAG, DCI, Subtarget);
51279 case X86ISD::FMADDSUB_RND:
51280 case X86ISD::FMSUBADD_RND:
51281 case X86ISD::FMADDSUB:
51282 case X86ISD::FMSUBADD: return combineFMADDSUB(N, DAG, DCI);
51283 case X86ISD::MOVMSK: return combineMOVMSK(N, DAG, DCI, Subtarget);
51284 case X86ISD::MGATHER:
51285 case X86ISD::MSCATTER: return combineX86GatherScatter(N, DAG, DCI);
51286 case ISD::MGATHER:
51287 case ISD::MSCATTER: return combineGatherScatter(N, DAG, DCI);
51288 case X86ISD::PCMPEQ:
51289 case X86ISD::PCMPGT: return combineVectorCompare(N, DAG, Subtarget);
51290 case X86ISD::PMULDQ:
51291 case X86ISD::PMULUDQ: return combinePMULDQ(N, DAG, DCI, Subtarget);
51292 case X86ISD::KSHIFTL:
51293 case X86ISD::KSHIFTR: return combineKSHIFT(N, DAG, DCI);
51294 case ISD::FP16_TO_FP: return combineFP16_TO_FP(N, DAG, Subtarget);
51295 case ISD::STRICT_FP_EXTEND:
51296 case ISD::FP_EXTEND: return combineFP_EXTEND(N, DAG, Subtarget);
51297 case ISD::FP_ROUND: return combineFP_ROUND(N, DAG, Subtarget);
51298 case X86ISD::VBROADCAST_LOAD:
51299 case X86ISD::SUBV_BROADCAST_LOAD: return combineBROADCAST_LOAD(N, DAG, DCI);
51300 case X86ISD::MOVDQ2Q: return combineMOVDQ2Q(N, DAG);
51301 case X86ISD::PDEP: return combinePDEP(N, DAG, DCI);
51302 }
51303
51304 return SDValue();
51305}
51306
51307bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
51308 if (!isTypeLegal(VT))
51309 return false;
51310
51311 // There are no vXi8 shifts.
51312 if (Opc == ISD::SHL && VT.isVector() && VT.getVectorElementType() == MVT::i8)
51313 return false;
51314
51315 // TODO: Almost no 8-bit ops are desirable because they have no actual
51316 // size/speed advantages vs. 32-bit ops, but they do have a major
51317 // potential disadvantage by causing partial register stalls.
51318 //
51319 // 8-bit multiply/shl is probably not cheaper than 32-bit multiply/shl, and
51320 // we have specializations to turn 32-bit multiply/shl into LEA or other ops.
51321 // Also, see the comment in "IsDesirableToPromoteOp" - where we additionally
51322 // check for a constant operand to the multiply.
51323 if ((Opc == ISD::MUL || Opc == ISD::SHL) && VT == MVT::i8)
51324 return false;
51325
51326 // i16 instruction encodings are longer and some i16 instructions are slow,
51327 // so those are not desirable.
51328 if (VT == MVT::i16) {
51329 switch (Opc) {
51330 default:
51331 break;
51332 case ISD::LOAD:
51333 case ISD::SIGN_EXTEND:
51334 case ISD::ZERO_EXTEND:
51335 case ISD::ANY_EXTEND:
51336 case ISD::SHL:
51337 case ISD::SRA:
51338 case ISD::SRL:
51339 case ISD::SUB:
51340 case ISD::ADD:
51341 case ISD::MUL:
51342 case ISD::AND:
51343 case ISD::OR:
51344 case ISD::XOR:
51345 return false;
51346 }
51347 }
51348
51349 // Any legal type not explicitly accounted for above here is desirable.
51350 return true;
51351}
51352
51353SDValue X86TargetLowering::expandIndirectJTBranch(const SDLoc& dl,
51354 SDValue Value, SDValue Addr,
51355 SelectionDAG &DAG) const {
51356 const Module *M = DAG.getMachineFunction().getMMI().getModule();
51357 Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
51358 if (IsCFProtectionSupported) {
51359 // In case control-flow branch protection is enabled, we need to add
51360 // notrack prefix to the indirect branch.
51361 // In order to do that we create NT_BRIND SDNode.
51362 // Upon ISEL, the pattern will convert it to jmp with NoTrack prefix.
51363 return DAG.getNode(X86ISD::NT_BRIND, dl, MVT::Other, Value, Addr);
51364 }
51365
51366 return TargetLowering::expandIndirectJTBranch(dl, Value, Addr, DAG);
51367}
51368
51369bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
51370 EVT VT = Op.getValueType();
51371 bool Is8BitMulByConstant = VT == MVT::i8 && Op.getOpcode() == ISD::MUL &&
51372 isa<ConstantSDNode>(Op.getOperand(1));
51373
51374 // i16 is legal, but undesirable since i16 instruction encodings are longer
51375 // and some i16 instructions are slow.
51376 // 8-bit multiply-by-constant can usually be expanded to something cheaper
51377 // using LEA and/or other ALU ops.
51378 if (VT != MVT::i16 && !Is8BitMulByConstant)
51379 return false;
51380
51381 auto IsFoldableRMW = [](SDValue Load, SDValue Op) {
51382 if (!Op.hasOneUse())
51383 return false;
51384 SDNode *User = *Op->use_begin();
51385 if (!ISD::isNormalStore(User))
51386 return false;
51387 auto *Ld = cast<LoadSDNode>(Load);
51388 auto *St = cast<StoreSDNode>(User);
51389 return Ld->getBasePtr() == St->getBasePtr();
51390 };
51391
51392 auto IsFoldableAtomicRMW = [](SDValue Load, SDValue Op) {
51393 if (!Load.hasOneUse() || Load.getOpcode() != ISD::ATOMIC_LOAD)
51394 return false;
51395 if (!Op.hasOneUse())
51396 return false;
51397 SDNode *User = *Op->use_begin();
51398 if (User->getOpcode() != ISD::ATOMIC_STORE)
51399 return false;
51400 auto *Ld = cast<AtomicSDNode>(Load);
51401 auto *St = cast<AtomicSDNode>(User);
51402 return Ld->getBasePtr() == St->getBasePtr();
51403 };
51404
51405 bool Commute = false;
51406 switch (Op.getOpcode()) {
51407 default: return false;
51408 case ISD::SIGN_EXTEND:
51409 case ISD::ZERO_EXTEND:
51410 case ISD::ANY_EXTEND:
51411 break;
51412 case ISD::SHL:
51413 case ISD::SRA:
51414 case ISD::SRL: {
51415 SDValue N0 = Op.getOperand(0);
51416 // Look out for (store (shl (load), x)).
51417 if (MayFoldLoad(N0) && IsFoldableRMW(N0, Op))
51418 return false;
51419 break;
51420 }
51421 case ISD::ADD:
51422 case ISD::MUL:
51423 case ISD::AND:
51424 case ISD::OR:
51425 case ISD::XOR:
51426 Commute = true;
51427 LLVM_FALLTHROUGH[[gnu::fallthrough]];
51428 case ISD::SUB: {
51429 SDValue N0 = Op.getOperand(0);
51430 SDValue N1 = Op.getOperand(1);
51431 // Avoid disabling potential load folding opportunities.
51432 if (MayFoldLoad(N1) &&
51433 (!Commute || !isa<ConstantSDNode>(N0) ||
51434 (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N1, Op))))
51435 return false;
51436 if (MayFoldLoad(N0) &&
51437 ((Commute && !isa<ConstantSDNode>(N1)) ||
51438 (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N0, Op))))
51439 return false;
51440 if (IsFoldableAtomicRMW(N0, Op) ||
51441 (Commute && IsFoldableAtomicRMW(N1, Op)))
51442 return false;
51443 }
51444 }
51445
51446 PVT = MVT::i32;
51447 return true;
51448}
51449
51450//===----------------------------------------------------------------------===//
51451// X86 Inline Assembly Support
51452//===----------------------------------------------------------------------===//
51453
51454// Helper to match a string separated by whitespace.
51455static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
51456 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
51457
51458 for (StringRef Piece : Pieces) {
51459 if (!S.startswith(Piece)) // Check if the piece matches.
51460 return false;
51461
51462 S = S.substr(Piece.size());
51463 StringRef::size_type Pos = S.find_first_not_of(" \t");
51464 if (Pos == 0) // We matched a prefix.
51465 return false;
51466
51467 S = S.substr(Pos);
51468 }
51469
51470 return S.empty();
51471}
51472
51473static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
51474
51475 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
51476 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
51477 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
51478 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
51479
51480 if (AsmPieces.size() == 3)
51481 return true;
51482 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
51483 return true;
51484 }
51485 }
51486 return false;
51487}
51488
51489bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
51490 InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand());
51491
51492 const std::string &AsmStr = IA->getAsmString();
51493
51494 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
51495 if (!Ty || Ty->getBitWidth() % 16 != 0)
51496 return false;
51497
51498 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
51499 SmallVector<StringRef, 4> AsmPieces;
51500 SplitString(AsmStr, AsmPieces, ";\n");
51501
51502 switch (AsmPieces.size()) {
51503 default: return false;
51504 case 1:
51505 // FIXME: this should verify that we are targeting a 486 or better. If not,
51506 // we will turn this bswap into something that will be lowered to logical
51507 // ops instead of emitting the bswap asm. For now, we don't support 486 or
51508 // lower so don't worry about this.
51509 // bswap $0
51510 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
51511 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
51512 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
51513 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
51514 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
51515 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
51516 // No need to check constraints, nothing other than the equivalent of
51517 // "=r,0" would be valid here.
51518 return IntrinsicLowering::LowerToByteSwap(CI);
51519 }
51520
51521 // rorw $$8, ${0:w} --> llvm.bswap.i16
51522 if (CI->getType()->isIntegerTy(16) &&
51523 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
51524 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
51525 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
51526 AsmPieces.clear();
51527 StringRef ConstraintsStr = IA->getConstraintString();
51528 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
51529 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
51530 if (clobbersFlagRegisters(AsmPieces))
51531 return IntrinsicLowering::LowerToByteSwap(CI);
51532 }
51533 break;
51534 case 3:
51535 if (CI->getType()->isIntegerTy(32) &&
51536 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
51537 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
51538 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
51539 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
51540 AsmPieces.clear();
51541 StringRef ConstraintsStr = IA->getConstraintString();
51542 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
51543 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
51544 if (clobbersFlagRegisters(AsmPieces))
51545 return IntrinsicLowering::LowerToByteSwap(CI);
51546 }
51547
51548 if (CI->getType()->isIntegerTy(64)) {
51549 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
51550 if (Constraints.size() >= 2 &&
51551 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
51552 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
51553 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
51554 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
51555 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
51556 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
51557 return IntrinsicLowering::LowerToByteSwap(CI);
51558 }
51559 }
51560 break;
51561 }
51562 return false;
51563}
51564
51565static X86::CondCode parseConstraintCode(llvm::StringRef Constraint) {
51566 X86::CondCode Cond = StringSwitch<X86::CondCode>(Constraint)
51567 .Case("{@cca}", X86::COND_A)
51568 .Case("{@ccae}", X86::COND_AE)
51569 .Case("{@ccb}", X86::COND_B)
51570 .Case("{@ccbe}", X86::COND_BE)
51571 .Case("{@ccc}", X86::COND_B)
51572 .Case("{@cce}", X86::COND_E)
51573 .Case("{@ccz}", X86::COND_E)
51574 .Case("{@ccg}", X86::COND_G)
51575 .Case("{@ccge}", X86::COND_GE)
51576 .Case("{@ccl}", X86::COND_L)
51577 .Case("{@ccle}", X86::COND_LE)
51578 .Case("{@ccna}", X86::COND_BE)
51579 .Case("{@ccnae}", X86::COND_B)
51580 .Case("{@ccnb}", X86::COND_AE)
51581 .Case("{@ccnbe}", X86::COND_A)
51582 .Case("{@ccnc}", X86::COND_AE)
51583 .Case("{@ccne}", X86::COND_NE)
51584 .Case("{@ccnz}", X86::COND_NE)
51585 .Case("{@ccng}", X86::COND_LE)
51586 .Case("{@ccnge}", X86::COND_L)
51587 .Case("{@ccnl}", X86::COND_GE)
51588 .Case("{@ccnle}", X86::COND_G)
51589 .Case("{@ccno}", X86::COND_NO)
51590 .Case("{@ccnp}", X86::COND_NP)
51591 .Case("{@ccns}", X86::COND_NS)
51592 .Case("{@cco}", X86::COND_O)
51593 .Case("{@ccp}", X86::COND_P)
51594 .Case("{@ccs}", X86::COND_S)
51595 .Default(X86::COND_INVALID);
51596 return Cond;
51597}
51598
51599/// Given a constraint letter, return the type of constraint for this target.
51600X86TargetLowering::ConstraintType
51601X86TargetLowering::getConstraintType(StringRef Constraint) const {
51602 if (Constraint.size() == 1) {
51603 switch (Constraint[0]) {
51604 case 'R':
51605 case 'q':
51606 case 'Q':
51607 case 'f':
51608 case 't':
51609 case 'u':
51610 case 'y':
51611 case 'x':
51612 case 'v':
51613 case 'l':
51614 case 'k': // AVX512 masking registers.
51615 return C_RegisterClass;
51616 case 'a':
51617 case 'b':
51618 case 'c':
51619 case 'd':
51620 case 'S':
51621 case 'D':
51622 case 'A':
51623 return C_Register;
51624 case 'I':
51625 case 'J':
51626 case 'K':
51627 case 'N':
51628 case 'G':
51629 case 'L':
51630 case 'M':
51631 return C_Immediate;
51632 case 'C':
51633 case 'e':
51634 case 'Z':
51635 return C_Other;
51636 default:
51637 break;
51638 }
51639 }
51640 else if (Constraint.size() == 2) {
51641 switch (Constraint[0]) {
51642 default:
51643 break;
51644 case 'Y':
51645 switch (Constraint[1]) {
51646 default:
51647 break;
51648 case 'z':
51649 return C_Register;
51650 case 'i':
51651 case 'm':
51652 case 'k':
51653 case 't':
51654 case '2':
51655 return C_RegisterClass;
51656 }
51657 }
51658 } else if (parseConstraintCode(Constraint) != X86::COND_INVALID)
51659 return C_Other;
51660 return TargetLowering::getConstraintType(Constraint);
51661}
51662
51663/// Examine constraint type and operand type and determine a weight value.
51664/// This object must already have been set up with the operand type
51665/// and the current alternative constraint selected.
51666TargetLowering::ConstraintWeight
51667 X86TargetLowering::getSingleConstraintMatchWeight(
51668 AsmOperandInfo &info, const char *constraint) const {
51669 ConstraintWeight weight = CW_Invalid;
51670 Value *CallOperandVal = info.CallOperandVal;
51671 // If we don't have a value, we can't do a match,
51672 // but allow it at the lowest weight.
51673 if (!CallOperandVal)
51674 return CW_Default;
51675 Type *type = CallOperandVal->getType();
51676 // Look at the constraint type.
51677 switch (*constraint) {
51678 default:
51679 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
51680 LLVM_FALLTHROUGH[[gnu::fallthrough]];
51681 case 'R':
51682 case 'q':
51683 case 'Q':
51684 case 'a':
51685 case 'b':
51686 case 'c':
51687 case 'd':
51688 case 'S':
51689 case 'D':
51690 case 'A':
51691 if (CallOperandVal->getType()->isIntegerTy())
51692 weight = CW_SpecificReg;
51693 break;
51694 case 'f':
51695 case 't':
51696 case 'u':
51697 if (type->isFloatingPointTy())
51698 weight = CW_SpecificReg;
51699 break;
51700 case 'y':
51701 if (type->isX86_MMXTy() && Subtarget.hasMMX())
51702 weight = CW_SpecificReg;
51703 break;
51704 case 'Y':
51705 if (StringRef(constraint).size() != 2)
51706 break;
51707 switch (constraint[1]) {
51708 default:
51709 return CW_Invalid;
51710 // XMM0
51711 case 'z':
51712 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1()) ||
51713 ((type->getPrimitiveSizeInBits() == 256) && Subtarget.hasAVX()) ||
51714 ((type->getPrimitiveSizeInBits() == 512) && Subtarget.hasAVX512()))
51715 return CW_SpecificReg;
51716 return CW_Invalid;
51717 // Conditional OpMask regs (AVX512)
51718 case 'k':
51719 if ((type->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
51720 return CW_Register;
51721 return CW_Invalid;
51722 // Any MMX reg
51723 case 'm':
51724 if (type->isX86_MMXTy() && Subtarget.hasMMX())
51725 return weight;
51726 return CW_Invalid;
51727 // Any SSE reg when ISA >= SSE2, same as 'x'
51728 case 'i':
51729 case 't':
51730 case '2':
51731 if (!Subtarget.hasSSE2())
51732 return CW_Invalid;
51733 break;
51734 }
51735 break;
51736 case 'v':
51737 if ((type->getPrimitiveSizeInBits() == 512) && Subtarget.hasAVX512())
51738 weight = CW_Register;
51739 LLVM_FALLTHROUGH[[gnu::fallthrough]];
51740 case 'x':
51741 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1()) ||
51742 ((type->getPrimitiveSizeInBits() == 256) && Subtarget.hasAVX()))
51743 weight = CW_Register;
51744 break;
51745 case 'k':
51746 // Enable conditional vector operations using %k<#> registers.
51747 if ((type->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
51748 weight = CW_Register;
51749 break;
51750 case 'I':
51751 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
51752 if (C->getZExtValue() <= 31)
51753 weight = CW_Constant;
51754 }
51755 break;
51756 case 'J':
51757 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
51758 if (C->getZExtValue() <= 63)
51759 weight = CW_Constant;
51760 }
51761 break;
51762 case 'K':
51763 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
51764 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
51765 weight = CW_Constant;
51766 }
51767 break;
51768 case 'L':
51769 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
51770 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
51771 weight = CW_Constant;
51772 }
51773 break;
51774 case 'M':
51775 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
51776 if (C->getZExtValue() <= 3)
51777 weight = CW_Constant;
51778 }
51779 break;
51780 case 'N':
51781 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
51782 if (C->getZExtValue() <= 0xff)
51783 weight = CW_Constant;
51784 }
51785 break;
51786 case 'G':
51787 case 'C':
51788 if (isa<ConstantFP>(CallOperandVal)) {
51789 weight = CW_Constant;
51790 }
51791 break;
51792 case 'e':
51793 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
51794 if ((C->getSExtValue() >= -0x80000000LL) &&
51795 (C->getSExtValue() <= 0x7fffffffLL))
51796 weight = CW_Constant;
51797 }
51798 break;
51799 case 'Z':
51800 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
51801 if (C->getZExtValue() <= 0xffffffff)
51802 weight = CW_Constant;
51803 }
51804 break;
51805 }
51806 return weight;
51807}
51808
51809/// Try to replace an X constraint, which matches anything, with another that
51810/// has more specific requirements based on the type of the corresponding
51811/// operand.
51812const char *X86TargetLowering::
51813LowerXConstraint(EVT ConstraintVT) const {
51814 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
51815 // 'f' like normal targets.
51816 if (ConstraintVT.isFloatingPoint()) {
51817 if (Subtarget.hasSSE1())
51818 return "x";
51819 }
51820
51821 return TargetLowering::LowerXConstraint(ConstraintVT);
51822}
51823
51824// Lower @cc targets via setcc.
51825SDValue X86TargetLowering::LowerAsmOutputForConstraint(
51826 SDValue &Chain, SDValue &Flag, const SDLoc &DL,
51827 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
51828 X86::CondCode Cond = parseConstraintCode(OpInfo.ConstraintCode);
51829 if (Cond == X86::COND_INVALID)
51830 return SDValue();
51831 // Check that return type is valid.
51832 if (OpInfo.ConstraintVT.isVector() || !OpInfo.ConstraintVT.isInteger() ||
51833 OpInfo.ConstraintVT.getSizeInBits() < 8)
51834 report_fatal_error("Flag output operand is of invalid type");
51835
51836 // Get EFLAGS register. Only update chain when copyfrom is glued.
51837 if (Flag.getNode()) {
51838 Flag = DAG.getCopyFromReg(Chain, DL, X86::EFLAGS, MVT::i32, Flag);
51839 Chain = Flag.getValue(1);
51840 } else
51841 Flag = DAG.getCopyFromReg(Chain, DL, X86::EFLAGS, MVT::i32);
51842 // Extract CC code.
51843 SDValue CC = getSETCC(Cond, Flag, DL, DAG);
51844 // Extend to 32-bits
51845 SDValue Result = DAG.getNode(ISD::ZERO_EXTEND, DL, OpInfo.ConstraintVT, CC);
51846
51847 return Result;
51848}
51849
51850/// Lower the specified operand into the Ops vector.
51851/// If it is invalid, don't add anything to Ops.
51852void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
51853 std::string &Constraint,
51854 std::vector<SDValue>&Ops,
51855 SelectionDAG &DAG) const {
51856 SDValue Result;
51857
51858 // Only support length 1 constraints for now.
51859 if (Constraint.length() > 1) return;
51860
51861 char ConstraintLetter = Constraint[0];
51862 switch (ConstraintLetter) {
51863 default: break;
51864 case 'I':
51865 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
51866 if (C->getZExtValue() <= 31) {
51867 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
51868 Op.getValueType());
51869 break;
51870 }
51871 }
51872 return;
51873 case 'J':
51874 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
51875 if (C->getZExtValue() <= 63) {
51876 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
51877 Op.getValueType());
51878 break;
51879 }
51880 }
51881 return;
51882 case 'K':
51883 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
51884 if (isInt<8>(C->getSExtValue())) {
51885 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
51886 Op.getValueType());
51887 break;
51888 }
51889 }
51890 return;
51891 case 'L':
51892 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
51893 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
51894 (Subtarget.is64Bit() && C->getZExtValue() == 0xffffffff)) {
51895 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
51896 Op.getValueType());
51897 break;
51898 }
51899 }
51900 return;
51901 case 'M':
51902 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
51903 if (C->getZExtValue() <= 3) {
51904 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
51905 Op.getValueType());
51906 break;
51907 }
51908 }
51909 return;
51910 case 'N':
51911 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
51912 if (C->getZExtValue() <= 255) {
51913 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
51914 Op.getValueType());
51915 break;
51916 }
51917 }
51918 return;
51919 case 'O':
51920 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
51921 if (C->getZExtValue() <= 127) {
51922 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
51923 Op.getValueType());
51924 break;
51925 }
51926 }
51927 return;
51928 case 'e': {
51929 // 32-bit signed value
51930 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
51931 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
51932 C->getSExtValue())) {
51933 // Widen to 64 bits here to get it sign extended.
51934 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
51935 break;
51936 }
51937 // FIXME gcc accepts some relocatable values here too, but only in certain
51938 // memory models; it's complicated.
51939 }
51940 return;
51941 }
51942 case 'Z': {
51943 // 32-bit unsigned value
51944 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
51945 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
51946 C->getZExtValue())) {
51947 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
51948 Op.getValueType());
51949 break;
51950 }
51951 }
51952 // FIXME gcc accepts some relocatable values here too, but only in certain
51953 // memory models; it's complicated.
51954 return;
51955 }
51956 case 'i': {
51957 // Literal immediates are always ok.
51958 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
51959 bool IsBool = CST->getConstantIntValue()->getBitWidth() == 1;
51960 BooleanContent BCont = getBooleanContents(MVT::i64);
51961 ISD::NodeType ExtOpc = IsBool ? getExtendForContent(BCont)
51962 : ISD::SIGN_EXTEND;
51963 int64_t ExtVal = ExtOpc == ISD::ZERO_EXTEND ? CST->getZExtValue()
51964 : CST->getSExtValue();
51965 Result = DAG.getTargetConstant(ExtVal, SDLoc(Op), MVT::i64);
51966 break;
51967 }
51968
51969 // In any sort of PIC mode addresses need to be computed at runtime by
51970 // adding in a register or some sort of table lookup. These can't
51971 // be used as immediates.
51972 if (Subtarget.isPICStyleGOT() || Subtarget.isPICStyleStubPIC())
51973 return;
51974
51975 // If we are in non-pic codegen mode, we allow the address of a global (with
51976 // an optional displacement) to be used with 'i'.
51977 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op))
51978 // If we require an extra load to get this address, as in PIC mode, we
51979 // can't accept it.
51980 if (isGlobalStubReference(
51981 Subtarget.classifyGlobalReference(GA->getGlobal())))
51982 return;
51983 break;
51984 }
51985 }
51986
51987 if (Result.getNode()) {
51988 Ops.push_back(Result);
51989 return;
51990 }
51991 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
51992}
51993
51994/// Check if \p RC is a general purpose register class.
51995/// I.e., GR* or one of their variant.
51996static bool isGRClass(const TargetRegisterClass &RC) {
51997 return RC.hasSuperClassEq(&X86::GR8RegClass) ||
51998 RC.hasSuperClassEq(&X86::GR16RegClass) ||
51999 RC.hasSuperClassEq(&X86::GR32RegClass) ||
52000 RC.hasSuperClassEq(&X86::GR64RegClass) ||
52001 RC.hasSuperClassEq(&X86::LOW32_ADDR_ACCESS_RBPRegClass);
52002}
52003
52004/// Check if \p RC is a vector register class.
52005/// I.e., FR* / VR* or one of their variant.
52006static bool isFRClass(const TargetRegisterClass &RC) {
52007 return RC.hasSuperClassEq(&X86::FR32XRegClass) ||
52008 RC.hasSuperClassEq(&X86::FR64XRegClass) ||
52009 RC.hasSuperClassEq(&X86::VR128XRegClass) ||
52010 RC.hasSuperClassEq(&X86::VR256XRegClass) ||
52011 RC.hasSuperClassEq(&X86::VR512RegClass);
52012}
52013
52014/// Check if \p RC is a mask register class.
52015/// I.e., VK* or one of their variant.
52016static bool isVKClass(const TargetRegisterClass &RC) {
52017 return RC.hasSuperClassEq(&X86::VK1RegClass) ||
52018 RC.hasSuperClassEq(&X86::VK2RegClass) ||
52019 RC.hasSuperClassEq(&X86::VK4RegClass) ||
52020 RC.hasSuperClassEq(&X86::VK8RegClass) ||
52021 RC.hasSuperClassEq(&X86::VK16RegClass) ||
52022 RC.hasSuperClassEq(&X86::VK32RegClass) ||
52023 RC.hasSuperClassEq(&X86::VK64RegClass);
52024}
52025
52026std::pair<unsigned, const TargetRegisterClass *>
52027X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
52028 StringRef Constraint,
52029 MVT VT) const {
52030 // First, see if this is a constraint that directly corresponds to an LLVM
52031 // register class.
52032 if (Constraint.size() == 1) {
52033 // GCC Constraint Letters
52034 switch (Constraint[0]) {
52035 default: break;
52036 // 'A' means [ER]AX + [ER]DX.
52037 case 'A':
52038 if (Subtarget.is64Bit())
52039 return std::make_pair(X86::RAX, &X86::GR64_ADRegClass);
52040 assert((Subtarget.is32Bit() || Subtarget.is16Bit()) &&(static_cast <bool> ((Subtarget.is32Bit() || Subtarget.
is16Bit()) && "Expecting 64, 32 or 16 bit subtarget")
? void (0) : __assert_fail ("(Subtarget.is32Bit() || Subtarget.is16Bit()) && \"Expecting 64, 32 or 16 bit subtarget\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 52041, __extension__ __PRETTY_FUNCTION__))
52041 "Expecting 64, 32 or 16 bit subtarget")(static_cast <bool> ((Subtarget.is32Bit() || Subtarget.
is16Bit()) && "Expecting 64, 32 or 16 bit subtarget")
? void (0) : __assert_fail ("(Subtarget.is32Bit() || Subtarget.is16Bit()) && \"Expecting 64, 32 or 16 bit subtarget\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 52041, __extension__ __PRETTY_FUNCTION__))
;
52042 return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
52043
52044 // TODO: Slight differences here in allocation order and leaving
52045 // RIP in the class. Do they matter any more here than they do
52046 // in the normal allocation?
52047 case 'k':
52048 if (Subtarget.hasAVX512()) {
52049 if (VT == MVT::i1)
52050 return std::make_pair(0U, &X86::VK1RegClass);
52051 if (VT == MVT::i8)
52052 return std::make_pair(0U, &X86::VK8RegClass);
52053 if (VT == MVT::i16)
52054 return std::make_pair(0U, &X86::VK16RegClass);
52055 }
52056 if (Subtarget.hasBWI()) {
52057 if (VT == MVT::i32)
52058 return std::make_pair(0U, &X86::VK32RegClass);
52059 if (VT == MVT::i64)
52060 return std::make_pair(0U, &X86::VK64RegClass);
52061 }
52062 break;
52063 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
52064 if (Subtarget.is64Bit()) {
52065 if (VT == MVT::i8 || VT == MVT::i1)
52066 return std::make_pair(0U, &X86::GR8RegClass);
52067 if (VT == MVT::i16)
52068 return std::make_pair(0U, &X86::GR16RegClass);
52069 if (VT == MVT::i32 || VT == MVT::f32)
52070 return std::make_pair(0U, &X86::GR32RegClass);
52071 if (VT != MVT::f80 && !VT.isVector())
52072 return std::make_pair(0U, &X86::GR64RegClass);
52073 break;
52074 }
52075 LLVM_FALLTHROUGH[[gnu::fallthrough]];
52076 // 32-bit fallthrough
52077 case 'Q': // Q_REGS
52078 if (VT == MVT::i8 || VT == MVT::i1)
52079 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
52080 if (VT == MVT::i16)
52081 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
52082 if (VT == MVT::i32 || VT == MVT::f32 ||
52083 (!VT.isVector() && !Subtarget.is64Bit()))
52084 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
52085 if (VT != MVT::f80 && !VT.isVector())
52086 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
52087 break;
52088 case 'r': // GENERAL_REGS
52089 case 'l': // INDEX_REGS
52090 if (VT == MVT::i8 || VT == MVT::i1)
52091 return std::make_pair(0U, &X86::GR8RegClass);
52092 if (VT == MVT::i16)
52093 return std::make_pair(0U, &X86::GR16RegClass);
52094 if (VT == MVT::i32 || VT == MVT::f32 ||
52095 (!VT.isVector() && !Subtarget.is64Bit()))
52096 return std::make_pair(0U, &X86::GR32RegClass);
52097 if (VT != MVT::f80 && !VT.isVector())
52098 return std::make_pair(0U, &X86::GR64RegClass);
52099 break;
52100 case 'R': // LEGACY_REGS
52101 if (VT == MVT::i8 || VT == MVT::i1)
52102 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
52103 if (VT == MVT::i16)
52104 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
52105 if (VT == MVT::i32 || VT == MVT::f32 ||
52106 (!VT.isVector() && !Subtarget.is64Bit()))
52107 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
52108 if (VT != MVT::f80 && !VT.isVector())
52109 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
52110 break;
52111 case 'f': // FP Stack registers.
52112 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
52113 // value to the correct fpstack register class.
52114 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
52115 return std::make_pair(0U, &X86::RFP32RegClass);
52116 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
52117 return std::make_pair(0U, &X86::RFP64RegClass);
52118 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f80)
52119 return std::make_pair(0U, &X86::RFP80RegClass);
52120 break;
52121 case 'y': // MMX_REGS if MMX allowed.
52122 if (!Subtarget.hasMMX()) break;
52123 return std::make_pair(0U, &X86::VR64RegClass);
52124 case 'v':
52125 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
52126 if (!Subtarget.hasSSE1()) break;
52127 bool VConstraint = (Constraint[0] == 'v');
52128
52129 switch (VT.SimpleTy) {
52130 default: break;
52131 // Scalar SSE types.
52132 case MVT::f32:
52133 case MVT::i32:
52134 if (VConstraint && Subtarget.hasVLX())
52135 return std::make_pair(0U, &X86::FR32XRegClass);
52136 return std::make_pair(0U, &X86::FR32RegClass);
52137 case MVT::f64:
52138 case MVT::i64:
52139 if (VConstraint && Subtarget.hasVLX())
52140 return std::make_pair(0U, &X86::FR64XRegClass);
52141 return std::make_pair(0U, &X86::FR64RegClass);
52142 case MVT::i128:
52143 if (Subtarget.is64Bit()) {
52144 if (VConstraint && Subtarget.hasVLX())
52145 return std::make_pair(0U, &X86::VR128XRegClass);
52146 return std::make_pair(0U, &X86::VR128RegClass);
52147 }
52148 break;
52149 // Vector types and fp128.
52150 case MVT::f128:
52151 case MVT::v16i8:
52152 case MVT::v8i16:
52153 case MVT::v4i32:
52154 case MVT::v2i64:
52155 case MVT::v4f32:
52156 case MVT::v2f64:
52157 if (VConstraint && Subtarget.hasVLX())
52158 return std::make_pair(0U, &X86::VR128XRegClass);
52159 return std::make_pair(0U, &X86::VR128RegClass);
52160 // AVX types.
52161 case MVT::v32i8:
52162 case MVT::v16i16:
52163 case MVT::v8i32:
52164 case MVT::v4i64:
52165 case MVT::v8f32:
52166 case MVT::v4f64:
52167 if (VConstraint && Subtarget.hasVLX())
52168 return std::make_pair(0U, &X86::VR256XRegClass);
52169 if (Subtarget.hasAVX())
52170 return std::make_pair(0U, &X86::VR256RegClass);
52171 break;
52172 case MVT::v64i8:
52173 case MVT::v32i16:
52174 case MVT::v8f64:
52175 case MVT::v16f32:
52176 case MVT::v16i32:
52177 case MVT::v8i64:
52178 if (!Subtarget.hasAVX512()) break;
52179 if (VConstraint)
52180 return std::make_pair(0U, &X86::VR512RegClass);
52181 return std::make_pair(0U, &X86::VR512_0_15RegClass);
52182 }
52183 break;
52184 }
52185 } else if (Constraint.size() == 2 && Constraint[0] == 'Y') {
52186 switch (Constraint[1]) {
52187 default:
52188 break;
52189 case 'i':
52190 case 't':
52191 case '2':
52192 return getRegForInlineAsmConstraint(TRI, "x", VT);
52193 case 'm':
52194 if (!Subtarget.hasMMX()) break;
52195 return std::make_pair(0U, &X86::VR64RegClass);
52196 case 'z':
52197 if (!Subtarget.hasSSE1()) break;
52198 switch (VT.SimpleTy) {
52199 default: break;
52200 // Scalar SSE types.
52201 case MVT::f32:
52202 case MVT::i32:
52203 return std::make_pair(X86::XMM0, &X86::FR32RegClass);
52204 case MVT::f64:
52205 case MVT::i64:
52206 return std::make_pair(X86::XMM0, &X86::FR64RegClass);
52207 case MVT::f128:
52208 case MVT::v16i8:
52209 case MVT::v8i16:
52210 case MVT::v4i32:
52211 case MVT::v2i64:
52212 case MVT::v4f32:
52213 case MVT::v2f64:
52214 return std::make_pair(X86::XMM0, &X86::VR128RegClass);
52215 // AVX types.
52216 case MVT::v32i8:
52217 case MVT::v16i16:
52218 case MVT::v8i32:
52219 case MVT::v4i64:
52220 case MVT::v8f32:
52221 case MVT::v4f64:
52222 if (Subtarget.hasAVX())
52223 return std::make_pair(X86::YMM0, &X86::VR256RegClass);
52224 break;
52225 case MVT::v64i8:
52226 case MVT::v32i16:
52227 case MVT::v8f64:
52228 case MVT::v16f32:
52229 case MVT::v16i32:
52230 case MVT::v8i64:
52231 if (Subtarget.hasAVX512())
52232 return std::make_pair(X86::ZMM0, &X86::VR512_0_15RegClass);
52233 break;
52234 }
52235 break;
52236 case 'k':
52237 // This register class doesn't allocate k0 for masked vector operation.
52238 if (Subtarget.hasAVX512()) {
52239 if (VT == MVT::i1)
52240 return std::make_pair(0U, &X86::VK1WMRegClass);
52241 if (VT == MVT::i8)
52242 return std::make_pair(0U, &X86::VK8WMRegClass);
52243 if (VT == MVT::i16)
52244 return std::make_pair(0U, &X86::VK16WMRegClass);
52245 }
52246 if (Subtarget.hasBWI()) {
52247 if (VT == MVT::i32)
52248 return std::make_pair(0U, &X86::VK32WMRegClass);
52249 if (VT == MVT::i64)
52250 return std::make_pair(0U, &X86::VK64WMRegClass);
52251 }
52252 break;
52253 }
52254 }
52255
52256 if (parseConstraintCode(Constraint) != X86::COND_INVALID)
52257 return std::make_pair(0U, &X86::GR32RegClass);
52258
52259 // Use the default implementation in TargetLowering to convert the register
52260 // constraint into a member of a register class.
52261 std::pair<Register, const TargetRegisterClass*> Res;
52262 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
52263
52264 // Not found as a standard register?
52265 if (!Res.second) {
52266 // Only match x87 registers if the VT is one SelectionDAGBuilder can convert
52267 // to/from f80.
52268 if (VT == MVT::Other || VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f80) {
52269 // Map st(0) -> st(7) -> ST0
52270 if (Constraint.size() == 7 && Constraint[0] == '{' &&
52271 tolower(Constraint[1]) == 's' && tolower(Constraint[2]) == 't' &&
52272 Constraint[3] == '(' &&
52273 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
52274 Constraint[5] == ')' && Constraint[6] == '}') {
52275 // st(7) is not allocatable and thus not a member of RFP80. Return
52276 // singleton class in cases where we have a reference to it.
52277 if (Constraint[4] == '7')
52278 return std::make_pair(X86::FP7, &X86::RFP80_7RegClass);
52279 return std::make_pair(X86::FP0 + Constraint[4] - '0',
52280 &X86::RFP80RegClass);
52281 }
52282
52283 // GCC allows "st(0)" to be called just plain "st".
52284 if (StringRef("{st}").equals_insensitive(Constraint))
52285 return std::make_pair(X86::FP0, &X86::RFP80RegClass);
52286 }
52287
52288 // flags -> EFLAGS
52289 if (StringRef("{flags}").equals_insensitive(Constraint))
52290 return std::make_pair(X86::EFLAGS, &X86::CCRRegClass);
52291
52292 // dirflag -> DF
52293 // Only allow for clobber.
52294 if (StringRef("{dirflag}").equals_insensitive(Constraint) &&
52295 VT == MVT::Other)
52296 return std::make_pair(X86::DF, &X86::DFCCRRegClass);
52297
52298 // fpsr -> FPSW
52299 if (StringRef("{fpsr}").equals_insensitive(Constraint))
52300 return std::make_pair(X86::FPSW, &X86::FPCCRRegClass);
52301
52302 return Res;
52303 }
52304
52305 // Make sure it isn't a register that requires 64-bit mode.
52306 if (!Subtarget.is64Bit() &&
52307 (isFRClass(*Res.second) || isGRClass(*Res.second)) &&
52308 TRI->getEncodingValue(Res.first) >= 8) {
52309 // Register requires REX prefix, but we're in 32-bit mode.
52310 return std::make_pair(0, nullptr);
52311 }
52312
52313 // Make sure it isn't a register that requires AVX512.
52314 if (!Subtarget.hasAVX512() && isFRClass(*Res.second) &&
52315 TRI->getEncodingValue(Res.first) & 0x10) {
52316 // Register requires EVEX prefix.
52317 return std::make_pair(0, nullptr);
52318 }
52319
52320 // Otherwise, check to see if this is a register class of the wrong value
52321 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
52322 // turn into {ax},{dx}.
52323 // MVT::Other is used to specify clobber names.
52324 if (TRI->isTypeLegalForClass(*Res.second, VT) || VT == MVT::Other)
52325 return Res; // Correct type already, nothing to do.
52326
52327 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
52328 // return "eax". This should even work for things like getting 64bit integer
52329 // registers when given an f64 type.
52330 const TargetRegisterClass *Class = Res.second;
52331 // The generic code will match the first register class that contains the
52332 // given register. Thus, based on the ordering of the tablegened file,
52333 // the "plain" GR classes might not come first.
52334 // Therefore, use a helper method.
52335 if (isGRClass(*Class)) {
52336 unsigned Size = VT.getSizeInBits();
52337 if (Size == 1) Size = 8;
52338 Register DestReg = getX86SubSuperRegisterOrZero(Res.first, Size);
52339 if (DestReg > 0) {
52340 bool is64Bit = Subtarget.is64Bit();
52341 const TargetRegisterClass *RC =
52342 Size == 8 ? (is64Bit ? &X86::GR8RegClass : &X86::GR8_NOREXRegClass)
52343 : Size == 16 ? (is64Bit ? &X86::GR16RegClass : &X86::GR16_NOREXRegClass)
52344 : Size == 32 ? (is64Bit ? &X86::GR32RegClass : &X86::GR32_NOREXRegClass)
52345 : Size == 64 ? (is64Bit ? &X86::GR64RegClass : nullptr)
52346 : nullptr;
52347 if (Size == 64 && !is64Bit) {
52348 // Model GCC's behavior here and select a fixed pair of 32-bit
52349 // registers.
52350 switch (DestReg) {
52351 case X86::RAX:
52352 return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
52353 case X86::RDX:
52354 return std::make_pair(X86::EDX, &X86::GR32_DCRegClass);
52355 case X86::RCX:
52356 return std::make_pair(X86::ECX, &X86::GR32_CBRegClass);
52357 case X86::RBX:
52358 return std::make_pair(X86::EBX, &X86::GR32_BSIRegClass);
52359 case X86::RSI:
52360 return std::make_pair(X86::ESI, &X86::GR32_SIDIRegClass);
52361 case X86::RDI:
52362 return std::make_pair(X86::EDI, &X86::GR32_DIBPRegClass);
52363 case X86::RBP:
52364 return std::make_pair(X86::EBP, &X86::GR32_BPSPRegClass);
52365 default:
52366 return std::make_pair(0, nullptr);
52367 }
52368 }
52369 if (RC && RC->contains(DestReg))
52370 return std::make_pair(DestReg, RC);
52371 return Res;
52372 }
52373 // No register found/type mismatch.
52374 return std::make_pair(0, nullptr);
52375 } else if (isFRClass(*Class)) {
52376 // Handle references to XMM physical registers that got mapped into the
52377 // wrong class. This can happen with constraints like {xmm0} where the
52378 // target independent register mapper will just pick the first match it can
52379 // find, ignoring the required type.
52380
52381 // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
52382 if (VT == MVT::f32 || VT == MVT::i32)
52383 Res.second = &X86::FR32XRegClass;
52384 else if (VT == MVT::f64 || VT == MVT::i64)
52385 Res.second = &X86::FR64XRegClass;
52386 else if (TRI->isTypeLegalForClass(X86::VR128XRegClass, VT))
52387 Res.second = &X86::VR128XRegClass;
52388 else if (TRI->isTypeLegalForClass(X86::VR256XRegClass, VT))
52389 Res.second = &X86::VR256XRegClass;
52390 else if (TRI->isTypeLegalForClass(X86::VR512RegClass, VT))
52391 Res.second = &X86::VR512RegClass;
52392 else {
52393 // Type mismatch and not a clobber: Return an error;
52394 Res.first = 0;
52395 Res.second = nullptr;
52396 }
52397 } else if (isVKClass(*Class)) {
52398 if (VT == MVT::i1)
52399 Res.second = &X86::VK1RegClass;
52400 else if (VT == MVT::i8)
52401 Res.second = &X86::VK8RegClass;
52402 else if (VT == MVT::i16)
52403 Res.second = &X86::VK16RegClass;
52404 else if (VT == MVT::i32)
52405 Res.second = &X86::VK32RegClass;
52406 else if (VT == MVT::i64)
52407 Res.second = &X86::VK64RegClass;
52408 else {
52409 // Type mismatch and not a clobber: Return an error;
52410 Res.first = 0;
52411 Res.second = nullptr;
52412 }
52413 }
52414
52415 return Res;
52416}
52417
52418InstructionCost X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
52419 const AddrMode &AM,
52420 Type *Ty,
52421 unsigned AS) const {
52422 // Scaling factors are not free at all.
52423 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
52424 // will take 2 allocations in the out of order engine instead of 1
52425 // for plain addressing mode, i.e. inst (reg1).
52426 // E.g.,
52427 // vaddps (%rsi,%rdx), %ymm0, %ymm1
52428 // Requires two allocations (one for the load, one for the computation)
52429 // whereas:
52430 // vaddps (%rsi), %ymm0, %ymm1
52431 // Requires just 1 allocation, i.e., freeing allocations for other operations
52432 // and having less micro operations to execute.
52433 //
52434 // For some X86 architectures, this is even worse because for instance for
52435 // stores, the complex addressing mode forces the instruction to use the
52436 // "load" ports instead of the dedicated "store" port.
52437 // E.g., on Haswell:
52438 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
52439 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
52440 if (isLegalAddressingMode(DL, AM, Ty, AS))
52441 // Scale represents reg2 * scale, thus account for 1
52442 // as soon as we use a second register.
52443 return AM.Scale != 0;
52444 return -1;
52445}
52446
52447bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
52448 // Integer division on x86 is expensive. However, when aggressively optimizing
52449 // for code size, we prefer to use a div instruction, as it is usually smaller
52450 // than the alternative sequence.
52451 // The exception to this is vector division. Since x86 doesn't have vector
52452 // integer division, leaving the division as-is is a loss even in terms of
52453 // size, because it will have to be scalarized, while the alternative code
52454 // sequence can be performed in vector form.
52455 bool OptSize = Attr.hasFnAttribute(Attribute::MinSize);
52456 return OptSize && !VT.isVector();
52457}
52458
52459void X86TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
52460 if (!Subtarget.is64Bit())
52461 return;
52462
52463 // Update IsSplitCSR in X86MachineFunctionInfo.
52464 X86MachineFunctionInfo *AFI =
52465 Entry->getParent()->getInfo<X86MachineFunctionInfo>();
52466 AFI->setIsSplitCSR(true);
52467}
52468
52469void X86TargetLowering::insertCopiesSplitCSR(
52470 MachineBasicBlock *Entry,
52471 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
52472 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
52473 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
52474 if (!IStart)
52475 return;
52476
52477 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
52478 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
52479 MachineBasicBlock::iterator MBBI = Entry->begin();
52480 for (const MCPhysReg *I = IStart; *I; ++I) {
52481 const TargetRegisterClass *RC = nullptr;
52482 if (X86::GR64RegClass.contains(*I))
52483 RC = &X86::GR64RegClass;
52484 else
52485 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 52485)
;
52486
52487 Register NewVR = MRI->createVirtualRegister(RC);
52488 // Create copy from CSR to a virtual register.
52489 // FIXME: this currently does not emit CFI pseudo-instructions, it works
52490 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
52491 // nounwind. If we want to generalize this later, we may need to emit
52492 // CFI pseudo-instructions.
52493 assert((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-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 52495, __extension__ __PRETTY_FUNCTION__))
52494 Entry->getParent()->getFunction().hasFnAttribute(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-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 52495, __extension__ __PRETTY_FUNCTION__))
52495 "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-13~++20210726100616+dead50d4427c/llvm/lib/Target/X86/X86ISelLowering.cpp"
, 52495, __extension__ __PRETTY_FUNCTION__))
;
52496 Entry->addLiveIn(*I);
52497 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
52498 .addReg(*I);
52499
52500 // Insert the copy-back instructions right before the terminator.
52501 for (auto *Exit : Exits)
52502 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
52503 TII->get(TargetOpcode::COPY), *I)
52504 .addReg(NewVR);
52505 }
52506}
52507
52508bool X86TargetLowering::supportSwiftError() const {
52509 return Subtarget.is64Bit();
52510}
52511
52512/// Returns true if stack probing through a function call is requested.
52513bool X86TargetLowering::hasStackProbeSymbol(MachineFunction &MF) const {
52514 return !getStackProbeSymbolName(MF).empty();
52515}
52516
52517/// Returns true if stack probing through inline assembly is requested.
52518bool X86TargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
52519
52520 // No inline stack probe for Windows, they have their own mechanism.
52521 if (Subtarget.isOSWindows() ||
52522 MF.getFunction().hasFnAttribute("no-stack-arg-probe"))
52523 return false;
52524
52525 // If the function specifically requests inline stack probes, emit them.
52526 if (MF.getFunction().hasFnAttribute("probe-stack"))
52527 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
52528 "inline-asm";
52529
52530 return false;
52531}
52532
52533/// Returns the name of the symbol used to emit stack probes or the empty
52534/// string if not applicable.
52535StringRef
52536X86TargetLowering::getStackProbeSymbolName(MachineFunction &MF) const {
52537 // Inline Stack probes disable stack probe call
52538 if (hasInlineStackProbe(MF))
52539 return "";
52540
52541 // If the function specifically requests stack probes, emit them.
52542 if (MF.getFunction().hasFnAttribute("probe-stack"))
52543 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString();
52544
52545 // Generally, if we aren't on Windows, the platform ABI does not include
52546 // support for stack probes, so don't emit them.
52547 if (!Subtarget.isOSWindows() || Subtarget.isTargetMachO() ||
52548 MF.getFunction().hasFnAttribute("no-stack-arg-probe"))
52549 return "";
52550
52551 // We need a stack probe to conform to the Windows ABI. Choose the right
52552 // symbol.
52553 if (Subtarget.is64Bit())
52554 return Subtarget.isTargetCygMing() ? "___chkstk_ms" : "__chkstk";
52555 return Subtarget.isTargetCygMing() ? "_alloca" : "_chkstk";
52556}
52557
52558unsigned
52559X86TargetLowering::getStackProbeSize(MachineFunction &MF) const {
52560 // The default stack probe size is 4096 if the function has no stackprobesize
52561 // attribute.
52562 unsigned StackProbeSize = 4096;
52563 const Function &Fn = MF.getFunction();
52564 if (Fn.hasFnAttribute("stack-probe-size"))
52565 Fn.getFnAttribute("stack-probe-size")
52566 .getValueAsString()
52567 .getAsInteger(0, StackProbeSize);
52568 return StackProbeSize;
52569}
52570
52571Align X86TargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
52572 if (ML->isInnermost() &&
52573 ExperimentalPrefInnermostLoopAlignment.getNumOccurrences())
52574 return Align(1ULL << ExperimentalPrefInnermostLoopAlignment);
52575 return TargetLowering::getPrefLoopAlignment();
52576}

/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/Support/Casting.h

1//===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- 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 isa<X>(), cast<X>(), dyn_cast<X>(), cast_or_null<X>(),
10// and dyn_cast_or_null<X>() templates.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_SUPPORT_CASTING_H
15#define LLVM_SUPPORT_CASTING_H
16
17#include "llvm/Support/Compiler.h"
18#include "llvm/Support/type_traits.h"
19#include <cassert>
20#include <memory>
21#include <type_traits>
22
23namespace llvm {
24
25//===----------------------------------------------------------------------===//
26// isa<x> Support Templates
27//===----------------------------------------------------------------------===//
28
29// Define a template that can be specialized by smart pointers to reflect the
30// fact that they are automatically dereferenced, and are not involved with the
31// template selection process... the default implementation is a noop.
32//
33template<typename From> struct simplify_type {
34 using SimpleType = From; // The real type this represents...
35
36 // An accessor to get the real value...
37 static SimpleType &getSimplifiedValue(From &Val) { return Val; }
38};
39
40template<typename From> struct simplify_type<const From> {
41 using NonConstSimpleType = typename simplify_type<From>::SimpleType;
42 using SimpleType =
43 typename add_const_past_pointer<NonConstSimpleType>::type;
44 using RetType =
45 typename add_lvalue_reference_if_not_pointer<SimpleType>::type;
46
47 static RetType getSimplifiedValue(const From& Val) {
48 return simplify_type<From>::getSimplifiedValue(const_cast<From&>(Val));
49 }
50};
51
52// The core of the implementation of isa<X> is here; To and From should be
53// the names of classes. This template can be specialized to customize the
54// implementation of isa<> without rewriting it from scratch.
55template <typename To, typename From, typename Enabler = void>
56struct isa_impl {
57 static inline bool doit(const From &Val) {
58 return To::classof(&Val);
59 }
60};
61
62/// Always allow upcasts, and perform no dynamic check for them.
63template <typename To, typename From>
64struct isa_impl<To, From, std::enable_if_t<std::is_base_of<To, From>::value>> {
65 static inline bool doit(const From &) { return true; }
66};
67
68template <typename To, typename From> struct isa_impl_cl {
69 static inline bool doit(const From &Val) {
70 return isa_impl<To, From>::doit(Val);
71 }
72};
73
74template <typename To, typename From> struct isa_impl_cl<To, const From> {
75 static inline bool doit(const From &Val) {
76 return isa_impl<To, From>::doit(Val);
77 }
78};
79
80template <typename To, typename From>
81struct isa_impl_cl<To, const std::unique_ptr<From>> {
82 static inline bool doit(const std::unique_ptr<From> &Val) {
83 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/Support/Casting.h"
, 83, __extension__ __PRETTY_FUNCTION__))
;
84 return isa_impl_cl<To, From>::doit(*Val);
85 }
86};
87
88template <typename To, typename From> struct isa_impl_cl<To, From*> {
89 static inline bool doit(const From *Val) {
90 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/Support/Casting.h"
, 90, __extension__ __PRETTY_FUNCTION__))
;
91 return isa_impl<To, From>::doit(*Val);
92 }
93};
94
95template <typename To, typename From> struct isa_impl_cl<To, From*const> {
96 static inline bool doit(const From *Val) {
97 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/Support/Casting.h"
, 97, __extension__ __PRETTY_FUNCTION__))
;
98 return isa_impl<To, From>::doit(*Val);
99 }
100};
101
102template <typename To, typename From> struct isa_impl_cl<To, const From*> {
103 static inline bool doit(const From *Val) {
104 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/Support/Casting.h"
, 104, __extension__ __PRETTY_FUNCTION__))
;
105 return isa_impl<To, From>::doit(*Val);
106 }
107};
108
109template <typename To, typename From> struct isa_impl_cl<To, const From*const> {
110 static inline bool doit(const From *Val) {
111 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/Support/Casting.h"
, 111, __extension__ __PRETTY_FUNCTION__))
;
112 return isa_impl<To, From>::doit(*Val);
113 }
114};
115
116template<typename To, typename From, typename SimpleFrom>
117struct isa_impl_wrap {
118 // When From != SimplifiedType, we can simplify the type some more by using
119 // the simplify_type template.
120 static bool doit(const From &Val) {
121 return isa_impl_wrap<To, SimpleFrom,
122 typename simplify_type<SimpleFrom>::SimpleType>::doit(
123 simplify_type<const From>::getSimplifiedValue(Val));
124 }
125};
126
127template<typename To, typename FromTy>
128struct isa_impl_wrap<To, FromTy, FromTy> {
129 // When From == SimpleType, we are as simple as we are going to get.
130 static bool doit(const FromTy &Val) {
131 return isa_impl_cl<To,FromTy>::doit(Val);
132 }
133};
134
135// isa<X> - Return true if the parameter to the template is an instance of one
136// of the template type arguments. Used like this:
137//
138// if (isa<Type>(myVal)) { ... }
139// if (isa<Type0, Type1, Type2>(myVal)) { ... }
140//
141template <class X, class Y> LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) {
142 return isa_impl_wrap<X, const Y,
143 typename simplify_type<const Y>::SimpleType>::doit(Val);
144}
145
146template <typename First, typename Second, typename... Rest, typename Y>
147LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) {
148 return isa<First>(Val) || isa<Second, Rest...>(Val);
149}
150
151// isa_and_nonnull<X> - Functionally identical to isa, except that a null value
152// is accepted.
153//
154template <typename... X, class Y>
155LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa_and_nonnull(const Y &Val) {
156 if (!Val)
157 return false;
158 return isa<X...>(Val);
159}
160
161//===----------------------------------------------------------------------===//
162// cast<x> Support Templates
163//===----------------------------------------------------------------------===//
164
165template<class To, class From> struct cast_retty;
166
167// Calculate what type the 'cast' function should return, based on a requested
168// type of To and a source type of From.
169template<class To, class From> struct cast_retty_impl {
170 using ret_type = To &; // Normal case, return Ty&
171};
172template<class To, class From> struct cast_retty_impl<To, const From> {
173 using ret_type = const To &; // Normal case, return Ty&
174};
175
176template<class To, class From> struct cast_retty_impl<To, From*> {
177 using ret_type = To *; // Pointer arg case, return Ty*
178};
179
180template<class To, class From> struct cast_retty_impl<To, const From*> {
181 using ret_type = const To *; // Constant pointer arg case, return const Ty*
182};
183
184template<class To, class From> struct cast_retty_impl<To, const From*const> {
185 using ret_type = const To *; // Constant pointer arg case, return const Ty*
186};
187
188template <class To, class From>
189struct cast_retty_impl<To, std::unique_ptr<From>> {
190private:
191 using PointerType = typename cast_retty_impl<To, From *>::ret_type;
192 using ResultType = std::remove_pointer_t<PointerType>;
193
194public:
195 using ret_type = std::unique_ptr<ResultType>;
196};
197
198template<class To, class From, class SimpleFrom>
199struct cast_retty_wrap {
200 // When the simplified type and the from type are not the same, use the type
201 // simplifier to reduce the type, then reuse cast_retty_impl to get the
202 // resultant type.
203 using ret_type = typename cast_retty<To, SimpleFrom>::ret_type;
204};
205
206template<class To, class FromTy>
207struct cast_retty_wrap<To, FromTy, FromTy> {
208 // When the simplified type is equal to the from type, use it directly.
209 using ret_type = typename cast_retty_impl<To,FromTy>::ret_type;
210};
211
212template<class To, class From>
213struct cast_retty {
214 using ret_type = typename cast_retty_wrap<
215 To, From, typename simplify_type<From>::SimpleType>::ret_type;
216};
217
218// Ensure the non-simple values are converted using the simplify_type template
219// that may be specialized by smart pointers...
220//
221template<class To, class From, class SimpleFrom> struct cast_convert_val {
222 // This is not a simple type, use the template to simplify it...
223 static typename cast_retty<To, From>::ret_type doit(From &Val) {
224 return cast_convert_val<To, SimpleFrom,
41
Returning without writing to 'Val.Node'
225 typename simplify_type<SimpleFrom>::SimpleType>::doit(
226 simplify_type<From>::getSimplifiedValue(Val));
38
Calling 'simplify_type::getSimplifiedValue'
40
Returning from 'simplify_type::getSimplifiedValue'
227 }
228};
229
230template<class To, class FromTy> struct cast_convert_val<To,FromTy,FromTy> {
231 // This _is_ a simple type, just cast it.
232 static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) {
233 typename cast_retty<To, FromTy>::ret_type Res2
234 = (typename cast_retty<To, FromTy>::ret_type)const_cast<FromTy&>(Val);
235 return Res2;
236 }
237};
238
239template <class X> struct is_simple_type {
240 static const bool value =
241 std::is_same<X, typename simplify_type<X>::SimpleType>::value;
242};
243
244// cast<X> - Return the argument parameter cast to the specified type. This
245// casting operator asserts that the type is correct, so it does not return null
246// on failure. It does not allow a null argument (use cast_or_null for that).
247// It is typically used like this:
248//
249// cast<Instruction>(myVal)->getParent()
250//
251template <class X, class Y>
252inline std::enable_if_t<!is_simple_type<Y>::value,
253 typename cast_retty<X, const Y>::ret_type>
254cast(const Y &Val) {
255 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/Support/Casting.h"
, 255, __extension__ __PRETTY_FUNCTION__))
;
256 return cast_convert_val<
257 X, const Y, typename simplify_type<const Y>::SimpleType>::doit(Val);
258}
259
260template <class X, class Y>
261inline typename cast_retty<X, Y>::ret_type cast(Y &Val) {
262 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/Support/Casting.h"
, 262, __extension__ __PRETTY_FUNCTION__))
;
35
Assuming 'Val' is a 'FrameIndexSDNode'
36
'?' condition is true
263 return cast_convert_val<X, Y,
37
Calling 'cast_convert_val::doit'
42
Returning from 'cast_convert_val::doit'
43
Returning without writing to 'Val.Node'
264 typename simplify_type<Y>::SimpleType>::doit(Val);
265}
266
267template <class X, class Y>
268inline typename cast_retty<X, Y *>::ret_type cast(Y *Val) {
269 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/Support/Casting.h"
, 269, __extension__ __PRETTY_FUNCTION__))
;
270 return cast_convert_val<X, Y*,
271 typename simplify_type<Y*>::SimpleType>::doit(Val);
272}
273
274template <class X, class Y>
275inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
276cast(std::unique_ptr<Y> &&Val) {
277 assert(isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val.get()) &&
"cast<Ty>() argument of incompatible type!") ? void (0
) : __assert_fail ("isa<X>(Val.get()) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/Support/Casting.h"
, 277, __extension__ __PRETTY_FUNCTION__))
;
278 using ret_type = typename cast_retty<X, std::unique_ptr<Y>>::ret_type;
279 return ret_type(
280 cast_convert_val<X, Y *, typename simplify_type<Y *>::SimpleType>::doit(
281 Val.release()));
282}
283
284// cast_or_null<X> - Functionally identical to cast, except that a null value is
285// accepted.
286//
287template <class X, class Y>
288LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<
289 !is_simple_type<Y>::value, typename cast_retty<X, const Y>::ret_type>
290cast_or_null(const Y &Val) {
291 if (!Val)
292 return nullptr;
293 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/Support/Casting.h"
, 293, __extension__ __PRETTY_FUNCTION__))
;
294 return cast<X>(Val);
295}
296
297template <class X, class Y>
298LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<!is_simple_type<Y>::value,
299 typename cast_retty<X, Y>::ret_type>
300cast_or_null(Y &Val) {
301 if (!Val)
302 return nullptr;
303 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/Support/Casting.h"
, 303, __extension__ __PRETTY_FUNCTION__))
;
304 return cast<X>(Val);
305}
306
307template <class X, class Y>
308LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
309cast_or_null(Y *Val) {
310 if (!Val) return nullptr;
311 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/Support/Casting.h"
, 311, __extension__ __PRETTY_FUNCTION__))
;
312 return cast<X>(Val);
313}
314
315template <class X, class Y>
316inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
317cast_or_null(std::unique_ptr<Y> &&Val) {
318 if (!Val)
319 return nullptr;
320 return cast<X>(std::move(Val));
321}
322
323// dyn_cast<X> - Return the argument parameter cast to the specified type. This
324// casting operator returns null if the argument is of the wrong type, so it can
325// be used to test for a type as well as cast if successful. This should be
326// used in the context of an if statement like this:
327//
328// if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... }
329//
330
331template <class X, class Y>
332LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<
333 !is_simple_type<Y>::value, typename cast_retty<X, const Y>::ret_type>
334dyn_cast(const Y &Val) {
335 return isa<X>(Val) ? cast<X>(Val) : nullptr;
336}
337
338template <class X, class Y>
339LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y>::ret_type dyn_cast(Y &Val) {
340 return isa<X>(Val) ? cast<X>(Val) : nullptr;
32
Assuming 'Val' is a 'FrameIndexSDNode'
33
'?' condition is true
34
Calling 'cast<llvm::FrameIndexSDNode, llvm::SDValue>'
44
Returning from 'cast<llvm::FrameIndexSDNode, llvm::SDValue>'
45
Returning without writing to 'Val.Node'
341}
342
343template <class X, class Y>
344LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type dyn_cast(Y *Val) {
345 return isa<X>(Val) ? cast<X>(Val) : nullptr;
346}
347
348// dyn_cast_or_null<X> - Functionally identical to dyn_cast, except that a null
349// value is accepted.
350//
351template <class X, class Y>
352LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<
353 !is_simple_type<Y>::value, typename cast_retty<X, const Y>::ret_type>
354dyn_cast_or_null(const Y &Val) {
355 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
356}
357
358template <class X, class Y>
359LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<!is_simple_type<Y>::value,
360 typename cast_retty<X, Y>::ret_type>
361dyn_cast_or_null(Y &Val) {
362 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
363}
364
365template <class X, class Y>
366LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
367dyn_cast_or_null(Y *Val) {
368 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
369}
370
371// unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>,
372// taking ownership of the input pointer iff isa<X>(Val) is true. If the
373// cast is successful, From refers to nullptr on exit and the casted value
374// is returned. If the cast is unsuccessful, the function returns nullptr
375// and From is unchanged.
376template <class X, class Y>
377LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &Val)
378 -> decltype(cast<X>(Val)) {
379 if (!isa<X>(Val))
380 return nullptr;
381 return cast<X>(std::move(Val));
382}
383
384template <class X, class Y>
385LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val) {
386 return unique_dyn_cast<X, Y>(Val);
387}
388
389// dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast, except that
390// a null value is accepted.
391template <class X, class Y>
392LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &Val)
393 -> decltype(cast<X>(Val)) {
394 if (!Val)
395 return nullptr;
396 return unique_dyn_cast<X, Y>(Val);
397}
398
399template <class X, class Y>
400LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val) {
401 return unique_dyn_cast_or_null<X, Y>(Val);
402}
403
404} // end namespace llvm
405
406#endif // LLVM_SUPPORT_CASTING_H

/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h

1//===- llvm/CodeGen/SelectionDAGNodes.h - SelectionDAG Nodes ----*- 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 declares the SDNode class and derived classes, which are used to
10// represent the nodes and operations present in a SelectionDAG. These nodes
11// and operations are machine code level operations, with some similarities to
12// the GCC RTL representation.
13//
14// Clients should include the SelectionDAG.h file instead of this file directly.
15//
16//===----------------------------------------------------------------------===//
17
18#ifndef LLVM_CODEGEN_SELECTIONDAGNODES_H
19#define LLVM_CODEGEN_SELECTIONDAGNODES_H
20
21#include "llvm/ADT/APFloat.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/BitVector.h"
24#include "llvm/ADT/FoldingSet.h"
25#include "llvm/ADT/GraphTraits.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/ilist_node.h"
29#include "llvm/ADT/iterator.h"
30#include "llvm/ADT/iterator_range.h"
31#include "llvm/CodeGen/ISDOpcodes.h"
32#include "llvm/CodeGen/MachineMemOperand.h"
33#include "llvm/CodeGen/Register.h"
34#include "llvm/CodeGen/ValueTypes.h"
35#include "llvm/IR/Constants.h"
36#include "llvm/IR/DebugLoc.h"
37#include "llvm/IR/Instruction.h"
38#include "llvm/IR/Instructions.h"
39#include "llvm/IR/Metadata.h"
40#include "llvm/IR/Operator.h"
41#include "llvm/Support/AlignOf.h"
42#include "llvm/Support/AtomicOrdering.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/MachineValueType.h"
46#include "llvm/Support/TypeSize.h"
47#include <algorithm>
48#include <cassert>
49#include <climits>
50#include <cstddef>
51#include <cstdint>
52#include <cstring>
53#include <iterator>
54#include <string>
55#include <tuple>
56
57namespace llvm {
58
59class APInt;
60class Constant;
61template <typename T> struct DenseMapInfo;
62class GlobalValue;
63class MachineBasicBlock;
64class MachineConstantPoolValue;
65class MCSymbol;
66class raw_ostream;
67class SDNode;
68class SelectionDAG;
69class Type;
70class Value;
71
72void checkForCycles(const SDNode *N, const SelectionDAG *DAG = nullptr,
73 bool force = false);
74
75/// This represents a list of ValueType's that has been intern'd by
76/// a SelectionDAG. Instances of this simple value class are returned by
77/// SelectionDAG::getVTList(...).
78///
79struct SDVTList {
80 const EVT *VTs;
81 unsigned int NumVTs;
82};
83
84namespace ISD {
85
86 /// Node predicates
87
88/// If N is a BUILD_VECTOR or SPLAT_VECTOR node whose elements are all the
89/// same constant or undefined, return true and return the constant value in
90/// \p SplatValue.
91bool isConstantSplatVector(const SDNode *N, APInt &SplatValue);
92
93/// Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where
94/// all of the elements are ~0 or undef. If \p BuildVectorOnly is set to
95/// true, it only checks BUILD_VECTOR.
96bool isConstantSplatVectorAllOnes(const SDNode *N,
97 bool BuildVectorOnly = false);
98
99/// Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where
100/// all of the elements are 0 or undef. If \p BuildVectorOnly is set to true, it
101/// only checks BUILD_VECTOR.
102bool isConstantSplatVectorAllZeros(const SDNode *N,
103 bool BuildVectorOnly = false);
104
105/// Return true if the specified node is a BUILD_VECTOR where all of the
106/// elements are ~0 or undef.
107bool isBuildVectorAllOnes(const SDNode *N);
108
109/// Return true if the specified node is a BUILD_VECTOR where all of the
110/// elements are 0 or undef.
111bool isBuildVectorAllZeros(const SDNode *N);
112
113/// Return true if the specified node is a BUILD_VECTOR node of all
114/// ConstantSDNode or undef.
115bool isBuildVectorOfConstantSDNodes(const SDNode *N);
116
117/// Return true if the specified node is a BUILD_VECTOR node of all
118/// ConstantFPSDNode or undef.
119bool isBuildVectorOfConstantFPSDNodes(const SDNode *N);
120
121/// Return true if the node has at least one operand and all operands of the
122/// specified node are ISD::UNDEF.
123bool allOperandsUndef(const SDNode *N);
124
125} // end namespace ISD
126
127//===----------------------------------------------------------------------===//
128/// Unlike LLVM values, Selection DAG nodes may return multiple
129/// values as the result of a computation. Many nodes return multiple values,
130/// from loads (which define a token and a return value) to ADDC (which returns
131/// a result and a carry value), to calls (which may return an arbitrary number
132/// of values).
133///
134/// As such, each use of a SelectionDAG computation must indicate the node that
135/// computes it as well as which return value to use from that node. This pair
136/// of information is represented with the SDValue value type.
137///
138class SDValue {
139 friend struct DenseMapInfo<SDValue>;
140
141 SDNode *Node = nullptr; // The node defining the value we are using.
142 unsigned ResNo = 0; // Which return value of the node we are using.
143
144public:
145 SDValue() = default;
146 SDValue(SDNode *node, unsigned resno);
147
148 /// get the index which selects a specific result in the SDNode
149 unsigned getResNo() const { return ResNo; }
150
151 /// get the SDNode which holds the desired result
152 SDNode *getNode() const { return Node; }
153
154 /// set the SDNode
155 void setNode(SDNode *N) { Node = N; }
156
157 inline SDNode *operator->() const { return Node; }
158
159 bool operator==(const SDValue &O) const {
160 return Node == O.Node && ResNo == O.ResNo;
161 }
162 bool operator!=(const SDValue &O) const {
163 return !operator==(O);
164 }
165 bool operator<(const SDValue &O) const {
166 return std::tie(Node, ResNo) < std::tie(O.Node, O.ResNo);
167 }
168 explicit operator bool() const {
169 return Node != nullptr;
170 }
171
172 SDValue getValue(unsigned R) const {
173 return SDValue(Node, R);
174 }
175
176 /// Return true if this node is an operand of N.
177 bool isOperandOf(const SDNode *N) const;
178
179 /// Return the ValueType of the referenced return value.
180 inline EVT getValueType() const;
181
182 /// Return the simple ValueType of the referenced return value.
183 MVT getSimpleValueType() const {
184 return getValueType().getSimpleVT();
185 }
186
187 /// Returns the size of the value in bits.
188 ///
189 /// If the value type is a scalable vector type, the scalable property will
190 /// be set and the runtime size will be a positive integer multiple of the
191 /// base size.
192 TypeSize getValueSizeInBits() const {
193 return getValueType().getSizeInBits();
194 }
195
196 uint64_t getScalarValueSizeInBits() const {
197 return getValueType().getScalarType().getFixedSizeInBits();
198 }
199
200 // Forwarding methods - These forward to the corresponding methods in SDNode.
201 inline unsigned getOpcode() const;
202 inline unsigned getNumOperands() const;
203 inline const SDValue &getOperand(unsigned i) const;
204 inline uint64_t getConstantOperandVal(unsigned i) const;
205 inline const APInt &getConstantOperandAPInt(unsigned i) const;
206 inline bool isTargetMemoryOpcode() const;
207 inline bool isTargetOpcode() const;
208 inline bool isMachineOpcode() const;
209 inline bool isUndef() const;
210 inline unsigned getMachineOpcode() const;
211 inline const DebugLoc &getDebugLoc() const;
212 inline void dump() const;
213 inline void dump(const SelectionDAG *G) const;
214 inline void dumpr() const;
215 inline void dumpr(const SelectionDAG *G) const;
216
217 /// Return true if this operand (which must be a chain) reaches the
218 /// specified operand without crossing any side-effecting instructions.
219 /// In practice, this looks through token factors and non-volatile loads.
220 /// In order to remain efficient, this only
221 /// looks a couple of nodes in, it does not do an exhaustive search.
222 bool reachesChainWithoutSideEffects(SDValue Dest,
223 unsigned Depth = 2) const;
224
225 /// Return true if there are no nodes using value ResNo of Node.
226 inline bool use_empty() const;
227
228 /// Return true if there is exactly one node using value ResNo of Node.
229 inline bool hasOneUse() const;
230};
231
232template<> struct DenseMapInfo<SDValue> {
233 static inline SDValue getEmptyKey() {
234 SDValue V;
235 V.ResNo = -1U;
236 return V;
237 }
238
239 static inline SDValue getTombstoneKey() {
240 SDValue V;
241 V.ResNo = -2U;
242 return V;
243 }
244
245 static unsigned getHashValue(const SDValue &Val) {
246 return ((unsigned)((uintptr_t)Val.getNode() >> 4) ^
247 (unsigned)((uintptr_t)Val.getNode() >> 9)) + Val.getResNo();
248 }
249
250 static bool isEqual(const SDValue &LHS, const SDValue &RHS) {
251 return LHS == RHS;
252 }
253};
254
255/// Allow casting operators to work directly on
256/// SDValues as if they were SDNode*'s.
257template<> struct simplify_type<SDValue> {
258 using SimpleType = SDNode *;
259
260 static SimpleType getSimplifiedValue(SDValue &Val) {
261 return Val.getNode();
39
Returning without writing to 'Val.Node'
262 }
263};
264template<> struct simplify_type<const SDValue> {
265 using SimpleType = /*const*/ SDNode *;
266
267 static SimpleType getSimplifiedValue(const SDValue &Val) {
268 return Val.getNode();
269 }
270};
271
272/// Represents a use of a SDNode. This class holds an SDValue,
273/// which records the SDNode being used and the result number, a
274/// pointer to the SDNode using the value, and Next and Prev pointers,
275/// which link together all the uses of an SDNode.
276///
277class SDUse {
278 /// Val - The value being used.
279 SDValue Val;
280 /// User - The user of this value.
281 SDNode *User = nullptr;
282 /// Prev, Next - Pointers to the uses list of the SDNode referred by
283 /// this operand.
284 SDUse **Prev = nullptr;
285 SDUse *Next = nullptr;
286
287public:
288 SDUse() = default;
289 SDUse(const SDUse &U) = delete;
290 SDUse &operator=(const SDUse &) = delete;
291
292 /// Normally SDUse will just implicitly convert to an SDValue that it holds.
293 operator const SDValue&() const { return Val; }
294
295 /// If implicit conversion to SDValue doesn't work, the get() method returns
296 /// the SDValue.
297 const SDValue &get() const { return Val; }
298
299 /// This returns the SDNode that contains this Use.
300 SDNode *getUser() { return User; }
301
302 /// Get the next SDUse in the use list.
303 SDUse *getNext() const { return Next; }
304
305 /// Convenience function for get().getNode().
306 SDNode *getNode() const { return Val.getNode(); }
307 /// Convenience function for get().getResNo().
308 unsigned getResNo() const { return Val.getResNo(); }
309 /// Convenience function for get().getValueType().
310 EVT getValueType() const { return Val.getValueType(); }
311
312 /// Convenience function for get().operator==
313 bool operator==(const SDValue &V) const {
314 return Val == V;
315 }
316
317 /// Convenience function for get().operator!=
318 bool operator!=(const SDValue &V) const {
319 return Val != V;
320 }
321
322 /// Convenience function for get().operator<
323 bool operator<(const SDValue &V) const {
324 return Val < V;
325 }
326
327private:
328 friend class SelectionDAG;
329 friend class SDNode;
330 // TODO: unfriend HandleSDNode once we fix its operand handling.
331 friend class HandleSDNode;
332
333 void setUser(SDNode *p) { User = p; }
334
335 /// Remove this use from its existing use list, assign it the
336 /// given value, and add it to the new value's node's use list.
337 inline void set(const SDValue &V);
338 /// Like set, but only supports initializing a newly-allocated
339 /// SDUse with a non-null value.
340 inline void setInitial(const SDValue &V);
341 /// Like set, but only sets the Node portion of the value,
342 /// leaving the ResNo portion unmodified.
343 inline void setNode(SDNode *N);
344
345 void addToList(SDUse **List) {
346 Next = *List;
347 if (Next) Next->Prev = &Next;
348 Prev = List;
349 *List = this;
350 }
351
352 void removeFromList() {
353 *Prev = Next;
354 if (Next) Next->Prev = Prev;
355 }
356};
357
358/// simplify_type specializations - Allow casting operators to work directly on
359/// SDValues as if they were SDNode*'s.
360template<> struct simplify_type<SDUse> {
361 using SimpleType = SDNode *;
362
363 static SimpleType getSimplifiedValue(SDUse &Val) {
364 return Val.getNode();
365 }
366};
367
368/// These are IR-level optimization flags that may be propagated to SDNodes.
369/// TODO: This data structure should be shared by the IR optimizer and the
370/// the backend.
371struct SDNodeFlags {
372private:
373 bool NoUnsignedWrap : 1;
374 bool NoSignedWrap : 1;
375 bool Exact : 1;
376 bool NoNaNs : 1;
377 bool NoInfs : 1;
378 bool NoSignedZeros : 1;
379 bool AllowReciprocal : 1;
380 bool AllowContract : 1;
381 bool ApproximateFuncs : 1;
382 bool AllowReassociation : 1;
383
384 // We assume instructions do not raise floating-point exceptions by default,
385 // and only those marked explicitly may do so. We could choose to represent
386 // this via a positive "FPExcept" flags like on the MI level, but having a
387 // negative "NoFPExcept" flag here (that defaults to true) makes the flag
388 // intersection logic more straightforward.
389 bool NoFPExcept : 1;
390
391public:
392 /// Default constructor turns off all optimization flags.
393 SDNodeFlags()
394 : NoUnsignedWrap(false), NoSignedWrap(false), Exact(false), NoNaNs(false),
395 NoInfs(false), NoSignedZeros(false), AllowReciprocal(false),
396 AllowContract(false), ApproximateFuncs(false),
397 AllowReassociation(false), NoFPExcept(false) {}
398
399 /// Propagate the fast-math-flags from an IR FPMathOperator.
400 void copyFMF(const FPMathOperator &FPMO) {
401 setNoNaNs(FPMO.hasNoNaNs());
402 setNoInfs(FPMO.hasNoInfs());
403 setNoSignedZeros(FPMO.hasNoSignedZeros());
404 setAllowReciprocal(FPMO.hasAllowReciprocal());
405 setAllowContract(FPMO.hasAllowContract());
406 setApproximateFuncs(FPMO.hasApproxFunc());
407 setAllowReassociation(FPMO.hasAllowReassoc());
408 }
409
410 // These are mutators for each flag.
411 void setNoUnsignedWrap(bool b) { NoUnsignedWrap = b; }
412 void setNoSignedWrap(bool b) { NoSignedWrap = b; }
413 void setExact(bool b) { Exact = b; }
414 void setNoNaNs(bool b) { NoNaNs = b; }
415 void setNoInfs(bool b) { NoInfs = b; }
416 void setNoSignedZeros(bool b) { NoSignedZeros = b; }
417 void setAllowReciprocal(bool b) { AllowReciprocal = b; }
418 void setAllowContract(bool b) { AllowContract = b; }
419 void setApproximateFuncs(bool b) { ApproximateFuncs = b; }
420 void setAllowReassociation(bool b) { AllowReassociation = b; }
421 void setNoFPExcept(bool b) { NoFPExcept = b; }
422
423 // These are accessors for each flag.
424 bool hasNoUnsignedWrap() const { return NoUnsignedWrap; }
425 bool hasNoSignedWrap() const { return NoSignedWrap; }
426 bool hasExact() const { return Exact; }
427 bool hasNoNaNs() const { return NoNaNs; }
428 bool hasNoInfs() const { return NoInfs; }
429 bool hasNoSignedZeros() const { return NoSignedZeros; }
430 bool hasAllowReciprocal() const { return AllowReciprocal; }
431 bool hasAllowContract() const { return AllowContract; }
432 bool hasApproximateFuncs() const { return ApproximateFuncs; }
433 bool hasAllowReassociation() const { return AllowReassociation; }
434 bool hasNoFPExcept() const { return NoFPExcept; }
435
436 /// Clear any flags in this flag set that aren't also set in Flags. All
437 /// flags will be cleared if Flags are undefined.
438 void intersectWith(const SDNodeFlags Flags) {
439 NoUnsignedWrap &= Flags.NoUnsignedWrap;
440 NoSignedWrap &= Flags.NoSignedWrap;
441 Exact &= Flags.Exact;
442 NoNaNs &= Flags.NoNaNs;
443 NoInfs &= Flags.NoInfs;
444 NoSignedZeros &= Flags.NoSignedZeros;
445 AllowReciprocal &= Flags.AllowReciprocal;
446 AllowContract &= Flags.AllowContract;
447 ApproximateFuncs &= Flags.ApproximateFuncs;
448 AllowReassociation &= Flags.AllowReassociation;
449 NoFPExcept &= Flags.NoFPExcept;
450 }
451};
452
453/// Represents one node in the SelectionDAG.
454///
455class SDNode : public FoldingSetNode, public ilist_node<SDNode> {
456private:
457 /// The operation that this node performs.
458 int16_t NodeType;
459
460protected:
461 // We define a set of mini-helper classes to help us interpret the bits in our
462 // SubclassData. These are designed to fit within a uint16_t so they pack
463 // with NodeType.
464
465#if defined(_AIX) && (!defined(__GNUC__4) || defined(__clang__1))
466// Except for GCC; by default, AIX compilers store bit-fields in 4-byte words
467// and give the `pack` pragma push semantics.
468#define BEGIN_TWO_BYTE_PACK() _Pragma("pack(2)")pack(2)
469#define END_TWO_BYTE_PACK() _Pragma("pack(pop)")pack(pop)
470#else
471#define BEGIN_TWO_BYTE_PACK()
472#define END_TWO_BYTE_PACK()
473#endif
474
475BEGIN_TWO_BYTE_PACK()
476 class SDNodeBitfields {
477 friend class SDNode;
478 friend class MemIntrinsicSDNode;
479 friend class MemSDNode;
480 friend class SelectionDAG;
481
482 uint16_t HasDebugValue : 1;
483 uint16_t IsMemIntrinsic : 1;
484 uint16_t IsDivergent : 1;
485 };
486 enum { NumSDNodeBits = 3 };
487
488 class ConstantSDNodeBitfields {
489 friend class ConstantSDNode;
490
491 uint16_t : NumSDNodeBits;
492
493 uint16_t IsOpaque : 1;
494 };
495
496 class MemSDNodeBitfields {
497 friend class MemSDNode;
498 friend class MemIntrinsicSDNode;
499 friend class AtomicSDNode;
500
501 uint16_t : NumSDNodeBits;
502
503 uint16_t IsVolatile : 1;
504 uint16_t IsNonTemporal : 1;
505 uint16_t IsDereferenceable : 1;
506 uint16_t IsInvariant : 1;
507 };
508 enum { NumMemSDNodeBits = NumSDNodeBits + 4 };
509
510 class LSBaseSDNodeBitfields {
511 friend class LSBaseSDNode;
512 friend class MaskedLoadStoreSDNode;
513 friend class MaskedGatherScatterSDNode;
514
515 uint16_t : NumMemSDNodeBits;
516
517 // This storage is shared between disparate class hierarchies to hold an
518 // enumeration specific to the class hierarchy in use.
519 // LSBaseSDNode => enum ISD::MemIndexedMode
520 // MaskedLoadStoreBaseSDNode => enum ISD::MemIndexedMode
521 // MaskedGatherScatterSDNode => enum ISD::MemIndexType
522 uint16_t AddressingMode : 3;
523 };
524 enum { NumLSBaseSDNodeBits = NumMemSDNodeBits + 3 };
525
526 class LoadSDNodeBitfields {
527 friend class LoadSDNode;
528 friend class MaskedLoadSDNode;
529 friend class MaskedGatherSDNode;
530
531 uint16_t : NumLSBaseSDNodeBits;
532
533 uint16_t ExtTy : 2; // enum ISD::LoadExtType
534 uint16_t IsExpanding : 1;
535 };
536
537 class StoreSDNodeBitfields {
538 friend class StoreSDNode;
539 friend class MaskedStoreSDNode;
540 friend class MaskedScatterSDNode;
541
542 uint16_t : NumLSBaseSDNodeBits;
543
544 uint16_t IsTruncating : 1;
545 uint16_t IsCompressing : 1;
546 };
547
548 union {
549 char RawSDNodeBits[sizeof(uint16_t)];
550 SDNodeBitfields SDNodeBits;
551 ConstantSDNodeBitfields ConstantSDNodeBits;
552 MemSDNodeBitfields MemSDNodeBits;
553 LSBaseSDNodeBitfields LSBaseSDNodeBits;
554 LoadSDNodeBitfields LoadSDNodeBits;
555 StoreSDNodeBitfields StoreSDNodeBits;
556 };
557END_TWO_BYTE_PACK()
558#undef BEGIN_TWO_BYTE_PACK
559#undef END_TWO_BYTE_PACK
560
561 // RawSDNodeBits must cover the entirety of the union. This means that all of
562 // the union's members must have size <= RawSDNodeBits. We write the RHS as
563 // "2" instead of sizeof(RawSDNodeBits) because MSVC can't handle the latter.
564 static_assert(sizeof(SDNodeBitfields) <= 2, "field too wide");
565 static_assert(sizeof(ConstantSDNodeBitfields) <= 2, "field too wide");
566 static_assert(sizeof(MemSDNodeBitfields) <= 2, "field too wide");
567 static_assert(sizeof(LSBaseSDNodeBitfields) <= 2, "field too wide");
568 static_assert(sizeof(LoadSDNodeBitfields) <= 2, "field too wide");
569 static_assert(sizeof(StoreSDNodeBitfields) <= 2, "field too wide");
570
571private:
572 friend class SelectionDAG;
573 // TODO: unfriend HandleSDNode once we fix its operand handling.
574 friend class HandleSDNode;
575
576 /// Unique id per SDNode in the DAG.
577 int NodeId = -1;
578
579 /// The values that are used by this operation.
580 SDUse *OperandList = nullptr;
581
582 /// The types of the values this node defines. SDNode's may
583 /// define multiple values simultaneously.
584 const EVT *ValueList;
585
586 /// List of uses for this SDNode.
587 SDUse *UseList = nullptr;
588
589 /// The number of entries in the Operand/Value list.
590 unsigned short NumOperands = 0;
591 unsigned short NumValues;
592
593 // The ordering of the SDNodes. It roughly corresponds to the ordering of the
594 // original LLVM instructions.
595 // This is used for turning off scheduling, because we'll forgo
596 // the normal scheduling algorithms and output the instructions according to
597 // this ordering.
598 unsigned IROrder;
599
600 /// Source line information.
601 DebugLoc debugLoc;
602
603 /// Return a pointer to the specified value type.
604 static const EVT *getValueTypeList(EVT VT);
605
606 SDNodeFlags Flags;
607
608public:
609 /// Unique and persistent id per SDNode in the DAG.
610 /// Used for debug printing.
611 uint16_t PersistentId;
612
613 //===--------------------------------------------------------------------===//
614 // Accessors
615 //
616
617 /// Return the SelectionDAG opcode value for this node. For
618 /// pre-isel nodes (those for which isMachineOpcode returns false), these
619 /// are the opcode values in the ISD and <target>ISD namespaces. For
620 /// post-isel opcodes, see getMachineOpcode.
621 unsigned getOpcode() const { return (unsigned short)NodeType; }
622
623 /// Test if this node has a target-specific opcode (in the
624 /// \<target\>ISD namespace).
625 bool isTargetOpcode() const { return NodeType >= ISD::BUILTIN_OP_END; }
626
627 /// Test if this node has a target-specific opcode that may raise
628 /// FP exceptions (in the \<target\>ISD namespace and greater than
629 /// FIRST_TARGET_STRICTFP_OPCODE). Note that all target memory
630 /// opcode are currently automatically considered to possibly raise
631 /// FP exceptions as well.
632 bool isTargetStrictFPOpcode() const {
633 return NodeType >= ISD::FIRST_TARGET_STRICTFP_OPCODE;
634 }
635
636 /// Test if this node has a target-specific
637 /// memory-referencing opcode (in the \<target\>ISD namespace and
638 /// greater than FIRST_TARGET_MEMORY_OPCODE).
639 bool isTargetMemoryOpcode() const {
640 return NodeType >= ISD::FIRST_TARGET_MEMORY_OPCODE;
641 }
642
643 /// Return true if the type of the node type undefined.
644 bool isUndef() const { return NodeType == ISD::UNDEF; }
645
646 /// Test if this node is a memory intrinsic (with valid pointer information).
647 /// INTRINSIC_W_CHAIN and INTRINSIC_VOID nodes are sometimes created for
648 /// non-memory intrinsics (with chains) that are not really instances of
649 /// MemSDNode. For such nodes, we need some extra state to determine the
650 /// proper classof relationship.
651 bool isMemIntrinsic() const {
652 return (NodeType == ISD::INTRINSIC_W_CHAIN ||
653 NodeType == ISD::INTRINSIC_VOID) &&
654 SDNodeBits.IsMemIntrinsic;
655 }
656
657 /// Test if this node is a strict floating point pseudo-op.
658 bool isStrictFPOpcode() {
659 switch (NodeType) {
660 default:
661 return false;
662 case ISD::STRICT_FP16_TO_FP:
663 case ISD::STRICT_FP_TO_FP16:
664#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
665 case ISD::STRICT_##DAGN:
666#include "llvm/IR/ConstrainedOps.def"
667 return true;
668 }
669 }
670
671 /// Test if this node has a post-isel opcode, directly
672 /// corresponding to a MachineInstr opcode.
673 bool isMachineOpcode() const { return NodeType < 0; }
674
675 /// This may only be called if isMachineOpcode returns
676 /// true. It returns the MachineInstr opcode value that the node's opcode
677 /// corresponds to.
678 unsigned getMachineOpcode() const {
679 assert(isMachineOpcode() && "Not a MachineInstr opcode!")(static_cast <bool> (isMachineOpcode() && "Not a MachineInstr opcode!"
) ? void (0) : __assert_fail ("isMachineOpcode() && \"Not a MachineInstr opcode!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 679, __extension__ __PRETTY_FUNCTION__))
;
680 return ~NodeType;
681 }
682
683 bool getHasDebugValue() const { return SDNodeBits.HasDebugValue; }
684 void setHasDebugValue(bool b) { SDNodeBits.HasDebugValue = b; }
685
686 bool isDivergent() const { return SDNodeBits.IsDivergent; }
687
688 /// Return true if there are no uses of this node.
689 bool use_empty() const { return UseList == nullptr; }
690
691 /// Return true if there is exactly one use of this node.
692 bool hasOneUse() const { return hasSingleElement(uses()); }
693
694 /// Return the number of uses of this node. This method takes
695 /// time proportional to the number of uses.
696 size_t use_size() const { return std::distance(use_begin(), use_end()); }
697
698 /// Return the unique node id.
699 int getNodeId() const { return NodeId; }
700
701 /// Set unique node id.
702 void setNodeId(int Id) { NodeId = Id; }
703
704 /// Return the node ordering.
705 unsigned getIROrder() const { return IROrder; }
706
707 /// Set the node ordering.
708 void setIROrder(unsigned Order) { IROrder = Order; }
709
710 /// Return the source location info.
711 const DebugLoc &getDebugLoc() const { return debugLoc; }
712
713 /// Set source location info. Try to avoid this, putting
714 /// it in the constructor is preferable.
715 void setDebugLoc(DebugLoc dl) { debugLoc = std::move(dl); }
716
717 /// This class provides iterator support for SDUse
718 /// operands that use a specific SDNode.
719 class use_iterator {
720 friend class SDNode;
721
722 SDUse *Op = nullptr;
723
724 explicit use_iterator(SDUse *op) : Op(op) {}
725
726 public:
727 using iterator_category = std::forward_iterator_tag;
728 using value_type = SDUse;
729 using difference_type = std::ptrdiff_t;
730 using pointer = value_type *;
731 using reference = value_type &;
732
733 use_iterator() = default;
734 use_iterator(const use_iterator &I) : Op(I.Op) {}
735
736 bool operator==(const use_iterator &x) const {
737 return Op == x.Op;
738 }
739 bool operator!=(const use_iterator &x) const {
740 return !operator==(x);
741 }
742
743 /// Return true if this iterator is at the end of uses list.
744 bool atEnd() const { return Op == nullptr; }
745
746 // Iterator traversal: forward iteration only.
747 use_iterator &operator++() { // Preincrement
748 assert(Op && "Cannot increment end iterator!")(static_cast <bool> (Op && "Cannot increment end iterator!"
) ? void (0) : __assert_fail ("Op && \"Cannot increment end iterator!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 748, __extension__ __PRETTY_FUNCTION__))
;
749 Op = Op->getNext();
750 return *this;
751 }
752
753 use_iterator operator++(int) { // Postincrement
754 use_iterator tmp = *this; ++*this; return tmp;
755 }
756
757 /// Retrieve a pointer to the current user node.
758 SDNode *operator*() const {
759 assert(Op && "Cannot dereference end iterator!")(static_cast <bool> (Op && "Cannot dereference end iterator!"
) ? void (0) : __assert_fail ("Op && \"Cannot dereference end iterator!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 759, __extension__ __PRETTY_FUNCTION__))
;
760 return Op->getUser();
761 }
762
763 SDNode *operator->() const { return operator*(); }
764
765 SDUse &getUse() const { return *Op; }
766
767 /// Retrieve the operand # of this use in its user.
768 unsigned getOperandNo() const {
769 assert(Op && "Cannot dereference end iterator!")(static_cast <bool> (Op && "Cannot dereference end iterator!"
) ? void (0) : __assert_fail ("Op && \"Cannot dereference end iterator!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 769, __extension__ __PRETTY_FUNCTION__))
;
770 return (unsigned)(Op - Op->getUser()->OperandList);
771 }
772 };
773
774 /// Provide iteration support to walk over all uses of an SDNode.
775 use_iterator use_begin() const {
776 return use_iterator(UseList);
777 }
778
779 static use_iterator use_end() { return use_iterator(nullptr); }
780
781 inline iterator_range<use_iterator> uses() {
782 return make_range(use_begin(), use_end());
783 }
784 inline iterator_range<use_iterator> uses() const {
785 return make_range(use_begin(), use_end());
786 }
787
788 /// Return true if there are exactly NUSES uses of the indicated value.
789 /// This method ignores uses of other values defined by this operation.
790 bool hasNUsesOfValue(unsigned NUses, unsigned Value) const;
791
792 /// Return true if there are any use of the indicated value.
793 /// This method ignores uses of other values defined by this operation.
794 bool hasAnyUseOfValue(unsigned Value) const;
795
796 /// Return true if this node is the only use of N.
797 bool isOnlyUserOf(const SDNode *N) const;
798
799 /// Return true if this node is an operand of N.
800 bool isOperandOf(const SDNode *N) const;
801
802 /// Return true if this node is a predecessor of N.
803 /// NOTE: Implemented on top of hasPredecessor and every bit as
804 /// expensive. Use carefully.
805 bool isPredecessorOf(const SDNode *N) const {
806 return N->hasPredecessor(this);
807 }
808
809 /// Return true if N is a predecessor of this node.
810 /// N is either an operand of this node, or can be reached by recursively
811 /// traversing up the operands.
812 /// NOTE: This is an expensive method. Use it carefully.
813 bool hasPredecessor(const SDNode *N) const;
814
815 /// Returns true if N is a predecessor of any node in Worklist. This
816 /// helper keeps Visited and Worklist sets externally to allow unions
817 /// searches to be performed in parallel, caching of results across
818 /// queries and incremental addition to Worklist. Stops early if N is
819 /// found but will resume. Remember to clear Visited and Worklists
820 /// if DAG changes. MaxSteps gives a maximum number of nodes to visit before
821 /// giving up. The TopologicalPrune flag signals that positive NodeIds are
822 /// topologically ordered (Operands have strictly smaller node id) and search
823 /// can be pruned leveraging this.
824 static bool hasPredecessorHelper(const SDNode *N,
825 SmallPtrSetImpl<const SDNode *> &Visited,
826 SmallVectorImpl<const SDNode *> &Worklist,
827 unsigned int MaxSteps = 0,
828 bool TopologicalPrune = false) {
829 SmallVector<const SDNode *, 8> DeferredNodes;
830 if (Visited.count(N))
831 return true;
832
833 // Node Id's are assigned in three places: As a topological
834 // ordering (> 0), during legalization (results in values set to
835 // 0), new nodes (set to -1). If N has a topolgical id then we
836 // know that all nodes with ids smaller than it cannot be
837 // successors and we need not check them. Filter out all node
838 // that can't be matches. We add them to the worklist before exit
839 // in case of multiple calls. Note that during selection the topological id
840 // may be violated if a node's predecessor is selected before it. We mark
841 // this at selection negating the id of unselected successors and
842 // restricting topological pruning to positive ids.
843
844 int NId = N->getNodeId();
845 // If we Invalidated the Id, reconstruct original NId.
846 if (NId < -1)
847 NId = -(NId + 1);
848
849 bool Found = false;
850 while (!Worklist.empty()) {
851 const SDNode *M = Worklist.pop_back_val();
852 int MId = M->getNodeId();
853 if (TopologicalPrune && M->getOpcode() != ISD::TokenFactor && (NId > 0) &&
854 (MId > 0) && (MId < NId)) {
855 DeferredNodes.push_back(M);
856 continue;
857 }
858 for (const SDValue &OpV : M->op_values()) {
859 SDNode *Op = OpV.getNode();
860 if (Visited.insert(Op).second)
861 Worklist.push_back(Op);
862 if (Op == N)
863 Found = true;
864 }
865 if (Found)
866 break;
867 if (MaxSteps != 0 && Visited.size() >= MaxSteps)
868 break;
869 }
870 // Push deferred nodes back on worklist.
871 Worklist.append(DeferredNodes.begin(), DeferredNodes.end());
872 // If we bailed early, conservatively return found.
873 if (MaxSteps != 0 && Visited.size() >= MaxSteps)
874 return true;
875 return Found;
876 }
877
878 /// Return true if all the users of N are contained in Nodes.
879 /// NOTE: Requires at least one match, but doesn't require them all.
880 static bool areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N);
881
882 /// Return the number of values used by this operation.
883 unsigned getNumOperands() const { return NumOperands; }
884
885 /// Return the maximum number of operands that a SDNode can hold.
886 static constexpr size_t getMaxNumOperands() {
887 return std::numeric_limits<decltype(SDNode::NumOperands)>::max();
888 }
889
890 /// Helper method returns the integer value of a ConstantSDNode operand.
891 inline uint64_t getConstantOperandVal(unsigned Num) const;
892
893 /// Helper method returns the APInt of a ConstantSDNode operand.
894 inline const APInt &getConstantOperandAPInt(unsigned Num) const;
895
896 const SDValue &getOperand(unsigned Num) const {
897 assert(Num < NumOperands && "Invalid child # of SDNode!")(static_cast <bool> (Num < NumOperands && "Invalid child # of SDNode!"
) ? void (0) : __assert_fail ("Num < NumOperands && \"Invalid child # of SDNode!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 897, __extension__ __PRETTY_FUNCTION__))
;
898 return OperandList[Num];
899 }
900
901 using op_iterator = SDUse *;
902
903 op_iterator op_begin() const { return OperandList; }
904 op_iterator op_end() const { return OperandList+NumOperands; }
905 ArrayRef<SDUse> ops() const { return makeArrayRef(op_begin(), op_end()); }
906
907 /// Iterator for directly iterating over the operand SDValue's.
908 struct value_op_iterator
909 : iterator_adaptor_base<value_op_iterator, op_iterator,
910 std::random_access_iterator_tag, SDValue,
911 ptrdiff_t, value_op_iterator *,
912 value_op_iterator *> {
913 explicit value_op_iterator(SDUse *U = nullptr)
914 : iterator_adaptor_base(U) {}
915
916 const SDValue &operator*() const { return I->get(); }
917 };
918
919 iterator_range<value_op_iterator> op_values() const {
920 return make_range(value_op_iterator(op_begin()),
921 value_op_iterator(op_end()));
922 }
923
924 SDVTList getVTList() const {
925 SDVTList X = { ValueList, NumValues };
926 return X;
927 }
928
929 /// If this node has a glue operand, return the node
930 /// to which the glue operand points. Otherwise return NULL.
931 SDNode *getGluedNode() const {
932 if (getNumOperands() != 0 &&
933 getOperand(getNumOperands()-1).getValueType() == MVT::Glue)
934 return getOperand(getNumOperands()-1).getNode();
935 return nullptr;
936 }
937
938 /// If this node has a glue value with a user, return
939 /// the user (there is at most one). Otherwise return NULL.
940 SDNode *getGluedUser() const {
941 for (use_iterator UI = use_begin(), UE = use_end(); UI != UE; ++UI)
942 if (UI.getUse().get().getValueType() == MVT::Glue)
943 return *UI;
944 return nullptr;
945 }
946
947 SDNodeFlags getFlags() const { return Flags; }
948 void setFlags(SDNodeFlags NewFlags) { Flags = NewFlags; }
949
950 /// Clear any flags in this node that aren't also set in Flags.
951 /// If Flags is not in a defined state then this has no effect.
952 void intersectFlagsWith(const SDNodeFlags Flags);
953
954 /// Return the number of values defined/returned by this operator.
955 unsigned getNumValues() const { return NumValues; }
956
957 /// Return the type of a specified result.
958 EVT getValueType(unsigned ResNo) const {
959 assert(ResNo < NumValues && "Illegal result number!")(static_cast <bool> (ResNo < NumValues && "Illegal result number!"
) ? void (0) : __assert_fail ("ResNo < NumValues && \"Illegal result number!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 959, __extension__ __PRETTY_FUNCTION__))
;
960 return ValueList[ResNo];
961 }
962
963 /// Return the type of a specified result as a simple type.
964 MVT getSimpleValueType(unsigned ResNo) const {
965 return getValueType(ResNo).getSimpleVT();
966 }
967
968 /// Returns MVT::getSizeInBits(getValueType(ResNo)).
969 ///
970 /// If the value type is a scalable vector type, the scalable property will
971 /// be set and the runtime size will be a positive integer multiple of the
972 /// base size.
973 TypeSize getValueSizeInBits(unsigned ResNo) const {
974 return getValueType(ResNo).getSizeInBits();
975 }
976
977 using value_iterator = const EVT *;
978
979 value_iterator value_begin() const { return ValueList; }
980 value_iterator value_end() const { return ValueList+NumValues; }
981 iterator_range<value_iterator> values() const {
982 return llvm::make_range(value_begin(), value_end());
983 }
984
985 /// Return the opcode of this operation for printing.
986 std::string getOperationName(const SelectionDAG *G = nullptr) const;
987 static const char* getIndexedModeName(ISD::MemIndexedMode AM);
988 void print_types(raw_ostream &OS, const SelectionDAG *G) const;
989 void print_details(raw_ostream &OS, const SelectionDAG *G) const;
990 void print(raw_ostream &OS, const SelectionDAG *G = nullptr) const;
991 void printr(raw_ostream &OS, const SelectionDAG *G = nullptr) const;
992
993 /// Print a SelectionDAG node and all children down to
994 /// the leaves. The given SelectionDAG allows target-specific nodes
995 /// to be printed in human-readable form. Unlike printr, this will
996 /// print the whole DAG, including children that appear multiple
997 /// times.
998 ///
999 void printrFull(raw_ostream &O, const SelectionDAG *G = nullptr) const;
1000
1001 /// Print a SelectionDAG node and children up to
1002 /// depth "depth." The given SelectionDAG allows target-specific
1003 /// nodes to be printed in human-readable form. Unlike printr, this
1004 /// will print children that appear multiple times wherever they are
1005 /// used.
1006 ///
1007 void printrWithDepth(raw_ostream &O, const SelectionDAG *G = nullptr,
1008 unsigned depth = 100) const;
1009
1010 /// Dump this node, for debugging.
1011 void dump() const;
1012
1013 /// Dump (recursively) this node and its use-def subgraph.
1014 void dumpr() const;
1015
1016 /// Dump this node, for debugging.
1017 /// The given SelectionDAG allows target-specific nodes to be printed
1018 /// in human-readable form.
1019 void dump(const SelectionDAG *G) const;
1020
1021 /// Dump (recursively) this node and its use-def subgraph.
1022 /// The given SelectionDAG allows target-specific nodes to be printed
1023 /// in human-readable form.
1024 void dumpr(const SelectionDAG *G) const;
1025
1026 /// printrFull to dbgs(). The given SelectionDAG allows
1027 /// target-specific nodes to be printed in human-readable form.
1028 /// Unlike dumpr, this will print the whole DAG, including children
1029 /// that appear multiple times.
1030 void dumprFull(const SelectionDAG *G = nullptr) const;
1031
1032 /// printrWithDepth to dbgs(). The given
1033 /// SelectionDAG allows target-specific nodes to be printed in
1034 /// human-readable form. Unlike dumpr, this will print children
1035 /// that appear multiple times wherever they are used.
1036 ///
1037 void dumprWithDepth(const SelectionDAG *G = nullptr,
1038 unsigned depth = 100) const;
1039
1040 /// Gather unique data for the node.
1041 void Profile(FoldingSetNodeID &ID) const;
1042
1043 /// This method should only be used by the SDUse class.
1044 void addUse(SDUse &U) { U.addToList(&UseList); }
1045
1046protected:
1047 static SDVTList getSDVTList(EVT VT) {
1048 SDVTList Ret = { getValueTypeList(VT), 1 };
1049 return Ret;
1050 }
1051
1052 /// Create an SDNode.
1053 ///
1054 /// SDNodes are created without any operands, and never own the operand
1055 /// storage. To add operands, see SelectionDAG::createOperands.
1056 SDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs)
1057 : NodeType(Opc), ValueList(VTs.VTs), NumValues(VTs.NumVTs),
1058 IROrder(Order), debugLoc(std::move(dl)) {
1059 memset(&RawSDNodeBits, 0, sizeof(RawSDNodeBits));
1060 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor")(static_cast <bool> (debugLoc.hasTrivialDestructor() &&
"Expected trivial destructor") ? void (0) : __assert_fail ("debugLoc.hasTrivialDestructor() && \"Expected trivial destructor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1060, __extension__ __PRETTY_FUNCTION__))
;
1061 assert(NumValues == VTs.NumVTs &&(static_cast <bool> (NumValues == VTs.NumVTs &&
"NumValues wasn't wide enough for its operands!") ? void (0)
: __assert_fail ("NumValues == VTs.NumVTs && \"NumValues wasn't wide enough for its operands!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1062, __extension__ __PRETTY_FUNCTION__))
1062 "NumValues wasn't wide enough for its operands!")(static_cast <bool> (NumValues == VTs.NumVTs &&
"NumValues wasn't wide enough for its operands!") ? void (0)
: __assert_fail ("NumValues == VTs.NumVTs && \"NumValues wasn't wide enough for its operands!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1062, __extension__ __PRETTY_FUNCTION__))
;
1063 }
1064
1065 /// Release the operands and set this node to have zero operands.
1066 void DropOperands();
1067};
1068
1069/// Wrapper class for IR location info (IR ordering and DebugLoc) to be passed
1070/// into SDNode creation functions.
1071/// When an SDNode is created from the DAGBuilder, the DebugLoc is extracted
1072/// from the original Instruction, and IROrder is the ordinal position of
1073/// the instruction.
1074/// When an SDNode is created after the DAG is being built, both DebugLoc and
1075/// the IROrder are propagated from the original SDNode.
1076/// So SDLoc class provides two constructors besides the default one, one to
1077/// be used by the DAGBuilder, the other to be used by others.
1078class SDLoc {
1079private:
1080 DebugLoc DL;
1081 int IROrder = 0;
1082
1083public:
1084 SDLoc() = default;
1085 SDLoc(const SDNode *N) : DL(N->getDebugLoc()), IROrder(N->getIROrder()) {}
1086 SDLoc(const SDValue V) : SDLoc(V.getNode()) {}
1087 SDLoc(const Instruction *I, int Order) : IROrder(Order) {
1088 assert(Order >= 0 && "bad IROrder")(static_cast <bool> (Order >= 0 && "bad IROrder"
) ? void (0) : __assert_fail ("Order >= 0 && \"bad IROrder\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1088, __extension__ __PRETTY_FUNCTION__))
;
1089 if (I)
1090 DL = I->getDebugLoc();
1091 }
1092
1093 unsigned getIROrder() const { return IROrder; }
1094 const DebugLoc &getDebugLoc() const { return DL; }
1095};
1096
1097// Define inline functions from the SDValue class.
1098
1099inline SDValue::SDValue(SDNode *node, unsigned resno)
1100 : Node(node), ResNo(resno) {
1101 // Explicitly check for !ResNo to avoid use-after-free, because there are
1102 // callers that use SDValue(N, 0) with a deleted N to indicate successful
1103 // combines.
1104 assert((!Node || !ResNo || ResNo < Node->getNumValues()) &&(static_cast <bool> ((!Node || !ResNo || ResNo < Node
->getNumValues()) && "Invalid result number for the given node!"
) ? void (0) : __assert_fail ("(!Node || !ResNo || ResNo < Node->getNumValues()) && \"Invalid result number for the given node!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1105, __extension__ __PRETTY_FUNCTION__))
1105 "Invalid result number for the given node!")(static_cast <bool> ((!Node || !ResNo || ResNo < Node
->getNumValues()) && "Invalid result number for the given node!"
) ? void (0) : __assert_fail ("(!Node || !ResNo || ResNo < Node->getNumValues()) && \"Invalid result number for the given node!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1105, __extension__ __PRETTY_FUNCTION__))
;
1106 assert(ResNo < -2U && "Cannot use result numbers reserved for DenseMaps.")(static_cast <bool> (ResNo < -2U && "Cannot use result numbers reserved for DenseMaps."
) ? void (0) : __assert_fail ("ResNo < -2U && \"Cannot use result numbers reserved for DenseMaps.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1106, __extension__ __PRETTY_FUNCTION__))
;
1107}
1108
1109inline unsigned SDValue::getOpcode() const {
1110 return Node->getOpcode();
1111}
1112
1113inline EVT SDValue::getValueType() const {
1114 return Node->getValueType(ResNo);
1115}
1116
1117inline unsigned SDValue::getNumOperands() const {
1118 return Node->getNumOperands();
1119}
1120
1121inline const SDValue &SDValue::getOperand(unsigned i) const {
1122 return Node->getOperand(i);
51
Called C++ object pointer is null
1123}
1124
1125inline uint64_t SDValue::getConstantOperandVal(unsigned i) const {
1126 return Node->getConstantOperandVal(i);
1127}
1128
1129inline const APInt &SDValue::getConstantOperandAPInt(unsigned i) const {
1130 return Node->getConstantOperandAPInt(i);
1131}
1132
1133inline bool SDValue::isTargetOpcode() const {
1134 return Node->isTargetOpcode();
1135}
1136
1137inline bool SDValue::isTargetMemoryOpcode() const {
1138 return Node->isTargetMemoryOpcode();
1139}
1140
1141inline bool SDValue::isMachineOpcode() const {
1142 return Node->isMachineOpcode();
1143}
1144
1145inline unsigned SDValue::getMachineOpcode() const {
1146 return Node->getMachineOpcode();
1147}
1148
1149inline bool SDValue::isUndef() const {
1150 return Node->isUndef();
1151}
1152
1153inline bool SDValue::use_empty() const {
1154 return !Node->hasAnyUseOfValue(ResNo);
1155}
1156
1157inline bool SDValue::hasOneUse() const {
1158 return Node->hasNUsesOfValue(1, ResNo);
1159}
1160
1161inline const DebugLoc &SDValue::getDebugLoc() const {
1162 return Node->getDebugLoc();
1163}
1164
1165inline void SDValue::dump() const {
1166 return Node->dump();
1167}
1168
1169inline void SDValue::dump(const SelectionDAG *G) const {
1170 return Node->dump(G);
1171}
1172
1173inline void SDValue::dumpr() const {
1174 return Node->dumpr();
1175}
1176
1177inline void SDValue::dumpr(const SelectionDAG *G) const {
1178 return Node->dumpr(G);
1179}
1180
1181// Define inline functions from the SDUse class.
1182
1183inline void SDUse::set(const SDValue &V) {
1184 if (Val.getNode()) removeFromList();
1185 Val = V;
1186 if (V.getNode()) V.getNode()->addUse(*this);
1187}
1188
1189inline void SDUse::setInitial(const SDValue &V) {
1190 Val = V;
1191 V.getNode()->addUse(*this);
1192}
1193
1194inline void SDUse::setNode(SDNode *N) {
1195 if (Val.getNode()) removeFromList();
1196 Val.setNode(N);
1197 if (N) N->addUse(*this);
1198}
1199
1200/// This class is used to form a handle around another node that
1201/// is persistent and is updated across invocations of replaceAllUsesWith on its
1202/// operand. This node should be directly created by end-users and not added to
1203/// the AllNodes list.
1204class HandleSDNode : public SDNode {
1205 SDUse Op;
1206
1207public:
1208 explicit HandleSDNode(SDValue X)
1209 : SDNode(ISD::HANDLENODE, 0, DebugLoc(), getSDVTList(MVT::Other)) {
1210 // HandleSDNodes are never inserted into the DAG, so they won't be
1211 // auto-numbered. Use ID 65535 as a sentinel.
1212 PersistentId = 0xffff;
1213
1214 // Manually set up the operand list. This node type is special in that it's
1215 // always stack allocated and SelectionDAG does not manage its operands.
1216 // TODO: This should either (a) not be in the SDNode hierarchy, or (b) not
1217 // be so special.
1218 Op.setUser(this);
1219 Op.setInitial(X);
1220 NumOperands = 1;
1221 OperandList = &Op;
1222 }
1223 ~HandleSDNode();
1224
1225 const SDValue &getValue() const { return Op; }
1226};
1227
1228class AddrSpaceCastSDNode : public SDNode {
1229private:
1230 unsigned SrcAddrSpace;
1231 unsigned DestAddrSpace;
1232
1233public:
1234 AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, EVT VT,
1235 unsigned SrcAS, unsigned DestAS);
1236
1237 unsigned getSrcAddressSpace() const { return SrcAddrSpace; }
1238 unsigned getDestAddressSpace() const { return DestAddrSpace; }
1239
1240 static bool classof(const SDNode *N) {
1241 return N->getOpcode() == ISD::ADDRSPACECAST;
1242 }
1243};
1244
1245/// This is an abstract virtual class for memory operations.
1246class MemSDNode : public SDNode {
1247private:
1248 // VT of in-memory value.
1249 EVT MemoryVT;
1250
1251protected:
1252 /// Memory reference information.
1253 MachineMemOperand *MMO;
1254
1255public:
1256 MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs,
1257 EVT memvt, MachineMemOperand *MMO);
1258
1259 bool readMem() const { return MMO->isLoad(); }
1260 bool writeMem() const { return MMO->isStore(); }
1261
1262 /// Returns alignment and volatility of the memory access
1263 Align getOriginalAlign() const { return MMO->getBaseAlign(); }
1264 Align getAlign() const { return MMO->getAlign(); }
1265 // FIXME: Remove once transition to getAlign is over.
1266 unsigned getAlignment() const { return MMO->getAlign().value(); }
1267
1268 /// Return the SubclassData value, without HasDebugValue. This contains an
1269 /// encoding of the volatile flag, as well as bits used by subclasses. This
1270 /// function should only be used to compute a FoldingSetNodeID value.
1271 /// The HasDebugValue bit is masked out because CSE map needs to match
1272 /// nodes with debug info with nodes without debug info. Same is about
1273 /// isDivergent bit.
1274 unsigned getRawSubclassData() const {
1275 uint16_t Data;
1276 union {
1277 char RawSDNodeBits[sizeof(uint16_t)];
1278 SDNodeBitfields SDNodeBits;
1279 };
1280 memcpy(&RawSDNodeBits, &this->RawSDNodeBits, sizeof(this->RawSDNodeBits));
1281 SDNodeBits.HasDebugValue = 0;
1282 SDNodeBits.IsDivergent = false;
1283 memcpy(&Data, &RawSDNodeBits, sizeof(RawSDNodeBits));
1284 return Data;
1285 }
1286
1287 bool isVolatile() const { return MemSDNodeBits.IsVolatile; }
1288 bool isNonTemporal() const { return MemSDNodeBits.IsNonTemporal; }
1289 bool isDereferenceable() const { return MemSDNodeBits.IsDereferenceable; }
1290 bool isInvariant() const { return MemSDNodeBits.IsInvariant; }
1291
1292 // Returns the offset from the location of the access.
1293 int64_t getSrcValueOffset() const { return MMO->getOffset(); }
1294
1295 /// Returns the AA info that describes the dereference.
1296 AAMDNodes getAAInfo() const { return MMO->getAAInfo(); }
1297
1298 /// Returns the Ranges that describes the dereference.
1299 const MDNode *getRanges() const { return MMO->getRanges(); }
1300
1301 /// Returns the synchronization scope ID for this memory operation.
1302 SyncScope::ID getSyncScopeID() const { return MMO->getSyncScopeID(); }
1303
1304 /// Return the atomic ordering requirements for this memory operation. For
1305 /// cmpxchg atomic operations, return the atomic ordering requirements when
1306 /// store occurs.
1307 AtomicOrdering getSuccessOrdering() const {
1308 return MMO->getSuccessOrdering();
1309 }
1310
1311 /// Return a single atomic ordering that is at least as strong as both the
1312 /// success and failure orderings for an atomic operation. (For operations
1313 /// other than cmpxchg, this is equivalent to getSuccessOrdering().)
1314 AtomicOrdering getMergedOrdering() const { return MMO->getMergedOrdering(); }
1315
1316 /// Return true if the memory operation ordering is Unordered or higher.
1317 bool isAtomic() const { return MMO->isAtomic(); }
1318
1319 /// Returns true if the memory operation doesn't imply any ordering
1320 /// constraints on surrounding memory operations beyond the normal memory
1321 /// aliasing rules.
1322 bool isUnordered() const { return MMO->isUnordered(); }
1323
1324 /// Returns true if the memory operation is neither atomic or volatile.
1325 bool isSimple() const { return !isAtomic() && !isVolatile(); }
1326
1327 /// Return the type of the in-memory value.
1328 EVT getMemoryVT() const { return MemoryVT; }
1329
1330 /// Return a MachineMemOperand object describing the memory
1331 /// reference performed by operation.
1332 MachineMemOperand *getMemOperand() const { return MMO; }
1333
1334 const MachinePointerInfo &getPointerInfo() const {
1335 return MMO->getPointerInfo();
1336 }
1337
1338 /// Return the address space for the associated pointer
1339 unsigned getAddressSpace() const {
1340 return getPointerInfo().getAddrSpace();
1341 }
1342
1343 /// Update this MemSDNode's MachineMemOperand information
1344 /// to reflect the alignment of NewMMO, if it has a greater alignment.
1345 /// This must only be used when the new alignment applies to all users of
1346 /// this MachineMemOperand.
1347 void refineAlignment(const MachineMemOperand *NewMMO) {
1348 MMO->refineAlignment(NewMMO);
1349 }
1350
1351 const SDValue &getChain() const { return getOperand(0); }
1352
1353 const SDValue &getBasePtr() const {
1354 switch (getOpcode()) {
1355 case ISD::STORE:
1356 case ISD::MSTORE:
1357 return getOperand(2);
1358 case ISD::MGATHER:
1359 case ISD::MSCATTER:
1360 return getOperand(3);
1361 default:
1362 return getOperand(1);
1363 }
1364 }
1365
1366 // Methods to support isa and dyn_cast
1367 static bool classof(const SDNode *N) {
1368 // For some targets, we lower some target intrinsics to a MemIntrinsicNode
1369 // with either an intrinsic or a target opcode.
1370 switch (N->getOpcode()) {
1371 case ISD::LOAD:
1372 case ISD::STORE:
1373 case ISD::PREFETCH:
1374 case ISD::ATOMIC_CMP_SWAP:
1375 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1376 case ISD::ATOMIC_SWAP:
1377 case ISD::ATOMIC_LOAD_ADD:
1378 case ISD::ATOMIC_LOAD_SUB:
1379 case ISD::ATOMIC_LOAD_AND:
1380 case ISD::ATOMIC_LOAD_CLR:
1381 case ISD::ATOMIC_LOAD_OR:
1382 case ISD::ATOMIC_LOAD_XOR:
1383 case ISD::ATOMIC_LOAD_NAND:
1384 case ISD::ATOMIC_LOAD_MIN:
1385 case ISD::ATOMIC_LOAD_MAX:
1386 case ISD::ATOMIC_LOAD_UMIN:
1387 case ISD::ATOMIC_LOAD_UMAX:
1388 case ISD::ATOMIC_LOAD_FADD:
1389 case ISD::ATOMIC_LOAD_FSUB:
1390 case ISD::ATOMIC_LOAD:
1391 case ISD::ATOMIC_STORE:
1392 case ISD::MLOAD:
1393 case ISD::MSTORE:
1394 case ISD::MGATHER:
1395 case ISD::MSCATTER:
1396 return true;
1397 default:
1398 return N->isMemIntrinsic() || N->isTargetMemoryOpcode();
1399 }
1400 }
1401};
1402
1403/// This is an SDNode representing atomic operations.
1404class AtomicSDNode : public MemSDNode {
1405public:
1406 AtomicSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTL,
1407 EVT MemVT, MachineMemOperand *MMO)
1408 : MemSDNode(Opc, Order, dl, VTL, MemVT, MMO) {
1409 assert(((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE) ||(static_cast <bool> (((Opc != ISD::ATOMIC_LOAD &&
Opc != ISD::ATOMIC_STORE) || MMO->isAtomic()) && "then why are we using an AtomicSDNode?"
) ? void (0) : __assert_fail ("((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE) || MMO->isAtomic()) && \"then why are we using an AtomicSDNode?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1410, __extension__ __PRETTY_FUNCTION__))
1410 MMO->isAtomic()) && "then why are we using an AtomicSDNode?")(static_cast <bool> (((Opc != ISD::ATOMIC_LOAD &&
Opc != ISD::ATOMIC_STORE) || MMO->isAtomic()) && "then why are we using an AtomicSDNode?"
) ? void (0) : __assert_fail ("((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE) || MMO->isAtomic()) && \"then why are we using an AtomicSDNode?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1410, __extension__ __PRETTY_FUNCTION__))
;
1411 }
1412
1413 const SDValue &getBasePtr() const { return getOperand(1); }
1414 const SDValue &getVal() const { return getOperand(2); }
1415
1416 /// Returns true if this SDNode represents cmpxchg atomic operation, false
1417 /// otherwise.
1418 bool isCompareAndSwap() const {
1419 unsigned Op = getOpcode();
1420 return Op == ISD::ATOMIC_CMP_SWAP ||
1421 Op == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS;
1422 }
1423
1424 /// For cmpxchg atomic operations, return the atomic ordering requirements
1425 /// when store does not occur.
1426 AtomicOrdering getFailureOrdering() const {
1427 assert(isCompareAndSwap() && "Must be cmpxchg operation")(static_cast <bool> (isCompareAndSwap() && "Must be cmpxchg operation"
) ? void (0) : __assert_fail ("isCompareAndSwap() && \"Must be cmpxchg operation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1427, __extension__ __PRETTY_FUNCTION__))
;
1428 return MMO->getFailureOrdering();
1429 }
1430
1431 // Methods to support isa and dyn_cast
1432 static bool classof(const SDNode *N) {
1433 return N->getOpcode() == ISD::ATOMIC_CMP_SWAP ||
1434 N->getOpcode() == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS ||
1435 N->getOpcode() == ISD::ATOMIC_SWAP ||
1436 N->getOpcode() == ISD::ATOMIC_LOAD_ADD ||
1437 N->getOpcode() == ISD::ATOMIC_LOAD_SUB ||
1438 N->getOpcode() == ISD::ATOMIC_LOAD_AND ||
1439 N->getOpcode() == ISD::ATOMIC_LOAD_CLR ||
1440 N->getOpcode() == ISD::ATOMIC_LOAD_OR ||
1441 N->getOpcode() == ISD::ATOMIC_LOAD_XOR ||
1442 N->getOpcode() == ISD::ATOMIC_LOAD_NAND ||
1443 N->getOpcode() == ISD::ATOMIC_LOAD_MIN ||
1444 N->getOpcode() == ISD::ATOMIC_LOAD_MAX ||
1445 N->getOpcode() == ISD::ATOMIC_LOAD_UMIN ||
1446 N->getOpcode() == ISD::ATOMIC_LOAD_UMAX ||
1447 N->getOpcode() == ISD::ATOMIC_LOAD_FADD ||
1448 N->getOpcode() == ISD::ATOMIC_LOAD_FSUB ||
1449 N->getOpcode() == ISD::ATOMIC_LOAD ||
1450 N->getOpcode() == ISD::ATOMIC_STORE;
1451 }
1452};
1453
1454/// This SDNode is used for target intrinsics that touch
1455/// memory and need an associated MachineMemOperand. Its opcode may be
1456/// INTRINSIC_VOID, INTRINSIC_W_CHAIN, PREFETCH, or a target-specific opcode
1457/// with a value not less than FIRST_TARGET_MEMORY_OPCODE.
1458class MemIntrinsicSDNode : public MemSDNode {
1459public:
1460 MemIntrinsicSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
1461 SDVTList VTs, EVT MemoryVT, MachineMemOperand *MMO)
1462 : MemSDNode(Opc, Order, dl, VTs, MemoryVT, MMO) {
1463 SDNodeBits.IsMemIntrinsic = true;
1464 }
1465
1466 // Methods to support isa and dyn_cast
1467 static bool classof(const SDNode *N) {
1468 // We lower some target intrinsics to their target opcode
1469 // early a node with a target opcode can be of this class
1470 return N->isMemIntrinsic() ||
1471 N->getOpcode() == ISD::PREFETCH ||
1472 N->isTargetMemoryOpcode();
1473 }
1474};
1475
1476/// This SDNode is used to implement the code generator
1477/// support for the llvm IR shufflevector instruction. It combines elements
1478/// from two input vectors into a new input vector, with the selection and
1479/// ordering of elements determined by an array of integers, referred to as
1480/// the shuffle mask. For input vectors of width N, mask indices of 0..N-1
1481/// refer to elements from the LHS input, and indices from N to 2N-1 the RHS.
1482/// An index of -1 is treated as undef, such that the code generator may put
1483/// any value in the corresponding element of the result.
1484class ShuffleVectorSDNode : public SDNode {
1485 // The memory for Mask is owned by the SelectionDAG's OperandAllocator, and
1486 // is freed when the SelectionDAG object is destroyed.
1487 const int *Mask;
1488
1489protected:
1490 friend class SelectionDAG;
1491
1492 ShuffleVectorSDNode(EVT VT, unsigned Order, const DebugLoc &dl, const int *M)
1493 : SDNode(ISD::VECTOR_SHUFFLE, Order, dl, getSDVTList(VT)), Mask(M) {}
1494
1495public:
1496 ArrayRef<int> getMask() const {
1497 EVT VT = getValueType(0);
1498 return makeArrayRef(Mask, VT.getVectorNumElements());
1499 }
1500
1501 int getMaskElt(unsigned Idx) const {
1502 assert(Idx < getValueType(0).getVectorNumElements() && "Idx out of range!")(static_cast <bool> (Idx < getValueType(0).getVectorNumElements
() && "Idx out of range!") ? void (0) : __assert_fail
("Idx < getValueType(0).getVectorNumElements() && \"Idx out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1502, __extension__ __PRETTY_FUNCTION__))
;
1503 return Mask[Idx];
1504 }
1505
1506 bool isSplat() const { return isSplatMask(Mask, getValueType(0)); }
1507
1508 int getSplatIndex() const {
1509 assert(isSplat() && "Cannot get splat index for non-splat!")(static_cast <bool> (isSplat() && "Cannot get splat index for non-splat!"
) ? void (0) : __assert_fail ("isSplat() && \"Cannot get splat index for non-splat!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1509, __extension__ __PRETTY_FUNCTION__))
;
1510 EVT VT = getValueType(0);
1511 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1512 if (Mask[i] >= 0)
1513 return Mask[i];
1514
1515 // We can choose any index value here and be correct because all elements
1516 // are undefined. Return 0 for better potential for callers to simplify.
1517 return 0;
1518 }
1519
1520 static bool isSplatMask(const int *Mask, EVT VT);
1521
1522 /// Change values in a shuffle permute mask assuming
1523 /// the two vector operands have swapped position.
1524 static void commuteMask(MutableArrayRef<int> Mask) {
1525 unsigned NumElems = Mask.size();
1526 for (unsigned i = 0; i != NumElems; ++i) {
1527 int idx = Mask[i];
1528 if (idx < 0)
1529 continue;
1530 else if (idx < (int)NumElems)
1531 Mask[i] = idx + NumElems;
1532 else
1533 Mask[i] = idx - NumElems;
1534 }
1535 }
1536
1537 static bool classof(const SDNode *N) {
1538 return N->getOpcode() == ISD::VECTOR_SHUFFLE;
1539 }
1540};
1541
1542class ConstantSDNode : public SDNode {
1543 friend class SelectionDAG;
1544
1545 const ConstantInt *Value;
1546
1547 ConstantSDNode(bool isTarget, bool isOpaque, const ConstantInt *val, EVT VT)
1548 : SDNode(isTarget ? ISD::TargetConstant : ISD::Constant, 0, DebugLoc(),
1549 getSDVTList(VT)),
1550 Value(val) {
1551 ConstantSDNodeBits.IsOpaque = isOpaque;
1552 }
1553
1554public:
1555 const ConstantInt *getConstantIntValue() const { return Value; }
1556 const APInt &getAPIntValue() const { return Value->getValue(); }
1557 uint64_t getZExtValue() const { return Value->getZExtValue(); }
1558 int64_t getSExtValue() const { return Value->getSExtValue(); }
1559 uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX(18446744073709551615UL)) {
1560 return Value->getLimitedValue(Limit);
1561 }
1562 MaybeAlign getMaybeAlignValue() const { return Value->getMaybeAlignValue(); }
1563 Align getAlignValue() const { return Value->getAlignValue(); }
1564
1565 bool isOne() const { return Value->isOne(); }
1566 bool isNullValue() const { return Value->isZero(); }
1567 bool isAllOnesValue() const { return Value->isMinusOne(); }
1568
1569 bool isOpaque() const { return ConstantSDNodeBits.IsOpaque; }
1570
1571 static bool classof(const SDNode *N) {
1572 return N->getOpcode() == ISD::Constant ||
1573 N->getOpcode() == ISD::TargetConstant;
1574 }
1575};
1576
1577uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
1578 return cast<ConstantSDNode>(getOperand(Num))->getZExtValue();
1579}
1580
1581const APInt &SDNode::getConstantOperandAPInt(unsigned Num) const {
1582 return cast<ConstantSDNode>(getOperand(Num))->getAPIntValue();
1583}
1584
1585class ConstantFPSDNode : public SDNode {
1586 friend class SelectionDAG;
1587
1588 const ConstantFP *Value;
1589
1590 ConstantFPSDNode(bool isTarget, const ConstantFP *val, EVT VT)
1591 : SDNode(isTarget ? ISD::TargetConstantFP : ISD::ConstantFP, 0,
1592 DebugLoc(), getSDVTList(VT)),
1593 Value(val) {}
1594
1595public:
1596 const APFloat& getValueAPF() const { return Value->getValueAPF(); }
1597 const ConstantFP *getConstantFPValue() const { return Value; }
1598
1599 /// Return true if the value is positive or negative zero.
1600 bool isZero() const { return Value->isZero(); }
1601
1602 /// Return true if the value is a NaN.
1603 bool isNaN() const { return Value->isNaN(); }
1604
1605 /// Return true if the value is an infinity
1606 bool isInfinity() const { return Value->isInfinity(); }
1607
1608 /// Return true if the value is negative.
1609 bool isNegative() const { return Value->isNegative(); }
1610
1611 /// We don't rely on operator== working on double values, as
1612 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
1613 /// As such, this method can be used to do an exact bit-for-bit comparison of
1614 /// two floating point values.
1615
1616 /// We leave the version with the double argument here because it's just so
1617 /// convenient to write "2.0" and the like. Without this function we'd
1618 /// have to duplicate its logic everywhere it's called.
1619 bool isExactlyValue(double V) const {
1620 return Value->getValueAPF().isExactlyValue(V);
1621 }
1622 bool isExactlyValue(const APFloat& V) const;
1623
1624 static bool isValueValidForType(EVT VT, const APFloat& Val);
1625
1626 static bool classof(const SDNode *N) {
1627 return N->getOpcode() == ISD::ConstantFP ||
1628 N->getOpcode() == ISD::TargetConstantFP;
1629 }
1630};
1631
1632/// Returns true if \p V is a constant integer zero.
1633bool isNullConstant(SDValue V);
1634
1635/// Returns true if \p V is an FP constant with a value of positive zero.
1636bool isNullFPConstant(SDValue V);
1637
1638/// Returns true if \p V is an integer constant with all bits set.
1639bool isAllOnesConstant(SDValue V);
1640
1641/// Returns true if \p V is a constant integer one.
1642bool isOneConstant(SDValue V);
1643
1644/// Return the non-bitcasted source operand of \p V if it exists.
1645/// If \p V is not a bitcasted value, it is returned as-is.
1646SDValue peekThroughBitcasts(SDValue V);
1647
1648/// Return the non-bitcasted and one-use source operand of \p V if it exists.
1649/// If \p V is not a bitcasted one-use value, it is returned as-is.
1650SDValue peekThroughOneUseBitcasts(SDValue V);
1651
1652/// Return the non-extracted vector source operand of \p V if it exists.
1653/// If \p V is not an extracted subvector, it is returned as-is.
1654SDValue peekThroughExtractSubvectors(SDValue V);
1655
1656/// Returns true if \p V is a bitwise not operation. Assumes that an all ones
1657/// constant is canonicalized to be operand 1.
1658bool isBitwiseNot(SDValue V, bool AllowUndefs = false);
1659
1660/// Returns the SDNode if it is a constant splat BuildVector or constant int.
1661ConstantSDNode *isConstOrConstSplat(SDValue N, bool AllowUndefs = false,
1662 bool AllowTruncation = false);
1663
1664/// Returns the SDNode if it is a demanded constant splat BuildVector or
1665/// constant int.
1666ConstantSDNode *isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
1667 bool AllowUndefs = false,
1668 bool AllowTruncation = false);
1669
1670/// Returns the SDNode if it is a constant splat BuildVector or constant float.
1671ConstantFPSDNode *isConstOrConstSplatFP(SDValue N, bool AllowUndefs = false);
1672
1673/// Returns the SDNode if it is a demanded constant splat BuildVector or
1674/// constant float.
1675ConstantFPSDNode *isConstOrConstSplatFP(SDValue N, const APInt &DemandedElts,
1676 bool AllowUndefs = false);
1677
1678/// Return true if the value is a constant 0 integer or a splatted vector of
1679/// a constant 0 integer (with no undefs by default).
1680/// Build vector implicit truncation is not an issue for null values.
1681bool isNullOrNullSplat(SDValue V, bool AllowUndefs = false);
1682
1683/// Return true if the value is a constant 1 integer or a splatted vector of a
1684/// constant 1 integer (with no undefs).
1685/// Does not permit build vector implicit truncation.
1686bool isOneOrOneSplat(SDValue V, bool AllowUndefs = false);
1687
1688/// Return true if the value is a constant -1 integer or a splatted vector of a
1689/// constant -1 integer (with no undefs).
1690/// Does not permit build vector implicit truncation.
1691bool isAllOnesOrAllOnesSplat(SDValue V, bool AllowUndefs = false);
1692
1693/// Return true if \p V is either a integer or FP constant.
1694inline bool isIntOrFPConstant(SDValue V) {
1695 return isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V);
1696}
1697
1698class GlobalAddressSDNode : public SDNode {
1699 friend class SelectionDAG;
1700
1701 const GlobalValue *TheGlobal;
1702 int64_t Offset;
1703 unsigned TargetFlags;
1704
1705 GlobalAddressSDNode(unsigned Opc, unsigned Order, const DebugLoc &DL,
1706 const GlobalValue *GA, EVT VT, int64_t o,
1707 unsigned TF);
1708
1709public:
1710 const GlobalValue *getGlobal() const { return TheGlobal; }
1711 int64_t getOffset() const { return Offset; }
1712 unsigned getTargetFlags() const { return TargetFlags; }
1713 // Return the address space this GlobalAddress belongs to.
1714 unsigned getAddressSpace() const;
1715
1716 static bool classof(const SDNode *N) {
1717 return N->getOpcode() == ISD::GlobalAddress ||
1718 N->getOpcode() == ISD::TargetGlobalAddress ||
1719 N->getOpcode() == ISD::GlobalTLSAddress ||
1720 N->getOpcode() == ISD::TargetGlobalTLSAddress;
1721 }
1722};
1723
1724class FrameIndexSDNode : public SDNode {
1725 friend class SelectionDAG;
1726
1727 int FI;
1728
1729 FrameIndexSDNode(int fi, EVT VT, bool isTarg)
1730 : SDNode(isTarg ? ISD::TargetFrameIndex : ISD::FrameIndex,
1731 0, DebugLoc(), getSDVTList(VT)), FI(fi) {
1732 }
1733
1734public:
1735 int getIndex() const { return FI; }
1736
1737 static bool classof(const SDNode *N) {
1738 return N->getOpcode() == ISD::FrameIndex ||
1739 N->getOpcode() == ISD::TargetFrameIndex;
1740 }
1741};
1742
1743/// This SDNode is used for LIFETIME_START/LIFETIME_END values, which indicate
1744/// the offet and size that are started/ended in the underlying FrameIndex.
1745class LifetimeSDNode : public SDNode {
1746 friend class SelectionDAG;
1747 int64_t Size;
1748 int64_t Offset; // -1 if offset is unknown.
1749
1750 LifetimeSDNode(unsigned Opcode, unsigned Order, const DebugLoc &dl,
1751 SDVTList VTs, int64_t Size, int64_t Offset)
1752 : SDNode(Opcode, Order, dl, VTs), Size(Size), Offset(Offset) {}
1753public:
1754 int64_t getFrameIndex() const {
1755 return cast<FrameIndexSDNode>(getOperand(1))->getIndex();
1756 }
1757
1758 bool hasOffset() const { return Offset >= 0; }
1759 int64_t getOffset() const {
1760 assert(hasOffset() && "offset is unknown")(static_cast <bool> (hasOffset() && "offset is unknown"
) ? void (0) : __assert_fail ("hasOffset() && \"offset is unknown\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1760, __extension__ __PRETTY_FUNCTION__))
;
1761 return Offset;
1762 }
1763 int64_t getSize() const {
1764 assert(hasOffset() && "offset is unknown")(static_cast <bool> (hasOffset() && "offset is unknown"
) ? void (0) : __assert_fail ("hasOffset() && \"offset is unknown\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1764, __extension__ __PRETTY_FUNCTION__))
;
1765 return Size;
1766 }
1767
1768 // Methods to support isa and dyn_cast
1769 static bool classof(const SDNode *N) {
1770 return N->getOpcode() == ISD::LIFETIME_START ||
1771 N->getOpcode() == ISD::LIFETIME_END;
1772 }
1773};
1774
1775/// This SDNode is used for PSEUDO_PROBE values, which are the function guid and
1776/// the index of the basic block being probed. A pseudo probe serves as a place
1777/// holder and will be removed at the end of compilation. It does not have any
1778/// operand because we do not want the instruction selection to deal with any.
1779class PseudoProbeSDNode : public SDNode {
1780 friend class SelectionDAG;
1781 uint64_t Guid;
1782 uint64_t Index;
1783 uint32_t Attributes;
1784
1785 PseudoProbeSDNode(unsigned Opcode, unsigned Order, const DebugLoc &Dl,
1786 SDVTList VTs, uint64_t Guid, uint64_t Index, uint32_t Attr)
1787 : SDNode(Opcode, Order, Dl, VTs), Guid(Guid), Index(Index),
1788 Attributes(Attr) {}
1789
1790public:
1791 uint64_t getGuid() const { return Guid; }
1792 uint64_t getIndex() const { return Index; }
1793 uint32_t getAttributes() const { return Attributes; }
1794
1795 // Methods to support isa and dyn_cast
1796 static bool classof(const SDNode *N) {
1797 return N->getOpcode() == ISD::PSEUDO_PROBE;
1798 }
1799};
1800
1801class JumpTableSDNode : public SDNode {
1802 friend class SelectionDAG;
1803
1804 int JTI;
1805 unsigned TargetFlags;
1806
1807 JumpTableSDNode(int jti, EVT VT, bool isTarg, unsigned TF)
1808 : SDNode(isTarg ? ISD::TargetJumpTable : ISD::JumpTable,
1809 0, DebugLoc(), getSDVTList(VT)), JTI(jti), TargetFlags(TF) {
1810 }
1811
1812public:
1813 int getIndex() const { return JTI; }
1814 unsigned getTargetFlags() const { return TargetFlags; }
1815
1816 static bool classof(const SDNode *N) {
1817 return N->getOpcode() == ISD::JumpTable ||
1818 N->getOpcode() == ISD::TargetJumpTable;
1819 }
1820};
1821
1822class ConstantPoolSDNode : public SDNode {
1823 friend class SelectionDAG;
1824
1825 union {
1826 const Constant *ConstVal;
1827 MachineConstantPoolValue *MachineCPVal;
1828 } Val;
1829 int Offset; // It's a MachineConstantPoolValue if top bit is set.
1830 Align Alignment; // Minimum alignment requirement of CP.
1831 unsigned TargetFlags;
1832
1833 ConstantPoolSDNode(bool isTarget, const Constant *c, EVT VT, int o,
1834 Align Alignment, unsigned TF)
1835 : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, 0,
1836 DebugLoc(), getSDVTList(VT)),
1837 Offset(o), Alignment(Alignment), TargetFlags(TF) {
1838 assert(Offset >= 0 && "Offset is too large")(static_cast <bool> (Offset >= 0 && "Offset is too large"
) ? void (0) : __assert_fail ("Offset >= 0 && \"Offset is too large\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1838, __extension__ __PRETTY_FUNCTION__))
;
1839 Val.ConstVal = c;
1840 }
1841
1842 ConstantPoolSDNode(bool isTarget, MachineConstantPoolValue *v, EVT VT, int o,
1843 Align Alignment, unsigned TF)
1844 : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, 0,
1845 DebugLoc(), getSDVTList(VT)),
1846 Offset(o), Alignment(Alignment), TargetFlags(TF) {
1847 assert(Offset >= 0 && "Offset is too large")(static_cast <bool> (Offset >= 0 && "Offset is too large"
) ? void (0) : __assert_fail ("Offset >= 0 && \"Offset is too large\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1847, __extension__ __PRETTY_FUNCTION__))
;
1848 Val.MachineCPVal = v;
1849 Offset |= 1 << (sizeof(unsigned)*CHAR_BIT8-1);
1850 }
1851
1852public:
1853 bool isMachineConstantPoolEntry() const {
1854 return Offset < 0;
1855 }
1856
1857 const Constant *getConstVal() const {
1858 assert(!isMachineConstantPoolEntry() && "Wrong constantpool type")(static_cast <bool> (!isMachineConstantPoolEntry() &&
"Wrong constantpool type") ? void (0) : __assert_fail ("!isMachineConstantPoolEntry() && \"Wrong constantpool type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1858, __extension__ __PRETTY_FUNCTION__))
;
1859 return Val.ConstVal;
1860 }
1861
1862 MachineConstantPoolValue *getMachineCPVal() const {
1863 assert(isMachineConstantPoolEntry() && "Wrong constantpool type")(static_cast <bool> (isMachineConstantPoolEntry() &&
"Wrong constantpool type") ? void (0) : __assert_fail ("isMachineConstantPoolEntry() && \"Wrong constantpool type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1863, __extension__ __PRETTY_FUNCTION__))
;
1864 return Val.MachineCPVal;
1865 }
1866
1867 int getOffset() const {
1868 return Offset & ~(1 << (sizeof(unsigned)*CHAR_BIT8-1));
1869 }
1870
1871 // Return the alignment of this constant pool object, which is either 0 (for
1872 // default alignment) or the desired value.
1873 Align getAlign() const { return Alignment; }
1874 unsigned getTargetFlags() const { return TargetFlags; }
1875
1876 Type *getType() const;
1877
1878 static bool classof(const SDNode *N) {
1879 return N->getOpcode() == ISD::ConstantPool ||
1880 N->getOpcode() == ISD::TargetConstantPool;
1881 }
1882};
1883
1884/// Completely target-dependent object reference.
1885class TargetIndexSDNode : public SDNode {
1886 friend class SelectionDAG;
1887
1888 unsigned TargetFlags;
1889 int Index;
1890 int64_t Offset;
1891
1892public:
1893 TargetIndexSDNode(int Idx, EVT VT, int64_t Ofs, unsigned TF)
1894 : SDNode(ISD::TargetIndex, 0, DebugLoc(), getSDVTList(VT)),
1895 TargetFlags(TF), Index(Idx), Offset(Ofs) {}
1896
1897 unsigned getTargetFlags() const { return TargetFlags; }
1898 int getIndex() const { return Index; }
1899 int64_t getOffset() const { return Offset; }
1900
1901 static bool classof(const SDNode *N) {
1902 return N->getOpcode() == ISD::TargetIndex;
1903 }
1904};
1905
1906class BasicBlockSDNode : public SDNode {
1907 friend class SelectionDAG;
1908
1909 MachineBasicBlock *MBB;
1910
1911 /// Debug info is meaningful and potentially useful here, but we create
1912 /// blocks out of order when they're jumped to, which makes it a bit
1913 /// harder. Let's see if we need it first.
1914 explicit BasicBlockSDNode(MachineBasicBlock *mbb)
1915 : SDNode(ISD::BasicBlock, 0, DebugLoc(), getSDVTList(MVT::Other)), MBB(mbb)
1916 {}
1917
1918public:
1919 MachineBasicBlock *getBasicBlock() const { return MBB; }
1920
1921 static bool classof(const SDNode *N) {
1922 return N->getOpcode() == ISD::BasicBlock;
1923 }
1924};
1925
1926/// A "pseudo-class" with methods for operating on BUILD_VECTORs.
1927class BuildVectorSDNode : public SDNode {
1928public:
1929 // These are constructed as SDNodes and then cast to BuildVectorSDNodes.
1930 explicit BuildVectorSDNode() = delete;
1931
1932 /// Check if this is a constant splat, and if so, find the
1933 /// smallest element size that splats the vector. If MinSplatBits is
1934 /// nonzero, the element size must be at least that large. Note that the
1935 /// splat element may be the entire vector (i.e., a one element vector).
1936 /// Returns the splat element value in SplatValue. Any undefined bits in
1937 /// that value are zero, and the corresponding bits in the SplatUndef mask
1938 /// are set. The SplatBitSize value is set to the splat element size in
1939 /// bits. HasAnyUndefs is set to true if any bits in the vector are
1940 /// undefined. isBigEndian describes the endianness of the target.
1941 bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
1942 unsigned &SplatBitSize, bool &HasAnyUndefs,
1943 unsigned MinSplatBits = 0,
1944 bool isBigEndian = false) const;
1945
1946 /// Returns the demanded splatted value or a null value if this is not a
1947 /// splat.
1948 ///
1949 /// The DemandedElts mask indicates the elements that must be in the splat.
1950 /// If passed a non-null UndefElements bitvector, it will resize it to match
1951 /// the vector width and set the bits where elements are undef.
1952 SDValue getSplatValue(const APInt &DemandedElts,
1953 BitVector *UndefElements = nullptr) const;
1954
1955 /// Returns the splatted value or a null value if this is not a splat.
1956 ///
1957 /// If passed a non-null UndefElements bitvector, it will resize it to match
1958 /// the vector width and set the bits where elements are undef.
1959 SDValue getSplatValue(BitVector *UndefElements = nullptr) const;
1960
1961 /// Find the shortest repeating sequence of values in the build vector.
1962 ///
1963 /// e.g. { u, X, u, X, u, u, X, u } -> { X }
1964 /// { X, Y, u, Y, u, u, X, u } -> { X, Y }
1965 ///
1966 /// Currently this must be a power-of-2 build vector.
1967 /// The DemandedElts mask indicates the elements that must be present,
1968 /// undemanded elements in Sequence may be null (SDValue()). If passed a
1969 /// non-null UndefElements bitvector, it will resize it to match the original
1970 /// vector width and set the bits where elements are undef. If result is
1971 /// false, Sequence will be empty.
1972 bool getRepeatedSequence(const APInt &DemandedElts,
1973 SmallVectorImpl<SDValue> &Sequence,
1974 BitVector *UndefElements = nullptr) const;
1975
1976 /// Find the shortest repeating sequence of values in the build vector.
1977 ///
1978 /// e.g. { u, X, u, X, u, u, X, u } -> { X }
1979 /// { X, Y, u, Y, u, u, X, u } -> { X, Y }
1980 ///
1981 /// Currently this must be a power-of-2 build vector.
1982 /// If passed a non-null UndefElements bitvector, it will resize it to match
1983 /// the original vector width and set the bits where elements are undef.
1984 /// If result is false, Sequence will be empty.
1985 bool getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
1986 BitVector *UndefElements = nullptr) const;
1987
1988 /// Returns the demanded splatted constant or null if this is not a constant
1989 /// splat.
1990 ///
1991 /// The DemandedElts mask indicates the elements that must be in the splat.
1992 /// If passed a non-null UndefElements bitvector, it will resize it to match
1993 /// the vector width and set the bits where elements are undef.
1994 ConstantSDNode *
1995 getConstantSplatNode(const APInt &DemandedElts,
1996 BitVector *UndefElements = nullptr) const;
1997
1998 /// Returns the splatted constant or null if this is not a constant
1999 /// splat.
2000 ///
2001 /// If passed a non-null UndefElements bitvector, it will resize it to match
2002 /// the vector width and set the bits where elements are undef.
2003 ConstantSDNode *
2004 getConstantSplatNode(BitVector *UndefElements = nullptr) const;
2005
2006 /// Returns the demanded splatted constant FP or null if this is not a
2007 /// constant FP splat.
2008 ///
2009 /// The DemandedElts mask indicates the elements that must be in the splat.
2010 /// If passed a non-null UndefElements bitvector, it will resize it to match
2011 /// the vector width and set the bits where elements are undef.
2012 ConstantFPSDNode *
2013 getConstantFPSplatNode(const APInt &DemandedElts,
2014 BitVector *UndefElements = nullptr) const;
2015
2016 /// Returns the splatted constant FP or null if this is not a constant
2017 /// FP splat.
2018 ///
2019 /// If passed a non-null UndefElements bitvector, it will resize it to match
2020 /// the vector width and set the bits where elements are undef.
2021 ConstantFPSDNode *
2022 getConstantFPSplatNode(BitVector *UndefElements = nullptr) const;
2023
2024 /// If this is a constant FP splat and the splatted constant FP is an
2025 /// exact power or 2, return the log base 2 integer value. Otherwise,
2026 /// return -1.
2027 ///
2028 /// The BitWidth specifies the necessary bit precision.
2029 int32_t getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
2030 uint32_t BitWidth) const;
2031
2032 bool isConstant() const;
2033
2034 static bool classof(const SDNode *N) {
2035 return N->getOpcode() == ISD::BUILD_VECTOR;
2036 }
2037};
2038
2039/// An SDNode that holds an arbitrary LLVM IR Value. This is
2040/// used when the SelectionDAG needs to make a simple reference to something
2041/// in the LLVM IR representation.
2042///
2043class SrcValueSDNode : public SDNode {
2044 friend class SelectionDAG;
2045
2046 const Value *V;
2047
2048 /// Create a SrcValue for a general value.
2049 explicit SrcValueSDNode(const Value *v)
2050 : SDNode(ISD::SRCVALUE, 0, DebugLoc(), getSDVTList(MVT::Other)), V(v) {}
2051
2052public:
2053 /// Return the contained Value.
2054 const Value *getValue() const { return V; }
2055
2056 static bool classof(const SDNode *N) {
2057 return N->getOpcode() == ISD::SRCVALUE;
2058 }
2059};
2060
2061class MDNodeSDNode : public SDNode {
2062 friend class SelectionDAG;
2063
2064 const MDNode *MD;
2065
2066 explicit MDNodeSDNode(const MDNode *md)
2067 : SDNode(ISD::MDNODE_SDNODE, 0, DebugLoc(), getSDVTList(MVT::Other)), MD(md)
2068 {}
2069
2070public:
2071 const MDNode *getMD() const { return MD; }
2072
2073 static bool classof(const SDNode *N) {
2074 return N->getOpcode() == ISD::MDNODE_SDNODE;
2075 }
2076};
2077
2078class RegisterSDNode : public SDNode {
2079 friend class SelectionDAG;
2080
2081 Register Reg;
2082
2083 RegisterSDNode(Register reg, EVT VT)
2084 : SDNode(ISD::Register, 0, DebugLoc(), getSDVTList(VT)), Reg(reg) {}
2085
2086public:
2087 Register getReg() const { return Reg; }
2088
2089 static bool classof(const SDNode *N) {
2090 return N->getOpcode() == ISD::Register;
2091 }
2092};
2093
2094class RegisterMaskSDNode : public SDNode {
2095 friend class SelectionDAG;
2096
2097 // The memory for RegMask is not owned by the node.
2098 const uint32_t *RegMask;
2099
2100 RegisterMaskSDNode(const uint32_t *mask)
2101 : SDNode(ISD::RegisterMask, 0, DebugLoc(), getSDVTList(MVT::Untyped)),
2102 RegMask(mask) {}
2103
2104public:
2105 const uint32_t *getRegMask() const { return RegMask; }
2106
2107 static bool classof(const SDNode *N) {
2108 return N->getOpcode() == ISD::RegisterMask;
2109 }
2110};
2111
2112class BlockAddressSDNode : public SDNode {
2113 friend class SelectionDAG;
2114
2115 const BlockAddress *BA;
2116 int64_t Offset;
2117 unsigned TargetFlags;
2118
2119 BlockAddressSDNode(unsigned NodeTy, EVT VT, const BlockAddress *ba,
2120 int64_t o, unsigned Flags)
2121 : SDNode(NodeTy, 0, DebugLoc(), getSDVTList(VT)),
2122 BA(ba), Offset(o), TargetFlags(Flags) {}
2123
2124public:
2125 const BlockAddress *getBlockAddress() const { return BA; }
2126 int64_t getOffset() const { return Offset; }
2127 unsigned getTargetFlags() const { return TargetFlags; }
2128
2129 static bool classof(const SDNode *N) {
2130 return N->getOpcode() == ISD::BlockAddress ||
2131 N->getOpcode() == ISD::TargetBlockAddress;
2132 }
2133};
2134
2135class LabelSDNode : public SDNode {
2136 friend class SelectionDAG;
2137
2138 MCSymbol *Label;
2139
2140 LabelSDNode(unsigned Opcode, unsigned Order, const DebugLoc &dl, MCSymbol *L)
2141 : SDNode(Opcode, Order, dl, getSDVTList(MVT::Other)), Label(L) {
2142 assert(LabelSDNode::classof(this) && "not a label opcode")(static_cast <bool> (LabelSDNode::classof(this) &&
"not a label opcode") ? void (0) : __assert_fail ("LabelSDNode::classof(this) && \"not a label opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2142, __extension__ __PRETTY_FUNCTION__))
;
2143 }
2144
2145public:
2146 MCSymbol *getLabel() const { return Label; }
2147
2148 static bool classof(const SDNode *N) {
2149 return N->getOpcode() == ISD::EH_LABEL ||
2150 N->getOpcode() == ISD::ANNOTATION_LABEL;
2151 }
2152};
2153
2154class ExternalSymbolSDNode : public SDNode {
2155 friend class SelectionDAG;
2156
2157 const char *Symbol;
2158 unsigned TargetFlags;
2159
2160 ExternalSymbolSDNode(bool isTarget, const char *Sym, unsigned TF, EVT VT)
2161 : SDNode(isTarget ? ISD::TargetExternalSymbol : ISD::ExternalSymbol, 0,
2162 DebugLoc(), getSDVTList(VT)),
2163 Symbol(Sym), TargetFlags(TF) {}
2164
2165public:
2166 const char *getSymbol() const { return Symbol; }
2167 unsigned getTargetFlags() const { return TargetFlags; }
2168
2169 static bool classof(const SDNode *N) {
2170 return N->getOpcode() == ISD::ExternalSymbol ||
2171 N->getOpcode() == ISD::TargetExternalSymbol;
2172 }
2173};
2174
2175class MCSymbolSDNode : public SDNode {
2176 friend class SelectionDAG;
2177
2178 MCSymbol *Symbol;
2179
2180 MCSymbolSDNode(MCSymbol *Symbol, EVT VT)
2181 : SDNode(ISD::MCSymbol, 0, DebugLoc(), getSDVTList(VT)), Symbol(Symbol) {}
2182
2183public:
2184 MCSymbol *getMCSymbol() const { return Symbol; }
2185
2186 static bool classof(const SDNode *N) {
2187 return N->getOpcode() == ISD::MCSymbol;
2188 }
2189};
2190
2191class CondCodeSDNode : public SDNode {
2192 friend class SelectionDAG;
2193
2194 ISD::CondCode Condition;
2195
2196 explicit CondCodeSDNode(ISD::CondCode Cond)
2197 : SDNode(ISD::CONDCODE, 0, DebugLoc(), getSDVTList(MVT::Other)),
2198 Condition(Cond) {}
2199
2200public:
2201 ISD::CondCode get() const { return Condition; }
2202
2203 static bool classof(const SDNode *N) {
2204 return N->getOpcode() == ISD::CONDCODE;
2205 }
2206};
2207
2208/// This class is used to represent EVT's, which are used
2209/// to parameterize some operations.
2210class VTSDNode : public SDNode {
2211 friend class SelectionDAG;
2212
2213 EVT ValueType;
2214
2215 explicit VTSDNode(EVT VT)
2216 : SDNode(ISD::VALUETYPE, 0, DebugLoc(), getSDVTList(MVT::Other)),
2217 ValueType(VT) {}
2218
2219public:
2220 EVT getVT() const { return ValueType; }
2221
2222 static bool classof(const SDNode *N) {
2223 return N->getOpcode() == ISD::VALUETYPE;
2224 }
2225};
2226
2227/// Base class for LoadSDNode and StoreSDNode
2228class LSBaseSDNode : public MemSDNode {
2229public:
2230 LSBaseSDNode(ISD::NodeType NodeTy, unsigned Order, const DebugLoc &dl,
2231 SDVTList VTs, ISD::MemIndexedMode AM, EVT MemVT,
2232 MachineMemOperand *MMO)
2233 : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2234 LSBaseSDNodeBits.AddressingMode = AM;
2235 assert(getAddressingMode() == AM && "Value truncated")(static_cast <bool> (getAddressingMode() == AM &&
"Value truncated") ? void (0) : __assert_fail ("getAddressingMode() == AM && \"Value truncated\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2235, __extension__ __PRETTY_FUNCTION__))
;
2236 }
2237
2238 const SDValue &getOffset() const {
2239 return getOperand(getOpcode() == ISD::LOAD ? 2 : 3);
2240 }
2241
2242 /// Return the addressing mode for this load or store:
2243 /// unindexed, pre-inc, pre-dec, post-inc, or post-dec.
2244 ISD::MemIndexedMode getAddressingMode() const {
2245 return static_cast<ISD::MemIndexedMode>(LSBaseSDNodeBits.AddressingMode);
2246 }
2247
2248 /// Return true if this is a pre/post inc/dec load/store.
2249 bool isIndexed() const { return getAddressingMode() != ISD::UNINDEXED; }
2250
2251 /// Return true if this is NOT a pre/post inc/dec load/store.
2252 bool isUnindexed() const { return getAddressingMode() == ISD::UNINDEXED; }
2253
2254 static bool classof(const SDNode *N) {
2255 return N->getOpcode() == ISD::LOAD ||
2256 N->getOpcode() == ISD::STORE;
2257 }
2258};
2259
2260/// This class is used to represent ISD::LOAD nodes.
2261class LoadSDNode : public LSBaseSDNode {
2262 friend class SelectionDAG;
2263
2264 LoadSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2265 ISD::MemIndexedMode AM, ISD::LoadExtType ETy, EVT MemVT,
2266 MachineMemOperand *MMO)
2267 : LSBaseSDNode(ISD::LOAD, Order, dl, VTs, AM, MemVT, MMO) {
2268 LoadSDNodeBits.ExtTy = ETy;
2269 assert(readMem() && "Load MachineMemOperand is not a load!")(static_cast <bool> (readMem() && "Load MachineMemOperand is not a load!"
) ? void (0) : __assert_fail ("readMem() && \"Load MachineMemOperand is not a load!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2269, __extension__ __PRETTY_FUNCTION__))
;
2270 assert(!writeMem() && "Load MachineMemOperand is a store!")(static_cast <bool> (!writeMem() && "Load MachineMemOperand is a store!"
) ? void (0) : __assert_fail ("!writeMem() && \"Load MachineMemOperand is a store!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2270, __extension__ __PRETTY_FUNCTION__))
;
2271 }
2272
2273public:
2274 /// Return whether this is a plain node,
2275 /// or one of the varieties of value-extending loads.
2276 ISD::LoadExtType getExtensionType() const {
2277 return static_cast<ISD::LoadExtType>(LoadSDNodeBits.ExtTy);
2278 }
2279
2280 const SDValue &getBasePtr() const { return getOperand(1); }
2281 const SDValue &getOffset() const { return getOperand(2); }
2282
2283 static bool classof(const SDNode *N) {
2284 return N->getOpcode() == ISD::LOAD;
2285 }
2286};
2287
2288/// This class is used to represent ISD::STORE nodes.
2289class StoreSDNode : public LSBaseSDNode {
2290 friend class SelectionDAG;
2291
2292 StoreSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2293 ISD::MemIndexedMode AM, bool isTrunc, EVT MemVT,
2294 MachineMemOperand *MMO)
2295 : LSBaseSDNode(ISD::STORE, Order, dl, VTs, AM, MemVT, MMO) {
2296 StoreSDNodeBits.IsTruncating = isTrunc;
2297 assert(!readMem() && "Store MachineMemOperand is a load!")(static_cast <bool> (!readMem() && "Store MachineMemOperand is a load!"
) ? void (0) : __assert_fail ("!readMem() && \"Store MachineMemOperand is a load!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2297, __extension__ __PRETTY_FUNCTION__))
;
2298 assert(writeMem() && "Store MachineMemOperand is not a store!")(static_cast <bool> (writeMem() && "Store MachineMemOperand is not a store!"
) ? void (0) : __assert_fail ("writeMem() && \"Store MachineMemOperand is not a store!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2298, __extension__ __PRETTY_FUNCTION__))
;
2299 }
2300
2301public:
2302 /// Return true if the op does a truncation before store.
2303 /// For integers this is the same as doing a TRUNCATE and storing the result.
2304 /// For floats, it is the same as doing an FP_ROUND and storing the result.
2305 bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; }
2306 void setTruncatingStore(bool Truncating) {
2307 StoreSDNodeBits.IsTruncating = Truncating;
2308 }
2309
2310 const SDValue &getValue() const { return getOperand(1); }
2311 const SDValue &getBasePtr() const { return getOperand(2); }
2312 const SDValue &getOffset() const { return getOperand(3); }
2313
2314 static bool classof(const SDNode *N) {
2315 return N->getOpcode() == ISD::STORE;
2316 }
2317};
2318
2319/// This base class is used to represent MLOAD and MSTORE nodes
2320class MaskedLoadStoreSDNode : public MemSDNode {
2321public:
2322 friend class SelectionDAG;
2323
2324 MaskedLoadStoreSDNode(ISD::NodeType NodeTy, unsigned Order,
2325 const DebugLoc &dl, SDVTList VTs,
2326 ISD::MemIndexedMode AM, EVT MemVT,
2327 MachineMemOperand *MMO)
2328 : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2329 LSBaseSDNodeBits.AddressingMode = AM;
2330 assert(getAddressingMode() == AM && "Value truncated")(static_cast <bool> (getAddressingMode() == AM &&
"Value truncated") ? void (0) : __assert_fail ("getAddressingMode() == AM && \"Value truncated\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2330, __extension__ __PRETTY_FUNCTION__))
;
2331 }
2332
2333 // MaskedLoadSDNode (Chain, ptr, offset, mask, passthru)
2334 // MaskedStoreSDNode (Chain, data, ptr, offset, mask)
2335 // Mask is a vector of i1 elements
2336 const SDValue &getOffset() const {
2337 return getOperand(getOpcode() == ISD::MLOAD ? 2 : 3);
2338 }
2339 const SDValue &getMask() const {
2340 return getOperand(getOpcode() == ISD::MLOAD ? 3 : 4);
2341 }
2342
2343 /// Return the addressing mode for this load or store:
2344 /// unindexed, pre-inc, pre-dec, post-inc, or post-dec.
2345 ISD::MemIndexedMode getAddressingMode() const {
2346 return static_cast<ISD::MemIndexedMode>(LSBaseSDNodeBits.AddressingMode);
2347 }
2348
2349 /// Return true if this is a pre/post inc/dec load/store.
2350 bool isIndexed() const { return getAddressingMode() != ISD::UNINDEXED; }
2351
2352 /// Return true if this is NOT a pre/post inc/dec load/store.
2353 bool isUnindexed() const { return getAddressingMode() == ISD::UNINDEXED; }
2354
2355 static bool classof(const SDNode *N) {
2356 return N->getOpcode() == ISD::MLOAD ||
2357 N->getOpcode() == ISD::MSTORE;
2358 }
2359};
2360
2361/// This class is used to represent an MLOAD node
2362class MaskedLoadSDNode : public MaskedLoadStoreSDNode {
2363public:
2364 friend class SelectionDAG;
2365
2366 MaskedLoadSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2367 ISD::MemIndexedMode AM, ISD::LoadExtType ETy,
2368 bool IsExpanding, EVT MemVT, MachineMemOperand *MMO)
2369 : MaskedLoadStoreSDNode(ISD::MLOAD, Order, dl, VTs, AM, MemVT, MMO) {
2370 LoadSDNodeBits.ExtTy = ETy;
2371 LoadSDNodeBits.IsExpanding = IsExpanding;
2372 }
2373
2374 ISD::LoadExtType getExtensionType() const {
2375 return static_cast<ISD::LoadExtType>(LoadSDNodeBits.ExtTy);
2376 }
2377
2378 const SDValue &getBasePtr() const { return getOperand(1); }
2379 const SDValue &getOffset() const { return getOperand(2); }
2380 const SDValue &getMask() const { return getOperand(3); }
2381 const SDValue &getPassThru() const { return getOperand(4); }
2382
2383 static bool classof(const SDNode *N) {
2384 return N->getOpcode() == ISD::MLOAD;
2385 }
2386
2387 bool isExpandingLoad() const { return LoadSDNodeBits.IsExpanding; }
2388};
2389
2390/// This class is used to represent an MSTORE node
2391class MaskedStoreSDNode : public MaskedLoadStoreSDNode {
2392public:
2393 friend class SelectionDAG;
2394
2395 MaskedStoreSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2396 ISD::MemIndexedMode AM, bool isTrunc, bool isCompressing,
2397 EVT MemVT, MachineMemOperand *MMO)
2398 : MaskedLoadStoreSDNode(ISD::MSTORE, Order, dl, VTs, AM, MemVT, MMO) {
2399 StoreSDNodeBits.IsTruncating = isTrunc;
2400 StoreSDNodeBits.IsCompressing = isCompressing;
2401 }
2402
2403 /// Return true if the op does a truncation before store.
2404 /// For integers this is the same as doing a TRUNCATE and storing the result.
2405 /// For floats, it is the same as doing an FP_ROUND and storing the result.
2406 bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; }
2407
2408 /// Returns true if the op does a compression to the vector before storing.
2409 /// The node contiguously stores the active elements (integers or floats)
2410 /// in src (those with their respective bit set in writemask k) to unaligned
2411 /// memory at base_addr.
2412 bool isCompressingStore() const { return StoreSDNodeBits.IsCompressing; }
2413
2414 const SDValue &getValue() const { return getOperand(1); }
2415 const SDValue &getBasePtr() const { return getOperand(2); }
2416 const SDValue &getOffset() const { return getOperand(3); }
2417 const SDValue &getMask() const { return getOperand(4); }
2418
2419 static bool classof(const SDNode *N) {
2420 return N->getOpcode() == ISD::MSTORE;
2421 }
2422};
2423
2424/// This is a base class used to represent
2425/// MGATHER and MSCATTER nodes
2426///
2427class MaskedGatherScatterSDNode : public MemSDNode {
2428public:
2429 friend class SelectionDAG;
2430
2431 MaskedGatherScatterSDNode(ISD::NodeType NodeTy, unsigned Order,
2432 const DebugLoc &dl, SDVTList VTs, EVT MemVT,
2433 MachineMemOperand *MMO, ISD::MemIndexType IndexType)
2434 : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2435 LSBaseSDNodeBits.AddressingMode = IndexType;
2436 assert(getIndexType() == IndexType && "Value truncated")(static_cast <bool> (getIndexType() == IndexType &&
"Value truncated") ? void (0) : __assert_fail ("getIndexType() == IndexType && \"Value truncated\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2436, __extension__ __PRETTY_FUNCTION__))
;
2437 }
2438
2439 /// How is Index applied to BasePtr when computing addresses.
2440 ISD::MemIndexType getIndexType() const {
2441 return static_cast<ISD::MemIndexType>(LSBaseSDNodeBits.AddressingMode);
2442 }
2443 void setIndexType(ISD::MemIndexType IndexType) {
2444 LSBaseSDNodeBits.AddressingMode = IndexType;
2445 }
2446 bool isIndexScaled() const {
2447 return (getIndexType() == ISD::SIGNED_SCALED) ||
2448 (getIndexType() == ISD::UNSIGNED_SCALED);
2449 }
2450 bool isIndexSigned() const {
2451 return (getIndexType() == ISD::SIGNED_SCALED) ||
2452 (getIndexType() == ISD::SIGNED_UNSCALED);
2453 }
2454
2455 // In the both nodes address is Op1, mask is Op2:
2456 // MaskedGatherSDNode (Chain, passthru, mask, base, index, scale)
2457 // MaskedScatterSDNode (Chain, value, mask, base, index, scale)
2458 // Mask is a vector of i1 elements
2459 const SDValue &getBasePtr() const { return getOperand(3); }
2460 const SDValue &getIndex() const { return getOperand(4); }
2461 const SDValue &getMask() const { return getOperand(2); }
2462 const SDValue &getScale() const { return getOperand(5); }
2463
2464 static bool classof(const SDNode *N) {
2465 return N->getOpcode() == ISD::MGATHER ||
2466 N->getOpcode() == ISD::MSCATTER;
2467 }
2468};
2469
2470/// This class is used to represent an MGATHER node
2471///
2472class MaskedGatherSDNode : public MaskedGatherScatterSDNode {
2473public:
2474 friend class SelectionDAG;
2475
2476 MaskedGatherSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2477 EVT MemVT, MachineMemOperand *MMO,
2478 ISD::MemIndexType IndexType, ISD::LoadExtType ETy)
2479 : MaskedGatherScatterSDNode(ISD::MGATHER, Order, dl, VTs, MemVT, MMO,
2480 IndexType) {
2481 LoadSDNodeBits.ExtTy = ETy;
2482 }
2483
2484 const SDValue &getPassThru() const { return getOperand(1); }
2485
2486 ISD::LoadExtType getExtensionType() const {
2487 return ISD::LoadExtType(LoadSDNodeBits.ExtTy);
2488 }
2489
2490 static bool classof(const SDNode *N) {
2491 return N->getOpcode() == ISD::MGATHER;
2492 }
2493};
2494
2495/// This class is used to represent an MSCATTER node
2496///
2497class MaskedScatterSDNode : public MaskedGatherScatterSDNode {
2498public:
2499 friend class SelectionDAG;
2500
2501 MaskedScatterSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2502 EVT MemVT, MachineMemOperand *MMO,
2503 ISD::MemIndexType IndexType, bool IsTrunc)
2504 : MaskedGatherScatterSDNode(ISD::MSCATTER, Order, dl, VTs, MemVT, MMO,
2505 IndexType) {
2506 StoreSDNodeBits.IsTruncating = IsTrunc;
2507 }
2508
2509 /// Return true if the op does a truncation before store.
2510 /// For integers this is the same as doing a TRUNCATE and storing the result.
2511 /// For floats, it is the same as doing an FP_ROUND and storing the result.
2512 bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; }
2513
2514 const SDValue &getValue() const { return getOperand(1); }
2515
2516 static bool classof(const SDNode *N) {
2517 return N->getOpcode() == ISD::MSCATTER;
2518 }
2519};
2520
2521/// An SDNode that represents everything that will be needed
2522/// to construct a MachineInstr. These nodes are created during the
2523/// instruction selection proper phase.
2524///
2525/// Note that the only supported way to set the `memoperands` is by calling the
2526/// `SelectionDAG::setNodeMemRefs` function as the memory management happens
2527/// inside the DAG rather than in the node.
2528class MachineSDNode : public SDNode {
2529private:
2530 friend class SelectionDAG;
2531
2532 MachineSDNode(unsigned Opc, unsigned Order, const DebugLoc &DL, SDVTList VTs)
2533 : SDNode(Opc, Order, DL, VTs) {}
2534
2535 // We use a pointer union between a single `MachineMemOperand` pointer and
2536 // a pointer to an array of `MachineMemOperand` pointers. This is null when
2537 // the number of these is zero, the single pointer variant used when the
2538 // number is one, and the array is used for larger numbers.
2539 //
2540 // The array is allocated via the `SelectionDAG`'s allocator and so will
2541 // always live until the DAG is cleaned up and doesn't require ownership here.
2542 //
2543 // We can't use something simpler like `TinyPtrVector` here because `SDNode`
2544 // subclasses aren't managed in a conforming C++ manner. See the comments on
2545 // `SelectionDAG::MorphNodeTo` which details what all goes on, but the
2546 // constraint here is that these don't manage memory with their constructor or
2547 // destructor and can be initialized to a good state even if they start off
2548 // uninitialized.
2549 PointerUnion<MachineMemOperand *, MachineMemOperand **> MemRefs = {};
2550
2551 // Note that this could be folded into the above `MemRefs` member if doing so
2552 // is advantageous at some point. We don't need to store this in most cases.
2553 // However, at the moment this doesn't appear to make the allocation any
2554 // smaller and makes the code somewhat simpler to read.
2555 int NumMemRefs = 0;
2556
2557public:
2558 using mmo_iterator = ArrayRef<MachineMemOperand *>::const_iterator;
2559
2560 ArrayRef<MachineMemOperand *> memoperands() const {
2561 // Special case the common cases.
2562 if (NumMemRefs == 0)
2563 return {};
2564 if (NumMemRefs == 1)
2565 return makeArrayRef(MemRefs.getAddrOfPtr1(), 1);
2566
2567 // Otherwise we have an actual array.
2568 return makeArrayRef(MemRefs.get<MachineMemOperand **>(), NumMemRefs);
2569 }
2570 mmo_iterator memoperands_begin() const { return memoperands().begin(); }
2571 mmo_iterator memoperands_end() const { return memoperands().end(); }
2572 bool memoperands_empty() const { return memoperands().empty(); }
2573
2574 /// Clear out the memory reference descriptor list.
2575 void clearMemRefs() {
2576 MemRefs = nullptr;
2577 NumMemRefs = 0;
2578 }
2579
2580 static bool classof(const SDNode *N) {
2581 return N->isMachineOpcode();
2582 }
2583};
2584
2585/// An SDNode that records if a register contains a value that is guaranteed to
2586/// be aligned accordingly.
2587class AssertAlignSDNode : public SDNode {
2588 Align Alignment;
2589
2590public:
2591 AssertAlignSDNode(unsigned Order, const DebugLoc &DL, EVT VT, Align A)
2592 : SDNode(ISD::AssertAlign, Order, DL, getSDVTList(VT)), Alignment(A) {}
2593
2594 Align getAlign() const { return Alignment; }
2595
2596 static bool classof(const SDNode *N) {
2597 return N->getOpcode() == ISD::AssertAlign;
2598 }
2599};
2600
2601class SDNodeIterator {
2602 const SDNode *Node;
2603 unsigned Operand;
2604
2605 SDNodeIterator(const SDNode *N, unsigned Op) : Node(N), Operand(Op) {}
2606
2607public:
2608 using iterator_category = std::forward_iterator_tag;
2609 using value_type = SDNode;
2610 using difference_type = std::ptrdiff_t;
2611 using pointer = value_type *;
2612 using reference = value_type &;
2613
2614 bool operator==(const SDNodeIterator& x) const {
2615 return Operand == x.Operand;
2616 }
2617 bool operator!=(const SDNodeIterator& x) const { return !operator==(x); }
2618
2619 pointer operator*() const {
2620 return Node->getOperand(Operand).getNode();
2621 }
2622 pointer operator->() const { return operator*(); }
2623
2624 SDNodeIterator& operator++() { // Preincrement
2625 ++Operand;
2626 return *this;
2627 }
2628 SDNodeIterator operator++(int) { // Postincrement
2629 SDNodeIterator tmp = *this; ++*this; return tmp;
2630 }
2631 size_t operator-(SDNodeIterator Other) const {
2632 assert(Node == Other.Node &&(static_cast <bool> (Node == Other.Node && "Cannot compare iterators of two different nodes!"
) ? void (0) : __assert_fail ("Node == Other.Node && \"Cannot compare iterators of two different nodes!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2633, __extension__ __PRETTY_FUNCTION__))
2633 "Cannot compare iterators of two different nodes!")(static_cast <bool> (Node == Other.Node && "Cannot compare iterators of two different nodes!"
) ? void (0) : __assert_fail ("Node == Other.Node && \"Cannot compare iterators of two different nodes!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2633, __extension__ __PRETTY_FUNCTION__))
;
2634 return Operand - Other.Operand;
2635 }
2636
2637 static SDNodeIterator begin(const SDNode *N) { return SDNodeIterator(N, 0); }
2638 static SDNodeIterator end (const SDNode *N) {
2639 return SDNodeIterator(N, N->getNumOperands());
2640 }
2641
2642 unsigned getOperand() const { return Operand; }
2643 const SDNode *getNode() const { return Node; }
2644};
2645
2646template <> struct GraphTraits<SDNode*> {
2647 using NodeRef = SDNode *;
2648 using ChildIteratorType = SDNodeIterator;
2649
2650 static NodeRef getEntryNode(SDNode *N) { return N; }
2651
2652 static ChildIteratorType child_begin(NodeRef N) {
2653 return SDNodeIterator::begin(N);
2654 }
2655
2656 static ChildIteratorType child_end(NodeRef N) {
2657 return SDNodeIterator::end(N);
2658 }
2659};
2660
2661/// A representation of the largest SDNode, for use in sizeof().
2662///
2663/// This needs to be a union because the largest node differs on 32 bit systems
2664/// with 4 and 8 byte pointer alignment, respectively.
2665using LargestSDNode = AlignedCharArrayUnion<AtomicSDNode, TargetIndexSDNode,
2666 BlockAddressSDNode,
2667 GlobalAddressSDNode,
2668 PseudoProbeSDNode>;
2669
2670/// The SDNode class with the greatest alignment requirement.
2671using MostAlignedSDNode = GlobalAddressSDNode;
2672
2673namespace ISD {
2674
2675 /// Returns true if the specified node is a non-extending and unindexed load.
2676 inline bool isNormalLoad(const SDNode *N) {
2677 const LoadSDNode *Ld = dyn_cast<LoadSDNode>(N);
2678 return Ld && Ld->getExtensionType() == ISD::NON_EXTLOAD &&
2679 Ld->getAddressingMode() == ISD::UNINDEXED;
2680 }
2681
2682 /// Returns true if the specified node is a non-extending load.
2683 inline bool isNON_EXTLoad(const SDNode *N) {
2684 return isa<LoadSDNode>(N) &&
2685 cast<LoadSDNode>(N)->getExtensionType() == ISD::NON_EXTLOAD;
2686 }
2687
2688 /// Returns true if the specified node is a EXTLOAD.
2689 inline bool isEXTLoad(const SDNode *N) {
2690 return isa<LoadSDNode>(N) &&
2691 cast<LoadSDNode>(N)->getExtensionType() == ISD::EXTLOAD;
2692 }
2693
2694 /// Returns true if the specified node is a SEXTLOAD.
2695 inline bool isSEXTLoad(const SDNode *N) {
2696 return isa<LoadSDNode>(N) &&
2697 cast<LoadSDNode>(N)->getExtensionType() == ISD::SEXTLOAD;
2698 }
2699
2700 /// Returns true if the specified node is a ZEXTLOAD.
2701 inline bool isZEXTLoad(const SDNode *N) {
2702 return isa<LoadSDNode>(N) &&
2703 cast<LoadSDNode>(N)->getExtensionType() == ISD::ZEXTLOAD;
2704 }
2705
2706 /// Returns true if the specified node is an unindexed load.
2707 inline bool isUNINDEXEDLoad(const SDNode *N) {
2708 return isa<LoadSDNode>(N) &&
2709 cast<LoadSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
2710 }
2711
2712 /// Returns true if the specified node is a non-truncating
2713 /// and unindexed store.
2714 inline bool isNormalStore(const SDNode *N) {
2715 const StoreSDNode *St = dyn_cast<StoreSDNode>(N);
2716 return St && !St->isTruncatingStore() &&
2717 St->getAddressingMode() == ISD::UNINDEXED;
2718 }
2719
2720 /// Returns true if the specified node is an unindexed store.
2721 inline bool isUNINDEXEDStore(const SDNode *N) {
2722 return isa<StoreSDNode>(N) &&
2723 cast<StoreSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
2724 }
2725
2726 /// Attempt to match a unary predicate against a scalar/splat constant or
2727 /// every element of a constant BUILD_VECTOR.
2728 /// If AllowUndef is true, then UNDEF elements will pass nullptr to Match.
2729 bool matchUnaryPredicate(SDValue Op,
2730 std::function<bool(ConstantSDNode *)> Match,
2731 bool AllowUndefs = false);
2732
2733 /// Attempt to match a binary predicate against a pair of scalar/splat
2734 /// constants or every element of a pair of constant BUILD_VECTORs.
2735 /// If AllowUndef is true, then UNDEF elements will pass nullptr to Match.
2736 /// If AllowTypeMismatch is true then RetType + ArgTypes don't need to match.
2737 bool matchBinaryPredicate(
2738 SDValue LHS, SDValue RHS,
2739 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
2740 bool AllowUndefs = false, bool AllowTypeMismatch = false);
2741
2742 /// Returns true if the specified value is the overflow result from one
2743 /// of the overflow intrinsic nodes.
2744 inline bool isOverflowIntrOpRes(SDValue Op) {
2745 unsigned Opc = Op.getOpcode();
2746 return (Op.getResNo() == 1 &&
2747 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2748 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2749 }
2750
2751} // end namespace ISD
2752
2753} // end namespace llvm
2754
2755#endif // LLVM_CODEGEN_SELECTIONDAGNODES_H